From 9843bafafdcec1721b5715440011e5f7b72ac583 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ha=C3=9F?= Date: Mon, 3 Mar 2014 09:35:05 +0100 Subject: Added handler for FileHasNoContent exception, some clean up --- .../keychain/ui/ImportKeysListFragment.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java index 1118f0264..abc594b39 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java @@ -219,27 +219,34 @@ public class ImportKeysListFragment extends ListFragment implements } else { setListShownNoAnimation(true); } + + Exception error = data.getError(); + switch (loader.getId()) { case LOADER_ID_BYTES: + error = data.getError(); + + if(error instanceof ImportKeysListLoader.FileHasNoContent) { + AppMsg.makeText(getActivity(), R.string.error_import_file_no_content, + AppMsg.STYLE_ALERT).show(); + } break; case LOADER_ID_SERVER_QUERY: - Exception error = data.getError(); - - if(error == null){ + if(error == null) { AppMsg.makeText( getActivity(), getResources().getQuantityString(R.plurals.keys_found, mAdapter.getCount(), mAdapter.getCount()), AppMsg.STYLE_INFO ).show(); - } else if(error instanceof KeyServer.InsufficientQuery){ + } else if(error instanceof KeyServer.InsufficientQuery) { AppMsg.makeText(getActivity(), R.string.error_keyserver_insufficient_query, AppMsg.STYLE_ALERT).show(); - }else if(error instanceof KeyServer.QueryException){ + } else if(error instanceof KeyServer.QueryException) { AppMsg.makeText(getActivity(), R.string.error_keyserver_query, AppMsg.STYLE_ALERT).show(); - }else if(error instanceof KeyServer.TooManyResponses){ + } else if(error instanceof KeyServer.TooManyResponses) { AppMsg.makeText(getActivity(), R.string.error_keyserver_too_many_responses, AppMsg.STYLE_ALERT).show(); } -- cgit v1.2.3 From f484122c353aa66dbc1a3a776163eaa28d70e4d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ha=C3=9F?= Date: Mon, 3 Mar 2014 09:36:10 +0100 Subject: Added exception for empty files --- .../keychain/ui/adapter/ImportKeysListLoader.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java index 29e418db7..bc8e4d050 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java @@ -33,7 +33,14 @@ import org.sufficientlysecure.keychain.util.PositionAwareInputStream; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; +import com.devspark.appmsg.AppMsg; + public class ImportKeysListLoader extends AsyncTaskLoader>> { + + public static class FileHasNoContent extends Exception { + + } + Context mContext; InputData mInputData; @@ -92,6 +99,9 @@ public class ImportKeysListLoader extends AsyncTaskLoader 0) { + isEmpty = false; InputStream in = PGPUtil.getDecoderStream(bufferedInput); PGPObjectFactory objectFactory = new PGPObjectFactory(in); @@ -120,7 +131,12 @@ public class ImportKeysListLoader extends AsyncTaskLoader>(data, new FileHasNoContent()); } } -- cgit v1.2.3 From ec8a3469fff2718e47f6214f5364a13d84664967 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ha=C3=9F?= Date: Mon, 3 Mar 2014 15:07:07 +0100 Subject: Little fixes --- .../java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java | 1 - .../sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java index abc594b39..009c26ce5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java @@ -224,7 +224,6 @@ public class ImportKeysListFragment extends ListFragment implements switch (loader.getId()) { case LOADER_ID_BYTES: - error = data.getError(); if(error instanceof ImportKeysListLoader.FileHasNoContent) { AppMsg.makeText(getActivity(), R.string.error_import_file_no_content, diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java index bc8e4d050..19b17468b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java @@ -131,7 +131,7 @@ public class ImportKeysListLoader extends AsyncTaskLoader Date: Mon, 3 Mar 2014 20:42:38 +0100 Subject: Added handling for other exceptions in the ImportListLoader. --- .../keychain/ui/ImportKeysListFragment.java | 9 ++++++++ .../keychain/ui/adapter/ImportKeysListLoader.java | 25 ++++++++++++++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java index 009c26ce5..06925e5fa 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java @@ -228,6 +228,15 @@ public class ImportKeysListFragment extends ListFragment implements if(error instanceof ImportKeysListLoader.FileHasNoContent) { AppMsg.makeText(getActivity(), R.string.error_import_file_no_content, AppMsg.STYLE_ALERT).show(); + } else if(error instanceof ImportKeysListLoader.NonPGPPart) { + AppMsg.makeText(getActivity(), + ((ImportKeysListLoader.NonPGPPart) error).getCount() + " " + getResources(). + getQuantityString(R.plurals.error_import_non_pgp_part, + ((ImportKeysListLoader.NonPGPPart) error).getCount()), + new AppMsg.Style(AppMsg.LENGTH_LONG, R.color.confirm)).show(); + } else { + AppMsg.makeText(getActivity(), R.string.error_generic_report_bug, + new AppMsg.Style(AppMsg.LENGTH_LONG, R.color.alert)).show(); } break; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java index 19b17468b..98884689c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java @@ -20,7 +20,6 @@ package org.sufficientlysecure.keychain.ui.adapter; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.ArrayList; -import java.util.List; import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPObjectFactory; @@ -33,14 +32,22 @@ import org.sufficientlysecure.keychain.util.PositionAwareInputStream; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; -import com.devspark.appmsg.AppMsg; - public class ImportKeysListLoader extends AsyncTaskLoader>> { public static class FileHasNoContent extends Exception { } + public static class NonPGPPart extends Exception { + private int count; + public NonPGPPart(int count) { + this.count = count; + } + public int getCount() { + return count; + } + } + Context mContext; InputData mInputData; @@ -101,6 +108,7 @@ public class ImportKeysListLoader extends AsyncTaskLoader>(data, e); + nonPGPcounter = 0; } if(isEmpty) { Log.e(Constants.TAG, "File has no content!", new FileHasNoContent()); - entryListWrapper = new AsyncTaskResultWrapper>(data, new FileHasNoContent()); + entryListWrapper = new AsyncTaskResultWrapper> + (data, new FileHasNoContent()); + } + + if(nonPGPcounter > 0) { + entryListWrapper = new AsyncTaskResultWrapper> + (data, new NonPGPPart(nonPGPcounter)); } } -- cgit v1.2.3 From a12b67c538a1934a35c45fbed3569056a786df67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ha=C3=9F?= Date: Tue, 4 Mar 2014 13:56:46 +0100 Subject: Added exception is null option to display nothing if no error occured --- .../sufficientlysecure/keychain/ui/ImportKeysListFragment.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java index 06925e5fa..a6917d6f4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java @@ -225,14 +225,16 @@ public class ImportKeysListFragment extends ListFragment implements switch (loader.getId()) { case LOADER_ID_BYTES: - if(error instanceof ImportKeysListLoader.FileHasNoContent) { + if(error == null){ + // No error + } else if(error instanceof ImportKeysListLoader.FileHasNoContent) { AppMsg.makeText(getActivity(), R.string.error_import_file_no_content, AppMsg.STYLE_ALERT).show(); - } else if(error instanceof ImportKeysListLoader.NonPGPPart) { + } else if(error instanceof ImportKeysListLoader.NonPgpPart) { AppMsg.makeText(getActivity(), - ((ImportKeysListLoader.NonPGPPart) error).getCount() + " " + getResources(). + ((ImportKeysListLoader.NonPgpPart) error).getCount() + " " + getResources(). getQuantityString(R.plurals.error_import_non_pgp_part, - ((ImportKeysListLoader.NonPGPPart) error).getCount()), + ((ImportKeysListLoader.NonPgpPart) error).getCount()), new AppMsg.Style(AppMsg.LENGTH_LONG, R.color.confirm)).show(); } else { AppMsg.makeText(getActivity(), R.string.error_generic_report_bug, -- cgit v1.2.3 From 106027a7cd43001a2f9e620ee13ef60d39074c41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ha=C3=9F?= Date: Tue, 4 Mar 2014 13:58:26 +0100 Subject: Fixed some naming --- .../keychain/ui/adapter/ImportKeysListLoader.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java index 98884689c..7ca7bc998 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java @@ -38,9 +38,9 @@ public class ImportKeysListLoader extends AsyncTaskLoader>(data, e); - nonPGPcounter = 0; + nonPgpCounter = 0; } if(isEmpty) { @@ -151,9 +151,9 @@ public class ImportKeysListLoader extends AsyncTaskLoader 0) { + if(nonPgpCounter > 0) { entryListWrapper = new AsyncTaskResultWrapper> - (data, new NonPGPPart(nonPGPcounter)); + (data, new NonPgpPart(nonPgpCounter)); } } -- cgit v1.2.3 From 4851f7f8fc5ca82d60a55e95730bf6c11675979c Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Wed, 5 Mar 2014 15:54:27 +0100 Subject: copy public keylist as stub for unified keylist --- .../keychain/ui/KeyListActivity.java | 71 +++++ .../keychain/ui/KeyListFragment.java | 338 +++++++++++++++++++++ .../keychain/ui/adapter/KeyListAdapter.java | 232 ++++++++++++++ 3 files changed, 641 insertions(+) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java new file mode 100644 index 000000000..dd7aa9a26 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2012-2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.ui; + +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ExportHelper; + +import android.content.Intent; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; + +public class KeyListActivity extends DrawerActivity { + + ExportHelper mExportHelper; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mExportHelper = new ExportHelper(this); + + setContentView(R.layout.key_list_public_activity); + + // now setup navigation drawer in DrawerActivity... + setupDrawerNavigation(savedInstanceState); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + getMenuInflater().inflate(R.menu.key_list_public, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_key_list_public_import: + Intent intentImport = new Intent(this, ImportKeysActivity.class); + startActivityForResult(intentImport, 0); + + return true; + case R.id.menu_key_list_public_export: + mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR + + "/pubexport.asc"); + + return true; + default: + return super.onOptionsItemSelected(item); + } + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java new file mode 100644 index 000000000..6f94ffd1a --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -0,0 +1,338 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.ui; + +import java.util.ArrayList; +import java.util.Set; + +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.ui.adapter.KeyListAdapter; +import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; + +import se.emilsjolander.stickylistheaders.ApiLevelTooLowException; +import se.emilsjolander.stickylistheaders.StickyListHeadersListView; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.Messenger; +import android.support.v4.app.Fragment; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; +import android.view.ActionMode; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.AbsListView.MultiChoiceModeListener; +import android.widget.AdapterView; +import android.widget.ListView; +import android.widget.Toast; + +import com.beardedhen.androidbootstrap.BootstrapButton; + +/** + * Public key list with sticky list headers. It does _not_ extend ListFragment because it uses + * StickyListHeaders library which does not extend upon ListView. + */ +public class KeyListFragment extends Fragment implements AdapterView.OnItemClickListener, + LoaderManager.LoaderCallbacks { + + private KeyListAdapter mAdapter; + private StickyListHeadersListView mStickyList; + + // empty list layout + private BootstrapButton mButtonEmptyCreate; + private BootstrapButton mButtonEmptyImport; + + /** + * Load custom layout with StickyListView from library + */ + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.key_list_fragment, container, false); + + mButtonEmptyCreate = (BootstrapButton) view.findViewById(R.id.key_list_empty_button_create); + mButtonEmptyCreate.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + Intent intent = new Intent(getActivity(), EditKeyActivity.class); + intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); + intent.putExtra(EditKeyActivity.EXTRA_GENERATE_DEFAULT_KEYS, true); + intent.putExtra(EditKeyActivity.EXTRA_USER_IDS, ""); // show user id view + startActivityForResult(intent, 0); + } + }); + + mButtonEmptyImport = (BootstrapButton) view.findViewById(R.id.key_list_empty_button_import); + mButtonEmptyImport.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + Intent intent = new Intent(getActivity(), ImportKeysActivity.class); + intent.setAction(ImportKeysActivity.ACTION_IMPORT_KEY_FROM_FILE); + startActivityForResult(intent, 0); + } + }); + + return view; + } + + /** + * Define Adapter and Loader on create of Activity + */ + @SuppressLint("NewApi") + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + mStickyList = (StickyListHeadersListView) getActivity().findViewById(R.id.list); + + mStickyList.setOnItemClickListener(this); + mStickyList.setAreHeadersSticky(true); + mStickyList.setDrawingListUnderStickyHeader(false); + mStickyList.setFastScrollEnabled(true); + try { + mStickyList.setFastScrollAlwaysVisible(true); + } catch (ApiLevelTooLowException e) { + } + + // this view is made visible if no data is available + mStickyList.setEmptyView(getActivity().findViewById(R.id.empty)); + + /* + * ActionBarSherlock does not support MultiChoiceModeListener. Thus multi-selection is only + * available for Android >= 3.0 + */ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + mStickyList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); + mStickyList.getWrappedList().setMultiChoiceModeListener(new MultiChoiceModeListener() { + + private int count = 0; + + @Override + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + android.view.MenuInflater inflater = getActivity().getMenuInflater(); + inflater.inflate(R.menu.key_list_multi, menu); + return true; + } + + @Override + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; + } + + @Override + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + Set positions = mAdapter.getCurrentCheckedPosition(); + + // get IDs for checked positions as long array + long[] ids = new long[positions.size()]; + int i = 0; + for (int pos : positions) { + ids[i] = mAdapter.getItemId(pos); + i++; + } + + switch (item.getItemId()) { + case R.id.menu_key_list_multi_encrypt: { + encrypt(mode, ids); + break; + } + case R.id.menu_key_list_multi_delete: { + showDeleteKeyDialog(mode, ids); + break; + } + } + return true; + } + + @Override + public void onDestroyActionMode(ActionMode mode) { + count = 0; + mAdapter.clearSelection(); + } + + @Override + public void onItemCheckedStateChanged(ActionMode mode, int position, long id, + boolean checked) { + if (checked) { + count++; + mAdapter.setNewSelection(position, checked); + } else { + count--; + mAdapter.removeSelection(position); + } + + String keysSelected = getResources().getQuantityString( + R.plurals.key_list_selected_keys, count, count); + mode.setTitle(keysSelected); + } + + }); + } + + // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading + // Start out with a progress indicator. + // setListShown(false); + + // Create an empty adapter we will use to display the loaded data. + mAdapter = new KeyListAdapter(getActivity(), null, Id.type.public_key, USER_ID_INDEX); + mStickyList.setAdapter(mAdapter); + + // Prepare the loader. Either re-connect with an existing one, + // or start a new one. + getLoaderManager().initLoader(0, null, this); + } + + // These are the rows that we will retrieve. + static final String[] PROJECTION = new String[]{ + KeychainContract.KeyRings._ID, + KeychainContract.KeyRings.MASTER_KEY_ID, + KeychainContract.UserIds.USER_ID, + KeychainContract.Keys.IS_REVOKED + }; + + static final int USER_ID_INDEX = 2; + + static final String SORT_ORDER = UserIds.USER_ID + " ASC"; + + @Override + public Loader onCreateLoader(int id, Bundle args) { + // This is called when a new Loader needs to be created. This + // sample only has one Loader, so we don't care about the ID. + Uri baseUri = KeyRings.buildPublicKeyRingsUri(); + + // Now create and return a CursorLoader that will take care of + // creating a Cursor for the data being displayed. + return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, SORT_ORDER); + } + + @Override + public void onLoadFinished(Loader loader, Cursor data) { + // Swap the new cursor in. (The framework will take care of closing the + // old cursor once we return.) + mAdapter.swapCursor(data); + + mStickyList.setAdapter(mAdapter); + + // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading + // The list should now be shown. + // if (isResumed()) { + // setListShown(true); + // } else { + // setListShownNoAnimation(true); + // } + } + + @Override + public void onLoaderReset(Loader loader) { + // This is called when the last Cursor provided to onLoadFinished() + // above is about to be closed. We need to make sure we are no + // longer using it. + mAdapter.swapCursor(null); + } + + /** + * On click on item, start key view activity + */ + @Override + public void onItemClick(AdapterView adapterView, View view, int position, long id) { + Intent viewIntent = null; + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { + viewIntent = new Intent(getActivity(), ViewKeyActivity.class); + } else { + viewIntent = new Intent(getActivity(), ViewKeyActivityJB.class); + } + viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(id))); + startActivity(viewIntent); + } + + @TargetApi(11) + public void encrypt(ActionMode mode, long[] keyRingRowIds) { + // get master key ids from row ids + long[] keyRingIds = new long[keyRingRowIds.length]; + for (int i = 0; i < keyRingRowIds.length; i++) { + keyRingIds[i] = ProviderHelper.getPublicMasterKeyId(getActivity(), keyRingRowIds[i]); + } + + Intent intent = new Intent(getActivity(), EncryptActivity.class); + intent.setAction(EncryptActivity.ACTION_ENCRYPT); + intent.putExtra(EncryptActivity.EXTRA_ENCRYPTION_KEY_IDS, keyRingIds); + // used instead of startActivity set actionbar based on callingPackage + startActivityForResult(intent, 0); + + mode.finish(); + } + + /** + * Show dialog to delete key + * + * @param keyRingRowIds + */ + @TargetApi(11) + public void showDeleteKeyDialog(final ActionMode mode, long[] keyRingRowIds) { + // Message is received after key is deleted + Handler returnHandler = new Handler() { + @Override + public void handleMessage(Message message) { + if (message.what == DeleteKeyDialogFragment.MESSAGE_OKAY) { + Bundle returnData = message.getData(); + if (returnData != null + && returnData.containsKey(DeleteKeyDialogFragment.MESSAGE_NOT_DELETED)) { + ArrayList notDeleted = + returnData.getStringArrayList(DeleteKeyDialogFragment.MESSAGE_NOT_DELETED); + String notDeletedMsg = ""; + for (String userId : notDeleted) { + notDeletedMsg += userId + "\n"; + } + Toast.makeText(getActivity(), getString(R.string.error_can_not_delete_contacts, notDeletedMsg) + + getResources().getQuantityString(R.plurals.error_can_not_delete_info, notDeleted.size()), + Toast.LENGTH_LONG).show(); + + mode.finish(); + } + } + } + }; + + // Create a new Messenger for the communication back + Messenger messenger = new Messenger(returnHandler); + + DeleteKeyDialogFragment deleteKeyDialog = DeleteKeyDialogFragment.newInstance(messenger, + keyRingRowIds, Id.type.public_key); + + deleteKeyDialog.show(getActivity().getSupportFragmentManager(), "deleteKeyDialog"); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java new file mode 100644 index 000000000..2e0d1496b --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java @@ -0,0 +1,232 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.ui.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.database.Cursor; +import android.graphics.Color; +import android.support.v4.widget.CursorAdapter; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.util.Log; + +import java.util.HashMap; +import java.util.Set; + +import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; + +/** + * Implements StickyListHeadersAdapter from library + */ +public class KeyListAdapter extends CursorAdapter implements StickyListHeadersAdapter { + private LayoutInflater mInflater; + private int mSectionColumnIndex; + private int mIndexUserId; + private int mIndexIsRevoked; + + @SuppressLint("UseSparseArrays") + private HashMap mSelection = new HashMap(); + + public KeyListAdapter(Context context, Cursor c, int flags, int sectionColumnIndex) { + super(context, c, flags); + + mInflater = LayoutInflater.from(context); + mSectionColumnIndex = sectionColumnIndex; + initIndex(c); + } + + @Override + public Cursor swapCursor(Cursor newCursor) { + initIndex(newCursor); + + return super.swapCursor(newCursor); + } + + /** + * Get column indexes for performance reasons just once in constructor and swapCursor. For a + * performance comparison see http://stackoverflow.com/a/17999582 + * + * @param cursor + */ + private void initIndex(Cursor cursor) { + if (cursor != null) { + mIndexUserId = cursor.getColumnIndexOrThrow(KeychainContract.UserIds.USER_ID); + mIndexIsRevoked = cursor.getColumnIndexOrThrow(KeychainContract.Keys.IS_REVOKED); + } + } + + /** + * Bind cursor data to the item list view + *

+ * NOTE: CursorAdapter already implements the ViewHolder pattern in its getView() method. Thus + * no ViewHolder is required here. + */ + @Override + public void bindView(View view, Context context, Cursor cursor) { + TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId); + TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest); + TextView revoked = (TextView) view.findViewById(R.id.revoked); + + String userId = cursor.getString(mIndexUserId); + String[] userIdSplit = PgpKeyHelper.splitUserId(userId); + if (userIdSplit[0] != null) { + mainUserId.setText(userIdSplit[0]); + } else { + mainUserId.setText(R.string.user_id_no_name); + } + if (userIdSplit[1] != null) { + mainUserIdRest.setText(userIdSplit[1]); + mainUserIdRest.setVisibility(View.VISIBLE); + } else { + mainUserIdRest.setVisibility(View.GONE); + } + + boolean isRevoked = cursor.getInt(mIndexIsRevoked) > 0; + if (isRevoked) { + revoked.setVisibility(View.VISIBLE); + } else { + revoked.setVisibility(View.GONE); + } + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return mInflater.inflate(R.layout.key_list_item, null); + } + + /** + * Creates a new header view and binds the section headers to it. It uses the ViewHolder + * pattern. Most functionality is similar to getView() from Android's CursorAdapter. + *

+ * NOTE: The variables mDataValid and mCursor are available due to the super class + * CursorAdapter. + */ + @Override + public View getHeaderView(int position, View convertView, ViewGroup parent) { + HeaderViewHolder holder; + if (convertView == null) { + holder = new HeaderViewHolder(); + convertView = mInflater.inflate(R.layout.key_list_header, parent, false); + holder.text = (TextView) convertView.findViewById(R.id.stickylist_header_text); + convertView.setTag(holder); + } else { + holder = (HeaderViewHolder) convertView.getTag(); + } + + if (!mDataValid) { + // no data available at this point + Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); + return convertView; + } + + if (!mCursor.moveToPosition(position)) { + throw new IllegalStateException("couldn't move cursor to position " + position); + } + + // set header text as first char in user id + String userId = mCursor.getString(mSectionColumnIndex); + String headerText = convertView.getResources().getString(R.string.user_id_no_name); + if (userId != null && userId.length() > 0) { + headerText = "" + mCursor.getString(mSectionColumnIndex).subSequence(0, 1).charAt(0); + } + holder.text.setText(headerText); + return convertView; + } + + /** + * Header IDs should be static, position=1 should always return the same Id that is. + */ + @Override + public long getHeaderId(int position) { + if (!mDataValid) { + // no data available at this point + Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); + return -1; + } + + if (!mCursor.moveToPosition(position)) { + throw new IllegalStateException("couldn't move cursor to position " + position); + } + + // return the first character of the name as ID because this is what + // headers are based upon + String userId = mCursor.getString(mSectionColumnIndex); + if (userId != null && userId.length() > 0) { + return userId.subSequence(0, 1).charAt(0); + } else { + return Long.MAX_VALUE; + } + } + + class HeaderViewHolder { + TextView text; + } + + /** + * -------------------------- MULTI-SELECTION METHODS -------------- + */ + public void setNewSelection(int position, boolean value) { + mSelection.put(position, value); + notifyDataSetChanged(); + } + + public boolean isPositionChecked(int position) { + Boolean result = mSelection.get(position); + return result == null ? false : result; + } + + public Set getCurrentCheckedPosition() { + return mSelection.keySet(); + } + + public void removeSelection(int position) { + mSelection.remove(position); + notifyDataSetChanged(); + } + + public void clearSelection() { + mSelection.clear(); + notifyDataSetChanged(); + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // let the adapter handle setting up the row views + View v = super.getView(position, convertView, parent); + + /** + * Change color for multi-selection + */ + // default color + v.setBackgroundColor(Color.TRANSPARENT); + if (mSelection.get(position) != null) { + // this is a selected position, change color! + v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); + } + return v; + } + +} -- cgit v1.2.3 From 2e2a9bc967399b6adc353b1b34d3c7ed981e68f4 Mon Sep 17 00:00:00 2001 From: Miroojin Bakshi Date: Fri, 7 Mar 2014 21:16:58 +0530 Subject: Add option for sharing encrypted file. --- .../org/sufficientlysecure/keychain/ui/EncryptActivity.java | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index faac9b157..88a29cee9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -108,6 +108,7 @@ public class EncryptActivity extends DrawerActivity { private EditText mFilename = null; private CheckBox mDeleteAfter = null; + private CheckBox mShareAfter = null; private BootstrapButton mBrowse = null; private String mInputFilename = null; @@ -650,6 +651,15 @@ public class EncryptActivity extends DrawerActivity { .newInstance(mInputFilename); deleteFileDialog.show(getSupportFragmentManager(), "deleteDialog"); } + + if (mShareAfter.isChecked()) { + // Share encrypted file + Intent sendFileIntent = new Intent(Intent.ACTION_SEND); + sendFileIntent.setType("*/*"); + sendFileIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(mOutputFilename)); + startActivity(Intent.createChooser(sendFileIntent, + getString(R.string.title_send_file))); + } break; default: @@ -809,6 +819,7 @@ public class EncryptActivity extends DrawerActivity { } mDeleteAfter = (CheckBox) findViewById(R.id.deleteAfterEncryption); + mShareAfter = (CheckBox) findViewById(R.id.shareAfterEncryption); mAsciiArmor = (CheckBox) findViewById(R.id.asciiArmour); mAsciiArmor.setChecked(Preferences.getPreferences(this).getDefaultAsciiArmour()); -- cgit v1.2.3 From ba61e69a7dcc4e11778931eaf8f3b2c9e269d624 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 7 Mar 2014 19:50:36 +0100 Subject: Cleanup code, search with preceeding % --- .../keychain/ui/KeyListPublicFragment.java | 13 ++++---- .../keychain/ui/SelectPublicKeyFragment.java | 35 ++++++---------------- 2 files changed, 14 insertions(+), 34 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index f2cb8a265..3418fff85 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -180,7 +180,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer case R.id.menu_key_list_public_multi_select_all: { //Select all int localCount = mStickyList.getCount(); - for(int k = 0; k < localCount; k++) { + for (int k = 0; k < localCount; k++) { mStickyList.setItemChecked(k, true); } break; @@ -243,9 +243,9 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer Uri baseUri = KeyRings.buildPublicKeyRingsUri(); String where = null; String whereArgs[] = null; - if(mCurQuery != null){ + if (mCurQuery != null) { where = KeychainContract.UserIds.USER_ID + " LIKE ?"; - whereArgs = new String[]{mCurQuery+"%"}; + whereArgs = new String[]{"%" + mCurQuery + "%"}; } // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. @@ -291,7 +291,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(id))); startActivity(viewIntent); } - + @TargetApi(11) public void encrypt(ActionMode mode, long[] keyRingRowIds) { // get master key ids from row ids @@ -352,7 +352,6 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { - // Get the searchview MenuItem searchItem = menu.findItem(R.id.menu_key_list_public_search); mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); @@ -361,7 +360,6 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer mSearchView.setOnQueryTextListener(this); super.onCreateOptionsMenu(menu, inflater); - } @Override @@ -374,8 +372,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer // Called when the action bar search text has changed. Update // the search filter, and restart the loader to do a new query // with this filter. - String newQuery = !TextUtils.isEmpty(s) ? s : null; - mCurQuery = newQuery; + mCurQuery = !TextUtils.isEmpty(s) ? s : null; getLoaderManager().restartLoader(0, null, this); return true; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java index a43c84cf4..73335c2f9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java @@ -72,7 +72,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - mSearchView = (EditText)getActivity().findViewById(R.id.select_public_key_search); + mSearchView = (EditText) getActivity().findViewById(R.id.select_public_key_search); mSearchView.addTextChangedListener(this); mSelectedMasterKeyIds = getArguments().getLongArray(ARG_PRESELECTED_KEY_IDS); } @@ -106,7 +106,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T /** * Selects items based on master key ids in list view - * + * * @param masterKeyIds */ private void preselectMasterKeyIds(long[] masterKeyIds) { @@ -125,7 +125,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T /** * Returns all selected master key ids - * + * * @return */ public long[] getSelectedMasterKeyIds() { @@ -149,7 +149,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T /** * Returns all selected user ids - * + * * @return */ public String[] getSelectedUserIds() { @@ -173,7 +173,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T // These are the rows that we will retrieve. long now = new Date().getTime() / 1000; - String[] projection = new String[] { + String[] projection = new String[]{ KeyRings._ID, KeyRings.MASTER_KEY_ID, UserIds.USER_ID, @@ -190,7 +190,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T + Keys.CAN_ENCRYPT + " = '1' AND valid_keys." + Keys.CREATION + " <= '" + now + "' AND " + "(valid_keys." + Keys.EXPIRY + " IS NULL OR valid_keys." + Keys.EXPIRY + " >= '" + now + "')) AS " - + SelectKeyCursorAdapter.PROJECTION_ROW_VALID, }; + + SelectKeyCursorAdapter.PROJECTION_ROW_VALID,}; String inMasterKeyList = null; if (mSelectedMasterKeyIds != null && mSelectedMasterKeyIds.length > 0) { @@ -204,22 +204,6 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T inMasterKeyList += ")"; } - // if (searchString != null && searchString.trim().length() > 0) { - // String[] chunks = searchString.trim().split(" +"); - // qb.appendWhere("(EXISTS (SELECT tmp." + UserIds._ID + " FROM " + UserIds.TABLE_NAME - // + " AS tmp WHERE " + "tmp." + UserIds.KEY_ID + " = " + Keys.TABLE_NAME + "." - // + Keys._ID); - // for (int i = 0; i < chunks.length; ++i) { - // qb.appendWhere(" AND tmp." + UserIds.USER_ID + " LIKE "); - // qb.appendWhereEscapeString("%" + chunks[i] + "%"); - // } - // qb.appendWhere("))"); - // - // if (inIdList != null) { - // qb.appendWhere(" OR (" + inIdList + ")"); - // } - // } - String orderBy = UserIds.USER_ID + " ASC"; if (inMasterKeyList != null) { // sort by selected master keys @@ -227,9 +211,9 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T } String where = null; String whereArgs[] = null; - if(mCurQuery != null){ + if (mCurQuery != null) { where = UserIds.USER_ID + " LIKE ?"; - whereArgs = new String[]{mCurQuery+"%"}; + whereArgs = new String[]{"%" + mCurQuery + "%"}; } // Now create and return a CursorLoader that will take care of @@ -274,8 +258,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T @Override public void afterTextChanged(Editable editable) { - String newQuery = !TextUtils.isEmpty(editable.toString()) ? editable.toString() : null; - mCurQuery = newQuery; + mCurQuery = !TextUtils.isEmpty(editable.toString()) ? editable.toString() : null; getLoaderManager().restartLoader(0, null, this); } } -- cgit v1.2.3 From 357257139113940a7de5a91523b8127da1e59cb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 7 Mar 2014 20:58:33 +0100 Subject: Reworking main KeyListPublicFragment to get progress indicator --- .../keychain/ui/KeyListPublicFragment.java | 85 ++++++++++++++++++---- .../keychain/ui/KeyListSecretFragment.java | 11 +-- 2 files changed, 72 insertions(+), 24 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 3418fff85..3ee0202ef 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -57,6 +57,7 @@ import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; +import android.view.animation.AnimationUtils; import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.AdapterView; import android.widget.ListView; @@ -73,6 +74,12 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer private KeyListPublicAdapter mAdapter; private StickyListHeadersListView mStickyList; + + // rebuild functionality of ListFragment, http://stackoverflow.com/a/12504097 + boolean mListShown; + View mProgressContainer; + View mListContainer; + private String mCurQuery; private SearchView mSearchView; // empty list layout @@ -85,9 +92,14 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.key_list_public_fragment, container, false); - setHasOptionsMenu(true); - mButtonEmptyCreate = (BootstrapButton) view.findViewById(R.id.key_list_empty_button_create); + View root = inflater.inflate(R.layout.key_list_public_fragment, container, false); + + mStickyList = (StickyListHeadersListView) root.findViewById(R.id.key_list_public_list); + mStickyList.setOnItemClickListener(this); + + + // empty view + mButtonEmptyCreate = (BootstrapButton) root.findViewById(R.id.key_list_empty_button_create); mButtonEmptyCreate.setOnClickListener(new OnClickListener() { @Override @@ -99,8 +111,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer startActivityForResult(intent, 0); } }); - - mButtonEmptyImport = (BootstrapButton) view.findViewById(R.id.key_list_empty_button_import); + mButtonEmptyImport = (BootstrapButton) root.findViewById(R.id.key_list_empty_button_import); mButtonEmptyImport.setOnClickListener(new OnClickListener() { @Override @@ -111,7 +122,12 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer } }); - return view; + // rebuild functionality of ListFragment, http://stackoverflow.com/a/12504097 + mListContainer = root.findViewById(R.id.key_list_public_list_container); + mProgressContainer = root.findViewById(R.id.key_list_public_progress_container); + mListShown = true; + + return root; } /** @@ -122,9 +138,6 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - mStickyList = (StickyListHeadersListView) getActivity().findViewById(R.id.list); - - mStickyList.setOnItemClickListener(this); mStickyList.setAreHeadersSticky(true); mStickyList.setDrawingListUnderStickyHeader(false); mStickyList.setFastScrollEnabled(true); @@ -134,7 +147,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer } // this view is made visible if no data is available - mStickyList.setEmptyView(getActivity().findViewById(R.id.empty)); + mStickyList.setEmptyView(getActivity().findViewById(R.id.key_list_public_empty)); /* * ActionBarSherlock does not support MultiChoiceModeListener. Thus multi-selection is only @@ -211,9 +224,12 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer }); } + // We have a menu item to show in action bar. + setHasOptionsMenu(true); + // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading // Start out with a progress indicator. - // setListShown(false); + setListShown(false); // Create an empty adapter we will use to display the loaded data. mAdapter = new KeyListPublicAdapter(getActivity(), null, Id.type.public_key, USER_ID_INDEX); @@ -262,11 +278,11 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading // The list should now be shown. - // if (isResumed()) { - // setListShown(true); - // } else { - // setListShownNoAnimation(true); - // } + if (isResumed()) { + setListShown(true); + } else { + setListShownNoAnimation(true); + } } @Override @@ -376,4 +392,41 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer getLoaderManager().restartLoader(0, null, this); return true; } + + // rebuild functionality of ListFragment, http://stackoverflow.com/a/12504097 + public void setListShown(boolean shown, boolean animate) { + if (mListShown == shown) { + return; + } + mListShown = shown; + if (shown) { + if (animate) { + mProgressContainer.startAnimation(AnimationUtils.loadAnimation( + getActivity(), android.R.anim.fade_out)); + mListContainer.startAnimation(AnimationUtils.loadAnimation( + getActivity(), android.R.anim.fade_in)); + } + mProgressContainer.setVisibility(View.GONE); + mListContainer.setVisibility(View.VISIBLE); + } else { + if (animate) { + mProgressContainer.startAnimation(AnimationUtils.loadAnimation( + getActivity(), android.R.anim.fade_in)); + mListContainer.startAnimation(AnimationUtils.loadAnimation( + getActivity(), android.R.anim.fade_out)); + } + mProgressContainer.setVisibility(View.VISIBLE); + mListContainer.setVisibility(View.INVISIBLE); + } + } + + // rebuild functionality of ListFragment, http://stackoverflow.com/a/12504097 + public void setListShown(boolean shown) { + setListShown(shown, true); + } + + // rebuild functionality of ListFragment, http://stackoverflow.com/a/12504097 + public void setListShownNoAnimation(boolean shown) { + setListShown(shown, false); + } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java index eaac6d8b1..9a5477762 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java @@ -17,7 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import java.util.ArrayList; import java.util.Set; import org.sufficientlysecure.keychain.Id; @@ -50,12 +49,10 @@ import android.widget.AdapterView; import android.widget.ListView; import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.AdapterView.OnItemClickListener; -import android.widget.Toast; public class KeyListSecretFragment extends ListFragment implements LoaderManager.LoaderCallbacks, OnItemClickListener { - private KeyListSecretActivity mKeyListSecretActivity; private KeyListSecretAdapter mAdapter; /** @@ -66,8 +63,6 @@ public class KeyListSecretFragment extends ListFragment implements public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - mKeyListSecretActivity = (KeyListSecretActivity) getActivity(); - getListView().setOnItemClickListener(this); // Give some text to display if there is no data. In a real @@ -114,7 +109,7 @@ public class KeyListSecretFragment extends ListFragment implements case R.id.menu_key_list_public_multi_select_all: { //Select all int localCount = getListView().getCount(); - for(int k = 0; k < localCount; k++) { + for (int k = 0; k < localCount; k++) { getListView().setItemChecked(k, true); } break; @@ -153,7 +148,7 @@ public class KeyListSecretFragment extends ListFragment implements setListShown(false); // Create an empty adapter we will use to display the loaded data. - mAdapter = new KeyListSecretAdapter(mKeyListSecretActivity, null, 0); + mAdapter = new KeyListSecretAdapter(getActivity(), null, 0); setListAdapter(mAdapter); // Prepare the loader. Either re-connect with an existing one, @@ -203,7 +198,7 @@ public class KeyListSecretFragment extends ListFragment implements */ @Override public void onItemClick(AdapterView adapterView, View view, int position, long id) { - Intent editIntent = new Intent(mKeyListSecretActivity, EditKeyActivity.class); + Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsUri(Long.toString(id))); editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); startActivityForResult(editIntent, 0); -- cgit v1.2.3 From a1be0d302b44e76fcfdb04b2dea20cc4ea6e0e35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 7 Mar 2014 21:32:24 +0100 Subject: move search view from activity to fragment by setting it as a list header, better reusability! Required for service activites --- .../keychain/ui/KeyListPublicFragment.java | 4 +-- .../keychain/ui/SelectPublicKeyFragment.java | 33 +++++++++++----------- 2 files changed, 19 insertions(+), 18 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 3ee0202ef..f14fadd77 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -227,7 +227,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer // We have a menu item to show in action bar. setHasOptionsMenu(true); - // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading + // NOTE: Not supported by StickyListHeader, but reimplemented here // Start out with a progress indicator. setListShown(false); @@ -276,7 +276,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer mStickyList.setAdapter(mAdapter); - // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading + // NOTE: Not supported by StickyListHeader, but reimplemented here // The list should now be shown. if (isResumed()) { setListShown(true); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java index 73335c2f9..5e729027d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java @@ -30,7 +30,6 @@ import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; import org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter; -import android.app.Activity; import android.database.Cursor; import android.database.DatabaseUtils; import android.net.Uri; @@ -41,6 +40,7 @@ import android.support.v4.content.Loader; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; +import android.view.View; import android.widget.EditText; import android.widget.ListView; @@ -48,9 +48,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T LoaderManager.LoaderCallbacks { public static final String ARG_PRESELECTED_KEY_IDS = "preselected_key_ids"; - private Activity mActivity; private SelectKeyCursorAdapter mAdapter; - private ListView mListView; private EditText mSearchView; private long mSelectedMasterKeyIds[]; private String mCurQuery; @@ -72,8 +70,6 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - mSearchView = (EditText) getActivity().findViewById(R.id.select_public_key_search); - mSearchView.addTextChangedListener(this); mSelectedMasterKeyIds = getArguments().getLongArray(ARG_PRESELECTED_KEY_IDS); } @@ -84,15 +80,20 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - mActivity = getActivity(); - mListView = getListView(); - - mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); + getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // Give some text to display if there is no data. In a real // application this would come from a resource. setEmptyText(getString(R.string.list_empty)); - mAdapter = new SelectKeyCursorAdapter(mActivity, null, 0, mListView, Id.type.public_key); + // add header with search field + View headerView = getLayoutInflater(savedInstanceState) + .inflate(R.layout.select_public_key_fragment_header, null); + getListView().addHeaderView(headerView); + + mSearchView = (EditText) getActivity().findViewById(R.id.select_public_key_search); + mSearchView.addTextChangedListener(this); + + mAdapter = new SelectKeyCursorAdapter(getActivity(), null, 0, getListView(), Id.type.public_key); setListAdapter(mAdapter); @@ -111,11 +112,11 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T */ private void preselectMasterKeyIds(long[] masterKeyIds) { if (masterKeyIds != null) { - for (int i = 0; i < mListView.getCount(); ++i) { + for (int i = 0; i < getListView().getCount(); ++i) { long keyId = mAdapter.getMasterKeyId(i); for (int j = 0; j < masterKeyIds.length; ++j) { if (keyId == masterKeyIds[j]) { - mListView.setItemChecked(i, true); + getListView().setItemChecked(i, true); break; } } @@ -132,8 +133,8 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T // mListView.getCheckedItemIds() would give the row ids of the KeyRings not the master key // ids! Vector vector = new Vector(); - for (int i = 0; i < mListView.getCount(); ++i) { - if (mListView.isItemChecked(i)) { + for (int i = 0; i < getListView().getCount(); ++i) { + if (getListView().isItemChecked(i)) { vector.add(mAdapter.getMasterKeyId(i)); } } @@ -154,8 +155,8 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T */ public String[] getSelectedUserIds() { Vector userIds = new Vector(); - for (int i = 0; i < mListView.getCount(); ++i) { - if (mListView.isItemChecked(i)) { + for (int i = 0; i < getListView().getCount(); ++i) { + if (getListView().isItemChecked(i)) { userIds.add((String) mAdapter.getUserId(i)); } } -- cgit v1.2.3 From dd80ddd6f95d7f659929a49d3bff62492692c4fa Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Sat, 8 Mar 2014 02:04:50 +0530 Subject: Fix for #347 --- .../java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java | 3 +++ 1 file changed, 3 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 3418fff85..edd7df7ef 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -354,6 +354,9 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { // Get the searchview MenuItem searchItem = menu.findItem(R.id.menu_key_list_public_search); + MenuItem addContactItem = menu.findItem(R.id.menu_key_list_public_import); + + addContactItem.setVisible(false);//Hide Add Contacts Icon mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); // Execute this when searching -- cgit v1.2.3 From ca851ba21f6a5738467d04cada74d05950bf69b7 Mon Sep 17 00:00:00 2001 From: uberspot Date: Fri, 7 Mar 2014 21:48:26 +0200 Subject: remove unused imports and unthrown exceptions --- .../java/org/sufficientlysecure/keychain/helper/OtherHelper.java | 2 -- .../java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java | 3 +-- .../java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java | 6 ------ .../org/sufficientlysecure/keychain/provider/ProviderHelper.java | 2 -- .../keychain/service/KeychainIntentServiceHandler.java | 1 - .../main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java | 5 ----- .../org/sufficientlysecure/keychain/ui/PreferencesActivity.java | 2 -- .../keychain/ui/adapter/ImportKeysListLoader.java | 3 +-- .../keychain/ui/adapter/KeyListPublicAdapter.java | 1 - .../sufficientlysecure/keychain/ui/dialog/FileDialogFragment.java | 1 - 10 files changed, 2 insertions(+), 24 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java index 639ab17b8..34d90a17f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java @@ -17,8 +17,6 @@ package org.sufficientlysecure.keychain.helper; -import java.util.Calendar; -import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Set; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java index ccd6ff8df..252be1036 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java @@ -743,10 +743,9 @@ public class PgpDecryptVerify { * @param sig * @param line * @throws SignatureException - * @throws IOException */ private static void processLine(PGPSignature sig, byte[] line) - throws SignatureException, IOException { + throws SignatureException { int length = getLengthWithoutWhiteSpace(line); if (length > 0) { sig.update(line, 0, length); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 2495a212c..9d9cd4d11 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -17,11 +17,9 @@ package org.sufficientlysecure.keychain.pgp; -import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; @@ -29,12 +27,10 @@ import java.util.List; import org.spongycastle.bcpg.ArmoredOutputStream; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPKeyRing; -import org.spongycastle.openpgp.PGPObjectFactory; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPPublicKeyRing; import org.spongycastle.openpgp.PGPSecretKey; import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPUtil; import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; @@ -44,11 +40,9 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; import org.sufficientlysecure.keychain.util.HkpKeyServer; -import org.sufficientlysecure.keychain.util.InputData; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.KeyServer.AddKeyException; import org.sufficientlysecure.keychain.util.Log; -import org.sufficientlysecure.keychain.util.PositionAwareInputStream; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; import android.content.Context; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 8b642967f..68d9f801b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -23,8 +23,6 @@ import java.util.ArrayList; import java.util.Date; import org.spongycastle.bcpg.ArmoredOutputStream; -import org.spongycastle.bcpg.UserAttributePacket; -import org.spongycastle.bcpg.UserAttributeSubpacket; import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPPublicKeyRing; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java index 6eba9cc83..65c756f9a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java @@ -21,7 +21,6 @@ import org.sufficientlysecure.keychain.ui.dialog.ProgressDialogFragment; import org.sufficientlysecure.keychain.R; import android.app.Activity; -import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.Bundle; import android.os.Handler; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java index 9ccd7e088..cb923b052 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java @@ -22,16 +22,11 @@ import java.util.ArrayList; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.ui.adapter.TabsAdapter; -import android.content.Context; import android.content.Intent; import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentStatePagerAdapter; -import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; -import android.widget.TextView; public class HelpActivity extends ActionBarActivity { public static final String EXTRA_SELECTED_TAB = "selectedTab"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java index af20b499b..2e8f25890 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java @@ -25,7 +25,6 @@ import org.sufficientlysecure.keychain.helper.Preferences; import org.sufficientlysecure.keychain.ui.widget.IntegerListPreference; import android.annotation.SuppressLint; -import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; @@ -57,7 +56,6 @@ public class PreferencesActivity extends PreferenceActivity { // actionBar.setDisplayHomeAsUpEnabled(false); // actionBar.setHomeButtonEnabled(false); - //addPreferencesFromResource(R.xml.preferences); String action = getIntent().getAction(); if (action != null && action.equals(ACTION_PREFS_GEN)) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java index 76649b27b..357f5a3f1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java @@ -20,7 +20,6 @@ package org.sufficientlysecure.keychain.ui.adapter; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.ArrayList; -import java.util.List; import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPObjectFactory; @@ -88,7 +87,7 @@ public class ImportKeysListLoader extends AsyncTaskLoader Date: Fri, 7 Mar 2014 22:35:09 +0200 Subject: removed useless semicolons, fixed some parameters in documenation, simplified some conditionals --- .../keychain/compatibility/ClipboardReflection.java | 1 - .../java/org/sufficientlysecure/keychain/helper/ExportHelper.java | 2 +- .../org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java | 6 +++--- .../sufficientlysecure/keychain/provider/KeychainProvider.java | 5 +++-- .../org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java | 4 ++-- .../java/org/sufficientlysecure/keychain/ui/DecryptActivity.java | 2 -- .../java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java | 4 ++-- .../java/org/sufficientlysecure/keychain/ui/EncryptActivity.java | 2 -- .../java/org/sufficientlysecure/keychain/ui/HelpActivity.java | 8 ++++---- .../org/sufficientlysecure/keychain/ui/UploadKeyActivity.java | 2 +- .../java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java | 4 ++-- .../keychain/ui/adapter/ImportKeysListEntry.java | 4 +--- .../keychain/ui/dialog/DeleteFileDialogFragment.java | 2 +- .../keychain/ui/dialog/PassphraseDialogFragment.java | 4 ++-- .../org/sufficientlysecure/keychain/ui/widget/SectionView.java | 2 +- 15 files changed, 23 insertions(+), 29 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/ClipboardReflection.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/ClipboardReflection.java index 032af4c71..3164de7d1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/ClipboardReflection.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/ClipboardReflection.java @@ -59,7 +59,6 @@ public class ClipboardReflection { * Wrapper around ClipboardManager based on Android version using Reflection API * * @param context - * @param text */ public static CharSequence getClipboardText(Context context) { Object clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 21676a2a7..8f2c6c83d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -160,7 +160,7 @@ public class ExportHelper { Toast.makeText(activity, toastMessage, Toast.LENGTH_SHORT).show(); } - }; + } }; // Create a new Messenger for the communication back diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java index 20d446824..a30e0718f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java @@ -76,7 +76,7 @@ public class PgpConversionHelper { * * Singles keys are encoded as keyRings with one single key in it by Bouncy Castle * - * @param keysBytes + * @param keyBytes * @return */ public static PGPSecretKey BytesToPGPSecretKey(byte[] keyBytes) { @@ -125,7 +125,7 @@ public class PgpConversionHelper { /** * Convert from PGPSecretKey to byte[] * - * @param keysBytes + * @param key * @return */ public static byte[] PGPSecretKeyToBytes(PGPSecretKey key) { @@ -141,7 +141,7 @@ public class PgpConversionHelper { /** * Convert from PGPSecretKeyRing to byte[] * - * @param keysBytes + * @param keyRing * @return */ public static byte[] PGPSecretKeyRingToBytes(PGPSecretKeyRing keyRing) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 781f36758..3b60ffc87 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -304,7 +304,7 @@ public class KeychainProvider extends ContentProvider { /** * Returns type of the query (secret/public) * - * @param uri + * @param match * @return */ private int getKeyType(int match) { @@ -862,7 +862,8 @@ public class KeychainProvider extends ContentProvider { * Build default selection statement for KeyRings. If no extra selection is specified only build * where clause with rowId * - * @param uri + * @param defaultSelection + * @param keyType * @param selection * @return */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index aab6b81d9..9a56d768e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -249,7 +249,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements finish(); } } - }; + } }; // Create a new Messenger for the communication back @@ -295,7 +295,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements setResult(RESULT_OK); finish(); } - }; + } }; // Create a new Messenger for the communication back diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index 42288ca37..c111ed33b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -744,8 +744,6 @@ public class DecryptActivity extends DrawerActivity { } } } - - ; }; // Create a new Messenger for the communication back diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 647ab2728..898b0e67a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -224,7 +224,7 @@ public class EditKeyActivity extends ActionBarActivity { buildLayout(); } - }; + } }; // Create a new Messenger for the communication back @@ -561,7 +561,7 @@ public class EditKeyActivity extends ActionBarActivity { setResult(RESULT_OK, data); finish(); } - }; + } }; // Create a new Messenger for the communication back diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index 88a29cee9..b486fc151 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -669,8 +669,6 @@ public class EncryptActivity extends DrawerActivity { } } } - - ; }; // Create a new Messenger for the communication back diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java index cb923b052..ac8250bef 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java @@ -59,19 +59,19 @@ public class HelpActivity extends ActionBarActivity { Bundle startBundle = new Bundle(); startBundle.putInt(HelpHtmlFragment.ARG_HTML_FILE, R.raw.help_start); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_start)), - HelpHtmlFragment.class, startBundle, (selectedTab == 0 ? true : false)); + HelpHtmlFragment.class, startBundle, (selectedTab == 0) ); Bundle nfcBundle = new Bundle(); nfcBundle.putInt(HelpHtmlFragment.ARG_HTML_FILE, R.raw.help_nfc_beam); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_nfc_beam)), - HelpHtmlFragment.class, nfcBundle, (selectedTab == 1 ? true : false)); + HelpHtmlFragment.class, nfcBundle, (selectedTab == 1) ); Bundle changelogBundle = new Bundle(); changelogBundle.putInt(HelpHtmlFragment.ARG_HTML_FILE, R.raw.help_changelog); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_changelog)), - HelpHtmlFragment.class, changelogBundle, (selectedTab == 2 ? true : false)); + HelpHtmlFragment.class, changelogBundle, (selectedTab == 2) ); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_about)), - HelpAboutFragment.class, null, (selectedTab == 3 ? true : false)); + HelpAboutFragment.class, null, (selectedTab == 3) ); } } \ No newline at end of file diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java index 550d3047d..574d837d2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java @@ -113,7 +113,7 @@ public class UploadKeyActivity extends ActionBarActivity { Toast.LENGTH_SHORT).show(); finish(); } - }; + } }; // Create a new Messenger for the communication back diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 0a452bc8a..2db5fc27f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -88,12 +88,12 @@ public class ViewKeyActivity extends ActionBarActivity { Bundle mainBundle = new Bundle(); mainBundle.putParcelable(ViewKeyMainFragment.ARG_DATA_URI, mDataUri); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.key_view_tab_main)), - ViewKeyMainFragment.class, mainBundle, (selectedTab == 0 ? true : false)); + ViewKeyMainFragment.class, mainBundle, (selectedTab == 0)); Bundle certBundle = new Bundle(); certBundle.putParcelable(ViewKeyCertsFragment.ARG_DATA_URI, mDataUri); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.key_view_tab_certs)), - ViewKeyCertsFragment.class, certBundle, (selectedTab == 1 ? true : false)); + ViewKeyCertsFragment.class, certBundle, (selectedTab == 1)); } @Override diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index 4a7a9c93a..01b6deeaa 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -152,9 +152,7 @@ public class ImportKeysListEntry implements Serializable, Parcelable { // selected is default this.selected = true; - if (pgpKeyRing instanceof PGPSecretKeyRing) { - secretKey = true; - } else { + if ( !(pgpKeyRing instanceof PGPSecretKeyRing) ) { secretKey = false; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java index cd8bc79a9..c4e305984 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java @@ -95,7 +95,7 @@ public class DeleteFileDialogFragment extends DialogFragment { Toast.makeText(activity, R.string.file_delete_successful, Toast.LENGTH_SHORT).show(); } - }; + } }; // Create a new Messenger for the communication back diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java index c00232fd1..afa05cc91 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java @@ -158,7 +158,7 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor PGPSecretKey clickSecretKey = secretKey; if (clickSecretKey != null) { - while (keyOK == true) { + while (keyOK) { if (clickSecretKey != null) { // check again for loop try { PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder() @@ -207,7 +207,7 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor // cache the new passphrase Log.d(Constants.TAG, "Everything okay! Caching entered passphrase"); PassphraseCacheService.addCachedPassphrase(activity, keyId, passphrase); - if (keyOK == false && clickSecretKey.getKeyID() != keyId) { + if ( !keyOK && clickSecretKey.getKeyID() != keyId) { PassphraseCacheService.addCachedPassphrase(activity, clickSecretKey.getKeyID(), passphrase); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java index 47d6cd311..99622106f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java @@ -261,7 +261,7 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor .getByteArray(KeychainIntentService.RESULT_NEW_KEY)); addGeneratedKeyToView(newKey); } - }; + } }; // Create a new Messenger for the communication back -- cgit v1.2.3 From def9e5a492b04e42b8ebeb9c4189ccb655c8b1a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 7 Mar 2014 22:37:38 +0100 Subject: Move search view into onCreateView, fixes #365 --- .../keychain/ui/SelectPublicKeyFragment.java | 97 ++++++++++++++++++++-- 1 file changed, 91 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java index 5e729027d..6e338979a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java @@ -30,6 +30,7 @@ import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; import org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter; +import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.net.Uri; @@ -40,9 +41,16 @@ import android.support.v4.content.Loader; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; +import android.view.Gravity; +import android.view.LayoutInflater; import android.view.View; +import android.view.ViewGroup; import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.LinearLayout; import android.widget.ListView; +import android.widget.ProgressBar; +import android.widget.TextView; public class SelectPublicKeyFragment extends ListFragmentWorkaround implements TextWatcher, LoaderManager.LoaderCallbacks { @@ -53,6 +61,13 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T private long mSelectedMasterKeyIds[]; private String mCurQuery; + // copied from ListFragment + static final int INTERNAL_EMPTY_ID = 0x00ff0001; + static final int INTERNAL_PROGRESS_CONTAINER_ID = 0x00ff0002; + static final int INTERNAL_LIST_CONTAINER_ID = 0x00ff0003; + // added for search view + static final int SEARCH_ID = 0x00ff0004; + /** * Creates new instance of this fragment */ @@ -73,6 +88,81 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T mSelectedMasterKeyIds = getArguments().getLongArray(ARG_PRESELECTED_KEY_IDS); } + /** + * Copied from ListFragment and added EditText for search on top of list. + * We do not use a custom layout here, because this breaks the progress bar functionality + * of ListFragment. + * + * @param inflater + * @param container + * @param savedInstanceState + * @return + */ + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final Context context = getActivity(); + + FrameLayout root = new FrameLayout(context); + + // ------------------------------------------------------------------ + + LinearLayout pframe = new LinearLayout(context); + pframe.setId(INTERNAL_PROGRESS_CONTAINER_ID); + pframe.setOrientation(LinearLayout.VERTICAL); + pframe.setVisibility(View.GONE); + pframe.setGravity(Gravity.CENTER); + + ProgressBar progress = new ProgressBar(context, null, + android.R.attr.progressBarStyleLarge); + pframe.addView(progress, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + + root.addView(pframe, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); + + // ------------------------------------------------------------------ + + FrameLayout lframe = new FrameLayout(context); + lframe.setId(INTERNAL_LIST_CONTAINER_ID); + + TextView tv = new TextView(getActivity()); + tv.setId(INTERNAL_EMPTY_ID); + tv.setGravity(Gravity.CENTER); + lframe.addView(tv, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); + + // Added for search view: linearLayout, mSearchView + LinearLayout linearLayout = new LinearLayout(context); + linearLayout.setOrientation(LinearLayout.VERTICAL); + + mSearchView = new EditText(context); + mSearchView.setId(SEARCH_ID); + mSearchView.setHint(R.string.menu_search); + mSearchView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ic_action_search), null, null, null); + + linearLayout.addView(mSearchView, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + + ListView lv = new ListView(getActivity()); + lv.setId(android.R.id.list); + lv.setDrawSelectorOnTop(false); + linearLayout.addView(lv, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); + + lframe.addView(linearLayout, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); + + root.addView(lframe, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); + + // ------------------------------------------------------------------ + + root.setLayoutParams(new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); + + return root; + } + /** * Define Adapter and Loader on create of Activity */ @@ -81,16 +171,11 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); + // Give some text to display if there is no data. In a real // application this would come from a resource. setEmptyText(getString(R.string.list_empty)); - // add header with search field - View headerView = getLayoutInflater(savedInstanceState) - .inflate(R.layout.select_public_key_fragment_header, null); - getListView().addHeaderView(headerView); - - mSearchView = (EditText) getActivity().findViewById(R.id.select_public_key_search); mSearchView.addTextChangedListener(this); mAdapter = new SelectKeyCursorAdapter(getActivity(), null, 0, getListView(), Id.type.public_key); -- cgit v1.2.3 From 2737aedca7e72f1f18d7b0f5418edbf52ab7fcaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 7 Mar 2014 22:48:20 +0100 Subject: Revert "Fix for #347" This reverts commit dd80ddd6f95d7f659929a49d3bff62492692c4fa. --- .../java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java | 3 --- 1 file changed, 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 1938883a1..f14fadd77 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -370,9 +370,6 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { // Get the searchview MenuItem searchItem = menu.findItem(R.id.menu_key_list_public_search); - MenuItem addContactItem = menu.findItem(R.id.menu_key_list_public_import); - - addContactItem.setVisible(false);//Hide Add Contacts Icon mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); // Execute this when searching -- cgit v1.2.3 From 3fbda4245cf34d2f8e150e6a26ad4048cdb6b204 Mon Sep 17 00:00:00 2001 From: grait Date: Sat, 8 Mar 2014 03:24:16 +0530 Subject: progress is shown when creating the default key based on number of keys created so far --- .../sufficientlysecure/keychain/service/KeychainIntentService.java | 7 +++++++ .../java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 313655766..be9d126b3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -596,13 +596,20 @@ public class KeychainIntentService extends IntentService implements ProgressDial String passphrase = data.getString(GENERATE_KEY_SYMMETRIC_PASSPHRASE); /* Operation */ + int keysTotal = 2; + int keysCreated =0; + this.setProgress(keysCreated, keysTotal); PgpKeyOperation keyOperations = new PgpKeyOperation(this, this); PGPSecretKey masterKey = keyOperations.createKey(Id.choice.algorithm.rsa, 4096, passphrase, true); + keysCreated++; + setProgress(keysCreated, keysTotal); PGPSecretKey subKey = keyOperations.createKey(Id.choice.algorithm.rsa, 4096, passphrase, false); + keysCreated++; + setProgress(keysCreated, keysTotal ); // TODO: default to one master for cert, one sub for encrypt and one sub // for sign diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 898b0e67a..2507a77b1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -187,7 +187,7 @@ public class EditKeyActivity extends ActionBarActivity { // Message is received after generating is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler( - this, R.string.progress_generating, ProgressDialog.STYLE_SPINNER, true, + this, R.string.progress_generating, ProgressDialog.STYLE_HORIZONTAL, true, new DialogInterface.OnCancelListener() { @Override -- cgit v1.2.3 From b29c430959d4da2f6c99693d2fd138124d4736f8 Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Sat, 8 Mar 2014 15:28:46 +0530 Subject: Fix for #347 --- .../keychain/ui/KeyListPublicFragment.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 3418fff85..e1c43919f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -353,12 +353,23 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { // Get the searchview - MenuItem searchItem = menu.findItem(R.id.menu_key_list_public_search); + final MenuItem searchItem = menu.findItem(R.id.menu_key_list_public_search); + mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); // Execute this when searching mSearchView.setOnQueryTextListener(this); + //Collapse the SearchView if it does not have focus + mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + if (!hasFocus) { + MenuItemCompat.collapseActionView(searchItem); + } + } + }); + super.onCreateOptionsMenu(menu, inflater); } -- cgit v1.2.3 From 8c6cb8b0ab9e89f9d575af829e0dd1dd9e82e401 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 11:19:34 +0100 Subject: working unified list (no actions yet) --- .../keychain/provider/KeychainContract.java | 5 + .../keychain/provider/KeychainProvider.java | 75 ++++++ .../keychain/ui/DrawerActivity.java | 2 +- .../keychain/ui/KeyListActivity.java | 8 +- .../keychain/ui/KeyListFragment.java | 275 ++++++++++++++++++++- .../keychain/ui/adapter/KeyListAdapter.java | 232 ----------------- 6 files changed, 353 insertions(+), 244 deletions(-) delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index d8de30b37..706b30d05 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -78,6 +78,7 @@ public class KeychainContract { public static final String PATH_PUBLIC = "public"; public static final String PATH_SECRET = "secret"; + public static final String PATH_UNIFIED = "unified"; public static final String PATH_BY_MASTER_KEY_ID = "master_key_id"; public static final String PATH_BY_KEY_ID = "key_id"; @@ -100,6 +101,10 @@ public class KeychainContract { /** Use if a single item is returned */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.key_ring"; + public static Uri buildUnifiedKeyRingsUri() { + return CONTENT_URI.buildUpon().appendPath(PATH_UNIFIED).build(); + } + public static Uri buildPublicKeyRingsUri() { return CONTENT_URI.buildUpon().appendPath(PATH_PUBLIC).build(); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 781f36758..85e01ae53 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -81,6 +81,8 @@ public class KeychainProvider extends ContentProvider { private static final int API_APPS_BY_ROW_ID = 302; private static final int API_APPS_BY_PACKAGE_NAME = 303; + private static final int UNIFIED_KEY_RING = 401; + // private static final int DATA_STREAM = 401; protected UriMatcher mUriMatcher; @@ -226,6 +228,16 @@ public class KeychainProvider extends ContentProvider { matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_APPS_BY_PACKAGE_NAME); + /** + * unified key rings + *

+         *
+         * key_rings/unified
+         *
+         */
+        matcher.addURI(authority, KeychainContract.BASE_KEY_RINGS + "/"
+                + KeychainContract.PATH_UNIFIED, UNIFIED_KEY_RING);
+
         /**
          * data stream
          *
@@ -455,6 +467,69 @@ public class KeychainProvider extends ContentProvider {
 
         int match = mUriMatcher.match(uri);
 
+        // screw that switch
+        if(match == UNIFIED_KEY_RING) {
+
+            // join keyrings with keys and userIds
+            // Only get user id and key with rank 0 (main user id and main key)
+            qb.setTables(Tables.KEY_RINGS + " INNER JOIN " + Tables.KEYS + " ON " + "("
+                    + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "."
+                    + KeysColumns.KEY_RING_ROW_ID + " AND " + Tables.KEYS + "."
+                    + KeysColumns.RANK + " = '0') " + " INNER JOIN " + Tables.USER_IDS + " ON "
+                    + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.USER_IDS + "."
+                    + UserIdsColumns.KEY_RING_ROW_ID + " AND " + Tables.USER_IDS + "."
+                    + UserIdsColumns.RANK + " = '0')");
+
+            {
+                HashMap projectionMap = new HashMap();
+
+                projectionMap.put(KeyRingsColumns.TYPE, "MAX(" + Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + ")");
+
+                projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID);
+                projectionMap.put(KeyRingsColumns.KEY_RING_DATA, Tables.KEY_RINGS + "."
+                        + KeyRingsColumns.KEY_RING_DATA);
+                projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID);
+                // TODO: deprecated master key id
+                //projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEYS + "." + KeysColumns.KEY_ID);
+
+                projectionMap.put(KeysColumns.FINGERPRINT, Tables.KEYS + "." + KeysColumns.FINGERPRINT);
+                projectionMap.put(KeysColumns.IS_REVOKED, Tables.KEYS + "." + KeysColumns.IS_REVOKED);
+
+                projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." + UserIdsColumns.USER_ID);
+
+                qb.setProjectionMap(projectionMap);
+            }
+
+            if (TextUtils.isEmpty(sortOrder)) {
+                sortOrder = Tables.USER_IDS + "." + UserIdsColumns.USER_ID + " ASC";
+            }
+
+            // If no sort order is specified use the default
+            String orderBy;
+            if (TextUtils.isEmpty(sortOrder)) {
+                orderBy = Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " DESC";
+            } else {
+                orderBy = Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " DESC, " + sortOrder;
+            }
+
+            Cursor c = qb.query(db, projection, selection, selectionArgs,
+                    Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID,
+                    null, orderBy);
+
+            // Tell the cursor what uri to watch, so it knows when its source data changes
+            c.setNotificationUri(getContext().getContentResolver(), uri);
+
+            if (Constants.DEBUG) {
+                Log.d(Constants.TAG,
+                        "Query: "
+                                + qb.buildQuery(projection, selection, selectionArgs, Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID, null,
+                                orderBy, null));
+                Log.d(Constants.TAG, "Cursor: " + DatabaseUtils.dumpCursorToString(c));
+            }
+
+            return c;
+        }
+
         switch (match) {
             case PUBLIC_KEY_RING:
             case SECRET_KEY_RING:
diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java
index 08ca262c3..d7644ce4d 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java
@@ -50,7 +50,7 @@ public class DrawerActivity extends ActionBarActivity {
     private CharSequence mDrawerTitle;
     private CharSequence mTitle;
 
-    private static Class[] mItemsClass = new Class[] { KeyListPublicActivity.class,
+    private static Class[] mItemsClass = new Class[] { KeyListActivity.class,
             EncryptActivity.class, DecryptActivity.class, ImportKeysActivity.class,
             KeyListSecretActivity.class, RegisteredAppsListActivity.class };
     private Class mSelectedItem;
diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java
index dd7aa9a26..0bbe2edb1 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java
@@ -37,7 +37,7 @@ public class KeyListActivity extends DrawerActivity {
 
         mExportHelper = new ExportHelper(this);
 
-        setContentView(R.layout.key_list_public_activity);
+        setContentView(R.layout.key_list_activity);
 
         // now setup navigation drawer in DrawerActivity...
         setupDrawerNavigation(savedInstanceState);
@@ -46,19 +46,19 @@ public class KeyListActivity extends DrawerActivity {
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         super.onCreateOptionsMenu(menu);
-        getMenuInflater().inflate(R.menu.key_list_public, menu);
+        getMenuInflater().inflate(R.menu.key_list, menu);
         return true;
     }
 
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
-        case R.id.menu_key_list_public_import:
+        case R.id.menu_key_list_import:
             Intent intentImport = new Intent(this, ImportKeysActivity.class);
             startActivityForResult(intentImport, 0);
 
             return true;
-        case R.id.menu_key_list_public_export:
+        case R.id.menu_key_list_export:
             mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR
                     + "/pubexport.asc");
 
diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java
index 6f94ffd1a..a638796cd 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java
@@ -17,25 +17,32 @@
 
 package org.sufficientlysecure.keychain.ui;
 
+import java.util.HashMap;
 import java.util.ArrayList;
 import java.util.Set;
 
+import org.sufficientlysecure.keychain.Constants;
 import org.sufficientlysecure.keychain.Id;
 import org.sufficientlysecure.keychain.R;
+import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
 import org.sufficientlysecure.keychain.provider.KeychainContract;
 import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
+import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes;
 import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds;
 import org.sufficientlysecure.keychain.provider.ProviderHelper;
-import org.sufficientlysecure.keychain.ui.adapter.KeyListAdapter;
 import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment;
+import org.sufficientlysecure.keychain.util.Log;
 
 import se.emilsjolander.stickylistheaders.ApiLevelTooLowException;
 import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
+import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
 
 import android.annotation.SuppressLint;
 import android.annotation.TargetApi;
+import android.content.Context;
 import android.content.Intent;
 import android.database.Cursor;
+import android.graphics.Color;
 import android.net.Uri;
 import android.os.Build;
 import android.os.Bundle;
@@ -46,6 +53,7 @@ import android.support.v4.app.Fragment;
 import android.support.v4.app.LoaderManager;
 import android.support.v4.content.CursorLoader;
 import android.support.v4.content.Loader;
+import android.support.v4.widget.CursorAdapter;
 import android.view.ActionMode;
 import android.view.LayoutInflater;
 import android.view.Menu;
@@ -55,7 +63,9 @@ import android.view.View.OnClickListener;
 import android.view.ViewGroup;
 import android.widget.AbsListView.MultiChoiceModeListener;
 import android.widget.AdapterView;
+import android.widget.Button;
 import android.widget.ListView;
+import android.widget.TextView;
 import android.widget.Toast;
 
 import com.beardedhen.androidbootstrap.BootstrapButton;
@@ -207,7 +217,7 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick
         // setListShown(false);
 
         // Create an empty adapter we will use to display the loaded data.
-        mAdapter = new KeyListAdapter(getActivity(), null, Id.type.public_key, USER_ID_INDEX);
+        mAdapter = new KeyListAdapter(getActivity(), null, Id.type.public_key);
         mStickyList.setAdapter(mAdapter);
 
         // Prepare the loader. Either re-connect with an existing one,
@@ -218,20 +228,21 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick
     // These are the rows that we will retrieve.
     static final String[] PROJECTION = new String[]{
             KeychainContract.KeyRings._ID,
+            KeychainContract.KeyRings.TYPE,
             KeychainContract.KeyRings.MASTER_KEY_ID,
             KeychainContract.UserIds.USER_ID,
             KeychainContract.Keys.IS_REVOKED
     };
 
-    static final int USER_ID_INDEX = 2;
-
+    static final int INDEX_TYPE = 1;
+    static final int INDEX_UID = 3;
     static final String SORT_ORDER = UserIds.USER_ID + " ASC";
 
     @Override
     public Loader onCreateLoader(int id, Bundle args) {
         // This is called when a new Loader needs to be created. This
         // sample only has one Loader, so we don't care about the ID.
-        Uri baseUri = KeyRings.buildPublicKeyRingsUri();
+        Uri baseUri = KeyRings.buildUnifiedKeyRingsUri();
 
         // Now create and return a CursorLoader that will take care of
         // creating a Cursor for the data being displayed.
@@ -274,10 +285,14 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick
         } else {
             viewIntent = new Intent(getActivity(), ViewKeyActivityJB.class);
         }
-        viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(id)));
+        if(mAdapter.getKeyType(position) == KeyTypes.SECRET) {
+            viewIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(mAdapter.getMasterKeyId(position))));
+        } else {
+            viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsByMasterKeyIdUri(Long.toString(mAdapter.getMasterKeyId(position))));
+        }
         startActivity(viewIntent);
     }
-    
+
     @TargetApi(11)
     public void encrypt(ActionMode mode, long[] keyRingRowIds) {
         // get master key ids from row ids
@@ -335,4 +350,250 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick
         deleteKeyDialog.show(getActivity().getSupportFragmentManager(), "deleteKeyDialog");
     }
 
+    /**
+     * Implements StickyListHeadersAdapter from library
+     */
+    private class KeyListAdapter extends CursorAdapter implements StickyListHeadersAdapter {
+        private LayoutInflater mInflater;
+        private int mIndexUserId;
+        private int mIndexIsRevoked;
+        private int mMasterKeyId;
+
+        @SuppressLint("UseSparseArrays")
+        private HashMap mSelection = new HashMap();
+
+        public KeyListAdapter(Context context, Cursor c, int flags) {
+            super(context, c, flags);
+
+            mInflater = LayoutInflater.from(context);
+            initIndex(c);
+        }
+
+        @Override
+        public Cursor swapCursor(Cursor newCursor) {
+            initIndex(newCursor);
+
+            return super.swapCursor(newCursor);
+        }
+
+        /**
+         * Get column indexes for performance reasons just once in constructor and swapCursor. For a
+         * performance comparison see http://stackoverflow.com/a/17999582
+         *
+         * @param cursor
+         */
+        private void initIndex(Cursor cursor) {
+            if (cursor != null) {
+                mIndexUserId = cursor.getColumnIndexOrThrow(KeychainContract.UserIds.USER_ID);
+                mIndexIsRevoked = cursor.getColumnIndexOrThrow(KeychainContract.Keys.IS_REVOKED);
+                mMasterKeyId = cursor.getColumnIndexOrThrow(KeychainContract.KeyRings.MASTER_KEY_ID);
+            }
+        }
+
+        /**
+         * Bind cursor data to the item list view
+         * 

+ * NOTE: CursorAdapter already implements the ViewHolder pattern in its getView() method. Thus + * no ViewHolder is required here. + */ + @Override + public void bindView(View view, Context context, Cursor cursor) { + + { // set name and stuff, common to both key types + TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId); + TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest); + + String userId = cursor.getString(mIndexUserId); + String[] userIdSplit = PgpKeyHelper.splitUserId(userId); + if (userIdSplit[0] != null) { + mainUserId.setText(userIdSplit[0]); + } else { + mainUserId.setText(R.string.user_id_no_name); + } + if (userIdSplit[1] != null) { + mainUserIdRest.setText(userIdSplit[1]); + mainUserIdRest.setVisibility(View.VISIBLE); + } else { + mainUserIdRest.setVisibility(View.GONE); + } + } + + { // set edit button and revoked info, specific by key type + Button button = (Button) view.findViewById(R.id.edit); + TextView revoked = (TextView) view.findViewById(R.id.revoked); + + if(cursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { + // this is a secret key - show the edit button + revoked.setVisibility(View.GONE); + button.setVisibility(View.VISIBLE); + + final long id = cursor.getLong(mMasterKeyId); + button.setOnClickListener(new OnClickListener() { + public void onClick(View view) { + Log.d(Constants.TAG, "swag"); + Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); + // editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsUri(Long.toString(1))); + editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(id))); + editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); + startActivityForResult(editIntent, 0); + } + }); + } else { + // this is a public key - hide the edit button, show if it's revoked + button.setVisibility(View.GONE); + + boolean isRevoked = cursor.getInt(mIndexIsRevoked) > 0; + revoked.setVisibility(isRevoked ? View.VISIBLE : View.GONE); + } + } + + } + + public long getMasterKeyId(int id) { + + if (!mCursor.moveToPosition(id)) { + throw new IllegalStateException("couldn't move cursor to position " + id); + } + + return mCursor.getLong(mMasterKeyId); + + } + + public int getKeyType(int position) { + + if (!mCursor.moveToPosition(position)) { + throw new IllegalStateException("couldn't move cursor to position " + position); + } + + return mCursor.getInt(KeyListFragment.INDEX_TYPE); + + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return mInflater.inflate(R.layout.key_list_item, parent, false); + } + + /** + * Creates a new header view and binds the section headers to it. It uses the ViewHolder + * pattern. Most functionality is similar to getView() from Android's CursorAdapter. + *

+ * NOTE: The variables mDataValid and mCursor are available due to the super class + * CursorAdapter. + */ + @Override + public View getHeaderView(int position, View convertView, ViewGroup parent) { + HeaderViewHolder holder; + if (convertView == null) { + holder = new HeaderViewHolder(); + convertView = mInflater.inflate(R.layout.key_list_header, parent, false); + holder.text = (TextView) convertView.findViewById(R.id.stickylist_header_text); + convertView.setTag(holder); + } else { + holder = (HeaderViewHolder) convertView.getTag(); + } + + if (!mDataValid) { + // no data available at this point + Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); + return convertView; + } + + if (!mCursor.moveToPosition(position)) { + throw new IllegalStateException("couldn't move cursor to position " + position); + } + + if(mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { + holder.text.setText("My Keys"); + return convertView; + } + + // set header text as first char in user id + String userId = mCursor.getString(KeyListFragment.INDEX_UID); + String headerText = convertView.getResources().getString(R.string.user_id_no_name); + if (userId != null && userId.length() > 0) { + headerText = "" + mCursor.getString(KeyListFragment.INDEX_UID).subSequence(0, 1).charAt(0); + } + holder.text.setText(headerText); + return convertView; + } + + /** + * Header IDs should be static, position=1 should always return the same Id that is. + */ + @Override + public long getHeaderId(int position) { + if (!mDataValid) { + // no data available at this point + Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); + return -1; + } + + if (!mCursor.moveToPosition(position)) { + throw new IllegalStateException("couldn't move cursor to position " + position); + } + + // early breakout: all secret keys are assigned id 0 + if(mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) + return 1L; + + // otherwise, return the first character of the name as ID + String userId = mCursor.getString(KeyListFragment.INDEX_UID); + if (userId != null && userId.length() > 0) { + return userId.charAt(0); + } else { + return Long.MAX_VALUE; + } + } + + class HeaderViewHolder { + TextView text; + } + + /** + * -------------------------- MULTI-SELECTION METHODS -------------- + */ + public void setNewSelection(int position, boolean value) { + mSelection.put(position, value); + notifyDataSetChanged(); + } + + public boolean isPositionChecked(int position) { + Boolean result = mSelection.get(position); + return result == null ? false : result; + } + + public Set getCurrentCheckedPosition() { + return mSelection.keySet(); + } + + public void removeSelection(int position) { + mSelection.remove(position); + notifyDataSetChanged(); + } + + public void clearSelection() { + mSelection.clear(); + notifyDataSetChanged(); + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // let the adapter handle setting up the row views + View v = super.getView(position, convertView, parent); + + /** + * Change color for multi-selection + */ + // default color + v.setBackgroundColor(Color.TRANSPARENT); + if (mSelection.get(position) != null) { + // this is a selected position, change color! + v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); + } + return v; + } + + } + } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java deleted file mode 100644 index 2e0d1496b..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListAdapter.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui.adapter; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.database.Cursor; -import android.graphics.Color; -import android.support.v4.widget.CursorAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.util.Log; - -import java.util.HashMap; -import java.util.Set; - -import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; - -/** - * Implements StickyListHeadersAdapter from library - */ -public class KeyListAdapter extends CursorAdapter implements StickyListHeadersAdapter { - private LayoutInflater mInflater; - private int mSectionColumnIndex; - private int mIndexUserId; - private int mIndexIsRevoked; - - @SuppressLint("UseSparseArrays") - private HashMap mSelection = new HashMap(); - - public KeyListAdapter(Context context, Cursor c, int flags, int sectionColumnIndex) { - super(context, c, flags); - - mInflater = LayoutInflater.from(context); - mSectionColumnIndex = sectionColumnIndex; - initIndex(c); - } - - @Override - public Cursor swapCursor(Cursor newCursor) { - initIndex(newCursor); - - return super.swapCursor(newCursor); - } - - /** - * Get column indexes for performance reasons just once in constructor and swapCursor. For a - * performance comparison see http://stackoverflow.com/a/17999582 - * - * @param cursor - */ - private void initIndex(Cursor cursor) { - if (cursor != null) { - mIndexUserId = cursor.getColumnIndexOrThrow(KeychainContract.UserIds.USER_ID); - mIndexIsRevoked = cursor.getColumnIndexOrThrow(KeychainContract.Keys.IS_REVOKED); - } - } - - /** - * Bind cursor data to the item list view - *

- * NOTE: CursorAdapter already implements the ViewHolder pattern in its getView() method. Thus - * no ViewHolder is required here. - */ - @Override - public void bindView(View view, Context context, Cursor cursor) { - TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId); - TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest); - TextView revoked = (TextView) view.findViewById(R.id.revoked); - - String userId = cursor.getString(mIndexUserId); - String[] userIdSplit = PgpKeyHelper.splitUserId(userId); - if (userIdSplit[0] != null) { - mainUserId.setText(userIdSplit[0]); - } else { - mainUserId.setText(R.string.user_id_no_name); - } - if (userIdSplit[1] != null) { - mainUserIdRest.setText(userIdSplit[1]); - mainUserIdRest.setVisibility(View.VISIBLE); - } else { - mainUserIdRest.setVisibility(View.GONE); - } - - boolean isRevoked = cursor.getInt(mIndexIsRevoked) > 0; - if (isRevoked) { - revoked.setVisibility(View.VISIBLE); - } else { - revoked.setVisibility(View.GONE); - } - } - - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return mInflater.inflate(R.layout.key_list_item, null); - } - - /** - * Creates a new header view and binds the section headers to it. It uses the ViewHolder - * pattern. Most functionality is similar to getView() from Android's CursorAdapter. - *

- * NOTE: The variables mDataValid and mCursor are available due to the super class - * CursorAdapter. - */ - @Override - public View getHeaderView(int position, View convertView, ViewGroup parent) { - HeaderViewHolder holder; - if (convertView == null) { - holder = new HeaderViewHolder(); - convertView = mInflater.inflate(R.layout.key_list_header, parent, false); - holder.text = (TextView) convertView.findViewById(R.id.stickylist_header_text); - convertView.setTag(holder); - } else { - holder = (HeaderViewHolder) convertView.getTag(); - } - - if (!mDataValid) { - // no data available at this point - Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); - return convertView; - } - - if (!mCursor.moveToPosition(position)) { - throw new IllegalStateException("couldn't move cursor to position " + position); - } - - // set header text as first char in user id - String userId = mCursor.getString(mSectionColumnIndex); - String headerText = convertView.getResources().getString(R.string.user_id_no_name); - if (userId != null && userId.length() > 0) { - headerText = "" + mCursor.getString(mSectionColumnIndex).subSequence(0, 1).charAt(0); - } - holder.text.setText(headerText); - return convertView; - } - - /** - * Header IDs should be static, position=1 should always return the same Id that is. - */ - @Override - public long getHeaderId(int position) { - if (!mDataValid) { - // no data available at this point - Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); - return -1; - } - - if (!mCursor.moveToPosition(position)) { - throw new IllegalStateException("couldn't move cursor to position " + position); - } - - // return the first character of the name as ID because this is what - // headers are based upon - String userId = mCursor.getString(mSectionColumnIndex); - if (userId != null && userId.length() > 0) { - return userId.subSequence(0, 1).charAt(0); - } else { - return Long.MAX_VALUE; - } - } - - class HeaderViewHolder { - TextView text; - } - - /** - * -------------------------- MULTI-SELECTION METHODS -------------- - */ - public void setNewSelection(int position, boolean value) { - mSelection.put(position, value); - notifyDataSetChanged(); - } - - public boolean isPositionChecked(int position) { - Boolean result = mSelection.get(position); - return result == null ? false : result; - } - - public Set getCurrentCheckedPosition() { - return mSelection.keySet(); - } - - public void removeSelection(int position) { - mSelection.remove(position); - notifyDataSetChanged(); - } - - public void clearSelection() { - mSelection.clear(); - notifyDataSetChanged(); - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - // let the adapter handle setting up the row views - View v = super.getView(position, convertView, parent); - - /** - * Change color for multi-selection - */ - // default color - v.setBackgroundColor(Color.TRANSPARENT); - if (mSelection.get(position) != null) { - // this is a selected position, change color! - v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); - } - return v; - } - -} -- cgit v1.2.3 From 191c5b8130d1a6253ed715e35046db4678a16a8c Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 11:58:26 +0100 Subject: Make EditKeyActivity's uri handling (more) sane This activity didn't actually use the uri for anything, but just chopped off the last path segment and interpreted it as row id. What the hell. --- .../org/sufficientlysecure/keychain/provider/ProviderHelper.java | 4 ++-- .../java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 9bee42973..2d7558a49 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -451,13 +451,13 @@ public class ProviderHelper { */ public static boolean getSecretMasterKeyCanSign(Context context, long keyRingRowId) { Uri queryUri = KeyRings.buildSecretKeyRingsUri(String.valueOf(keyRingRowId)); - return getMasterKeyCanSign(context, queryUri, keyRingRowId); + return getMasterKeyCanSign(context, queryUri); } /** * Private helper method to get master key private empty status of keyring by its row id */ - private static boolean getMasterKeyCanSign(Context context, Uri queryUri, long keyRingRowId) { + public static boolean getMasterKeyCanSign(Context context, Uri queryUri) { String[] projection = new String[]{ KeyRings.MASTER_KEY_ID, "(SELECT COUNT(sign_keys." + Keys._ID + ") FROM " + Tables.KEYS diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 0bed6f264..e2822c898 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -265,12 +265,10 @@ public class EditKeyActivity extends ActionBarActivity { } else { Log.d(Constants.TAG, "uri: " + mDataUri); - long keyRingRowId = Long.valueOf(mDataUri.getLastPathSegment()); - // get master key id using row id - long masterKeyId = ProviderHelper.getSecretMasterKeyId(this, keyRingRowId); + long masterKeyId = ProviderHelper.getMasterKeyId(this, mDataUri); - masterCanSign = ProviderHelper.getSecretMasterKeyCanSign(this, keyRingRowId); + masterCanSign = ProviderHelper.getMasterKeyCanSign(this, mDataUri); finallyEdit(masterKeyId, masterCanSign); } } -- cgit v1.2.3 From aa8a8f069fb978563bf8d06994cfa7ef1fe316bd Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 12:00:24 +0100 Subject: Normalize public key uri in KeyListFragment Find the explicit row id of the public key id given in the uri in KeyListFragment and work with that. This way, passing in uris by master key id, mail address, or any other criteria, works. Might be a good idea to add an actual check if the row id is non-zero here, but not sure how to do a "bad intent" thing --- .../keychain/provider/ProviderHelper.java | 20 ++++++++++++++++++++ .../keychain/ui/KeyListFragment.java | 6 +----- .../keychain/ui/ViewKeyActivity.java | 9 ++++++++- 3 files changed, 29 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 2d7558a49..ea6d3a859 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -514,6 +514,26 @@ public class ProviderHelper { return masterKeyId; } + public static long getRowId(Context context, Uri queryUri) { + String[] projection = new String[]{KeyRings._ID}; + Cursor cursor = context.getContentResolver().query(queryUri, projection, null, null, null); + + long rowId = 0; + try { + if (cursor != null && cursor.moveToFirst()) { + int idCol = cursor.getColumnIndexOrThrow(KeyRings._ID); + + rowId = cursor.getLong(idCol); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + + return rowId; + } + /** * Get fingerprint of key */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index a638796cd..dbc24504e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -285,11 +285,7 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick } else { viewIntent = new Intent(getActivity(), ViewKeyActivityJB.class); } - if(mAdapter.getKeyType(position) == KeyTypes.SECRET) { - viewIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(mAdapter.getMasterKeyId(position)))); - } else { - viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsByMasterKeyIdUri(Long.toString(mAdapter.getMasterKeyId(position)))); - } + viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsByMasterKeyIdUri(Long.toString(mAdapter.getMasterKeyId(position)))); startActivity(viewIntent); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 0a452bc8a..ab46b8efc 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -36,6 +36,7 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.ClipboardReflection; import org.sufficientlysecure.keychain.helper.ExportHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.adapter.TabsAdapter; import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; @@ -83,7 +84,13 @@ public class ViewKeyActivity extends ActionBarActivity { selectedTab = intent.getExtras().getInt(EXTRA_SELECTED_TAB); } - mDataUri = getIntent().getData(); + { + // normalize mDataUri to a "by row id" query, to ensure it works with any + // given valid /public/ query + long rowId = ProviderHelper.getRowId(this, getIntent().getData()); + // TODO: handle (rowId == 0) with something else than a crash + mDataUri = KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(rowId)) ; + } Bundle mainBundle = new Bundle(); mainBundle.putParcelable(ViewKeyMainFragment.ARG_DATA_URI, mDataUri); -- cgit v1.2.3 From 7ad8977cf3f4117782d6568322ec76c5cd8e2475 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 12:28:20 +0100 Subject: move some placeholders into resources --- .../main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java | 3 +-- .../main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index dbc24504e..0099fb80d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -426,7 +426,6 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick final long id = cursor.getLong(mMasterKeyId); button.setOnClickListener(new OnClickListener() { public void onClick(View view) { - Log.d(Constants.TAG, "swag"); Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); // editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsUri(Long.toString(1))); editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(id))); @@ -500,7 +499,7 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick } if(mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { - holder.text.setText("My Keys"); + holder.text.setText(convertView.getResources().getString(R.string.my_keys)); return convertView; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index ab46b8efc..8f177dc6b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -114,7 +114,7 @@ public class ViewKeyActivity extends ActionBarActivity { public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: - Intent homeIntent = new Intent(this, KeyListPublicActivity.class); + Intent homeIntent = new Intent(this, KeyListActivity.class); homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(homeIntent); return true; -- cgit v1.2.3 From 706e212b6b1f5fbd30643d33336f3967d88e8b5b Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 13:17:52 +0100 Subject: add edit button and secret key info to public key view --- .../keychain/provider/ProviderHelper.java | 6 +++++ .../keychain/ui/KeyListFragment.java | 1 - .../keychain/ui/ViewKeyMainFragment.java | 30 ++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index ea6d3a859..b6bfc372a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -483,6 +483,12 @@ public class ProviderHelper { return (masterKeyId > 0); } + public static boolean hasSecretKeyByMasterKeyId(Context context, long masterKeyId) { + Uri queryUri = KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId)); + // see if we can get our master key id back from the uri + return getMasterKeyId(context, queryUri) == masterKeyId; + } + /** * Get master key id of keyring by its row id */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 0099fb80d..bdae88e55 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -427,7 +427,6 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick button.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); - // editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsUri(Long.toString(1))); editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(id))); editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); startActivityForResult(editIntent, 0); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 495764eaf..c7403b0a0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -19,6 +19,7 @@ package org.sufficientlysecure.keychain.ui; import android.content.Intent; import android.database.Cursor; +import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -59,6 +60,8 @@ public class ViewKeyMainFragment extends Fragment implements private TextView mExpiry; private TextView mCreation; private TextView mFingerprint; + private TextView mSecretKey; + private BootstrapButton mActionEdit; private BootstrapButton mActionEncrypt; private ListView mUserIds; @@ -85,8 +88,10 @@ public class ViewKeyMainFragment extends Fragment implements mCreation = (TextView) view.findViewById(R.id.creation); mExpiry = (TextView) view.findViewById(R.id.expiry); mFingerprint = (TextView) view.findViewById(R.id.fingerprint); + mSecretKey = (TextView) view.findViewById(R.id.secret_key); mUserIds = (ListView) view.findViewById(R.id.user_ids); mKeys = (ListView) view.findViewById(R.id.keys); + mActionEdit = (BootstrapButton) view.findViewById(R.id.action_edit); mActionEncrypt = (BootstrapButton) view.findViewById(R.id.action_encrypt); return view; @@ -116,6 +121,31 @@ public class ViewKeyMainFragment extends Fragment implements Log.i(Constants.TAG, "mDataUri: " + mDataUri.toString()); + { // label whether secret key is available, and edit button if it is + final long masterKeyId = ProviderHelper.getMasterKeyId(getActivity(), mDataUri); + if(ProviderHelper.hasSecretKeyByMasterKeyId(getActivity(), masterKeyId)) { + // set this attribute. this is a LITTLE unclean, but we have the info available + // right here, so why not. + mSecretKey.setTextColor(getResources().getColor(R.color.emphasis)); + mSecretKey.setText(R.string.secret_key_yes); + + // edit button + mActionEdit.setVisibility(View.VISIBLE); + mActionEdit.setOnClickListener(new View.OnClickListener() { + public void onClick(View view) { + Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); + editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId))); + editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); + startActivityForResult(editIntent, 0); + } + }); + } else { + mSecretKey.setTextColor(Color.BLACK); + mSecretKey.setText(getResources().getString(R.string.secret_key_no)); + mActionEdit.setVisibility(View.GONE); + } + } + mActionEncrypt.setOnClickListener(new View.OnClickListener() { @Override -- cgit v1.2.3 From 16116ba72572fc85fe00ec422248818da516506a Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 13:42:50 +0100 Subject: ditch old key list activities --- .../keychain/ui/DrawerActivity.java | 3 +- .../keychain/ui/KeyListPublicActivity.java | 71 ----- .../keychain/ui/KeyListPublicFragment.java | 338 --------------------- .../keychain/ui/KeyListSecretActivity.java | 94 ------ .../keychain/ui/KeyListSecretFragment.java | 234 -------------- .../keychain/ui/adapter/KeyListPublicAdapter.java | 233 -------------- .../keychain/ui/adapter/KeyListSecretAdapter.java | 138 --------- 7 files changed, 1 insertion(+), 1110 deletions(-) delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java index d7644ce4d..ebb520197 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java @@ -52,7 +52,7 @@ public class DrawerActivity extends ActionBarActivity { private static Class[] mItemsClass = new Class[] { KeyListActivity.class, EncryptActivity.class, DecryptActivity.class, ImportKeysActivity.class, - KeyListSecretActivity.class, RegisteredAppsListActivity.class }; + RegisteredAppsListActivity.class }; private Class mSelectedItem; private static final int MENU_ID_PREFERENCE = 222; @@ -72,7 +72,6 @@ public class DrawerActivity extends ActionBarActivity { new NavItem("fa-lock", getString(R.string.nav_encrypt)), new NavItem("fa-unlock", getString(R.string.nav_decrypt)), new NavItem("fa-download", getString(R.string.nav_import)), - new NavItem("fa-key", getString(R.string.nav_secret_keys)), new NavItem("fa-android", getString(R.string.nav_apps)) }; mDrawerList.setAdapter(new NavigationDrawerAdapter(this, R.layout.drawer_list_item, diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java deleted file mode 100644 index 4521786f7..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2012-2014 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ExportHelper; - -import android.content.Intent; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; - -public class KeyListPublicActivity extends DrawerActivity { - - ExportHelper mExportHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - mExportHelper = new ExportHelper(this); - - setContentView(R.layout.key_list_public_activity); - - // now setup navigation drawer in DrawerActivity... - setupDrawerNavigation(savedInstanceState); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - getMenuInflater().inflate(R.menu.key_list_public, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_key_list_public_import: - Intent intentImport = new Intent(this, ImportKeysActivity.class); - startActivityForResult(intentImport, 0); - - return true; - case R.id.menu_key_list_public_export: - mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR - + "/pubexport.asc"); - - return true; - default: - return super.onOptionsItemSelected(item); - } - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java deleted file mode 100644 index 0afa556cb..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui; - -import java.util.ArrayList; -import java.util.Set; - -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.ui.adapter.KeyListPublicAdapter; -import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; - -import se.emilsjolander.stickylistheaders.ApiLevelTooLowException; -import se.emilsjolander.stickylistheaders.StickyListHeadersListView; - -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.support.v4.app.Fragment; -import android.support.v4.app.LoaderManager; -import android.support.v4.content.CursorLoader; -import android.support.v4.content.Loader; -import android.view.ActionMode; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.AbsListView.MultiChoiceModeListener; -import android.widget.AdapterView; -import android.widget.ListView; -import android.widget.Toast; - -import com.beardedhen.androidbootstrap.BootstrapButton; - -/** - * Public key list with sticky list headers. It does _not_ extend ListFragment because it uses - * StickyListHeaders library which does not extend upon ListView. - */ -public class KeyListPublicFragment extends Fragment implements AdapterView.OnItemClickListener, - LoaderManager.LoaderCallbacks { - - private KeyListPublicAdapter mAdapter; - private StickyListHeadersListView mStickyList; - - // empty list layout - private BootstrapButton mButtonEmptyCreate; - private BootstrapButton mButtonEmptyImport; - - /** - * Load custom layout with StickyListView from library - */ - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.key_list_public_fragment, container, false); - - mButtonEmptyCreate = (BootstrapButton) view.findViewById(R.id.key_list_empty_button_create); - mButtonEmptyCreate.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - Intent intent = new Intent(getActivity(), EditKeyActivity.class); - intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); - intent.putExtra(EditKeyActivity.EXTRA_GENERATE_DEFAULT_KEYS, true); - intent.putExtra(EditKeyActivity.EXTRA_USER_IDS, ""); // show user id view - startActivityForResult(intent, 0); - } - }); - - mButtonEmptyImport = (BootstrapButton) view.findViewById(R.id.key_list_empty_button_import); - mButtonEmptyImport.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - Intent intent = new Intent(getActivity(), ImportKeysActivity.class); - intent.setAction(ImportKeysActivity.ACTION_IMPORT_KEY_FROM_FILE); - startActivityForResult(intent, 0); - } - }); - - return view; - } - - /** - * Define Adapter and Loader on create of Activity - */ - @SuppressLint("NewApi") - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - mStickyList = (StickyListHeadersListView) getActivity().findViewById(R.id.list); - - mStickyList.setOnItemClickListener(this); - mStickyList.setAreHeadersSticky(true); - mStickyList.setDrawingListUnderStickyHeader(false); - mStickyList.setFastScrollEnabled(true); - try { - mStickyList.setFastScrollAlwaysVisible(true); - } catch (ApiLevelTooLowException e) { - } - - // this view is made visible if no data is available - mStickyList.setEmptyView(getActivity().findViewById(R.id.empty)); - - /* - * ActionBarSherlock does not support MultiChoiceModeListener. Thus multi-selection is only - * available for Android >= 3.0 - */ - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - mStickyList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); - mStickyList.getWrappedList().setMultiChoiceModeListener(new MultiChoiceModeListener() { - - private int count = 0; - - @Override - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - android.view.MenuInflater inflater = getActivity().getMenuInflater(); - inflater.inflate(R.menu.key_list_public_multi, menu); - return true; - } - - @Override - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - return false; - } - - @Override - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - Set positions = mAdapter.getCurrentCheckedPosition(); - - // get IDs for checked positions as long array - long[] ids = new long[positions.size()]; - int i = 0; - for (int pos : positions) { - ids[i] = mAdapter.getItemId(pos); - i++; - } - - switch (item.getItemId()) { - case R.id.menu_key_list_public_multi_encrypt: { - encrypt(mode, ids); - break; - } - case R.id.menu_key_list_public_multi_delete: { - showDeleteKeyDialog(mode, ids); - break; - } - } - return true; - } - - @Override - public void onDestroyActionMode(ActionMode mode) { - count = 0; - mAdapter.clearSelection(); - } - - @Override - public void onItemCheckedStateChanged(ActionMode mode, int position, long id, - boolean checked) { - if (checked) { - count++; - mAdapter.setNewSelection(position, checked); - } else { - count--; - mAdapter.removeSelection(position); - } - - String keysSelected = getResources().getQuantityString( - R.plurals.key_list_selected_keys, count, count); - mode.setTitle(keysSelected); - } - - }); - } - - // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading - // Start out with a progress indicator. - // setListShown(false); - - // Create an empty adapter we will use to display the loaded data. - mAdapter = new KeyListPublicAdapter(getActivity(), null, Id.type.public_key, USER_ID_INDEX); - mStickyList.setAdapter(mAdapter); - - // Prepare the loader. Either re-connect with an existing one, - // or start a new one. - getLoaderManager().initLoader(0, null, this); - } - - // These are the rows that we will retrieve. - static final String[] PROJECTION = new String[]{ - KeychainContract.KeyRings._ID, - KeychainContract.KeyRings.MASTER_KEY_ID, - KeychainContract.UserIds.USER_ID, - KeychainContract.Keys.IS_REVOKED - }; - - static final int USER_ID_INDEX = 2; - - static final String SORT_ORDER = UserIds.USER_ID + " ASC"; - - @Override - public Loader onCreateLoader(int id, Bundle args) { - // This is called when a new Loader needs to be created. This - // sample only has one Loader, so we don't care about the ID. - Uri baseUri = KeyRings.buildPublicKeyRingsUri(); - - // Now create and return a CursorLoader that will take care of - // creating a Cursor for the data being displayed. - return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, SORT_ORDER); - } - - @Override - public void onLoadFinished(Loader loader, Cursor data) { - // Swap the new cursor in. (The framework will take care of closing the - // old cursor once we return.) - mAdapter.swapCursor(data); - - mStickyList.setAdapter(mAdapter); - - // NOTE: Not supported by StickyListHeader, thus no indicator is shown while loading - // The list should now be shown. - // if (isResumed()) { - // setListShown(true); - // } else { - // setListShownNoAnimation(true); - // } - } - - @Override - public void onLoaderReset(Loader loader) { - // This is called when the last Cursor provided to onLoadFinished() - // above is about to be closed. We need to make sure we are no - // longer using it. - mAdapter.swapCursor(null); - } - - /** - * On click on item, start key view activity - */ - @Override - public void onItemClick(AdapterView adapterView, View view, int position, long id) { - Intent viewIntent = null; - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { - viewIntent = new Intent(getActivity(), ViewKeyActivity.class); - } else { - viewIntent = new Intent(getActivity(), ViewKeyActivityJB.class); - } - viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(id))); - startActivity(viewIntent); - } - - @TargetApi(11) - public void encrypt(ActionMode mode, long[] keyRingRowIds) { - // get master key ids from row ids - long[] keyRingIds = new long[keyRingRowIds.length]; - for (int i = 0; i < keyRingRowIds.length; i++) { - keyRingIds[i] = ProviderHelper.getPublicMasterKeyId(getActivity(), keyRingRowIds[i]); - } - - Intent intent = new Intent(getActivity(), EncryptActivity.class); - intent.setAction(EncryptActivity.ACTION_ENCRYPT); - intent.putExtra(EncryptActivity.EXTRA_ENCRYPTION_KEY_IDS, keyRingIds); - // used instead of startActivity set actionbar based on callingPackage - startActivityForResult(intent, 0); - - mode.finish(); - } - - /** - * Show dialog to delete key - * - * @param keyRingRowIds - */ - @TargetApi(11) - public void showDeleteKeyDialog(final ActionMode mode, long[] keyRingRowIds) { - // Message is received after key is deleted - Handler returnHandler = new Handler() { - @Override - public void handleMessage(Message message) { - if (message.what == DeleteKeyDialogFragment.MESSAGE_OKAY) { - Bundle returnData = message.getData(); - if (returnData != null - && returnData.containsKey(DeleteKeyDialogFragment.MESSAGE_NOT_DELETED)) { - ArrayList notDeleted = - returnData.getStringArrayList(DeleteKeyDialogFragment.MESSAGE_NOT_DELETED); - String notDeletedMsg = ""; - for (String userId : notDeleted) { - notDeletedMsg += userId + "\n"; - } - Toast.makeText(getActivity(), getString(R.string.error_can_not_delete_contacts, notDeletedMsg) - + getResources().getQuantityString(R.plurals.error_can_not_delete_info, notDeleted.size()), - Toast.LENGTH_LONG).show(); - - mode.finish(); - } - } - } - }; - - // Create a new Messenger for the communication back - Messenger messenger = new Messenger(returnHandler); - - DeleteKeyDialogFragment deleteKeyDialog = DeleteKeyDialogFragment.newInstance(messenger, - keyRingRowIds, Id.type.public_key); - - deleteKeyDialog.show(getActivity().getSupportFragmentManager(), "deleteKeyDialog"); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java deleted file mode 100644 index e58ebe819..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ExportHelper; - -import android.content.Intent; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; - -public class KeyListSecretActivity extends DrawerActivity { - - ExportHelper mExportHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - mExportHelper = new ExportHelper(this); - - setContentView(R.layout.key_list_secret_activity); - - // now setup navigation drawer in DrawerActivity... - setupDrawerNavigation(savedInstanceState); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - getMenuInflater().inflate(R.menu.key_list_secret, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_key_list_secret_create: - createKey(); - - return true; - case R.id.menu_key_list_secret_create_expert: - createKeyExpert(); - - return true; - case R.id.menu_key_list_secret_export: - mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.path.APP_DIR - + "/secexport.asc"); - - return true; - case R.id.menu_key_list_secret_import: - Intent intentImportFromFile = new Intent(this, ImportKeysActivity.class); - intentImportFromFile.setAction(ImportKeysActivity.ACTION_IMPORT_KEY_FROM_FILE); - startActivityForResult(intentImportFromFile, 0); - - return true; - default: - return super.onOptionsItemSelected(item); - } - } - - private void createKey() { - Intent intent = new Intent(this, EditKeyActivity.class); - intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); - intent.putExtra(EditKeyActivity.EXTRA_GENERATE_DEFAULT_KEYS, true); - intent.putExtra(EditKeyActivity.EXTRA_USER_IDS, ""); // show user id view - startActivityForResult(intent, 0); - } - - private void createKeyExpert() { - Intent intent = new Intent(this, EditKeyActivity.class); - intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); - startActivityForResult(intent, 0); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java deleted file mode 100644 index 7bb77b60f..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui; - -import java.util.ArrayList; -import java.util.Set; - -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; -import org.sufficientlysecure.keychain.ui.adapter.KeyListSecretAdapter; -import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; - -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.support.v4.app.ListFragment; -import android.support.v4.app.LoaderManager; -import android.support.v4.content.CursorLoader; -import android.support.v4.content.Loader; -import android.view.ActionMode; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ListView; -import android.widget.AbsListView.MultiChoiceModeListener; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.Toast; - -public class KeyListSecretFragment extends ListFragment implements - LoaderManager.LoaderCallbacks, OnItemClickListener { - - private KeyListSecretActivity mKeyListSecretActivity; - private KeyListSecretAdapter mAdapter; - - /** - * Define Adapter and Loader on create of Activity - */ - @SuppressLint("NewApi") - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - mKeyListSecretActivity = (KeyListSecretActivity) getActivity(); - - getListView().setOnItemClickListener(this); - - // Give some text to display if there is no data. In a real - // application this would come from a resource. - setEmptyText(getString(R.string.list_empty)); - - /* - * ActionBarSherlock does not support MultiChoiceModeListener. Thus multi-selection is only - * available for Android >= 3.0 - */ - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); - getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() { - - private int count = 0; - - @Override - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - android.view.MenuInflater inflater = getActivity().getMenuInflater(); - inflater.inflate(R.menu.key_list_secret_multi, menu); - return true; - } - - @Override - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - return false; - } - - @Override - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - Set positions = mAdapter.getCurrentCheckedPosition(); - - // get IDs for checked positions as long array - long[] ids = new long[positions.size()]; - int i = 0; - for (int pos : positions) { - ids[i] = mAdapter.getItemId(pos); - i++; - } - - switch (item.getItemId()) { - case R.id.menu_key_list_public_multi_delete: { - showDeleteKeyDialog(mode, ids); - break; - } - } - return true; - } - - @Override - public void onDestroyActionMode(ActionMode mode) { - count = 0; - mAdapter.clearSelection(); - } - - @Override - public void onItemCheckedStateChanged(ActionMode mode, int position, long id, - boolean checked) { - if (checked) { - count++; - mAdapter.setNewSelection(position, checked); - } else { - count--; - mAdapter.removeSelection(position); - } - - String keysSelected = getResources().getQuantityString( - R.plurals.key_list_selected_keys, count, count); - mode.setTitle(keysSelected); - } - - }); - } - - // We have a menu item to show in action bar. - setHasOptionsMenu(true); - - // Start out with a progress indicator. - setListShown(false); - - // Create an empty adapter we will use to display the loaded data. - mAdapter = new KeyListSecretAdapter(mKeyListSecretActivity, null, 0); - setListAdapter(mAdapter); - - // Prepare the loader. Either re-connect with an existing one, - // or start a new one. - getLoaderManager().initLoader(0, null, this); - } - - // These are the rows that we will retrieve. - static final String[] PROJECTION = new String[]{KeyRings._ID, KeyRings.MASTER_KEY_ID, - UserIds.USER_ID}; - static final String SORT_ORDER = UserIds.USER_ID + " COLLATE LOCALIZED ASC"; - - public Loader onCreateLoader(int id, Bundle args) { - // This is called when a new Loader needs to be created. This - // sample only has one Loader, so we don't care about the ID. - // First, pick the base URI to use depending on whether we are - // currently filtering. - Uri baseUri = KeyRings.buildSecretKeyRingsUri(); - - // Now create and return a CursorLoader that will take care of - // creating a Cursor for the data being displayed. - return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, SORT_ORDER); - } - - public void onLoadFinished(Loader loader, Cursor data) { - // Swap the new cursor in. (The framework will take care of closing the - // old cursor once we return.) - mAdapter.swapCursor(data); - - // The list should now be shown. - if (isResumed()) { - setListShown(true); - } else { - setListShownNoAnimation(true); - } - } - - public void onLoaderReset(Loader loader) { - // This is called when the last Cursor provided to onLoadFinished() - // above is about to be closed. We need to make sure we are no - // longer using it. - mAdapter.swapCursor(null); - } - - /** - * On click on item, start key view activity - */ - @Override - public void onItemClick(AdapterView adapterView, View view, int position, long id) { - Intent editIntent = new Intent(mKeyListSecretActivity, EditKeyActivity.class); - editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsUri(Long.toString(id))); - editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); - startActivityForResult(editIntent, 0); - } - - /** - * Show dialog to delete key - * - * @param keyRingRowIds - */ - @TargetApi(11) - public void showDeleteKeyDialog(final ActionMode mode, long[] keyRingRowIds) { - // Message is received after key is deleted - Handler returnHandler = new Handler() { - @Override - public void handleMessage(Message message) { - if (message.what == DeleteKeyDialogFragment.MESSAGE_OKAY) { - mode.finish(); - } - } - }; - - // Create a new Messenger for the communication back - Messenger messenger = new Messenger(returnHandler); - - DeleteKeyDialogFragment deleteKeyDialog = DeleteKeyDialogFragment.newInstance(messenger, - keyRingRowIds, Id.type.secret_key); - - deleteKeyDialog.show(getActivity().getSupportFragmentManager(), "deleteKeyDialog"); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java deleted file mode 100644 index 257136cbd..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui.adapter; - -import java.util.HashMap; -import java.util.Set; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.util.Log; - -import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.database.Cursor; -import android.graphics.Color; -import android.support.v4.widget.CursorAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.RelativeLayout; -import android.widget.TextView; - -/** - * Implements StickyListHeadersAdapter from library - */ -public class KeyListPublicAdapter extends CursorAdapter implements StickyListHeadersAdapter { - private LayoutInflater mInflater; - private int mSectionColumnIndex; - private int mIndexUserId; - private int mIndexIsRevoked; - - @SuppressLint("UseSparseArrays") - private HashMap mSelection = new HashMap(); - - public KeyListPublicAdapter(Context context, Cursor c, int flags, int sectionColumnIndex) { - super(context, c, flags); - - mInflater = LayoutInflater.from(context); - mSectionColumnIndex = sectionColumnIndex; - initIndex(c); - } - - @Override - public Cursor swapCursor(Cursor newCursor) { - initIndex(newCursor); - - return super.swapCursor(newCursor); - } - - /** - * Get column indexes for performance reasons just once in constructor and swapCursor. For a - * performance comparison see http://stackoverflow.com/a/17999582 - * - * @param cursor - */ - private void initIndex(Cursor cursor) { - if (cursor != null) { - mIndexUserId = cursor.getColumnIndexOrThrow(KeychainContract.UserIds.USER_ID); - mIndexIsRevoked = cursor.getColumnIndexOrThrow(KeychainContract.Keys.IS_REVOKED); - } - } - - /** - * Bind cursor data to the item list view - *

- * NOTE: CursorAdapter already implements the ViewHolder pattern in its getView() method. Thus - * no ViewHolder is required here. - */ - @Override - public void bindView(View view, Context context, Cursor cursor) { - TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId); - TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest); - TextView revoked = (TextView) view.findViewById(R.id.revoked); - - String userId = cursor.getString(mIndexUserId); - String[] userIdSplit = PgpKeyHelper.splitUserId(userId); - if (userIdSplit[0] != null) { - mainUserId.setText(userIdSplit[0]); - } else { - mainUserId.setText(R.string.user_id_no_name); - } - if (userIdSplit[1] != null) { - mainUserIdRest.setText(userIdSplit[1]); - mainUserIdRest.setVisibility(View.VISIBLE); - } else { - mainUserIdRest.setVisibility(View.GONE); - } - - boolean isRevoked = cursor.getInt(mIndexIsRevoked) > 0; - if (isRevoked) { - revoked.setVisibility(View.VISIBLE); - } else { - revoked.setVisibility(View.GONE); - } - } - - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return mInflater.inflate(R.layout.key_list_public_item, null); - } - - /** - * Creates a new header view and binds the section headers to it. It uses the ViewHolder - * pattern. Most functionality is similar to getView() from Android's CursorAdapter. - *

- * NOTE: The variables mDataValid and mCursor are available due to the super class - * CursorAdapter. - */ - @Override - public View getHeaderView(int position, View convertView, ViewGroup parent) { - HeaderViewHolder holder; - if (convertView == null) { - holder = new HeaderViewHolder(); - convertView = mInflater.inflate(R.layout.key_list_public_header, parent, false); - holder.text = (TextView) convertView.findViewById(R.id.stickylist_header_text); - convertView.setTag(holder); - } else { - holder = (HeaderViewHolder) convertView.getTag(); - } - - if (!mDataValid) { - // no data available at this point - Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); - return convertView; - } - - if (!mCursor.moveToPosition(position)) { - throw new IllegalStateException("couldn't move cursor to position " + position); - } - - // set header text as first char in user id - String userId = mCursor.getString(mSectionColumnIndex); - String headerText = convertView.getResources().getString(R.string.user_id_no_name); - if (userId != null && userId.length() > 0) { - headerText = "" + mCursor.getString(mSectionColumnIndex).subSequence(0, 1).charAt(0); - } - holder.text.setText(headerText); - return convertView; - } - - /** - * Header IDs should be static, position=1 should always return the same Id that is. - */ - @Override - public long getHeaderId(int position) { - if (!mDataValid) { - // no data available at this point - Log.d(Constants.TAG, "getHeaderView: No data available at this point!"); - return -1; - } - - if (!mCursor.moveToPosition(position)) { - throw new IllegalStateException("couldn't move cursor to position " + position); - } - - // return the first character of the name as ID because this is what - // headers are based upon - String userId = mCursor.getString(mSectionColumnIndex); - if (userId != null && userId.length() > 0) { - return userId.subSequence(0, 1).charAt(0); - } else { - return Long.MAX_VALUE; - } - } - - class HeaderViewHolder { - TextView text; - } - - /** - * -------------------------- MULTI-SELECTION METHODS -------------- - */ - public void setNewSelection(int position, boolean value) { - mSelection.put(position, value); - notifyDataSetChanged(); - } - - public boolean isPositionChecked(int position) { - Boolean result = mSelection.get(position); - return result == null ? false : result; - } - - public Set getCurrentCheckedPosition() { - return mSelection.keySet(); - } - - public void removeSelection(int position) { - mSelection.remove(position); - notifyDataSetChanged(); - } - - public void clearSelection() { - mSelection.clear(); - notifyDataSetChanged(); - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - // let the adapter handle setting up the row views - View v = super.getView(position, convertView, parent); - - /** - * Change color for multi-selection - */ - // default color - v.setBackgroundColor(Color.TRANSPARENT); - if (mSelection.get(position) != null) { - // this is a selected position, change color! - v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); - } - return v; - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java deleted file mode 100644 index 11d1e8c17..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui.adapter; - -import java.util.HashMap; -import java.util.Set; - -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.database.Cursor; -import android.graphics.Color; -import android.support.v4.widget.CursorAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -public class KeyListSecretAdapter extends CursorAdapter { - private LayoutInflater mInflater; - - private int mIndexUserId; - - @SuppressLint("UseSparseArrays") - private HashMap mSelection = new HashMap(); - - public KeyListSecretAdapter(Context context, Cursor c, int flags) { - super(context, c, flags); - - mInflater = LayoutInflater.from(context); - initIndex(c); - } - - @Override - public Cursor swapCursor(Cursor newCursor) { - initIndex(newCursor); - - return super.swapCursor(newCursor); - } - - /** - * Get column indexes for performance reasons just once in constructor and swapCursor. For a - * performance comparison see http://stackoverflow.com/a/17999582 - * - * @param cursor - */ - private void initIndex(Cursor cursor) { - if (cursor != null) { - mIndexUserId = cursor.getColumnIndexOrThrow(UserIds.USER_ID); - } - } - - @Override - public void bindView(View view, Context context, Cursor cursor) { - TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId); - TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest); - - String userId = cursor.getString(mIndexUserId); - String[] userIdSplit = PgpKeyHelper.splitUserId(userId); - - if (userIdSplit[0] != null) { - mainUserId.setText(userIdSplit[0]); - } else { - mainUserId.setText(R.string.user_id_no_name); - } - if (userIdSplit[1] != null) { - mainUserIdRest.setText(userIdSplit[1]); - } else { - mainUserIdRest.setText(""); - } - } - - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return mInflater.inflate(R.layout.key_list_secret_item, null); - } - - /** -------------------------- MULTI-SELECTION METHODS -------------- */ - public void setNewSelection(int position, boolean value) { - mSelection.put(position, value); - notifyDataSetChanged(); - } - - public boolean isPositionChecked(int position) { - Boolean result = mSelection.get(position); - return result == null ? false : result; - } - - public Set getCurrentCheckedPosition() { - return mSelection.keySet(); - } - - public void removeSelection(int position) { - mSelection.remove(position); - notifyDataSetChanged(); - } - - public void clearSelection() { - mSelection.clear(); - notifyDataSetChanged(); - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - // let the adapter handle setting up the row views - View v = super.getView(position, convertView, parent); - - /** - * Change color for multi-selection - */ - // default color - v.setBackgroundColor(Color.TRANSPARENT); - if (mSelection.get(position) != null) { - // this is a selected position, change color! - v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); - } - return v; - } - -} -- cgit v1.2.3 From de6daf5c30c66e1152f06560e0030fb514d5f68f Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 14:08:44 +0100 Subject: better handling of multi select in ListKeysFragment --- .../keychain/ui/KeyListFragment.java | 39 ++++++++++++---------- 1 file changed, 22 insertions(+), 17 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index bdae88e55..941abdd6d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -164,22 +164,18 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - Set positions = mAdapter.getCurrentCheckedPosition(); // get IDs for checked positions as long array - long[] ids = new long[positions.size()]; - int i = 0; - for (int pos : positions) { - ids[i] = mAdapter.getItemId(pos); - i++; - } + long[] ids; switch (item.getItemId()) { case R.id.menu_key_list_multi_encrypt: { + ids = mAdapter.getCurrentSelectedMasterKeyIds(); encrypt(mode, ids); break; } case R.id.menu_key_list_multi_delete: { + ids = mAdapter.getCurrentSelectedItemIds(); showDeleteKeyDialog(mode, ids); break; } @@ -290,16 +286,10 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick } @TargetApi(11) - public void encrypt(ActionMode mode, long[] keyRingRowIds) { - // get master key ids from row ids - long[] keyRingIds = new long[keyRingRowIds.length]; - for (int i = 0; i < keyRingRowIds.length; i++) { - keyRingIds[i] = ProviderHelper.getPublicMasterKeyId(getActivity(), keyRingRowIds[i]); - } - + protected void encrypt(ActionMode mode, long[] keyRingMasterKeyIds) { Intent intent = new Intent(getActivity(), EncryptActivity.class); intent.setAction(EncryptActivity.ACTION_ENCRYPT); - intent.putExtra(EncryptActivity.EXTRA_ENCRYPTION_KEY_IDS, keyRingIds); + intent.putExtra(EncryptActivity.EXTRA_ENCRYPTION_KEY_IDS, keyRingMasterKeyIds); // used instead of startActivity set actionbar based on callingPackage startActivityForResult(intent, 0); @@ -312,6 +302,7 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick * @param keyRingRowIds */ @TargetApi(11) + // TODO: this method needs an overhaul to handle both public and secret keys gracefully! public void showDeleteKeyDialog(final ActionMode mode, long[] keyRingRowIds) { // Message is received after key is deleted Handler returnHandler = new Handler() { @@ -557,8 +548,22 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick return result == null ? false : result; } - public Set getCurrentCheckedPosition() { - return mSelection.keySet(); + public long[] getCurrentSelectedItemIds() { + long[] ids = new long[mSelection.size()]; + int i = 0; + // get master key ids + for (int pos : mSelection.keySet()) + ids[i++] = mAdapter.getItemId(pos); + return ids; + } + + public long[] getCurrentSelectedMasterKeyIds() { + long[] ids = new long[mSelection.size()]; + int i = 0; + // get master key ids + for (int pos : mSelection.keySet()) + ids[i++] = mAdapter.getMasterKeyId(pos); + return ids; } public void removeSelection(int position) { -- cgit v1.2.3 From be558944b52ac038c40bdf84a3d52c9ae2e7a218 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 8 Mar 2014 14:41:25 +0100 Subject: add contact count to My Keys header --- .../org/sufficientlysecure/keychain/ui/KeyListFragment.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 941abdd6d..96b75cf11 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -19,7 +19,6 @@ package org.sufficientlysecure.keychain.ui; import java.util.HashMap; import java.util.ArrayList; -import java.util.Set; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; @@ -473,6 +472,7 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick holder = new HeaderViewHolder(); convertView = mInflater.inflate(R.layout.key_list_header, parent, false); holder.text = (TextView) convertView.findViewById(R.id.stickylist_header_text); + holder.count = (TextView) convertView.findViewById(R.id.contacts_num); convertView.setTag(holder); } else { holder = (HeaderViewHolder) convertView.getTag(); @@ -489,6 +489,13 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick } if(mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { + { // set contact count + int num = mCursor.getCount(); + String contactsTotal = getResources().getQuantityString(R.plurals.n_contacts, num, num); + holder.count.setText(contactsTotal); + holder.count.setVisibility(View.VISIBLE); + } + holder.text.setText(convertView.getResources().getString(R.string.my_keys)); return convertView; } @@ -500,6 +507,7 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick headerText = "" + mCursor.getString(KeyListFragment.INDEX_UID).subSequence(0, 1).charAt(0); } holder.text.setText(headerText); + holder.count.setVisibility(View.GONE); return convertView; } @@ -533,6 +541,7 @@ public class KeyListFragment extends Fragment implements AdapterView.OnItemClick class HeaderViewHolder { TextView text; + TextView count; } /** -- cgit v1.2.3 From 402aeeabf3e5b4a27bbc6199f7eb044d7a1f9464 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Sat, 8 Mar 2014 17:19:57 +0100 Subject: use parameter in updateFromKeyserver --- .../main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 2db5fc27f..390de9ab9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -154,7 +154,7 @@ public class ViewKeyActivity extends ActionBarActivity { } private void updateFromKeyserver(Uri dataUri) { - long updateKeyId = ProviderHelper.getMasterKeyId(ViewKeyActivity.this, mDataUri); + long updateKeyId = ProviderHelper.getMasterKeyId(ViewKeyActivity.this, dataUri); if (updateKeyId == 0) { Log.e(Constants.TAG, "this shouldn't happen. KeyId == 0!"); -- cgit v1.2.3 From 14b38078115ab285b6c681c09fb1635fe98708b4 Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Sun, 9 Mar 2014 01:32:41 +0530 Subject: Revised fix for #347 --- .../keychain/ui/KeyListPublicFragment.java | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index e1c43919f..10edc7a7a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -353,22 +353,12 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { // Get the searchview - final MenuItem searchItem = menu.findItem(R.id.menu_key_list_public_search); - + MenuItem searchItem = menu.findItem(R.id.menu_key_list_public_search); mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); // Execute this when searching mSearchView.setOnQueryTextListener(this); - //Collapse the SearchView if it does not have focus - mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (!hasFocus) { - MenuItemCompat.collapseActionView(searchItem); - } - } - }); super.onCreateOptionsMenu(menu, inflater); } -- cgit v1.2.3 From 5b255a263ff6dfbc2518e527466dc98aabf2cace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Sun, 9 Mar 2014 01:49:25 +0100 Subject: Fix key id and fingerprint handling, use full key ids --- .../keychain/pgp/PgpImportExport.java | 2 +- .../keychain/pgp/PgpKeyHelper.java | 137 ++++++++++----------- .../keychain/provider/ProviderHelper.java | 10 +- .../keychain/ui/ImportKeysActivity.java | 2 +- .../keychain/ui/ViewKeyMainFragment.java | 2 +- .../keychain/ui/adapter/ImportKeysListEntry.java | 2 +- .../keychain/ui/adapter/ViewKeyKeysAdapter.java | 2 +- .../keychain/ui/widget/KeyEditor.java | 5 +- .../keychain/util/HkpKeyServer.java | 2 +- 9 files changed, 77 insertions(+), 87 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 9d9cd4d11..7c635a00b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -228,7 +228,7 @@ public class PgpImportExport { for (PGPSecretKey testSecretKey : new IterableIterator( secretKeyRing.getSecretKeys())) { if (!testSecretKey.isMasterKey()) { - if (PgpKeyHelper.isSecretKeyPrivateEmpty(testSecretKey)) { + if (testSecretKey.isPrivateKeyEmpty()) { // this is bad, something is very wrong... save = false; status = Id.return_value.bad; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index b3e21685e..71c921c33 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -32,6 +32,7 @@ import org.spongycastle.openpgp.PGPSecretKey; import org.spongycastle.openpgp.PGPSecretKeyRing; import org.spongycastle.openpgp.PGPSignature; import org.spongycastle.openpgp.PGPSignatureSubpacketVector; +import org.spongycastle.util.encoders.Hex; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.provider.ProviderHelper; @@ -415,55 +416,30 @@ public class PgpKeyHelper { String algorithmStr = null; switch (algorithm) { - case PGPPublicKey.RSA_ENCRYPT: - case PGPPublicKey.RSA_GENERAL: - case PGPPublicKey.RSA_SIGN: { - algorithmStr = "RSA"; - break; - } - - case PGPPublicKey.DSA: { - algorithmStr = "DSA"; - break; - } - - case PGPPublicKey.ELGAMAL_ENCRYPT: - case PGPPublicKey.ELGAMAL_GENERAL: { - algorithmStr = "ElGamal"; - break; - } + case PGPPublicKey.RSA_ENCRYPT: + case PGPPublicKey.RSA_GENERAL: + case PGPPublicKey.RSA_SIGN: { + algorithmStr = "RSA"; + break; + } - default: { - algorithmStr = "Unknown"; - break; - } - } - return algorithmStr + ", " + keySize + " bit"; - } + case PGPPublicKey.DSA: { + algorithmStr = "DSA"; + break; + } - /** - * Converts fingerprint to hex with whitespaces after 4 characters - * - * @param fp - * @return - */ - public static String convertFingerprintToHex(byte[] fp, boolean chunked) { - String fingerPrint = ""; - for (int i = 0; i < fp.length; ++i) { - if (chunked && i != 0 && i % 10 == 0) { - fingerPrint += " "; - } else if (chunked && i != 0 && i % 2 == 0) { - fingerPrint += " "; + case PGPPublicKey.ELGAMAL_ENCRYPT: + case PGPPublicKey.ELGAMAL_GENERAL: { + algorithmStr = "ElGamal"; + break; } - String chunk = Integer.toHexString((fp[i] + 256) % 256).toUpperCase(Locale.US); - while (chunk.length() < 2) { - chunk = "0" + chunk; + + default: { + algorithmStr = "Unknown"; + break; } - fingerPrint += chunk; } - - return fingerPrint; - + return algorithmStr + ", " + keySize + " bit"; } public static String getFingerPrint(Context context, long keyId) { @@ -481,52 +457,68 @@ public class PgpKeyHelper { return convertFingerprintToHex(key.getFingerprint(), true); } - public static boolean isSecretKeyPrivateEmpty(PGPSecretKey secretKey) { - return secretKey.isPrivateKeyEmpty(); - } - -// public static boolean isSecretKeyPrivateEmpty(Context context, long keyId) { -// PGPSecretKey secretKey = ProviderHelper.getPGPSecretKeyByKeyId(context, keyId); -// if (secretKey == null) { -// Log.e(Constants.TAG, "Key could not be found!"); -// return false; // could be a public key, assume it is not empty -// } -// return isSecretKeyPrivateEmpty(secretKey); -// } - - public static String convertKeyIdToHex(long keyId) { - String fingerPrint = Long.toHexString(keyId & 0xffffffffL).toUpperCase(Locale.US); - while (fingerPrint.length() < 8) { - fingerPrint = "0" + fingerPrint; + /** + * Converts fingerprint to hex (optional: with whitespaces after 4 characters) + *

+ * Fingerprint is shown using lowercase characters. Studies have shown that humans can + * better differentiate between numbers and letters when letters are lowercase. + * + * @param fingerprint + * @param split split into 4 character chunks + * @return + */ + public static String convertFingerprintToHex(byte[] fingerprint, boolean split) { + String hexString = Hex.toHexString(fingerprint); + if (split) { + hexString = hexString.replaceAll("(.{4})(?!$)", "$1 "); } - return fingerPrint; + + return hexString; } /** - * TODO: documentation - * + * Convert key id from long to 64 bit hex string + *

+ * V4: "The Key ID is the low-order 64 bits of the fingerprint" + *

+ * see http://tools.ietf.org/html/rfc4880#section-12.2 + * * @param keyId * @return */ - public static String convertKeyToHex(long keyId) { - return convertKeyIdToHex(keyId >> 32) + convertKeyIdToHex(keyId); + public static String convertKeyIdToHex(long keyId) { + return "0x" + convertKeyIdToHex32bit(keyId >> 32) + convertKeyIdToHex32bit(keyId); + } + + private static String convertKeyIdToHex32bit(long keyId) { + String hexString = Long.toHexString(keyId & 0xffffffffL).toLowerCase(Locale.US); + while (hexString.length() < 8) { + hexString = "0" + hexString; + } + return hexString; } - public static long convertHexToKeyId(String data) { - int len = data.length(); - String s2 = data.substring(len - 8); - String s1 = data.substring(0, len - 8); + /** + * Used in HkpKeyServer to convert hex encoded key ids back to long. + * + * @param hexString + * @return + */ + public static long convertHexToKeyId(String hexString) { + int len = hexString.length(); + String s2 = hexString.substring(len - 8); + String s1 = hexString.substring(0, len - 8); return (Long.parseLong(s1, 16) << 32) | Long.parseLong(s2, 16); } /** * Splits userId string into naming part, email part, and comment part - * + * * @param userId * @return array with naming (0), email (1), comment (2) */ public static String[] splitUserId(String userId) { - String[] result = new String[] { null, null, null }; + String[] result = new String[]{null, null, null}; if (userId == null || userId.equals("")) { return result; @@ -547,7 +539,6 @@ public class PgpKeyHelper { result[0] = matcher.group(1); result[1] = matcher.group(3); result[2] = matcher.group(2); - return result; } return result; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 68d9f801b..1a16f6db3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -341,10 +341,10 @@ public class ProviderHelper { long keyRingRowId, PGPSecretKey key, int rank) throws IOException { ContentValues values = new ContentValues(); - boolean has_private = true; + boolean hasPrivate = true; if (key.isMasterKey()) { - if (PgpKeyHelper.isSecretKeyPrivateEmpty(key)) { - has_private = false; + if (key.isPrivateKeyEmpty()) { + hasPrivate = false; } } @@ -352,8 +352,8 @@ public class ProviderHelper { values.put(Keys.IS_MASTER_KEY, key.isMasterKey()); values.put(Keys.ALGORITHM, key.getPublicKey().getAlgorithm()); values.put(Keys.KEY_SIZE, key.getPublicKey().getBitStrength()); - values.put(Keys.CAN_CERTIFY, (PgpKeyHelper.isCertificationKey(key) && has_private)); - values.put(Keys.CAN_SIGN, (PgpKeyHelper.isSigningKey(key) && has_private)); + values.put(Keys.CAN_CERTIFY, (PgpKeyHelper.isCertificationKey(key) && hasPrivate)); + values.put(Keys.CAN_SIGN, (PgpKeyHelper.isSigningKey(key) && hasPrivate)); values.put(Keys.CAN_ENCRYPT, PgpKeyHelper.isEncryptionKey(key)); values.put(Keys.IS_REVOKED, key.getPublicKey().isRevoked()); values.put(Keys.CREATION, PgpKeyHelper.getCreationDate(key).getTime() / 1000); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index 5ac421a44..7e31d795e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -161,7 +161,7 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa } else if (extras.containsKey(EXTRA_KEY_ID)) { long keyId = intent.getLongExtra(EXTRA_KEY_ID, 0); if (keyId != 0) { - query = "0x" + PgpKeyHelper.convertKeyToHex(keyId); + query = PgpKeyHelper.convertKeyIdToHex(keyId); } } else if (extras.containsKey(EXTRA_FINGERPRINT)) { String fingerprint = intent.getStringExtra(EXTRA_FINGERPRINT); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 495764eaf..7b83db87f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -225,7 +225,7 @@ public class ViewKeyMainFragment extends Fragment implements // get key id from MASTER_KEY_ID long keyId = data.getLong(KEYS_INDEX_KEY_ID); - String keyIdStr = "0x" + PgpKeyHelper.convertKeyIdToHex(keyId); + String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId); mKeyId.setText(keyIdStr); // get creation date from CREATION diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index 01b6deeaa..f764b879c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -165,7 +165,7 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.revoked = pgpKeyRing.getPublicKey().isRevoked(); this.fingerPrint = PgpKeyHelper.convertFingerprintToHex(pgpKeyRing.getPublicKey() .getFingerprint(), true); - this.hexKeyId = "0x" + PgpKeyHelper.convertKeyIdToHex(keyId); + this.hexKeyId = PgpKeyHelper.convertKeyIdToHex(keyId); this.bitStrength = pgpKeyRing.getPublicKey().getBitStrength(); int algorithm = pgpKeyRing.getPublicKey().getAlgorithm(); if (algorithm == PGPPublicKey.RSA_ENCRYPT || algorithm == PGPPublicKey.RSA_GENERAL diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index 54c7eb60e..046a98883 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -83,7 +83,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { ImageView encryptIcon = (ImageView) view.findViewById(R.id.ic_encryptKey); ImageView signIcon = (ImageView) view.findViewById(R.id.ic_signKey); - String keyIdStr = "0x" + PgpKeyHelper.convertKeyIdToHex(cursor.getLong(mIndexKeyId)); + String keyIdStr = PgpKeyHelper.convertKeyIdToHex(cursor.getLong(mIndexKeyId)); String algorithmStr = PgpKeyHelper.getAlgorithmInfo(cursor.getInt(mIndexAlgorithm), cursor.getInt(mIndexKeySize)); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java index 75a885bdd..65461cb4f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java @@ -174,9 +174,8 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { } mAlgorithm.setText(PgpKeyHelper.getAlgorithmInfo(key)); - String keyId1Str = PgpKeyHelper.convertKeyIdToHex(key.getKeyID()); - String keyId2Str = PgpKeyHelper.convertKeyIdToHex(key.getKeyID() >> 32); - mKeyId.setText(keyId1Str + " " + keyId2Str); + String keyIdStr = PgpKeyHelper.convertKeyIdToHex(key.getKeyID()); + mKeyId.setText(keyIdStr); Vector choices = new Vector(); boolean isElGamalKey = (key.getPublicKey().getAlgorithm() == PGPPublicKey.ELGAMAL_ENCRYPT); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 921d22f21..0681847f4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -226,7 +226,7 @@ public class HkpKeyServer extends KeyServer { HttpClient client = new DefaultHttpClient(); try { HttpGet get = new HttpGet("http://" + mHost + ":" + mPort - + "/pks/lookup?op=get&search=0x" + PgpKeyHelper.convertKeyToHex(keyId)); + + "/pks/lookup?op=get&search=0x" + PgpKeyHelper.convertKeyIdToHex(keyId)); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { -- cgit v1.2.3 From 059e57c5d0b9192308d7d0ae036a731a038f5d6c Mon Sep 17 00:00:00 2001 From: uberspot Date: Sun, 9 Mar 2014 04:09:00 +0200 Subject: Colorize fingerprint --- .../keychain/provider/ProviderHelper.java | 12 +++------- .../keychain/ui/ViewKeyMainFragment.java | 28 +++++++++++++++++++--- 2 files changed, 28 insertions(+), 12 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 1a16f6db3..ac0692213 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -87,7 +87,7 @@ public class ProviderHelper { } /** - * Retrieves the actual PGPPublicKeyRing object from the database blob based on the maserKeyId + * Retrieves the actual PGPPublicKeyRing object from the database blob based on the masterKeyId */ public static PGPPublicKeyRing getPGPPublicKeyRingByMasterKeyId(Context context, long masterKeyId) { @@ -110,11 +110,8 @@ public class ProviderHelper { */ public static PGPPublicKey getPGPPublicKeyByKeyId(Context context, long keyId) { PGPPublicKeyRing keyRing = getPGPPublicKeyRingByKeyId(context, keyId); - if (keyRing == null) { - return null; - } - return keyRing.getPublicKey(keyId); + return (keyRing == null)? null : keyRing.getPublicKey(keyId); } /** @@ -149,11 +146,8 @@ public class ProviderHelper { */ public static PGPSecretKey getPGPSecretKeyByKeyId(Context context, long keyId) { PGPSecretKeyRing keyRing = getPGPSecretKeyRingByKeyId(context, keyId); - if (keyRing == null) { - return null; - } - return keyRing.getSecretKey(keyId); + return (keyRing == null) ? null : keyRing.getSecretKey(keyId); } /** diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 7b83db87f..f8db19c16 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -19,13 +19,17 @@ package org.sufficientlysecure.keychain.ui; import android.content.Intent; import android.database.Cursor; +import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; +import android.text.Spannable; +import android.text.SpannableStringBuilder; import android.text.format.DateFormat; +import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -257,10 +261,10 @@ public class ViewKeyMainFragment extends Fragment implements // FALLBACK for old database entries fingerprintBlob = ProviderHelper.getFingerprint(getActivity(), mDataUri); } - String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); - fingerprint = fingerprint.replace(" ", "\n"); + String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true) + .replace(" ", "\n"); - mFingerprint.setText(fingerprint); + mFingerprint.setText(colorizeFingerprint(fingerprint)); } mKeysAdapter.swapCursor(data); @@ -271,6 +275,24 @@ public class ViewKeyMainFragment extends Fragment implements } } + private SpannableStringBuilder colorizeFingerprint(String fingerprint) { + SpannableStringBuilder sb = new SpannableStringBuilder(fingerprint); + ForegroundColorSpan fcs = new ForegroundColorSpan(Color.BLACK); + + // for each 4 characters of the fingerprint + 1 space + for (int i = 0; i < fingerprint.length(); i += 5) { + String fourChars = fingerprint.substring(i, Math.min(i + 4, fingerprint.length())); + + // Create a foreground color by converting the 4 fingerprint chars to an int hashcode + // and then converting that int to hex to use as a color + fcs = new ForegroundColorSpan( + Color.parseColor(String.format("#%06X", (0xFFFFFF & fourChars.hashCode())))); + sb.setSpan(fcs, i, Math.min(i+4, fingerprint.length()), Spannable.SPAN_INCLUSIVE_INCLUSIVE); + } + + return sb; + } + /** * This is called when the last Cursor provided to onLoadFinished() above is about to be closed. * We need to make sure we are no longer using it. -- cgit v1.2.3 From 4874ea567a81f5b2e67895296782f36d294a8d77 Mon Sep 17 00:00:00 2001 From: grait Date: Sun, 9 Mar 2014 17:45:58 +0530 Subject: progress bar while key creation - added plurals based on no.of keys while key creation --- .../org/sufficientlysecure/keychain/service/KeychainIntentService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index be9d126b3..67ce7a395 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -598,7 +598,8 @@ public class KeychainIntentService extends IntentService implements ProgressDial /* Operation */ int keysTotal = 2; int keysCreated =0; - this.setProgress(keysCreated, keysTotal); + setProgress(getApplicationContext().getResources().getQuantityString(R.plurals.progress_generating,keysTotal), + keysCreated, keysTotal); PgpKeyOperation keyOperations = new PgpKeyOperation(this, this); PGPSecretKey masterKey = keyOperations.createKey(Id.choice.algorithm.rsa, -- cgit v1.2.3 From b107766f5b311d9a0d80fd23306a11f41c438c66 Mon Sep 17 00:00:00 2001 From: rafaelav Date: Sat, 8 Mar 2014 12:28:28 +0100 Subject: Issue #178 - Hide advanced options in EncryptActivity --- .../keychain/ui/EncryptActivity.java | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index b486fc151..665035d0c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -52,17 +52,21 @@ import android.os.Message; import android.os.Messenger; import android.view.View; import android.view.View.OnClickListener; +import android.view.animation.AlphaAnimation; +import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; +import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; import com.beardedhen.androidbootstrap.BootstrapButton; +import com.beardedhen.androidbootstrap.FontAwesomeText; import com.devspark.appmsg.AppMsg; public class EncryptActivity extends DrawerActivity { @@ -114,6 +118,11 @@ public class EncryptActivity extends DrawerActivity { private String mInputFilename = null; private String mOutputFilename = null; + private Integer mShortAnimationDuration = null; + private boolean mFileAdvancedSettingsVisible = false; + private TextView mFileAdvancedSettings = null; + private LinearLayout mFileAdvancedSettingsContainer = null; + private FontAwesomeText mAdvancedSettingsIcon; private boolean mAsciiArmorDemand = false; private boolean mOverrideAsciiArmor = false; @@ -148,6 +157,9 @@ public class EncryptActivity extends DrawerActivity { updateMode(); updateActionBarButtons(); + + // retrieve and cache the system's short animation time + mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime); } /** @@ -793,6 +805,50 @@ public class EncryptActivity extends DrawerActivity { } }); + mAdvancedSettingsIcon = (FontAwesomeText) findViewById(R.id.advancedSettingsIcon); + mFileAdvancedSettingsContainer = (LinearLayout) findViewById(R.id.fileAdvancedSettingsContainer); + mFileAdvancedSettings = (TextView) findViewById(R.id.advancedSettings); + + LinearLayout advancedSettingsControl = (LinearLayout) findViewById(R.id.advancedSettingsControl); + advancedSettingsControl.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + mFileAdvancedSettingsVisible = !mFileAdvancedSettingsVisible; + if (mFileAdvancedSettingsVisible) { + mAdvancedSettingsIcon.setIcon("fa-chevron-down"); + mFileAdvancedSettingsContainer.setVisibility(View.VISIBLE); + AlphaAnimation animation = new AlphaAnimation(0f, 1f); + animation.setDuration(mShortAnimationDuration); + mFileAdvancedSettingsContainer.startAnimation(animation); + mFileAdvancedSettings.setText(R.string.btn_encryption_advanced_settings_hide); + + } else { + mAdvancedSettingsIcon.setIcon("fa-chevron-right"); + AlphaAnimation animation = new AlphaAnimation(1f, 0f); + animation.setDuration(mShortAnimationDuration); + animation.setAnimationListener(new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { + // do nothing + } + + @Override + public void onAnimationEnd(Animation animation) { + // making sure that at the end the container is completely removed from view + mFileAdvancedSettingsContainer.setVisibility(View.GONE); + } + + @Override + public void onAnimationRepeat(Animation animation) { + // do nothing + } + }); + mFileAdvancedSettingsContainer.startAnimation(animation); + mFileAdvancedSettings.setText(R.string.btn_encryption_advanced_settings_show); + } + } + }); + mFileCompression = (Spinner) findViewById(R.id.fileCompression); Choice[] choices = new Choice[]{ new Choice(Id.choice.compression.none, getString(R.string.choice_none) + " (" -- cgit v1.2.3 From 8d85aa5876949aec45a908760411790f3601c632 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Sun, 9 Mar 2014 23:51:18 +0100 Subject: remove unneeded replace for newline on fingerprint --- .../java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index f8db19c16..65fe08484 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -261,8 +261,7 @@ public class ViewKeyMainFragment extends Fragment implements // FALLBACK for old database entries fingerprintBlob = ProviderHelper.getFingerprint(getActivity(), mDataUri); } - String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true) - .replace(" ", "\n"); + String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); mFingerprint.setText(colorizeFingerprint(fingerprint)); } -- cgit v1.2.3 From 7d2c3f860e4ce291a4607bee43d4a36ff0093989 Mon Sep 17 00:00:00 2001 From: Sreeram Boyapati Date: Mon, 10 Mar 2014 08:31:53 +0530 Subject: Fix to passphrase dialog and Issue #207 --- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 50 +++++++++++++++++++--- 1 file changed, 44 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 6bcb84f46..95a254bf2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -24,10 +24,13 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.ProviderHelper; +import android.Manifest; import android.app.Activity; +import android.app.ActivityOptions; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; @@ -40,6 +43,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment { private TextView mKeyUserId; private TextView mKeyUserIdRest; + private TextView mKeyMasterKeyIdHex; private BootstrapButton mSelectKeyButton; private Boolean mFilterCertify; @@ -61,26 +65,58 @@ public class SelectSecretKeyLayoutFragment extends Fragment { public void selectKey(long secretKeyId) { if (secretKeyId == Id.key.none) { - mKeyUserId.setText(R.string.api_settings_no_key); + mKeyMasterKeyIdHex.setText(R.string.api_settings_no_key); mKeyUserIdRest.setText(""); + mKeyUserId.setVisibility(View.GONE); + mKeyUserIdRest.setVisibility(View.GONE); + } else { String uid = getResources().getString(R.string.user_id_no_name); String uidExtra = ""; + String masterkeyIdHex = ""; + PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRingByMasterKeyId( getActivity(), secretKeyId); if (keyRing != null) { PGPSecretKey key = PgpKeyHelper.getMasterKey(keyRing); + masterkeyIdHex = PgpKeyHelper.convertKeyIdToHex(secretKeyId); + if (key != null) { String userId = PgpKeyHelper.getMainUserIdSafe(getActivity(), key); - String chunks[] = userId.split(" <", 2); + /*String chunks[] = mUserId.split(" <", 2); uid = chunks[0]; if (chunks.length > 1) { uidExtra = "<" + chunks[1]; - } + }*/ + String[] userIdSplit = PgpKeyHelper.splitUserId(userId); + String userName, userEmail; + + if (userIdSplit[0] != null) { userName = userIdSplit[0]; } + else { userName = "No Name"; } + + if (userIdSplit[1] != null) { userEmail = userIdSplit[1]; } + else { userEmail = "No Email"; } + + mKeyMasterKeyIdHex.setText(masterkeyIdHex); + mKeyUserId.setText(userName); + mKeyUserIdRest.setText(userEmail); + mKeyUserId.setVisibility(View.VISIBLE); + mKeyUserIdRest.setVisibility(View.VISIBLE); } + else{ + mKeyMasterKeyIdHex.setText("No key found for KeyRing"); + mKeyUserId.setVisibility(View.GONE); + mKeyUserIdRest.setVisibility(View.GONE); + + } + } - mKeyUserId.setText(uid); - mKeyUserIdRest.setText(uidExtra); + else{ + mKeyMasterKeyIdHex.setText("No KeyRings found for MasterId: "+secretKeyId); + mKeyUserId.setVisibility(View.GONE); + mKeyUserIdRest.setVisibility(View.GONE); + } + } } @@ -98,6 +134,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment { mKeyUserId = (TextView) view.findViewById(R.id.select_secret_key_user_id); mKeyUserIdRest = (TextView) view.findViewById(R.id.select_secret_key_user_id_rest); + mKeyMasterKeyIdHex = (TextView) view.findViewById(R.id.select_secret_key_master_key_hex); mSelectKeyButton = (BootstrapButton) view .findViewById(R.id.select_secret_key_select_key_button); mFilterCertify = false; @@ -117,6 +154,8 @@ public class SelectSecretKeyLayoutFragment extends Fragment { startActivityForResult(intent, REQUEST_CODE_SELECT_KEY); } + //Select Secret Key Activity delivers the intent which was sent by it using interface to Select + // Secret Key Fragment.Intent contains Master Key Id, User Email, User Name, Master Key Id Hex. @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode & 0xFFFF) { @@ -125,7 +164,6 @@ public class SelectSecretKeyLayoutFragment extends Fragment { if (resultCode == Activity.RESULT_OK) { Bundle bundle = data.getExtras(); secretKeyId = bundle.getLong(SelectSecretKeyActivity.RESULT_EXTRA_MASTER_KEY_ID); - selectKey(secretKeyId); // remove displayed errors -- cgit v1.2.3 From b47f291d1272954a27c5d1313480dd4cc4dbfe05 Mon Sep 17 00:00:00 2001 From: Sreeram Boyapati Date: Mon, 10 Mar 2014 11:49:18 +0530 Subject: ViewHolder Pattern Implemented --- .../keychain/ui/adapter/ImportKeysAdapter.java | 65 +++++++++++++--------- 1 file changed, 39 insertions(+), 26 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index 52186b662..4f7623bce 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -42,7 +42,15 @@ public class ImportKeysAdapter extends ArrayAdapter { protected Activity mActivity; protected List data; + static class ViewHolder{ + private TextView mainUserId; + private TextView mainUserIdRest; + private TextView keyId; + private TextView fingerprint; + private TextView algorithm; + private TextView status; + } public ImportKeysAdapter(Activity activity) { super(activity, -1); mActivity = activity; @@ -86,16 +94,21 @@ public class ImportKeysAdapter extends ArrayAdapter { public View getView(int position, View convertView, ViewGroup parent) { ImportKeysListEntry entry = data.get(position); - - View view = mInflater.inflate(R.layout.import_keys_list_entry, null); - - TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId); - TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest); - TextView keyId = (TextView) view.findViewById(R.id.keyId); - TextView fingerprint = (TextView) view.findViewById(R.id.fingerprint); - TextView algorithm = (TextView) view.findViewById(R.id.algorithm); - TextView status = (TextView) view.findViewById(R.id.status); - + ViewHolder holder; + if(convertView == null) { + holder = new ViewHolder(); + convertView = mInflater.inflate(R.layout.import_keys_list_entry, null); + holder.mainUserId = (TextView) convertView.findViewById(R.id.mainUserId); + holder.mainUserIdRest = (TextView) convertView.findViewById(R.id.mainUserIdRest); + holder.keyId = (TextView) convertView.findViewById(R.id.keyId); + holder.fingerprint = (TextView) convertView.findViewById(R.id.fingerprint); + holder.algorithm = (TextView) convertView.findViewById(R.id.algorithm); + holder.status = (TextView) convertView.findViewById(R.id.status); + convertView.setTag(holder); + } + else{ + holder = (ViewHolder)convertView.getTag(); + } // main user id String userId = entry.userIds.get(0); String[] userIdSplit = PgpKeyHelper.splitUserId(userId); @@ -105,39 +118,39 @@ public class ImportKeysAdapter extends ArrayAdapter { // show red user id if it is a secret key if (entry.secretKey) { userIdSplit[0] = mActivity.getString(R.string.secret_key) + " " + userIdSplit[0]; - mainUserId.setTextColor(Color.RED); + holder.mainUserId.setTextColor(Color.RED); } - mainUserId.setText(userIdSplit[0]); + holder.mainUserId.setText(userIdSplit[0]); } else { - mainUserId.setText(R.string.user_id_no_name); + holder.mainUserId.setText(R.string.user_id_no_name); } // email if (userIdSplit[1] != null) { - mainUserIdRest.setText(userIdSplit[1]); - mainUserIdRest.setVisibility(View.VISIBLE); + holder.mainUserIdRest.setText(userIdSplit[1]); + holder.mainUserIdRest.setVisibility(View.VISIBLE); } else { - mainUserIdRest.setVisibility(View.GONE); + holder.mainUserIdRest.setVisibility(View.GONE); } - keyId.setText(entry.hexKeyId); + holder.keyId.setText(entry.hexKeyId); if (entry.fingerPrint != null) { - fingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrint); - fingerprint.setVisibility(View.VISIBLE); + holder.fingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrint); + holder.fingerprint.setVisibility(View.VISIBLE); } else { - fingerprint.setVisibility(View.GONE); + holder.fingerprint.setVisibility(View.GONE); } - algorithm.setText("" + entry.bitStrength + "/" + entry.algorithm); + holder.algorithm.setText("" + entry.bitStrength + "/" + entry.algorithm); if (entry.revoked) { - status.setText(R.string.revoked); + holder.status.setText(R.string.revoked); } else { - status.setVisibility(View.GONE); + holder.status.setVisibility(View.GONE); } - LinearLayout ll = (LinearLayout) view.findViewById(R.id.list); + LinearLayout ll = (LinearLayout) convertView.findViewById(R.id.list); if (entry.userIds.size() == 1) { ll.setVisibility(View.GONE); } else { @@ -162,10 +175,10 @@ public class ImportKeysAdapter extends ArrayAdapter { } } - CheckBox cBox = (CheckBox) view.findViewById(R.id.selected); + CheckBox cBox = (CheckBox) convertView.findViewById(R.id.selected); cBox.setChecked(entry.isSelected()); - return view; + return convertView; } } -- cgit v1.2.3 From b927c0f26ace30651b3cb9df9d71741745563aaf Mon Sep 17 00:00:00 2001 From: Miroojin Bakshi Date: Mon, 10 Mar 2014 15:25:09 +0530 Subject: Highlight search query in SelectPublicKeyFragment and KeyListPublicFragment --- .../keychain/ui/KeyListPublicFragment.java | 2 +- .../keychain/ui/SelectPublicKeyFragment.java | 1 + .../keychain/ui/adapter/KeyListPublicAdapter.java | 35 +++++++++++++++++++- .../ui/adapter/SelectKeyCursorAdapter.java | 37 +++++++++++++++++++++- 4 files changed, 72 insertions(+), 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 40a016f55..59dd31a21 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -272,8 +272,8 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer public void onLoadFinished(Loader loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) + mAdapter.setSearchQuery(mCurQuery); mAdapter.swapCursor(data); - mStickyList.setAdapter(mAdapter); // NOTE: Not supported by StickyListHeader, but reimplemented here diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java index 6e338979a..c1c9aa705 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java @@ -311,6 +311,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T public void onLoadFinished(Loader loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) + mAdapter.setSearchQuery(mCurQuery); mAdapter.swapCursor(data); // The list should now be shown. diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java index 086d2c178..dcc368e7b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java @@ -19,6 +19,8 @@ package org.sufficientlysecure.keychain.ui.adapter; import java.util.HashMap; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; @@ -33,6 +35,9 @@ import android.content.Context; import android.database.Cursor; import android.graphics.Color; import android.support.v4.widget.CursorAdapter; +import android.text.Html; +import android.text.Spannable; +import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -46,13 +51,14 @@ public class KeyListPublicAdapter extends CursorAdapter implements StickyListHea private int mSectionColumnIndex; private int mIndexUserId; private int mIndexIsRevoked; + private String mCurQuery; @SuppressLint("UseSparseArrays") private HashMap mSelection = new HashMap(); public KeyListPublicAdapter(Context context, Cursor c, int flags, int sectionColumnIndex) { super(context, c, flags); - + mCurQuery = null; mInflater = LayoutInflater.from(context); mSectionColumnIndex = sectionColumnIndex; initIndex(c); @@ -78,6 +84,10 @@ public class KeyListPublicAdapter extends CursorAdapter implements StickyListHea } } + public void setSearchQuery(String searchQuery){ + mCurQuery = searchQuery; + } + /** * Bind cursor data to the item list view *

@@ -110,6 +120,10 @@ public class KeyListPublicAdapter extends CursorAdapter implements StickyListHea } else { revoked.setVisibility(View.GONE); } + if(mCurQuery != null){ + mainUserId.setText(highlightSearchKey(userIdSplit[0])); + mainUserIdRest.setText(highlightSearchKey(userIdSplit[1])); + } } @Override @@ -228,5 +242,24 @@ public class KeyListPublicAdapter extends CursorAdapter implements StickyListHea } return v; } + private Spannable highlightSearchKey(String text) { + Spannable highlight; + Pattern pattern; + Matcher matcher; + String orig_str; + + orig_str = Html.fromHtml(text).toString(); + highlight = (Spannable) Html.fromHtml(text); + pattern = Pattern.compile("(?i)" + mCurQuery); + matcher = pattern.matcher(orig_str); + if (matcher.find()) { + highlight.setSpan( + new ForegroundColorSpan(0xFF33B5E5), + matcher.start(), + matcher.end(), + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + return highlight; + } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java index d44dd5890..03010f7a2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java @@ -26,6 +26,9 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; +import android.text.Html; +import android.text.Spannable; +import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -33,6 +36,9 @@ import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class SelectKeyCursorAdapter extends CursorAdapter { protected int mKeyType; @@ -47,6 +53,7 @@ public class SelectKeyCursorAdapter extends CursorAdapter { public final static String PROJECTION_ROW_AVAILABLE = "available"; public final static String PROJECTION_ROW_VALID = "valid"; + private String mCurQuery; public SelectKeyCursorAdapter(Context context, Cursor c, int flags, ListView listView, int keyType) { @@ -55,7 +62,7 @@ public class SelectKeyCursorAdapter extends CursorAdapter { mInflater = LayoutInflater.from(context); mListView = listView; mKeyType = keyType; - + mCurQuery = null; initIndex(c); } @@ -158,6 +165,11 @@ public class SelectKeyCursorAdapter extends CursorAdapter { mainUserIdRest.setEnabled(valid); keyId.setEnabled(valid); status.setEnabled(valid); + + if(mCurQuery != null){ + mainUserId.setText(highlightSearchKey(userIdSplit[0])); + mainUserIdRest.setText(highlightSearchKey(userIdSplit[1])); + } } @Override @@ -165,4 +177,27 @@ public class SelectKeyCursorAdapter extends CursorAdapter { return mInflater.inflate(R.layout.select_key_item, null); } + public void setSearchQuery(String searchQuery){ + mCurQuery = searchQuery; + } + + private Spannable highlightSearchKey(String text) { + Spannable highlight; + Pattern pattern; + Matcher matcher; + String orig_str; + + orig_str = Html.fromHtml(text).toString(); + highlight = (Spannable) Html.fromHtml(text); + pattern = Pattern.compile("(?i)" + mCurQuery); + matcher = pattern.matcher(orig_str); + if (matcher.find()) { + highlight.setSpan( + new ForegroundColorSpan(0xFF33B5E5), + matcher.start(), + matcher.end(), + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + return highlight; + } } -- cgit v1.2.3 From 2b4b09d13c1592adc617bda39cc44f632481fc2b Mon Sep 17 00:00:00 2001 From: Tharindu Wijewardane Date: Mon, 10 Mar 2014 17:10:16 +0530 Subject: Issue #378 ( private keys are no longer red ): Fixed --- .../sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java | 3 +++ 1 file changed, 3 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index f764b879c..ac1f582f1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -155,6 +155,9 @@ public class ImportKeysListEntry implements Serializable, Parcelable { if ( !(pgpKeyRing instanceof PGPSecretKeyRing) ) { secretKey = false; } + else{ + secretKey = true; + } userIds = new ArrayList(); for (String userId : new IterableIterator(pgpKeyRing.getPublicKey().getUserIDs())) { -- cgit v1.2.3 From 98da2d0c48eec809009e4c129ef13dd4a6f93cc3 Mon Sep 17 00:00:00 2001 From: Miroojin Bakshi Date: Mon, 10 Mar 2014 21:10:04 +0530 Subject: Create custom HighlightQueryCursorAdapter --- .../ui/adapter/HighlightQueryCursorAdapter.java | 61 ++++++++++++++++++++++ .../keychain/ui/adapter/KeyListPublicAdapter.java | 38 ++------------ .../ui/adapter/SelectKeyCursorAdapter.java | 39 ++------------ 3 files changed, 70 insertions(+), 68 deletions(-) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java new file mode 100644 index 000000000..1c41cbf03 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java @@ -0,0 +1,61 @@ +package org.sufficientlysecure.keychain.ui.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.database.Cursor; +import android.text.Spannable; +import android.text.style.ForegroundColorSpan; +import android.view.View; +import android.view.ViewGroup; +import android.support.v4.widget.CursorAdapter; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class HighlightQueryCursorAdapter extends CursorAdapter { + + private String mCurQuery; + + public HighlightQueryCursorAdapter(Context context, Cursor c, int flags) { + super(context, c, flags); + mCurQuery = null; + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return null; + } + + + @Override + public void bindView(View view, Context context, Cursor cursor) { + + } + + public void setSearchQuery(String searchQuery){ + mCurQuery = searchQuery; + } + + public String getSearchQuery(){ + return mCurQuery; + } + + protected Spannable highlightSearchKey(String text) { + Spannable highlight; + Pattern pattern; + Matcher matcher; + + highlight = Spannable.Factory.getInstance().newSpannable(text);; + pattern = Pattern.compile("(?i)" + mCurQuery); + matcher = pattern.matcher(text); + if (matcher.find()) { + highlight.setSpan( + new ForegroundColorSpan(0xFF33B5E5), + matcher.start(), + matcher.end(), + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + return highlight; + } +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java index dcc368e7b..888284ec0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java @@ -19,8 +19,7 @@ package org.sufficientlysecure.keychain.ui.adapter; import java.util.HashMap; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; + import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; @@ -34,10 +33,6 @@ import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.graphics.Color; -import android.support.v4.widget.CursorAdapter; -import android.text.Html; -import android.text.Spannable; -import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -46,19 +41,17 @@ import android.widget.TextView; /** * Implements StickyListHeadersAdapter from library */ -public class KeyListPublicAdapter extends CursorAdapter implements StickyListHeadersAdapter { +public class KeyListPublicAdapter extends HighlightQueryCursorAdapter implements StickyListHeadersAdapter { private LayoutInflater mInflater; private int mSectionColumnIndex; private int mIndexUserId; private int mIndexIsRevoked; - private String mCurQuery; @SuppressLint("UseSparseArrays") private HashMap mSelection = new HashMap(); public KeyListPublicAdapter(Context context, Cursor c, int flags, int sectionColumnIndex) { super(context, c, flags); - mCurQuery = null; mInflater = LayoutInflater.from(context); mSectionColumnIndex = sectionColumnIndex; initIndex(c); @@ -84,10 +77,6 @@ public class KeyListPublicAdapter extends CursorAdapter implements StickyListHea } } - public void setSearchQuery(String searchQuery){ - mCurQuery = searchQuery; - } - /** * Bind cursor data to the item list view *

@@ -120,7 +109,9 @@ public class KeyListPublicAdapter extends CursorAdapter implements StickyListHea } else { revoked.setVisibility(View.GONE); } - if(mCurQuery != null){ + String query = getSearchQuery(); + + if(query != null){ mainUserId.setText(highlightSearchKey(userIdSplit[0])); mainUserIdRest.setText(highlightSearchKey(userIdSplit[1])); } @@ -242,24 +233,5 @@ public class KeyListPublicAdapter extends CursorAdapter implements StickyListHea } return v; } - private Spannable highlightSearchKey(String text) { - Spannable highlight; - Pattern pattern; - Matcher matcher; - String orig_str; - - orig_str = Html.fromHtml(text).toString(); - highlight = (Spannable) Html.fromHtml(text); - pattern = Pattern.compile("(?i)" + mCurQuery); - matcher = pattern.matcher(orig_str); - if (matcher.find()) { - highlight.setSpan( - new ForegroundColorSpan(0xFF33B5E5), - matcher.start(), - matcher.end(), - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - } - return highlight; - } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java index 03010f7a2..a7ef0785b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java @@ -25,10 +25,6 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; import android.content.Context; import android.database.Cursor; -import android.support.v4.widget.CursorAdapter; -import android.text.Html; -import android.text.Spannable; -import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -36,10 +32,9 @@ import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -public class SelectKeyCursorAdapter extends CursorAdapter { + +public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { protected int mKeyType; @@ -53,7 +48,6 @@ public class SelectKeyCursorAdapter extends CursorAdapter { public final static String PROJECTION_ROW_AVAILABLE = "available"; public final static String PROJECTION_ROW_VALID = "valid"; - private String mCurQuery; public SelectKeyCursorAdapter(Context context, Cursor c, int flags, ListView listView, int keyType) { @@ -62,7 +56,6 @@ public class SelectKeyCursorAdapter extends CursorAdapter { mInflater = LayoutInflater.from(context); mListView = listView; mKeyType = keyType; - mCurQuery = null; initIndex(c); } @@ -165,8 +158,8 @@ public class SelectKeyCursorAdapter extends CursorAdapter { mainUserIdRest.setEnabled(valid); keyId.setEnabled(valid); status.setEnabled(valid); - - if(mCurQuery != null){ + String query = getSearchQuery(); + if(query != null){ mainUserId.setText(highlightSearchKey(userIdSplit[0])); mainUserIdRest.setText(highlightSearchKey(userIdSplit[1])); } @@ -176,28 +169,4 @@ public class SelectKeyCursorAdapter extends CursorAdapter { public View newView(Context context, Cursor cursor, ViewGroup parent) { return mInflater.inflate(R.layout.select_key_item, null); } - - public void setSearchQuery(String searchQuery){ - mCurQuery = searchQuery; - } - - private Spannable highlightSearchKey(String text) { - Spannable highlight; - Pattern pattern; - Matcher matcher; - String orig_str; - - orig_str = Html.fromHtml(text).toString(); - highlight = (Spannable) Html.fromHtml(text); - pattern = Pattern.compile("(?i)" + mCurQuery); - matcher = pattern.matcher(orig_str); - if (matcher.find()) { - highlight.setSpan( - new ForegroundColorSpan(0xFF33B5E5), - matcher.start(), - matcher.end(), - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - } - return highlight; - } } -- cgit v1.2.3 From 2166d6668079035fa2fbf7e16863fadccbe294c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 17:06:11 +0100 Subject: Cleanup ImportKeysListEntry --- .../keychain/ui/adapter/ImportKeysListEntry.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index ac1f582f1..a52e9b447 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -125,7 +125,10 @@ public class ImportKeysListEntry implements Serializable, Parcelable { * Constructor for later querying from keyserver */ public ImportKeysListEntry() { + // keys from keyserver are always public keys secretKey = false; + // do not select by default + selected = false; userIds = new ArrayList(); } @@ -152,11 +155,10 @@ public class ImportKeysListEntry implements Serializable, Parcelable { // selected is default this.selected = true; - if ( !(pgpKeyRing instanceof PGPSecretKeyRing) ) { - secretKey = false; - } - else{ + if (pgpKeyRing instanceof PGPSecretKeyRing) { secretKey = true; + } else { + secretKey = false; } userIds = new ArrayList(); -- cgit v1.2.3 From caa0740919f2acae636dfdd6bdcd971a3bf6473c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 17:22:19 +0100 Subject: Improve hightlight query code: make cursor abstract, tidy up code --- .../ui/adapter/HighlightQueryCursorAdapter.java | 73 ++++++++++++---------- .../keychain/ui/adapter/KeyListPublicAdapter.java | 17 ++--- .../keychain/ui/adapter/KeyListSecretAdapter.java | 7 ++- .../ui/adapter/SelectKeyCursorAdapter.java | 9 +-- 4 files changed, 51 insertions(+), 55 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java index 1c41cbf03..fd7a2dc30 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java @@ -1,19 +1,34 @@ +/* + * Copyright (C) 2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + package org.sufficientlysecure.keychain.ui.adapter; -import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; +import android.support.v4.widget.CursorAdapter; import android.text.Spannable; import android.text.style.ForegroundColorSpan; -import android.view.View; -import android.view.ViewGroup; -import android.support.v4.widget.CursorAdapter; + +import org.sufficientlysecure.keychain.R; import java.util.regex.Matcher; import java.util.regex.Pattern; - -public class HighlightQueryCursorAdapter extends CursorAdapter { +public abstract class HighlightQueryCursorAdapter extends CursorAdapter { private String mCurQuery; @@ -22,40 +37,30 @@ public class HighlightQueryCursorAdapter extends CursorAdapter { mCurQuery = null; } - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return null; - } - - - @Override - public void bindView(View view, Context context, Cursor cursor) { - - } - - public void setSearchQuery(String searchQuery){ + public void setSearchQuery(String searchQuery) { mCurQuery = searchQuery; } - public String getSearchQuery(){ + public String getSearchQuery() { return mCurQuery; } - protected Spannable highlightSearchKey(String text) { - Spannable highlight; - Pattern pattern; - Matcher matcher; - - highlight = Spannable.Factory.getInstance().newSpannable(text);; - pattern = Pattern.compile("(?i)" + mCurQuery); - matcher = pattern.matcher(text); - if (matcher.find()) { - highlight.setSpan( - new ForegroundColorSpan(0xFF33B5E5), - matcher.start(), - matcher.end(), - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + protected Spannable highlightSearchQuery(String text) { + Spannable highlight = Spannable.Factory.getInstance().newSpannable(text); + + if (mCurQuery != null) { + Pattern pattern = Pattern.compile("(?i)" + mCurQuery); + Matcher matcher = pattern.matcher(text); + if (matcher.find()) { + highlight.setSpan( + new ForegroundColorSpan(mContext.getResources().getColor(R.color.emphasis)), + matcher.start(), + matcher.end(), + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + return highlight; + } else { + return highlight; } - return highlight; } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java index 888284ec0..0cd2606a1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java @@ -92,12 +92,12 @@ public class KeyListPublicAdapter extends HighlightQueryCursorAdapter implements String userId = cursor.getString(mIndexUserId); String[] userIdSplit = PgpKeyHelper.splitUserId(userId); if (userIdSplit[0] != null) { - mainUserId.setText(userIdSplit[0]); + mainUserId.setText(highlightSearchQuery(userIdSplit[0])); } else { mainUserId.setText(R.string.user_id_no_name); } if (userIdSplit[1] != null) { - mainUserIdRest.setText(userIdSplit[1]); + mainUserIdRest.setText(highlightSearchQuery(userIdSplit[1])); mainUserIdRest.setVisibility(View.VISIBLE); } else { mainUserIdRest.setVisibility(View.GONE); @@ -109,12 +109,6 @@ public class KeyListPublicAdapter extends HighlightQueryCursorAdapter implements } else { revoked.setVisibility(View.GONE); } - String query = getSearchQuery(); - - if(query != null){ - mainUserId.setText(highlightSearchKey(userIdSplit[0])); - mainUserIdRest.setText(highlightSearchKey(userIdSplit[1])); - } } @Override @@ -225,11 +219,12 @@ public class KeyListPublicAdapter extends HighlightQueryCursorAdapter implements /** * Change color for multi-selection */ - // default color - v.setBackgroundColor(Color.TRANSPARENT); if (mSelection.get(position) != null && mSelection.get(position).booleanValue()) { - // this is a selected position, change color! + // color for selected items v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); + } else { + // default color + v.setBackgroundColor(Color.TRANSPARENT); } return v; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java index 11d1e8c17..a86508597 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java @@ -126,11 +126,12 @@ public class KeyListSecretAdapter extends CursorAdapter { /** * Change color for multi-selection */ - // default color - v.setBackgroundColor(Color.TRANSPARENT); if (mSelection.get(position) != null) { - // this is a selected position, change color! + // color for selected items v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); + } else { + // default color + v.setBackgroundColor(Color.TRANSPARENT); } return v; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java index a7ef0785b..6d67a0e65 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java @@ -104,12 +104,12 @@ public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { String[] userIdSplit = PgpKeyHelper.splitUserId(userId); if (userIdSplit[0] != null) { - mainUserId.setText(userIdSplit[0]); + mainUserId.setText(highlightSearchQuery(userIdSplit[0])); } else { mainUserId.setText(R.string.user_id_no_name); } if (userIdSplit[1] != null) { - mainUserIdRest.setText(userIdSplit[1]); + mainUserIdRest.setText(highlightSearchQuery(userIdSplit[1])); } else { mainUserIdRest.setText(""); } @@ -158,11 +158,6 @@ public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { mainUserIdRest.setEnabled(valid); keyId.setEnabled(valid); status.setEnabled(valid); - String query = getSearchQuery(); - if(query != null){ - mainUserId.setText(highlightSearchKey(userIdSplit[0])); - mainUserIdRest.setText(highlightSearchKey(userIdSplit[1])); - } } @Override -- cgit v1.2.3 From e00436b4096466af37b3e32c3f3277c3604d85ee Mon Sep 17 00:00:00 2001 From: Bhargav Golla Date: Fri, 7 Mar 2014 18:21:16 -0500 Subject: Lint changes Deleting lint-report gen files Adding lint output files to gitignore --- .../main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java index 75a885bdd..f1516faaa 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java @@ -30,6 +30,7 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.util.Choice; +import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; @@ -110,6 +111,7 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { setExpiryDate(null); mExpiryDateButton.setOnClickListener(new OnClickListener() { + @TargetApi(11) public void onClick(View v) { GregorianCalendar date = mExpiryDate; if (date == null) { -- cgit v1.2.3 From 83c346fec447a6748848938e994e19997d29092c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 17:49:30 +0100 Subject: Make code more tidy for multiselect --- .../keychain/ui/KeyListPublicFragment.java | 18 +++++------------- .../keychain/ui/KeyListSecretFragment.java | 16 ++++------------ .../keychain/ui/adapter/KeyListPublicAdapter.java | 9 --------- .../keychain/ui/adapter/KeyListSecretAdapter.java | 11 +---------- 4 files changed, 10 insertions(+), 44 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 59dd31a21..c2b21027c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -171,15 +171,8 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - Set positions = mAdapter.getCurrentCheckedPosition(); - - // get IDs for checked positions as long array - long[] ids = new long[positions.size()]; - int i = 0; - for (int pos : positions) { - ids[i] = mAdapter.getItemId(pos); - i++; - } + // get row ids for checked positions as long array + long[] ids = mStickyList.getCheckedItemIds(); switch (item.getItemId()) { case R.id.menu_key_list_public_multi_encrypt: { @@ -192,9 +185,8 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer } case R.id.menu_key_list_public_multi_select_all: { //Select all - int localCount = mStickyList.getCount(); - for (int k = 0; k < localCount; k++) { - mStickyList.setItemChecked(k, true); + for (int i = 0; i < mStickyList.getCount(); i++) { + mStickyList.setItemChecked(i, true); } break; } @@ -215,7 +207,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer } else { mAdapter.removeSelection(position); } - int count = mAdapter.getCurrentCheckedPosition().size(); + int count = mStickyList.getCheckedItemCount(); String keysSelected = getResources().getQuantityString( R.plurals.key_list_selected_keys, count, count); mode.setTitle(keysSelected); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java index 9a5477762..76212afc3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java @@ -91,15 +91,8 @@ public class KeyListSecretFragment extends ListFragment implements @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - Set positions = mAdapter.getCurrentCheckedPosition(); - - // get IDs for checked positions as long array - long[] ids = new long[positions.size()]; - int i = 0; - for (int pos : positions) { - ids[i] = mAdapter.getItemId(pos); - i++; - } + // get row ids for checked positions as long array + long[] ids = getListView().getCheckedItemIds(); switch (item.getItemId()) { case R.id.menu_key_list_public_multi_delete: { @@ -108,9 +101,8 @@ public class KeyListSecretFragment extends ListFragment implements } case R.id.menu_key_list_public_multi_select_all: { //Select all - int localCount = getListView().getCount(); - for (int k = 0; k < localCount; k++) { - getListView().setItemChecked(k, true); + for (int i = 0; i < getListView().getCount(); i++) { + getListView().setItemChecked(i, true); } break; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java index 0cd2606a1..b8f60633e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java @@ -192,15 +192,6 @@ public class KeyListPublicAdapter extends HighlightQueryCursorAdapter implements notifyDataSetChanged(); } - public boolean isPositionChecked(int position) { - Boolean result = mSelection.get(position); - return result == null ? false : result; - } - - public Set getCurrentCheckedPosition() { - return mSelection.keySet(); - } - public void removeSelection(int position) { mSelection.remove(position); notifyDataSetChanged(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java index a86508597..ca3a26066 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java @@ -98,16 +98,7 @@ public class KeyListSecretAdapter extends CursorAdapter { mSelection.put(position, value); notifyDataSetChanged(); } - - public boolean isPositionChecked(int position) { - Boolean result = mSelection.get(position); - return result == null ? false : result; - } - - public Set getCurrentCheckedPosition() { - return mSelection.keySet(); - } - + public void removeSelection(int position) { mSelection.remove(position); notifyDataSetChanged(); -- cgit v1.2.3 From a41ee31b6c5cfbef067efb0843593a2459861b9c Mon Sep 17 00:00:00 2001 From: Sreeram Boyapati Date: Mon, 10 Mar 2014 22:37:23 +0530 Subject: Added string reference for Issue #207 --- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 95a254bf2..ca5d8b262 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -92,10 +92,10 @@ public class SelectSecretKeyLayoutFragment extends Fragment { String userName, userEmail; if (userIdSplit[0] != null) { userName = userIdSplit[0]; } - else { userName = "No Name"; } + else { userName = getActivity().getResources().getString(R.string.user_id_no_name); } if (userIdSplit[1] != null) { userEmail = userIdSplit[1]; } - else { userEmail = "No Email"; } + else { userEmail = getActivity().getResources().getString(R.string.error_user_id_no_email); } mKeyMasterKeyIdHex.setText(masterkeyIdHex); mKeyUserId.setText(userName); @@ -104,7 +104,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment { mKeyUserIdRest.setVisibility(View.VISIBLE); } else{ - mKeyMasterKeyIdHex.setText("No key found for KeyRing"); + mKeyMasterKeyIdHex.setText(getActivity().getResources().getString(R.string.no_key)); mKeyUserId.setVisibility(View.GONE); mKeyUserIdRest.setVisibility(View.GONE); @@ -112,7 +112,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment { } else{ - mKeyMasterKeyIdHex.setText("No KeyRings found for MasterId: "+secretKeyId); + mKeyMasterKeyIdHex.setText(getActivity().getResources().getString(R.string.no_keys_added_or_updated)+" for master id: "+secretKeyId); mKeyUserId.setVisibility(View.GONE); mKeyUserIdRest.setVisibility(View.GONE); } -- cgit v1.2.3 From d91e2673d7b291e1798e1acee506749eae3cdd01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 18:23:47 +0100 Subject: Revert "Lint changes" This reverts commit e00436b4096466af37b3e32c3f3277c3604d85ee. --- .../main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java | 2 -- 1 file changed, 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java index 9f25fac42..65461cb4f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java @@ -30,7 +30,6 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.util.Choice; -import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; @@ -111,7 +110,6 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { setExpiryDate(null); mExpiryDateButton.setOnClickListener(new OnClickListener() { - @TargetApi(11) public void onClick(View v) { GregorianCalendar date = mExpiryDate; if (date == null) { -- cgit v1.2.3 From b90e680ff91ae12e9ae31682b1ab118d6c49ab7e Mon Sep 17 00:00:00 2001 From: Bhargav Golla Date: Mon, 10 Mar 2014 14:59:15 -0400 Subject: Lint changes after testing --- .../sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java | 1 - .../main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java index 6c62d14e0..d63d866fd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java @@ -120,7 +120,6 @@ public class ProgressDialogFragment extends DialogFragment { int messageId = getArguments().getInt(ARG_MESSAGE_ID); int style = getArguments().getInt(ARG_STYLE); boolean cancelable = getArguments().getBoolean(ARG_CANCELABLE); - dialog.setMessage(getString(messageId)); dialog.setProgressStyle(style); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java index 65461cb4f..9f25fac42 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java @@ -30,6 +30,7 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.util.Choice; +import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; @@ -110,6 +111,7 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { setExpiryDate(null); mExpiryDateButton.setOnClickListener(new OnClickListener() { + @TargetApi(11) public void onClick(View v) { GregorianCalendar date = mExpiryDate; if (date == null) { -- cgit v1.2.3 From 6fab8a126a6f5e71ec921d4d45f279fb16a8b7da Mon Sep 17 00:00:00 2001 From: Daniel Hammann Date: Mon, 10 Mar 2014 20:58:15 +0100 Subject: Reset cursor query when closing search view #386 Without focus the search result get erased. --- .../sufficientlysecure/keychain/ui/KeyListPublicFragment.java | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index c2b21027c..92c6262b6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -367,6 +367,16 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer // Execute this when searching mSearchView.setOnQueryTextListener(this); + //Erase search result without focus + mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + if (!hasFocus) { + mCurQuery = null; + getLoaderManager().restartLoader(0, null, KeyListPublicFragment.this); + } + } + }); super.onCreateOptionsMenu(menu, inflater); } -- cgit v1.2.3 From be41a0a3e13dde2f3f21d4c49e23285966799507 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 22:19:43 +0100 Subject: Fix progress_generating and reformat --- .../keychain/service/KeychainIntentService.java | 10 +- .../service/KeychainIntentServiceHandler.java | 21 ++++- .../keychain/ui/EditKeyActivity.java | 3 +- .../ui/dialog/DeleteFileDialogFragment.java | 7 +- .../keychain/ui/dialog/ProgressDialogFragment.java | 12 +-- .../keychain/ui/widget/SectionView.java | 101 +++++++++++---------- 6 files changed, 93 insertions(+), 61 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 67ce7a395..12ad694c9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -597,9 +597,11 @@ public class KeychainIntentService extends IntentService implements ProgressDial /* Operation */ int keysTotal = 2; - int keysCreated =0; - setProgress(getApplicationContext().getResources().getQuantityString(R.plurals.progress_generating,keysTotal), - keysCreated, keysTotal); + int keysCreated = 0; + setProgress( + getResources().getQuantityString(R.plurals.progress_generating, keysTotal), + keysCreated, + keysTotal); PgpKeyOperation keyOperations = new PgpKeyOperation(this, this); PGPSecretKey masterKey = keyOperations.createKey(Id.choice.algorithm.rsa, @@ -610,7 +612,7 @@ public class KeychainIntentService extends IntentService implements ProgressDial PGPSecretKey subKey = keyOperations.createKey(Id.choice.algorithm.rsa, 4096, passphrase, false); keysCreated++; - setProgress(keysCreated, keysTotal ); + setProgress(keysCreated, keysTotal); // TODO: default to one master for cert, one sub for encrypt and one sub // for sign diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java index 65c756f9a..c3de39235 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java @@ -55,6 +55,10 @@ public class KeychainIntentServiceHandler extends Handler { this.mProgressDialogFragment = progressDialogFragment; } + public KeychainIntentServiceHandler(Activity activity, String progressDialogMessage, int progressDialogStyle) { + this(activity, progressDialogMessage, progressDialogStyle, false, null); + } + public KeychainIntentServiceHandler(Activity activity, int progressDialogMessageId, int progressDialogStyle) { this(activity, progressDialogMessageId, progressDialogStyle, false, null); } @@ -62,9 +66,22 @@ public class KeychainIntentServiceHandler extends Handler { public KeychainIntentServiceHandler(Activity activity, int progressDialogMessageId, int progressDialogStyle, boolean cancelable, OnCancelListener onCancelListener) { + this(activity, + activity.getString(progressDialogMessageId), + progressDialogStyle, + cancelable, + onCancelListener); + } + + public KeychainIntentServiceHandler(Activity activity, String progressDialogMessage, + int progressDialogStyle, boolean cancelable, + OnCancelListener onCancelListener) { this.mActivity = activity; - this.mProgressDialogFragment = ProgressDialogFragment.newInstance(progressDialogMessageId, - progressDialogStyle, cancelable, onCancelListener); + this.mProgressDialogFragment = ProgressDialogFragment.newInstance( + progressDialogMessage, + progressDialogStyle, + cancelable, + onCancelListener); } public void showProgressDialog(FragmentActivity activity) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 2507a77b1..ddeb8846f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -187,7 +187,8 @@ public class EditKeyActivity extends ActionBarActivity { // Message is received after generating is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler( - this, R.string.progress_generating, ProgressDialog.STYLE_HORIZONTAL, true, + this, getResources().getQuantityString(R.plurals.progress_generating, 1), + ProgressDialog.STYLE_HORIZONTAL, true, new DialogInterface.OnCancelListener() { @Override diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java index c4e305984..162bf32fd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java @@ -67,7 +67,7 @@ public class DeleteFileDialogFragment extends DialogFragment { alert.setMessage(this.getString(R.string.file_delete_confirmation, deleteFile)); alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - + @Override public void onClick(DialogInterface dialog, int id) { dismiss(); @@ -83,7 +83,10 @@ public class DeleteFileDialogFragment extends DialogFragment { intent.putExtra(KeychainIntentService.EXTRA_DATA, data); ProgressDialogFragment deletingDialog = ProgressDialogFragment.newInstance( - R.string.progress_deleting_securely, ProgressDialog.STYLE_HORIZONTAL, false, null); + getString(R.string.progress_deleting_securely), + ProgressDialog.STYLE_HORIZONTAL, + false, + null); // Message is received after deleting is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(activity, deletingDialog) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java index 6c62d14e0..90947e42b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java @@ -30,7 +30,7 @@ import android.view.KeyEvent; import org.sufficientlysecure.keychain.R; public class ProgressDialogFragment extends DialogFragment { - private static final String ARG_MESSAGE_ID = "message_id"; + private static final String ARG_MESSAGE = "message_id"; private static final String ARG_STYLE = "style"; private static final String ARG_CANCELABLE = "cancelable"; @@ -39,16 +39,16 @@ public class ProgressDialogFragment extends DialogFragment { /** * Creates new instance of this fragment * - * @param messageId + * @param message * @param style * @param cancelable * @return */ - public static ProgressDialogFragment newInstance(int messageId, int style, boolean cancelable, + public static ProgressDialogFragment newInstance(String message, int style, boolean cancelable, OnCancelListener onCancelListener) { ProgressDialogFragment frag = new ProgressDialogFragment(); Bundle args = new Bundle(); - args.putInt(ARG_MESSAGE_ID, messageId); + args.putString(ARG_MESSAGE, message); args.putInt(ARG_STYLE, style); args.putBoolean(ARG_CANCELABLE, cancelable); @@ -117,11 +117,11 @@ public class ProgressDialogFragment extends DialogFragment { dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); - int messageId = getArguments().getInt(ARG_MESSAGE_ID); + String message = getArguments().getString(ARG_MESSAGE); int style = getArguments().getInt(ARG_STYLE); boolean cancelable = getArguments().getBoolean(ARG_CANCELABLE); - dialog.setMessage(getString(messageId)); + dialog.setMessage(message); dialog.setProgressStyle(style); if (cancelable) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java index 99622106f..0acfe13bc 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java @@ -80,19 +80,19 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor public void setType(int type) { mType = type; switch (type) { - case Id.type.user_id: { - mTitle.setText(R.string.section_user_ids); - break; - } + case Id.type.user_id: { + mTitle.setText(R.string.section_user_ids); + break; + } - case Id.type.key: { - mTitle.setText(R.string.section_keys); - break; - } + case Id.type.key: { + mTitle.setText(R.string.section_keys); + break; + } - default: { - break; - } + default: { + break; + } } } @@ -103,7 +103,9 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override protected void onFinishInflate() { mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); @@ -121,7 +123,9 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor super.onFinishInflate(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ public void onDeleted(Editor editor) { this.updateEditorsVisible(); } @@ -131,38 +135,40 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor mEditors.setVisibility(hasChildren ? View.VISIBLE : View.GONE); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ public void onClick(View v) { if (canEdit) { switch (mType) { - case Id.type.user_id: { - UserIdEditor view = (UserIdEditor) mInflater.inflate( - R.layout.edit_key_user_id_item, mEditors, false); - view.setEditorListener(this); - if (mEditors.getChildCount() == 0) { - view.setIsMainUserId(true); + case Id.type.user_id: { + UserIdEditor view = (UserIdEditor) mInflater.inflate( + R.layout.edit_key_user_id_item, mEditors, false); + view.setEditorListener(this); + if (mEditors.getChildCount() == 0) { + view.setIsMainUserId(true); + } + mEditors.addView(view); + break; } - mEditors.addView(view); - break; - } - case Id.type.key: { - CreateKeyDialogFragment mCreateKeyDialogFragment = CreateKeyDialogFragment.newInstance(mEditors.getChildCount()); - mCreateKeyDialogFragment.setOnAlgorithmSelectedListener(new CreateKeyDialogFragment.OnAlgorithmSelectedListener() { - @Override - public void onAlgorithmSelected(Choice algorithmChoice, int keySize) { - mNewKeyAlgorithmChoice = algorithmChoice; - mNewKeySize = keySize; - createKey(); - } - }); - mCreateKeyDialogFragment.show(mActivity.getSupportFragmentManager(), "createKeyDialog"); - break; - } + case Id.type.key: { + CreateKeyDialogFragment mCreateKeyDialogFragment = CreateKeyDialogFragment.newInstance(mEditors.getChildCount()); + mCreateKeyDialogFragment.setOnAlgorithmSelectedListener(new CreateKeyDialogFragment.OnAlgorithmSelectedListener() { + @Override + public void onAlgorithmSelected(Choice algorithmChoice, int keySize) { + mNewKeyAlgorithmChoice = algorithmChoice; + mNewKeySize = keySize; + createKey(); + } + }); + mCreateKeyDialogFragment.show(mActivity.getSupportFragmentManager(), "createKeyDialog"); + break; + } - default: { - break; - } + default: { + break; + } } this.updateEditorsVisible(); } @@ -238,13 +244,16 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor intent.putExtra(KeychainIntentService.EXTRA_DATA, data); // show progress dialog - mGeneratingDialog = ProgressDialogFragment.newInstance(R.string.progress_generating, - ProgressDialog.STYLE_SPINNER, true, new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - mActivity.stopService(intent); - } - }); + mGeneratingDialog = ProgressDialogFragment.newInstance( + getResources().getQuantityString(R.plurals.progress_generating, 1), + ProgressDialog.STYLE_SPINNER, + true, + new DialogInterface.OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + mActivity.stopService(intent); + } + }); // Message is received after generating is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(mActivity, -- cgit v1.2.3 From bac68c4c730ba033df411215f4982b0dd2d24b1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 22:22:37 +0100 Subject: Fix progress_generating and reformat --- .../org/sufficientlysecure/keychain/service/KeychainIntentService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 12ad694c9..902c66fe9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -599,7 +599,7 @@ public class KeychainIntentService extends IntentService implements ProgressDial int keysTotal = 2; int keysCreated = 0; setProgress( - getResources().getQuantityString(R.plurals.progress_generating, keysTotal), + getApplicationContext().getResources().getQuantityString(R.plurals.progress_generating, keysTotal), keysCreated, keysTotal); PgpKeyOperation keyOperations = new PgpKeyOperation(this, this); -- cgit v1.2.3 From 59091e417ffbd8eb6d66d1ef4fe6ce2505d6577d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 22:37:13 +0100 Subject: getString before init of KeychainIntentHandler --- .../keychain/helper/ExportHelper.java | 2 +- .../service/KeychainIntentServiceHandler.java | 80 +++++++++------------- .../keychain/ui/CertifyKeyActivity.java | 4 +- .../keychain/ui/DecryptActivity.java | 2 +- .../keychain/ui/EditKeyActivity.java | 2 +- .../keychain/ui/EncryptActivity.java | 2 +- .../keychain/ui/ImportKeysActivity.java | 4 +- .../keychain/ui/UploadKeyActivity.java | 2 +- .../keychain/ui/dialog/ProgressDialogFragment.java | 13 ++-- 9 files changed, 49 insertions(+), 62 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 8f2c6c83d..6aa28fec8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -139,7 +139,7 @@ public class ExportHelper { // Message is received after exporting is done in ApgService KeychainIntentServiceHandler exportHandler = new KeychainIntentServiceHandler(activity, - R.string.progress_exporting, ProgressDialog.STYLE_HORIZONTAL) { + activity.getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java index c3de39235..ebc002ceb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java @@ -50,29 +50,17 @@ public class KeychainIntentServiceHandler extends Handler { this.mActivity = activity; } - public KeychainIntentServiceHandler(Activity activity, ProgressDialogFragment progressDialogFragment) { + public KeychainIntentServiceHandler(Activity activity, + ProgressDialogFragment progressDialogFragment) { this.mActivity = activity; this.mProgressDialogFragment = progressDialogFragment; } - public KeychainIntentServiceHandler(Activity activity, String progressDialogMessage, int progressDialogStyle) { + public KeychainIntentServiceHandler(Activity activity, String progressDialogMessage, + int progressDialogStyle) { this(activity, progressDialogMessage, progressDialogStyle, false, null); } - public KeychainIntentServiceHandler(Activity activity, int progressDialogMessageId, int progressDialogStyle) { - this(activity, progressDialogMessageId, progressDialogStyle, false, null); - } - - public KeychainIntentServiceHandler(Activity activity, int progressDialogMessageId, - int progressDialogStyle, boolean cancelable, - OnCancelListener onCancelListener) { - this(activity, - activity.getString(progressDialogMessageId), - progressDialogStyle, - cancelable, - onCancelListener); - } - public KeychainIntentServiceHandler(Activity activity, String progressDialogMessage, int progressDialogStyle, boolean cancelable, OnCancelListener onCancelListener) { @@ -100,43 +88,43 @@ public class KeychainIntentServiceHandler extends Handler { Bundle data = message.getData(); switch (message.arg1) { - case MESSAGE_OKAY: - mProgressDialogFragment.dismissAllowingStateLoss(); + case MESSAGE_OKAY: + mProgressDialogFragment.dismissAllowingStateLoss(); - break; + break; - case MESSAGE_EXCEPTION: - mProgressDialogFragment.dismissAllowingStateLoss(); + case MESSAGE_EXCEPTION: + mProgressDialogFragment.dismissAllowingStateLoss(); - // show error from service - if (data.containsKey(DATA_ERROR)) { - Toast.makeText(mActivity, - mActivity.getString(R.string.error_message, data.getString(DATA_ERROR)), - Toast.LENGTH_SHORT).show(); - } + // show error from service + if (data.containsKey(DATA_ERROR)) { + Toast.makeText(mActivity, + mActivity.getString(R.string.error_message, data.getString(DATA_ERROR)), + Toast.LENGTH_SHORT).show(); + } - break; - - case MESSAGE_UPDATE_PROGRESS: - if (data.containsKey(DATA_PROGRESS) && data.containsKey(DATA_PROGRESS_MAX)) { - - // update progress from service - if (data.containsKey(DATA_MESSAGE)) { - mProgressDialogFragment.setProgress(data.getString(DATA_MESSAGE), - data.getInt(DATA_PROGRESS), data.getInt(DATA_PROGRESS_MAX)); - } else if (data.containsKey(DATA_MESSAGE_ID)) { - mProgressDialogFragment.setProgress(data.getInt(DATA_MESSAGE_ID), - data.getInt(DATA_PROGRESS), data.getInt(DATA_PROGRESS_MAX)); - } else { - mProgressDialogFragment.setProgress(data.getInt(DATA_PROGRESS), - data.getInt(DATA_PROGRESS_MAX)); + break; + + case MESSAGE_UPDATE_PROGRESS: + if (data.containsKey(DATA_PROGRESS) && data.containsKey(DATA_PROGRESS_MAX)) { + + // update progress from service + if (data.containsKey(DATA_MESSAGE)) { + mProgressDialogFragment.setProgress(data.getString(DATA_MESSAGE), + data.getInt(DATA_PROGRESS), data.getInt(DATA_PROGRESS_MAX)); + } else if (data.containsKey(DATA_MESSAGE_ID)) { + mProgressDialogFragment.setProgress(data.getInt(DATA_MESSAGE_ID), + data.getInt(DATA_PROGRESS), data.getInt(DATA_PROGRESS_MAX)); + } else { + mProgressDialogFragment.setProgress(data.getInt(DATA_PROGRESS), + data.getInt(DATA_PROGRESS_MAX)); + } } - } - break; + break; - default: - break; + default: + break; } } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index 9a56d768e..029dda1a0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -230,7 +230,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements // Message is received after signing is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - R.string.progress_signing, ProgressDialog.STYLE_SPINNER) { + getString(R.string.progress_signing), ProgressDialog.STYLE_SPINNER) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); @@ -283,7 +283,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements // Message is received after uploading is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - R.string.progress_exporting, ProgressDialog.STYLE_HORIZONTAL) { + getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index c111ed33b..76acf15b0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -646,7 +646,7 @@ public class DecryptActivity extends DrawerActivity { // Message is received after encrypting is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - R.string.progress_decrypting, ProgressDialog.STYLE_HORIZONTAL) { + getString(R.string.progress_decrypting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index ddeb8846f..334fe5d3a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -544,7 +544,7 @@ public class EditKeyActivity extends ActionBarActivity { // Message is received after saving is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - R.string.progress_saving, ProgressDialog.STYLE_HORIZONTAL) { + getString(R.string.progress_saving), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index 665035d0c..8f8952763 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -617,7 +617,7 @@ public class EncryptActivity extends DrawerActivity { // Message is received after encrypting is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - R.string.progress_encrypting, ProgressDialog.STYLE_HORIZONTAL) { + getString(R.string.progress_encrypting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index 7e31d795e..6fd67ca65 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -362,9 +362,9 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa // Message is received after importing is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - R.string.progress_importing, ProgressDialog.STYLE_HORIZONTAL) { + getString(R.string.progress_importing), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java index 574d837d2..6f0aaa0f0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java @@ -102,7 +102,7 @@ public class UploadKeyActivity extends ActionBarActivity { // Message is received after uploading is done in ApgService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - R.string.progress_exporting, ProgressDialog.STYLE_HORIZONTAL) { + getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java index 90947e42b..b7a1882ef 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java @@ -30,7 +30,7 @@ import android.view.KeyEvent; import org.sufficientlysecure.keychain.R; public class ProgressDialogFragment extends DialogFragment { - private static final String ARG_MESSAGE = "message_id"; + private static final String ARG_MESSAGE = "message"; private static final String ARG_STYLE = "style"; private static final String ARG_CANCELABLE = "cancelable"; @@ -128,11 +128,11 @@ public class ProgressDialogFragment extends DialogFragment { dialog.setButton(DialogInterface.BUTTON_NEGATIVE, activity.getString(R.string.progress_cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - } - }); + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.cancel(); + } + }); } // Disable the back button @@ -140,7 +140,6 @@ public class ProgressDialogFragment extends DialogFragment { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } -- cgit v1.2.3 From 8fa62161df84ab7c7bcba55eb6991c6b5e26ac45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Mon, 10 Mar 2014 22:46:30 +0100 Subject: More fixes for KeychainIntentServiceHandler --- .../keychain/ui/ImportKeysActivity.java | 84 +++++++++++----------- 1 file changed, 43 insertions(+), 41 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index 6fd67ca65..f04a0e227 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -360,51 +360,53 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa // } - // Message is received after importing is done in ApgService - KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - getString(R.string.progress_importing), ProgressDialog.STYLE_HORIZONTAL) { - public void handleMessage(Message message) { - // handle messages by standard KeychainIntentServiceHandler first - super.handleMessage(message); - - if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { - // get returned data bundle - Bundle returnData = message.getData(); - - int added = returnData.getInt(KeychainIntentService.RESULT_IMPORT_ADDED); - int updated = returnData - .getInt(KeychainIntentService.RESULT_IMPORT_UPDATED); - int bad = returnData.getInt(KeychainIntentService.RESULT_IMPORT_BAD); - String toastMessage; - if (added > 0 && updated > 0) { - String addedStr = getResources().getQuantityString( - R.plurals.keys_added_and_updated_1, added, added); - String updatedStr = getResources().getQuantityString( - R.plurals.keys_added_and_updated_2, updated, updated); - toastMessage = addedStr + updatedStr; - } else if (added > 0) { - toastMessage = getResources().getQuantityString(R.plurals.keys_added, - added, added); - } else if (updated > 0) { - toastMessage = getResources().getQuantityString(R.plurals.keys_updated, - updated, updated); - } else { - toastMessage = getString(R.string.no_keys_added_or_updated); - } - AppMsg.makeText(ImportKeysActivity.this, toastMessage, AppMsg.STYLE_INFO) - .show(); - if (bad > 0) { - BadImportKeyDialogFragment badImportKeyDialogFragment = BadImportKeyDialogFragment.newInstance(bad); - badImportKeyDialogFragment.show(getSupportFragmentManager(), "badKeyDialog"); - } - } - } - }; - /** * Import keys with mImportData */ public void importKeys() { + // Message is received after importing is done in ApgService + KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler( + this, + getString(R.string.progress_importing), + ProgressDialog.STYLE_HORIZONTAL) { + public void handleMessage(Message message) { + // handle messages by standard KeychainIntentServiceHandler first + super.handleMessage(message); + + if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { + // get returned data bundle + Bundle returnData = message.getData(); + + int added = returnData.getInt(KeychainIntentService.RESULT_IMPORT_ADDED); + int updated = returnData + .getInt(KeychainIntentService.RESULT_IMPORT_UPDATED); + int bad = returnData.getInt(KeychainIntentService.RESULT_IMPORT_BAD); + String toastMessage; + if (added > 0 && updated > 0) { + String addedStr = getResources().getQuantityString( + R.plurals.keys_added_and_updated_1, added, added); + String updatedStr = getResources().getQuantityString( + R.plurals.keys_added_and_updated_2, updated, updated); + toastMessage = addedStr + updatedStr; + } else if (added > 0) { + toastMessage = getResources().getQuantityString(R.plurals.keys_added, + added, added); + } else if (updated > 0) { + toastMessage = getResources().getQuantityString(R.plurals.keys_updated, + updated, updated); + } else { + toastMessage = getString(R.string.no_keys_added_or_updated); + } + AppMsg.makeText(ImportKeysActivity.this, toastMessage, AppMsg.STYLE_INFO) + .show(); + if (bad > 0) { + BadImportKeyDialogFragment badImportKeyDialogFragment = BadImportKeyDialogFragment.newInstance(bad); + badImportKeyDialogFragment.show(getSupportFragmentManager(), "badKeyDialog"); + } + } + } + }; + if (mListFragment.getKeyBytes() != null || mListFragment.getDataUri() != null) { Log.d(Constants.TAG, "importKeys started"); -- cgit v1.2.3 From 3cad8b6248d136f21ef4bc4697feada299c8a58e Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 11 Mar 2014 00:42:03 +0200 Subject: Appropriate save Icon in EditKeyActivity --- .../keychain/helper/ActionBarHelper.java | 60 ++++++++++++++++++++++ .../keychain/ui/EditKeyActivity.java | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java index b55075e6c..6aa8e7d74 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java @@ -113,4 +113,64 @@ public class ActionBarHelper { actionBar.setCustomView(customActionBarView); } + /** + * Sets custom view on ActionBar for Save activities + * + * @param actionBar + * @param saveText + * @param saveOnClickListener + */ + public static void setSaveView(ActionBar actionBar, int saveText, + OnClickListener saveOnClickListener) { + // Inflate a "Save" custom action bar view to serve as the "Up" affordance. + final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() + .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); + final View customActionBarView = inflater + .inflate(R.layout.actionbar_custom_view_save, null); + + ((TextView) customActionBarView.findViewById(R.id.actionbar_save_text)).setText(saveText); + customActionBarView.findViewById(R.id.actionbar_save).setOnClickListener( + saveOnClickListener); + + // Show the custom action bar view and hide the normal Home icon and title. + actionBar.setDisplayShowTitleEnabled(false); + actionBar.setDisplayShowHomeEnabled(false); + actionBar.setDisplayShowCustomEnabled(true); + actionBar.setCustomView(customActionBarView); + } + + /** + * Sets custom view on ActionBar for Save/Cancel activities + * + * @param actionBar + * @param saveText + * @param saveOnClickListener + * @param cancelText + * @param cancelOnClickListener + */ + public static void setSaveCancelView(ActionBar actionBar, int saveText, + OnClickListener saveOnClickListener, int cancelText, + OnClickListener cancelOnClickListener) { + + // Inflate a "Done"/"Cancel" custom action bar view + final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() + .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); + final View customActionBarView = inflater.inflate( + R.layout.actionbar_custom_view_save_cancel, null); + + ((TextView) customActionBarView.findViewById(R.id.actionbar_save_text)).setText(saveText); + customActionBarView.findViewById(R.id.actionbar_save).setOnClickListener( + saveOnClickListener); + ((TextView) customActionBarView.findViewById(R.id.actionbar_cancel_text)) + .setText(cancelText); + customActionBarView.findViewById(R.id.actionbar_cancel).setOnClickListener( + cancelOnClickListener); + + // Show the custom action bar view and hide the normal Home icon and title. + actionBar.setDisplayShowTitleEnabled(false); + actionBar.setDisplayShowHomeEnabled(false); + actionBar.setDisplayShowCustomEnabled(true); + actionBar.setCustomView(customActionBarView, new ActionBar.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 334fe5d3a..628f642d8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -250,7 +250,7 @@ public class EditKeyActivity extends ActionBarActivity { */ private void handleActionEditKey(Intent intent) { // Inflate a "Done"/"Cancel" custom action bar - ActionBarHelper.setDoneView(getSupportActionBar(), R.string.btn_save, + ActionBarHelper.setSaveView(getSupportActionBar(), R.string.btn_save, new View.OnClickListener() { @Override public void onClick(View v) { -- cgit v1.2.3 From 506782b6890c2aa41adf0042d64c0f24e28975f1 Mon Sep 17 00:00:00 2001 From: Daniel Hammann Date: Tue, 11 Mar 2014 00:07:53 +0100 Subject: OnFocusChangeListener replaced with OnActionExpandListener For same behaviour like contacts app #386 #387 --- .../keychain/ui/KeyListPublicFragment.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 92c6262b6..707001de9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -368,13 +368,17 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer mSearchView.setOnQueryTextListener(this); //Erase search result without focus - mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { + MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override - public void onFocusChange(View v, boolean hasFocus) { - if (!hasFocus) { - mCurQuery = null; - getLoaderManager().restartLoader(0, null, KeyListPublicFragment.this); - } + public boolean onMenuItemActionExpand(MenuItem item) { + return true; + } + + @Override + public boolean onMenuItemActionCollapse(MenuItem item) { + mCurQuery = null; + getLoaderManager().restartLoader(0, null, KeyListPublicFragment.this); + return true; } }); -- cgit v1.2.3 From 50ed5db001ccff0efe9c1e0b121f4292b7be1e7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 11 Mar 2014 00:28:28 +0100 Subject: cleanup --- .../keychain/ui/KeyListPublicFragment.java | 2 +- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 78 ++++++++++------------ 2 files changed, 37 insertions(+), 43 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index 707001de9..c62695417 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -367,7 +367,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer // Execute this when searching mSearchView.setOnQueryTextListener(this); - //Erase search result without focus + // Erase search result without focus MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index ca5d8b262..c9129285e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -71,50 +71,44 @@ public class SelectSecretKeyLayoutFragment extends Fragment { mKeyUserIdRest.setVisibility(View.GONE); } else { - String uid = getResources().getString(R.string.user_id_no_name); - String uidExtra = ""; - String masterkeyIdHex = ""; - PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRingByMasterKeyId( getActivity(), secretKeyId); if (keyRing != null) { PGPSecretKey key = PgpKeyHelper.getMasterKey(keyRing); - masterkeyIdHex = PgpKeyHelper.convertKeyIdToHex(secretKeyId); + String masterkeyIdHex = PgpKeyHelper.convertKeyIdToHex(secretKeyId); if (key != null) { String userId = PgpKeyHelper.getMainUserIdSafe(getActivity(), key); - /*String chunks[] = mUserId.split(" <", 2); - uid = chunks[0]; - if (chunks.length > 1) { - uidExtra = "<" + chunks[1]; - }*/ + String[] userIdSplit = PgpKeyHelper.splitUserId(userId); - String userName, userEmail; + String userName, userEmail; - if (userIdSplit[0] != null) { userName = userIdSplit[0]; } - else { userName = getActivity().getResources().getString(R.string.user_id_no_name); } + if (userIdSplit[0] != null) { + userName = userIdSplit[0]; + } else { + userName = getActivity().getResources().getString(R.string.user_id_no_name); + } - if (userIdSplit[1] != null) { userEmail = userIdSplit[1]; } - else { userEmail = getActivity().getResources().getString(R.string.error_user_id_no_email); } + if (userIdSplit[1] != null) { + userEmail = userIdSplit[1]; + } else { + userEmail = getActivity().getResources().getString(R.string.error_user_id_no_email); + } mKeyMasterKeyIdHex.setText(masterkeyIdHex); mKeyUserId.setText(userName); mKeyUserIdRest.setText(userEmail); mKeyUserId.setVisibility(View.VISIBLE); mKeyUserIdRest.setVisibility(View.VISIBLE); - } - else{ + } else { mKeyMasterKeyIdHex.setText(getActivity().getResources().getString(R.string.no_key)); mKeyUserId.setVisibility(View.GONE); mKeyUserIdRest.setVisibility(View.GONE); - } - - } - else{ - mKeyMasterKeyIdHex.setText(getActivity().getResources().getString(R.string.no_keys_added_or_updated)+" for master id: "+secretKeyId); - mKeyUserId.setVisibility(View.GONE); - mKeyUserIdRest.setVisibility(View.GONE); + } else { + mKeyMasterKeyIdHex.setText(getActivity().getResources().getString(R.string.no_keys_added_or_updated) + " for master id: " + secretKeyId); + mKeyUserId.setVisibility(View.GONE); + mKeyUserIdRest.setVisibility(View.GONE); } } @@ -154,31 +148,31 @@ public class SelectSecretKeyLayoutFragment extends Fragment { startActivityForResult(intent, REQUEST_CODE_SELECT_KEY); } - //Select Secret Key Activity delivers the intent which was sent by it using interface to Select + // Select Secret Key Activity delivers the intent which was sent by it using interface to Select // Secret Key Fragment.Intent contains Master Key Id, User Email, User Name, Master Key Id Hex. @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode & 0xFFFF) { - case REQUEST_CODE_SELECT_KEY: { - long secretKeyId; - if (resultCode == Activity.RESULT_OK) { - Bundle bundle = data.getExtras(); - secretKeyId = bundle.getLong(SelectSecretKeyActivity.RESULT_EXTRA_MASTER_KEY_ID); - selectKey(secretKeyId); - - // remove displayed errors - mKeyUserId.setError(null); - - // give value back to callback - mCallback.onKeySelected(secretKeyId); + case REQUEST_CODE_SELECT_KEY: { + long secretKeyId; + if (resultCode == Activity.RESULT_OK) { + Bundle bundle = data.getExtras(); + secretKeyId = bundle.getLong(SelectSecretKeyActivity.RESULT_EXTRA_MASTER_KEY_ID); + selectKey(secretKeyId); + + // remove displayed errors + mKeyUserId.setError(null); + + // give value back to callback + mCallback.onKeySelected(secretKeyId); + } + break; } - break; - } - default: - super.onActivityResult(requestCode, resultCode, data); + default: + super.onActivityResult(requestCode, resultCode, data); - break; + break; } } } -- cgit v1.2.3 From d93731701255e082b02bf80c5c029db8838b15b0 Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 11 Mar 2014 01:50:17 +0200 Subject: Remove duplicate code from ActionBarHelper. You can now set the drawables via the method calls --- .../keychain/helper/ActionBarHelper.java | 107 ++++++--------------- .../service/remote/AppSettingsActivity.java | 2 +- .../service/remote/RemoteServiceActivity.java | 10 +- .../keychain/ui/EditKeyActivity.java | 10 +- .../keychain/ui/PreferencesKeyServerActivity.java | 4 +- .../keychain/ui/SelectPublicKeyActivity.java | 4 +- 6 files changed, 42 insertions(+), 95 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java index 6aa8e7d74..2276e0f8a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java @@ -22,6 +22,7 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.util.Log; import android.app.Activity; +import android.graphics.drawable.Drawable; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; @@ -56,28 +57,33 @@ public class ActionBarHelper { * Sets custom view on ActionBar for Done/Cancel activities * * @param actionBar - * @param doneText - * @param doneOnClickListener - * @param cancelText - * @param cancelOnClickListener + * @param firstText + * @param firstDrawableId + * @param firstOnClickListener + * @param secondText + * @param secondDrawableId + * @param secondOnClickListener */ - public static void setDoneCancelView(ActionBar actionBar, int doneText, - OnClickListener doneOnClickListener, int cancelText, - OnClickListener cancelOnClickListener) { + public static void setTwoButtonView(ActionBar actionBar, int firstText, int firstDrawableId, + OnClickListener firstOnClickListener, int secondText, int secondDrawableId, + OnClickListener secondOnClickListener) { - // Inflate a "Done"/"Cancel" custom action bar view + // Inflate the custom action bar view final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); final View customActionBarView = inflater.inflate( R.layout.actionbar_custom_view_done_cancel, null); - ((TextView) customActionBarView.findViewById(R.id.actionbar_done_text)).setText(doneText); + TextView firstTextView = ((TextView) customActionBarView.findViewById(R.id.actionbar_done_text)); + firstTextView.setText(firstText); + firstTextView.setCompoundDrawablesWithIntrinsicBounds(firstDrawableId, 0, 0, 0); customActionBarView.findViewById(R.id.actionbar_done).setOnClickListener( - doneOnClickListener); - ((TextView) customActionBarView.findViewById(R.id.actionbar_cancel_text)) - .setText(cancelText); + firstOnClickListener); + TextView secondTextView = ((TextView) customActionBarView.findViewById(R.id.actionbar_cancel_text)); + secondTextView.setText(secondText); + secondTextView.setCompoundDrawablesWithIntrinsicBounds(secondDrawableId, 0, 0, 0); customActionBarView.findViewById(R.id.actionbar_cancel).setOnClickListener( - cancelOnClickListener); + secondOnClickListener); // Show the custom action bar view and hide the normal Home icon and title. actionBar.setDisplayShowTitleEnabled(false); @@ -91,20 +97,22 @@ public class ActionBarHelper { * Sets custom view on ActionBar for Done activities * * @param actionBar - * @param doneText - * @param doneOnClickListener + * @param firstText + * @param firstOnClickListener */ - public static void setDoneView(ActionBar actionBar, int doneText, - OnClickListener doneOnClickListener) { + public static void setOneButtonView(ActionBar actionBar, int firstText, int firstDrawableId, + OnClickListener firstOnClickListener) { // Inflate a "Done" custom action bar view to serve as the "Up" affordance. final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); final View customActionBarView = inflater .inflate(R.layout.actionbar_custom_view_done, null); - ((TextView) customActionBarView.findViewById(R.id.actionbar_done_text)).setText(doneText); + TextView firstTextView = ((TextView) customActionBarView.findViewById(R.id.actionbar_done_text)); + firstTextView.setText(firstText); + firstTextView.setCompoundDrawablesWithIntrinsicBounds(firstDrawableId, 0, 0, 0); customActionBarView.findViewById(R.id.actionbar_done).setOnClickListener( - doneOnClickListener); + firstOnClickListener); // Show the custom action bar view and hide the normal Home icon and title. actionBar.setDisplayShowTitleEnabled(false); @@ -112,65 +120,4 @@ public class ActionBarHelper { actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(customActionBarView); } - - /** - * Sets custom view on ActionBar for Save activities - * - * @param actionBar - * @param saveText - * @param saveOnClickListener - */ - public static void setSaveView(ActionBar actionBar, int saveText, - OnClickListener saveOnClickListener) { - // Inflate a "Save" custom action bar view to serve as the "Up" affordance. - final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() - .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); - final View customActionBarView = inflater - .inflate(R.layout.actionbar_custom_view_save, null); - - ((TextView) customActionBarView.findViewById(R.id.actionbar_save_text)).setText(saveText); - customActionBarView.findViewById(R.id.actionbar_save).setOnClickListener( - saveOnClickListener); - - // Show the custom action bar view and hide the normal Home icon and title. - actionBar.setDisplayShowTitleEnabled(false); - actionBar.setDisplayShowHomeEnabled(false); - actionBar.setDisplayShowCustomEnabled(true); - actionBar.setCustomView(customActionBarView); - } - - /** - * Sets custom view on ActionBar for Save/Cancel activities - * - * @param actionBar - * @param saveText - * @param saveOnClickListener - * @param cancelText - * @param cancelOnClickListener - */ - public static void setSaveCancelView(ActionBar actionBar, int saveText, - OnClickListener saveOnClickListener, int cancelText, - OnClickListener cancelOnClickListener) { - - // Inflate a "Done"/"Cancel" custom action bar view - final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() - .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); - final View customActionBarView = inflater.inflate( - R.layout.actionbar_custom_view_save_cancel, null); - - ((TextView) customActionBarView.findViewById(R.id.actionbar_save_text)).setText(saveText); - customActionBarView.findViewById(R.id.actionbar_save).setOnClickListener( - saveOnClickListener); - ((TextView) customActionBarView.findViewById(R.id.actionbar_cancel_text)) - .setText(cancelText); - customActionBarView.findViewById(R.id.actionbar_cancel).setOnClickListener( - cancelOnClickListener); - - // Show the custom action bar view and hide the normal Home icon and title. - actionBar.setDisplayShowTitleEnabled(false); - actionBar.setDisplayShowHomeEnabled(false); - actionBar.setDisplayShowCustomEnabled(true); - actionBar.setCustomView(customActionBarView, new ActionBar.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java index a7afc9698..178b2fc67 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java @@ -41,7 +41,7 @@ public class AppSettingsActivity extends ActionBarActivity { super.onCreate(savedInstanceState); // Inflate a "Done" custom action bar - ActionBarHelper.setDoneView(getSupportActionBar(), R.string.api_settings_save, + ActionBarHelper.setOneButtonView(getSupportActionBar(), R.string.api_settings_save, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java index 11b3ee217..8fb562884 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java @@ -88,7 +88,7 @@ public class RemoteServiceActivity extends ActionBarActivity { final byte[] packageSignature = extras.getByteArray(EXTRA_PACKAGE_SIGNATURE); // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setDoneCancelView(getSupportActionBar(), R.string.api_register_allow, + ActionBarHelper.setTwoButtonView(getSupportActionBar(), R.string.api_register_allow, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { @@ -108,7 +108,7 @@ public class RemoteServiceActivity extends ActionBarActivity { RemoteServiceActivity.this.finish(); } } - }, R.string.api_register_disallow, new View.OnClickListener() { + }, R.string.api_register_disallow, R.drawable.ic_action_cancel, new View.OnClickListener() { @Override public void onClick(View v) { // Disallow @@ -161,7 +161,7 @@ public class RemoteServiceActivity extends ActionBarActivity { } // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setDoneCancelView(getSupportActionBar(), R.string.btn_okay, + ActionBarHelper.setTwoButtonView(getSupportActionBar(), R.string.btn_okay, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { @@ -173,7 +173,7 @@ public class RemoteServiceActivity extends ActionBarActivity { RemoteServiceActivity.this.setResult(RESULT_OK, resultData); RemoteServiceActivity.this.finish(); } - }, R.string.btn_do_not_save, new View.OnClickListener() { + }, R.string.btn_do_not_save, R.drawable.ic_action_cancel, new View.OnClickListener() { @Override public void onClick(View v) { // cancel @@ -214,7 +214,7 @@ public class RemoteServiceActivity extends ActionBarActivity { String text = "" + errorMessage + ""; // Inflate a "Done" custom action bar view - ActionBarHelper.setDoneView(getSupportActionBar(), R.string.btn_okay, + ActionBarHelper.setOneButtonView(getSupportActionBar(), R.string.btn_okay, R.drawable.ic_action_done, new View.OnClickListener() { @Override diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 628f642d8..19f991640 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -134,14 +134,14 @@ public class EditKeyActivity extends ActionBarActivity { * @param intent */ private void handleActionCreateKey(Intent intent) { - // Inflate a "Done"/"Cancel" custom action bar - ActionBarHelper.setDoneCancelView(getSupportActionBar(), R.string.btn_save, + // Inflate a "Save"/"Cancel" custom action bar + ActionBarHelper.setTwoButtonView(getSupportActionBar(), R.string.btn_save, R.drawable.ic_action_save, new View.OnClickListener() { @Override public void onClick(View v) { saveClicked(); } - }, R.string.btn_do_not_save, new View.OnClickListener() { + }, R.string.btn_do_not_save, R.drawable.ic_action_cancel, new View.OnClickListener() { @Override public void onClick(View v) { cancelClicked(); @@ -249,8 +249,8 @@ public class EditKeyActivity extends ActionBarActivity { * @param intent */ private void handleActionEditKey(Intent intent) { - // Inflate a "Done"/"Cancel" custom action bar - ActionBarHelper.setSaveView(getSupportActionBar(), R.string.btn_save, + // Inflate a "Save"/"Cancel" custom action bar + ActionBarHelper.setOneButtonView(getSupportActionBar(), R.string.btn_save, R.drawable.ic_action_save, new View.OnClickListener() { @Override public void onClick(View v) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java index b5ac739ae..492e9f200 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java @@ -50,14 +50,14 @@ public class PreferencesKeyServerActivity extends ActionBarActivity implements O super.onCreate(savedInstanceState); // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setDoneCancelView(getSupportActionBar(), R.string.btn_okay, + ActionBarHelper.setTwoButtonView(getSupportActionBar(), R.string.btn_okay, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { // ok okClicked(); } - }, R.string.btn_do_not_save, new View.OnClickListener() { + }, R.string.btn_do_not_save, R.drawable.ic_action_cancel, new View.OnClickListener() { @Override public void onClick(View v) { // cancel diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java index 86ae0073f..3c63628f7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java @@ -46,14 +46,14 @@ public class SelectPublicKeyActivity extends ActionBarActivity { super.onCreate(savedInstanceState); // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setDoneCancelView(getSupportActionBar(), R.string.btn_okay, + ActionBarHelper.setTwoButtonView(getSupportActionBar(), R.string.btn_okay, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { // ok okClicked(); } - }, R.string.btn_do_not_save, new View.OnClickListener() { + }, R.string.btn_do_not_save, R.drawable.ic_action_cancel, new View.OnClickListener() { @Override public void onClick(View v) { // cancel -- cgit v1.2.3 From 361c45a481c75b3c62f7d9f46c9a6d2a7c4f97f0 Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 11 Mar 2014 03:22:05 +0200 Subject: Make export work with rowIds instead of MasterKeyIds --- .../keychain/helper/ExportHelper.java | 15 +++--- .../keychain/pgp/PgpImportExport.java | 60 ++++++++++------------ .../keychain/provider/ProviderHelper.java | 40 +++++++++++++++ .../keychain/service/KeychainIntentService.java | 24 +++++---- .../keychain/ui/EditKeyActivity.java | 3 +- .../keychain/ui/ViewKeyActivity.java | 3 +- 6 files changed, 92 insertions(+), 53 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 6aa28fec8..90e1f8cba 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -63,7 +63,7 @@ public class ExportHelper { /** * Show dialog where to export keys */ - public void showExportKeysDialog(final Uri dataUri, final int keyType, + public void showExportKeysDialog(final long[] rowIds, final int keyType, final String exportFilename) { mExportFilename = exportFilename; @@ -75,7 +75,7 @@ public class ExportHelper { Bundle data = message.getData(); mExportFilename = data.getString(FileDialogFragment.MESSAGE_DATA_FILENAME); - exportKeys(dataUri, keyType); + exportKeys(rowIds, keyType); } } }; @@ -86,7 +86,7 @@ public class ExportHelper { DialogFragmentWorkaround.INTERFACE.runnableRunDelayed(new Runnable() { public void run() { String title = null; - if (dataUri == null) { + if (rowIds == null) { // export all keys title = activity.getString(R.string.title_export_keys); } else { @@ -112,7 +112,7 @@ public class ExportHelper { /** * Export keys */ - public void exportKeys(Uri dataUri, int keyType) { + public void exportKeys(long[] rowIds, int keyType) { Log.d(Constants.TAG, "exportKeys started"); // Send all information needed to service to export key in other thread @@ -126,13 +126,10 @@ public class ExportHelper { data.putString(KeychainIntentService.EXPORT_FILENAME, mExportFilename); data.putInt(KeychainIntentService.EXPORT_KEY_TYPE, keyType); - if (dataUri == null) { + if (rowIds == null) { data.putBoolean(KeychainIntentService.EXPORT_ALL, true); } else { - // TODO: put data uri into service??? - long keyRingMasterKeyId = ProviderHelper.getMasterKeyId(activity, dataUri); - - data.putLong(KeychainIntentService.EXPORT_KEY_RING_MASTER_KEY_ID, keyRingMasterKeyId); + data.putLongArray(KeychainIntentService.EXPORT_KEY_RING_ROW_ID, rowIds); } intent.putExtra(KeychainIntentService.EXTRA_DATA, data); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 7c635a00b..0a17a2be4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -155,59 +155,53 @@ public class PgpImportExport { return returnData; } - public Bundle exportKeyRings(ArrayList keyRingMasterKeyIds, int keyType, + public Bundle exportKeyRings(ArrayList keyRingRowIds, int keyType, OutputStream outStream) throws PgpGeneralException, FileNotFoundException, PGPException, IOException { Bundle returnData = new Bundle(); + int rowIdsSize = keyRingRowIds.size(); + updateProgress( mContext.getResources().getQuantityString(R.plurals.progress_exporting_key, - keyRingMasterKeyIds.size()), 0, 100); + rowIdsSize), 0, 100); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { throw new PgpGeneralException( mContext.getString(R.string.error_external_storage_not_ready)); } - - if (keyType == Id.type.secret_key) { - ArmoredOutputStream outSec = new ArmoredOutputStream(outStream); - outSec.setHeader("Version", PgpHelper.getFullVersion(mContext)); - - for (int i = 0; i < keyRingMasterKeyIds.size(); ++i) { - updateProgress(i * 100 / keyRingMasterKeyIds.size() / 2, 100); - - PGPSecretKeyRing secretKeyRing = ProviderHelper.getPGPSecretKeyRingByMasterKeyId( - mContext, keyRingMasterKeyIds.get(i)); + // For each row id + for (int i = 0; i < rowIdsSize; ++i) { + // Create an output stream + ArmoredOutputStream arOutStream = new ArmoredOutputStream(outStream); + arOutStream.setHeader("Version", PgpHelper.getFullVersion(mContext)); + + // If the keyType is secret get the PGPSecretKeyRing + // based on the row id and encode it to the output + if (keyType == Id.type.secret_key) { + updateProgress(i * 100 / rowIdsSize / 2, 100); + PGPSecretKeyRing secretKeyRing = + ProviderHelper.getPGPSecretKeyRingByRowId(mContext, keyRingRowIds.get(i)); if (secretKeyRing != null) { - secretKeyRing.encode(outSec); - } - } - outSec.close(); - } else { - // export public keyrings... - ArmoredOutputStream outPub = new ArmoredOutputStream(outStream); - outPub.setHeader("Version", PgpHelper.getFullVersion(mContext)); - - for (int i = 0; i < keyRingMasterKeyIds.size(); ++i) { - // double the needed time if exporting both public and secret parts - if (keyType == Id.type.secret_key) { - updateProgress(i * 100 / keyRingMasterKeyIds.size() / 2, 100); - } else { - updateProgress(i * 100 / keyRingMasterKeyIds.size(), 100); + secretKeyRing.encode(arOutStream); } - - PGPPublicKeyRing publicKeyRing = ProviderHelper.getPGPPublicKeyRingByMasterKeyId( - mContext, keyRingMasterKeyIds.get(i)); + // Else if it's a public key get the PGPPublicKeyRing + // and encode that to the output + } else { + updateProgress(i * 100 / rowIdsSize, 100); + PGPPublicKeyRing publicKeyRing = + ProviderHelper.getPGPPublicKeyRingByRowId(mContext, keyRingRowIds.get(i)); if (publicKeyRing != null) { - publicKeyRing.encode(outPub); + publicKeyRing.encode(arOutStream); } } - outPub.close(); + + arOutStream.close(); } - returnData.putInt(KeychainIntentService.RESULT_EXPORT, keyRingMasterKeyIds.size()); + returnData.putInt(KeychainIntentService.RESULT_EXPORT, rowIdsSize); updateProgress(R.string.progress_done, 100, 100); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index ac0692213..dd538fbf4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -404,6 +404,30 @@ public class ProviderHelper { return masterKeyIds; } + /** + * Private helper method + */ + private static ArrayList getKeyRingsRowIds(Context context, Uri queryUri) { + Cursor cursor = context.getContentResolver().query(queryUri, + new String[]{KeyRings._ID}, null, null, null); + + ArrayList rowIds = new ArrayList(); + if (cursor != null) { + int IdCol = cursor.getColumnIndex(KeyRings._ID); + if (cursor.moveToFirst()) { + do { + rowIds.add(cursor.getLong(IdCol)); + } while (cursor.moveToNext()); + } + } + + if (cursor != null) { + cursor.close(); + } + + return rowIds; + } + /** * Retrieves ids of all SecretKeyRings */ @@ -420,6 +444,22 @@ public class ProviderHelper { return getKeyRingsMasterKeyIds(context, queryUri); } + /** + * Retrieves ids of all SecretKeyRings + */ + public static ArrayList getSecretKeyRingsRowIds(Context context) { + Uri queryUri = KeyRings.buildSecretKeyRingsUri(); + return getKeyRingsRowIds(context, queryUri); + } + + /** + * Retrieves ids of all PublicKeyRings + */ + public static ArrayList getPublicKeyRingsRowIds(Context context) { + Uri queryUri = KeyRings.buildPublicKeyRingsUri(); + return getKeyRingsRowIds(context, queryUri); + } + public static void deletePublicKeyRing(Context context, long rowId) { ContentResolver cr = context.getContentResolver(); cr.delete(KeyRings.buildPublicKeyRingsUri(Long.toString(rowId)), null, null); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 902c66fe9..93238349d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -50,6 +50,7 @@ import org.sufficientlysecure.keychain.pgp.PgpImportExport; import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; import org.sufficientlysecure.keychain.pgp.PgpSignEncrypt; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainContract.DataStream; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; @@ -153,6 +154,7 @@ public class KeychainIntentService extends IntentService implements ProgressDial public static final String EXPORT_KEY_TYPE = "export_key_type"; public static final String EXPORT_ALL = "export_all"; public static final String EXPORT_KEY_RING_MASTER_KEY_ID = "export_key_ring_id"; + public static final String EXPORT_KEY_RING_ROW_ID = "export_key_rind_row_id"; // upload key public static final String UPLOAD_KEY_SERVER = "upload_key_server"; @@ -675,10 +677,12 @@ public class KeychainIntentService extends IntentService implements ProgressDial String outputFile = data.getString(EXPORT_FILENAME); + long[] rowIds = new long[0]; + + // If not exporting all keys get the rowIds of the keys to export from the intent boolean exportAll = data.getBoolean(EXPORT_ALL); - long keyRingMasterKeyId = -1; if (!exportAll) { - keyRingMasterKeyId = data.getLong(EXPORT_KEY_RING_MASTER_KEY_ID); + rowIds = data.getLongArray(EXPORT_KEY_RING_ROW_ID); } /* Operation */ @@ -691,24 +695,26 @@ public class KeychainIntentService extends IntentService implements ProgressDial // OutputStream FileOutputStream outStream = new FileOutputStream(outputFile); - ArrayList keyRingMasterKeyIds = new ArrayList(); + ArrayList keyRingRowIds = new ArrayList(); if (exportAll) { - // get all key ring row ids based on export type + // get all key ring row ids based on export type if (keyType == Id.type.public_key) { - keyRingMasterKeyIds = ProviderHelper.getPublicKeyRingsMasterKeyIds(this); + keyRingRowIds = ProviderHelper.getPublicKeyRingsRowIds(this); } else { - keyRingMasterKeyIds = ProviderHelper.getSecretKeyRingsMasterKeyIds(this); + keyRingRowIds = ProviderHelper.getSecretKeyRingsRowIds(this); } } else { - keyRingMasterKeyIds.add(keyRingMasterKeyId); + for(long rowId : rowIds) { + keyRingRowIds.add(rowId); + } } - Bundle resultData = new Bundle(); + Bundle resultData; PgpImportExport pgpImportExport = new PgpImportExport(this, this); resultData = pgpImportExport - .exportKeyRings(keyRingMasterKeyIds, keyType, outStream); + .exportKeyRings(keyRingRowIds, keyType, outStream); sendMessageToHandler(KeychainIntentServiceHandler.MESSAGE_OKAY, resultData); } catch (Exception e) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 19f991640..6e16afef1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -329,7 +329,8 @@ public class EditKeyActivity extends ActionBarActivity { cancelClicked(); return true; case R.id.menu_key_edit_export_file: - mExportHelper.showExportKeysDialog(mDataUri, Id.type.secret_key, Constants.path.APP_DIR + long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; + mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.path.APP_DIR + "/secexport.asc"); return true; case R.id.menu_key_edit_delete: { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 390de9ab9..3641f4d96 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -118,7 +118,8 @@ public class ViewKeyActivity extends ActionBarActivity { uploadToKeyserver(mDataUri); return true; case R.id.menu_key_view_export_file: - mExportHelper.showExportKeysDialog(mDataUri, Id.type.public_key, Constants.path.APP_DIR + long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; + mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.path.APP_DIR + "/pubexport.asc"); return true; case R.id.menu_key_view_share_default_fingerprint: -- cgit v1.2.3 From 43a20ad1da62a32eb48ecedcd6dc33df5396dfeb Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 11 Mar 2014 03:53:00 +0200 Subject: Add export... button and functionality in multi-select --- .../main/java/org/sufficientlysecure/keychain/Constants.java | 2 ++ .../org/sufficientlysecure/keychain/helper/ExportHelper.java | 1 - .../org/sufficientlysecure/keychain/ui/EditKeyActivity.java | 3 +-- .../sufficientlysecure/keychain/ui/KeyListPublicActivity.java | 3 +-- .../sufficientlysecure/keychain/ui/KeyListPublicFragment.java | 9 ++++++++- .../sufficientlysecure/keychain/ui/KeyListSecretActivity.java | 3 +-- .../sufficientlysecure/keychain/ui/KeyListSecretFragment.java | 11 +++++++++-- .../org/sufficientlysecure/keychain/ui/ViewKeyActivity.java | 3 +-- 8 files changed, 23 insertions(+), 12 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java index 4428c7133..34a3de8d5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java @@ -43,6 +43,8 @@ public final class Constants { public static final class path { public static final String APP_DIR = Environment.getExternalStorageDirectory() + "/OpenPGP-Keychain"; + public static final String APP_DIR_FILE_SEC = APP_DIR + "/secexport.asc"; + public static final String APP_DIR_FILE_PUB = APP_DIR + "/pubexport.asc"; } public static final class pref { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 90e1f8cba..19dfccbde 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -20,7 +20,6 @@ import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround; -import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 6e16afef1..72dc97ccd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -330,8 +330,7 @@ public class EditKeyActivity extends ActionBarActivity { return true; case R.id.menu_key_edit_export_file: long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; - mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.path.APP_DIR - + "/secexport.asc"); + mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); return true; case R.id.menu_key_edit_delete: { // Message is received after key is deleted diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java index 4521786f7..9bd9ee225 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicActivity.java @@ -59,8 +59,7 @@ public class KeyListPublicActivity extends DrawerActivity { return true; case R.id.menu_key_list_public_export: - mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR - + "/pubexport.asc"); + mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); return true; default: diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index c62695417..2fb280ccd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -18,10 +18,11 @@ package org.sufficientlysecure.keychain.ui; import java.util.ArrayList; -import java.util.Set; +import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ExportHelper; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; @@ -47,6 +48,7 @@ import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.MenuItemCompat; +import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.view.ActionMode; @@ -179,6 +181,11 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer encrypt(mode, ids); break; } + case R.id.menu_key_list_public_multi_export: { + ExportHelper mExportHelper = new ExportHelper((ActionBarActivity) getActivity()); + mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); + break; + } case R.id.menu_key_list_public_multi_delete: { showDeleteKeyDialog(mode, ids); break; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java index e58ebe819..cd3c8b4fd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretActivity.java @@ -62,8 +62,7 @@ public class KeyListSecretActivity extends DrawerActivity { return true; case R.id.menu_key_list_secret_export: - mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.path.APP_DIR - + "/secexport.asc"); + mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); return true; case R.id.menu_key_list_secret_import: diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java index 76212afc3..e84b2f4c8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListSecretFragment.java @@ -17,10 +17,10 @@ package org.sufficientlysecure.keychain.ui; -import java.util.Set; - +import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ExportHelper; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; @@ -41,6 +41,7 @@ import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; +import android.support.v7.app.ActionBarActivity; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; @@ -106,6 +107,12 @@ public class KeyListSecretFragment extends ListFragment implements } break; } + case R.id.menu_key_list_public_multi_export: { + ExportHelper mExportHelper = new ExportHelper((ActionBarActivity) getActivity()); + mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); + break; + } + } return true; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 3641f4d96..4cc5e1b62 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -119,8 +119,7 @@ public class ViewKeyActivity extends ActionBarActivity { return true; case R.id.menu_key_view_export_file: long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; - mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.path.APP_DIR - + "/pubexport.asc"); + mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); return true; case R.id.menu_key_view_share_default_fingerprint: shareKey(mDataUri, true); -- cgit v1.2.3 From e8122df35d71bc09013dcc90d35fadbb1126b0cd Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 11 Mar 2014 04:13:58 +0200 Subject: minor clean up in colorize method --- .../java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 65fe08484..adb06a068 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -280,13 +280,14 @@ public class ViewKeyMainFragment extends Fragment implements // for each 4 characters of the fingerprint + 1 space for (int i = 0; i < fingerprint.length(); i += 5) { - String fourChars = fingerprint.substring(i, Math.min(i + 4, fingerprint.length())); + int minFingLength = Math.min(i + 4, fingerprint.length()); + String fourChars = fingerprint.substring(i, minFingLength); // Create a foreground color by converting the 4 fingerprint chars to an int hashcode // and then converting that int to hex to use as a color fcs = new ForegroundColorSpan( Color.parseColor(String.format("#%06X", (0xFFFFFF & fourChars.hashCode())))); - sb.setSpan(fcs, i, Math.min(i+4, fingerprint.length()), Spannable.SPAN_INCLUSIVE_INCLUSIVE); + sb.setSpan(fcs, i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } return sb; -- cgit v1.2.3 From e2ec5a38823270a64709cd730dedf93d68219a7b Mon Sep 17 00:00:00 2001 From: Tharindu Wijewardane Date: Tue, 11 Mar 2014 11:04:31 +0530 Subject: Issue #393 ( PublicKeyListFragment: Query not really resetted ) : Fixed --- .../java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java | 1 + 1 file changed, 1 insertion(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java index c62695417..514b0e00e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListPublicFragment.java @@ -377,6 +377,7 @@ public class KeyListPublicFragment extends Fragment implements SearchView.OnQuer @Override public boolean onMenuItemActionCollapse(MenuItem item) { mCurQuery = null; + mSearchView.setQuery("", true); getLoaderManager().restartLoader(0, null, KeyListPublicFragment.this); return true; } -- cgit v1.2.3 From d586ad288d2a6db803c12c8ae4a600630004f7bc Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 11 Mar 2014 23:42:45 +0200 Subject: fix plenty of lint warnings, make some for loops into foreach, remove unused imports and throw exceptions --- .../org/sufficientlysecure/keychain/helper/ActionBarHelper.java | 1 - .../java/org/sufficientlysecure/keychain/helper/Preferences.java | 8 ++++---- .../main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java | 3 +-- .../java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java | 8 +++++--- .../java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java | 2 +- .../keychain/service/PassphraseCacheService.java | 5 +++-- .../java/org/sufficientlysecure/keychain/ui/DecryptActivity.java | 4 ++++ .../keychain/ui/PreferencesKeyServerActivity.java | 4 ++-- .../sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java | 4 ++-- .../keychain/ui/adapter/KeyListPublicAdapter.java | 2 -- .../keychain/ui/adapter/KeyListSecretAdapter.java | 1 - .../keychain/ui/dialog/CreateKeyDialogFragment.java | 3 ++- 12 files changed, 24 insertions(+), 21 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java index 2276e0f8a..24e8ff4c7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java @@ -22,7 +22,6 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.util.Log; import android.app.Activity; -import android.graphics.drawable.Drawable; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java index 493f25707..f18a290b3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java @@ -144,8 +144,8 @@ public class Preferences { Constants.defaults.KEY_SERVERS); Vector servers = new Vector(); String chunks[] = rawData.split(","); - for (int i = 0; i < chunks.length; ++i) { - String tmp = chunks[i].trim(); + for (String c : chunks) { + String tmp = c.trim(); if (tmp.length() > 0) { servers.add(tmp); } @@ -156,8 +156,8 @@ public class Preferences { public void setKeyServers(String[] value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); String rawData = ""; - for (int i = 0; i < value.length; ++i) { - String tmp = value[i].trim(); + for (String v : value) { + String tmp = v.trim(); if (tmp.length() == 0) { continue; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java index 7ac904d89..1db4f98b1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java @@ -193,11 +193,10 @@ public class PgpHelper { * @param context * @param progress * @param file - * @throws FileNotFoundException * @throws IOException */ public static void deleteFileSecurely(Context context, ProgressDialogUpdater progress, File file) - throws FileNotFoundException, IOException { + throws IOException { long length = file.length(); SecureRandom random = new SecureRandom(); RandomAccessFile raf = new RandomAccessFile(file, "rws"); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 0a17a2be4..138e54f71 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -79,8 +79,9 @@ public class PgpImportExport { public boolean uploadKeyRingToServer(HkpKeyServer server, PGPPublicKeyRing keyring) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ArmoredOutputStream aos = new ArmoredOutputStream(bos); + ArmoredOutputStream aos = null; try { + aos = new ArmoredOutputStream(bos); aos.write(keyring.getEncoded()); aos.close(); @@ -95,7 +96,8 @@ public class PgpImportExport { return false; } finally { try { - bos.close(); + if (aos != null) aos.close(); + if (bos != null) bos.close(); } catch (IOException e) { } } @@ -156,7 +158,7 @@ public class PgpImportExport { } public Bundle exportKeyRings(ArrayList keyRingRowIds, int keyType, - OutputStream outStream) throws PgpGeneralException, FileNotFoundException, + OutputStream outStream) throws PgpGeneralException, PGPException, IOException { Bundle returnData = new Bundle(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index e1ca88fb0..5ebb53f20 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -190,7 +190,7 @@ public class PgpKeyOperation { } public void changeSecretKeyPassphrase(PGPSecretKeyRing keyRing, String oldPassPhrase, - String newPassPhrase) throws IOException, PGPException, PGPException, + String newPassPhrase) throws IOException, PGPException, NoSuchProviderException { updateProgress(R.string.progress_building_key, 0, 100); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java index abd2320e3..ce34d451d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java @@ -21,6 +21,7 @@ import java.util.Date; import java.util.HashMap; import java.util.Iterator; +import android.util.LongSparseArray; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPPrivateKey; import org.spongycastle.openpgp.PGPSecretKey; @@ -77,7 +78,7 @@ public class PassphraseCacheService extends Service { private BroadcastReceiver mIntentReceiver; - private HashMap mPassphraseCache = new HashMap(); + private LongSparseArray mPassphraseCache = new LongSparseArray(); Context mContext; @@ -347,7 +348,7 @@ public class PassphraseCacheService extends Service { Log.d(TAG, "Timeout of keyId " + keyId + ", removed from memory!"); // stop whole service if no cached passphrases remaining - if (mPassphraseCache.isEmpty()) { + if (mPassphraseCache.size() == 0) { Log.d(TAG, "No passphrases remaining in memory, stopping service!"); stopSelf(); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index 76acf15b0..38d763ce4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -530,6 +530,10 @@ public class DecryptActivity extends DrawerActivity { Log.e(Constants.TAG, "File not found!", e); AppMsg.makeText(this, getString(R.string.error_file_not_found, e.getMessage()), AppMsg.STYLE_ALERT).show(); + } finally { + try { + if (inStream != null) inStream.close(); + } catch (Exception e){ } } } else { inStream = new ByteArrayInputStream(mMessage.getText().toString().getBytes()); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java index 492e9f200..50fec1ffc 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java @@ -81,11 +81,11 @@ public class PreferencesKeyServerActivity extends ActionBarActivity implements O Intent intent = getIntent(); String servers[] = intent.getStringArrayExtra(EXTRA_KEY_SERVERS); if (servers != null) { - for (int i = 0; i < servers.length; ++i) { + for (String serv : servers) { KeyServerEditor view = (KeyServerEditor) mInflater.inflate( R.layout.key_server_editor, mEditors, false); view.setEditorListener(this); - view.setValue(servers[i]); + view.setValue(serv); mEditors.addView(view); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java index c1c9aa705..d320af451 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java @@ -199,8 +199,8 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T if (masterKeyIds != null) { for (int i = 0; i < getListView().getCount(); ++i) { long keyId = mAdapter.getMasterKeyId(i); - for (int j = 0; j < masterKeyIds.length; ++j) { - if (keyId == masterKeyIds[j]) { + for (long masterKeyId : masterKeyIds) { + if (keyId == masterKeyId) { getListView().setItemChecked(i, true); break; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java index b8f60633e..d7bb62d01 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListPublicAdapter.java @@ -18,8 +18,6 @@ package org.sufficientlysecure.keychain.ui.adapter; import java.util.HashMap; -import java.util.Set; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java index ca3a26066..0bffcaa19 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyListSecretAdapter.java @@ -18,7 +18,6 @@ package org.sufficientlysecure.keychain.ui.adapter; import java.util.HashMap; -import java.util.Set; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java index 98b677511..a47601c9b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java @@ -32,6 +32,7 @@ import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.util.Choice; +import java.util.ArrayList; import java.util.Vector; public class CreateKeyDialogFragment extends DialogFragment { @@ -78,7 +79,7 @@ public class CreateKeyDialogFragment extends DialogFragment { boolean wouldBeMasterKey = (childCount == 0); final Spinner algorithm = (Spinner) view.findViewById(R.id.create_key_algorithm); - Vector choices = new Vector(); + ArrayList choices = new ArrayList(); choices.add(new Choice(Id.choice.algorithm.dsa, getResources().getString( R.string.dsa))); if (!wouldBeMasterKey) { -- cgit v1.2.3 From b955c3de0173cc2014f9b56553ef984d196deb1b Mon Sep 17 00:00:00 2001 From: uberspot Date: Wed, 12 Mar 2014 02:04:04 +0200 Subject: Add Email suggestions in Create Key activity --- .../keychain/helper/ContactHelper.java | 41 ++++++++++++++++++++++ .../keychain/ui/widget/UserIdEditor.java | 17 ++++++--- 2 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java new file mode 100644 index 000000000..f8ed21816 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2014 Dominik Schürmann + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.sufficientlysecure.keychain.helper; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.content.Context; +import android.util.Patterns; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class ContactHelper { + + public static final List getMailAccounts(Context context) { + final Account[] accounts = AccountManager.get(context).getAccounts(); + final Set emailSet = new HashSet(); + for (Account account : accounts) { + if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) { + emailSet.add(account.name); + } + } + return new ArrayList(emailSet); + } +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java index 5428b626e..71cd89ae8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java @@ -19,6 +19,7 @@ package org.sufficientlysecure.keychain.ui.widget; import java.util.regex.Matcher; import java.util.regex.Pattern; +import android.widget.*; import org.sufficientlysecure.keychain.R; import android.content.Context; @@ -26,11 +27,9 @@ import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.RadioButton; import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.helper.ContactHelper; public class UserIdEditor extends LinearLayout implements Editor, OnClickListener { private EditorListener mEditorListener = null; @@ -38,7 +37,7 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene private BootstrapButton mDeleteButton; private RadioButton mIsMainUserId; private EditText mName; - private EditText mEmail; + private AutoCompleteTextView mEmail; private EditText mComment; // see http://www.regular-expressions.info/email.html @@ -102,9 +101,17 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene mIsMainUserId.setOnClickListener(this); mName = (EditText) findViewById(R.id.name); - mEmail = (EditText) findViewById(R.id.email); + mEmail = (AutoCompleteTextView) findViewById(R.id.email); mComment = (EditText) findViewById(R.id.comment); + + mEmail.setThreshold(1); // Start working from first character + mEmail.setAdapter( + new ArrayAdapter + (this.getContext(), android.R.layout.simple_dropdown_item_1line, + ContactHelper.getMailAccounts(getContext()) + )); + super.onFinishInflate(); } -- cgit v1.2.3 From 11b19f0fce6b398bb24f31f5b90a7bf293608372 Mon Sep 17 00:00:00 2001 From: Miroojin Bakshi Date: Wed, 12 Mar 2014 20:14:56 +0530 Subject: Fix error in importing/updating keys from keyserver by removing extra 0x --- .../main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 0681847f4..32266839c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -226,7 +226,7 @@ public class HkpKeyServer extends KeyServer { HttpClient client = new DefaultHttpClient(); try { HttpGet get = new HttpGet("http://" + mHost + ":" + mPort - + "/pks/lookup?op=get&search=0x" + PgpKeyHelper.convertKeyIdToHex(keyId)); + + "/pks/lookup?op=get&search=" + PgpKeyHelper.convertKeyIdToHex(keyId)); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { -- cgit v1.2.3 From e909b6bb9d582dd2fec767410d039a0cf3189635 Mon Sep 17 00:00:00 2001 From: uberspot Date: Wed, 12 Mar 2014 18:48:17 +0200 Subject: change colorizing of fingerprint to use SHA1 based on apg's commit 67ffc24526 --- .../keychain/helper/OtherHelper.java | 22 ++++++++++ .../keychain/ui/ViewKeyMainFragment.java | 50 ++++++++++++++++------ 2 files changed, 60 insertions(+), 12 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java index 34d90a17f..292b5bf3d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java @@ -17,6 +17,9 @@ package org.sufficientlysecure.keychain.helper; +import java.security.DigestException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Set; @@ -58,4 +61,23 @@ public class OtherHelper { } } + /** + * Converts the given bytes to a unique RGB color using SHA1 algorithm + * @param bytes + * @return an integer array containing 3 numeric color representations (Red, Green, Black) + * @throws NoSuchAlgorithmException + * @throws DigestException + */ + public static int[] getRgbForData(byte[] bytes) throws NoSuchAlgorithmException, DigestException { + MessageDigest md = MessageDigest.getInstance("SHA1"); + + md.update(bytes); + byte[] digest = md.digest(); + + int[] result = {((int) digest[0] + 256) % 256, + ((int) digest[1] + 256) % 256, + ((int) digest[2] + 256) % 256}; + return result; + } + } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index adb06a068..d223a259f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -29,6 +29,7 @@ import android.support.v4.content.Loader; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.format.DateFormat; +import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; @@ -40,6 +41,7 @@ import com.beardedhen.androidbootstrap.BootstrapButton; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; @@ -47,6 +49,8 @@ import org.sufficientlysecure.keychain.ui.adapter.ViewKeyKeysAdapter; import org.sufficientlysecure.keychain.ui.adapter.ViewKeyUserIdsAdapter; import org.sufficientlysecure.keychain.util.Log; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Date; @@ -276,18 +280,40 @@ public class ViewKeyMainFragment extends Fragment implements private SpannableStringBuilder colorizeFingerprint(String fingerprint) { SpannableStringBuilder sb = new SpannableStringBuilder(fingerprint); - ForegroundColorSpan fcs = new ForegroundColorSpan(Color.BLACK); - - // for each 4 characters of the fingerprint + 1 space - for (int i = 0; i < fingerprint.length(); i += 5) { - int minFingLength = Math.min(i + 4, fingerprint.length()); - String fourChars = fingerprint.substring(i, minFingLength); - - // Create a foreground color by converting the 4 fingerprint chars to an int hashcode - // and then converting that int to hex to use as a color - fcs = new ForegroundColorSpan( - Color.parseColor(String.format("#%06X", (0xFFFFFF & fourChars.hashCode())))); - sb.setSpan(fcs, i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE); + try { + // for each 4 characters of the fingerprint + 1 space + for (int i = 0; i < fingerprint.length(); i += 5) { + int minFingLength = Math.min(i + 4, fingerprint.length()); + String fourChars = fingerprint.substring(i, minFingLength); + + int raw = Integer.parseInt(fourChars, 16); + byte[] bytes = {(byte) ((raw >> 8) & 0xff - 128), (byte) (raw & 0xff - 128)}; + int[] color = OtherHelper.getRgbForData(bytes); + + // Convert rgb to brightness + int brightness = (int) (0.2126*color[0] + 0.7152*color[1] + 0.0722*color[2]); + + // Detect dark colors and invert their background to white to make them more distinguishable + if (brightness < 40) { + sb.setSpan(new BackgroundColorSpan(Color.WHITE), + i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE); + + // Detect bright colors and invert their background to black to make them more distinguishable + } else if (brightness > 210) { + sb.setSpan(new BackgroundColorSpan(Color.BLACK), + i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE); + } + + // Create a foreground color with the 3 digest integers as RGB + // and then converting that int to hex to use as a color + sb.setSpan(new ForegroundColorSpan(Color.rgb(color[0], color[1], color[2])), + i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE); + } + } catch (Exception e) { + Log.e(Constants.TAG, "Colorization failed", e); + // if anything goes wrong, then just display the fingerprint without colour, + // instead of partially correct colour or wrong colours + return new SpannableStringBuilder(fingerprint); } return sb; -- cgit v1.2.3 From 0b0809ec17203ea14068b064360e45e435796829 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Thu, 13 Mar 2014 00:16:11 +0100 Subject: keychainprovider cleanup, kindasorta removed code redundancy, and the query is in the switch thing now, I didn't put everything into its own separate sources (yet?). --- .../keychain/provider/KeychainProvider.java | 96 +++++++++------------- .../keychain/ui/KeyListFragment.java | 7 +- 2 files changed, 47 insertions(+), 56 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 8b0efdbbd..3782f85fd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -467,70 +467,53 @@ public class KeychainProvider extends ContentProvider { int match = mUriMatcher.match(uri); - // screw that switch - if(match == UNIFIED_KEY_RING) { + // all query() parameters, for good measure + String groupBy = null, having = null; - // join keyrings with keys and userIds - // Only get user id and key with rank 0 (main user id and main key) - qb.setTables(Tables.KEY_RINGS + " INNER JOIN " + Tables.KEYS + " ON " + "(" - + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "." - + KeysColumns.KEY_RING_ROW_ID + " AND " + Tables.KEYS + "." - + KeysColumns.RANK + " = '0') " + " INNER JOIN " + Tables.USER_IDS + " ON " - + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.USER_IDS + "." - + UserIdsColumns.KEY_RING_ROW_ID + " AND " + Tables.USER_IDS + "." - + UserIdsColumns.RANK + " = '0')"); - - { - HashMap projectionMap = new HashMap(); - - projectionMap.put(KeyRingsColumns.TYPE, "MAX(" + Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + ")"); - - projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID); - projectionMap.put(KeyRingsColumns.KEY_RING_DATA, Tables.KEY_RINGS + "." - + KeyRingsColumns.KEY_RING_DATA); - projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID); - // TODO: deprecated master key id - //projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEYS + "." + KeysColumns.KEY_ID); - - projectionMap.put(KeysColumns.FINGERPRINT, Tables.KEYS + "." + KeysColumns.FINGERPRINT); - projectionMap.put(KeysColumns.IS_REVOKED, Tables.KEYS + "." + KeysColumns.IS_REVOKED); + switch (match) { + case UNIFIED_KEY_RING: - projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." + UserIdsColumns.USER_ID); + { // SELECT + // todo: outsource into getprojectionmapforthingies? don't really see the point. + HashMap projectionMap = new HashMap(); - qb.setProjectionMap(projectionMap); - } + // from keyrings table + projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID); + projectionMap.put(KeyRingsColumns.TYPE, + "MAX(" + Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + ")"); + projectionMap.put(KeyRingsColumns.KEY_RING_DATA, Tables.KEY_RINGS + "." + + KeyRingsColumns.KEY_RING_DATA); + projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, + Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID); - if (TextUtils.isEmpty(sortOrder)) { - sortOrder = Tables.USER_IDS + "." + UserIdsColumns.USER_ID + " ASC"; - } + // from keys table + projectionMap.put(KeysColumns.FINGERPRINT, Tables.KEYS + "." + KeysColumns.FINGERPRINT); + projectionMap.put(KeysColumns.IS_REVOKED, Tables.KEYS + "." + KeysColumns.IS_REVOKED); - // If no sort order is specified use the default - String orderBy; - if (TextUtils.isEmpty(sortOrder)) { - orderBy = Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " DESC"; - } else { - orderBy = Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " DESC, " + sortOrder; - } + // from user id table + projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." + UserIdsColumns.USER_ID); - Cursor c = qb.query(db, projection, selection, selectionArgs, - Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID, - null, orderBy); + qb.setProjectionMap(projectionMap); + } - // Tell the cursor what uri to watch, so it knows when its source data changes - c.setNotificationUri(getContext().getContentResolver(), uri); + { // FROM + // todo: outsource into buildUnifiedQuery()? see above. + // join keyrings with keys and userIds + // Only get user id and key with rank 0 (main user id and main key) + qb.setTables(Tables.KEY_RINGS + " INNER JOIN " + Tables.KEYS + " ON " + "(" + + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "." + + KeysColumns.KEY_RING_ROW_ID + " AND " + Tables.KEYS + "." + + KeysColumns.RANK + " = '0') " + " INNER JOIN " + Tables.USER_IDS + " ON " + + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.USER_IDS + "." + + UserIdsColumns.KEY_RING_ROW_ID + " AND " + Tables.USER_IDS + "." + + UserIdsColumns.RANK + " = '0')"); + } - if (Constants.DEBUG) { - Log.d(Constants.TAG, - "Query: " - + qb.buildQuery(projection, selection, selectionArgs, Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID, null, - orderBy, null)); - Log.d(Constants.TAG, "Cursor: " + DatabaseUtils.dumpCursorToString(c)); - } + // GROUP BY + groupBy = Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID; - return c; - } + break; - switch (match) { case PUBLIC_KEY_RING: case SECRET_KEY_RING: qb = buildKeyRingQuery(qb, match); @@ -705,7 +688,7 @@ public class KeychainProvider extends ContentProvider { orderBy = sortOrder; } - Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy); + Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, having, orderBy); // Tell the cursor what uri to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); @@ -855,6 +838,9 @@ public class KeychainProvider extends ContentProvider { // notify of changes in db getContext().getContentResolver().notifyChange(uri, null); + getContext().getContentResolver().notifyChange( + KeyRings.buildUnifiedKeyRingsUri().buildUpon().appendPath("lulz").build(), null + ); return count; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 5b57132d4..72af24717 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -31,6 +31,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; +import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; import org.sufficientlysecure.keychain.util.Log; @@ -255,7 +256,11 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL static final int INDEX_TYPE = 1; static final int INDEX_UID = 3; - static final String SORT_ORDER = UserIds.USER_ID + " ASC"; + static final String SORT_ORDER = + // show secret before public key + KeychainDatabase.Tables.KEY_RINGS + "." + KeyRings.TYPE + " DESC, " + // sort by user id otherwise + + UserIds.USER_ID + " ASC"; @Override public Loader onCreateLoader(int id, Bundle args) { -- cgit v1.2.3 From b9a907df0b305350c4ccf4f44d1178a0267c1062 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Thu, 13 Mar 2014 00:29:28 +0100 Subject: remove special treatment for unified list query note: the unified query /will/ need special treatment once certs are joined in, so I am leaving this as an artifact commit for later reference or point to revert to. --- .../keychain/provider/KeychainProvider.java | 53 ++++++---------------- 1 file changed, 14 insertions(+), 39 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 3782f85fd..cc08b26bd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -377,6 +377,10 @@ public class KeychainProvider extends ContentProvider { projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." + UserIdsColumns.USER_ID); + // type attribute is special: if there is any grouping, choose secret over public type + projectionMap.put(KeyRingsColumns.TYPE, + "MAX(" + Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + ") AS " + KeyRingsColumns.TYPE); + return projectionMap; } @@ -411,9 +415,11 @@ public class KeychainProvider extends ContentProvider { * Builds default query for keyRings: KeyRings table is joined with UserIds and Keys */ private SQLiteQueryBuilder buildKeyRingQuery(SQLiteQueryBuilder qb, int match) { - // public or secret keyring - qb.appendWhere(Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " = "); - qb.appendWhereEscapeString(Integer.toString(getKeyType(match))); + if(match != UNIFIED_KEY_RING) { + // public or secret keyring + qb.appendWhere(Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " = "); + qb.appendWhereEscapeString(Integer.toString(getKeyType(match))); + } // join keyrings with keys and userIds // Only get user id and key with rank 0 (main user id and main key) @@ -472,46 +478,15 @@ public class KeychainProvider extends ContentProvider { switch (match) { case UNIFIED_KEY_RING: + qb = buildKeyRingQuery(qb, match); - { // SELECT - // todo: outsource into getprojectionmapforthingies? don't really see the point. - HashMap projectionMap = new HashMap(); - - // from keyrings table - projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID); - projectionMap.put(KeyRingsColumns.TYPE, - "MAX(" + Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + ")"); - projectionMap.put(KeyRingsColumns.KEY_RING_DATA, Tables.KEY_RINGS + "." - + KeyRingsColumns.KEY_RING_DATA); - projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, - Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID); - - // from keys table - projectionMap.put(KeysColumns.FINGERPRINT, Tables.KEYS + "." + KeysColumns.FINGERPRINT); - projectionMap.put(KeysColumns.IS_REVOKED, Tables.KEYS + "." + KeysColumns.IS_REVOKED); - - // from user id table - projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." + UserIdsColumns.USER_ID); - - qb.setProjectionMap(projectionMap); - } + // GROUP BY so we don't get duplicates + groupBy = Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID; - { // FROM - // todo: outsource into buildUnifiedQuery()? see above. - // join keyrings with keys and userIds - // Only get user id and key with rank 0 (main user id and main key) - qb.setTables(Tables.KEY_RINGS + " INNER JOIN " + Tables.KEYS + " ON " + "(" - + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "." - + KeysColumns.KEY_RING_ROW_ID + " AND " + Tables.KEYS + "." - + KeysColumns.RANK + " = '0') " + " INNER JOIN " + Tables.USER_IDS + " ON " - + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.USER_IDS + "." - + UserIdsColumns.KEY_RING_ROW_ID + " AND " + Tables.USER_IDS + "." - + UserIdsColumns.RANK + " = '0')"); + if (TextUtils.isEmpty(sortOrder)) { + sortOrder = KeyRings.TYPE + " DESC, " + Tables.USER_IDS + "." + UserIdsColumns.USER_ID + " ASC"; } - // GROUP BY - groupBy = Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID; - break; case PUBLIC_KEY_RING: -- cgit v1.2.3 From 3f649d4458ef08c03bb671f78f2a65478c829400 Mon Sep 17 00:00:00 2001 From: grait Date: Tue, 11 Mar 2014 01:37:16 +0530 Subject: Export is cancellable now --- .../keychain/helper/ExportHelper.java | 30 +++++++++++++--------- .../keychain/pgp/PgpImportExport.java | 24 +++++++++++++++-- .../keychain/service/KeychainIntentService.java | 14 ++++++++-- 3 files changed, 52 insertions(+), 16 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 19dfccbde..245c5fda1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -16,17 +16,8 @@ package org.sufficientlysecure.keychain.helper; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround; -import org.sufficientlysecure.keychain.service.KeychainIntentService; -import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; -import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; -import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment; -import org.sufficientlysecure.keychain.util.Log; - import android.app.ProgressDialog; +import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; @@ -36,6 +27,16 @@ import android.os.Messenger; import android.support.v7.app.ActionBarActivity; import android.widget.Toast; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround; +import org.sufficientlysecure.keychain.service.KeychainIntentService; +import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; +import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; +import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment; +import org.sufficientlysecure.keychain.util.Log; + public class ExportHelper { protected FileDialogFragment mFileDialog; protected String mExportFilename; @@ -115,7 +116,7 @@ public class ExportHelper { Log.d(Constants.TAG, "exportKeys started"); // Send all information needed to service to export key in other thread - Intent intent = new Intent(activity, KeychainIntentService.class); + final Intent intent = new Intent(activity, KeychainIntentService.class); intent.setAction(KeychainIntentService.ACTION_EXPORT_KEYRING); @@ -135,7 +136,12 @@ public class ExportHelper { // Message is received after exporting is done in ApgService KeychainIntentServiceHandler exportHandler = new KeychainIntentServiceHandler(activity, - activity.getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL) { + activity.getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL, true, new DialogInterface.OnCancelListener() { + @Override + public void onCancel(DialogInterface dialogInterface) { + activity.stopService(intent); + } + }) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 138e54f71..0315650eb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -50,15 +50,28 @@ import android.os.Bundle; import android.os.Environment; public class PgpImportExport { + + public interface KeychainServiceListener{ + public boolean hasServiceStopped(); + } private Context mContext; private ProgressDialogUpdater mProgress; + private KeychainServiceListener mKeychainServiceListener; + public PgpImportExport(Context context, ProgressDialogUpdater progress) { super(); this.mContext = context; this.mProgress = progress; } + public PgpImportExport(Context context, ProgressDialogUpdater progress, KeychainServiceListener keychainListener){ + super(); + this.mContext = context; + this.mProgress = progress; + this.mKeychainServiceListener = keychainListener; + } + public void updateProgress(int message, int current, int total) { if (mProgress != null) { mProgress.setProgress(message, current, total); @@ -188,8 +201,10 @@ public class PgpImportExport { if (secretKeyRing != null) { secretKeyRing.encode(arOutStream); } - // Else if it's a public key get the PGPPublicKeyRing - // and encode that to the output + if(mKeychainServiceListener.hasServiceStopped()==true){ + arOutStream.close(); + return null; + } } else { updateProgress(i * 100 / rowIdsSize, 100); PGPPublicKeyRing publicKeyRing = @@ -198,6 +213,11 @@ public class PgpImportExport { if (publicKeyRing != null) { publicKeyRing.encode(arOutStream); } + + if(mKeychainServiceListener.hasServiceStopped() == true){ + arOutStream.close(); + return null; + } } arOutStream.close(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 93238349d..83531c8e2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -73,7 +73,7 @@ import android.os.RemoteException; * data from the activities or other apps, queues these intents, executes them, and stops itself * after doing them. */ -public class KeychainIntentService extends IntentService implements ProgressDialogUpdater { +public class KeychainIntentService extends IntentService implements ProgressDialogUpdater, PgpImportExport.KeychainServiceListener { /* extras that can be given by intent */ public static final String EXTRA_MESSENGER = "messenger"; @@ -712,10 +712,15 @@ public class KeychainIntentService extends IntentService implements ProgressDial Bundle resultData; - PgpImportExport pgpImportExport = new PgpImportExport(this, this); + PgpImportExport pgpImportExport = new PgpImportExport(this, this, this); + resultData = pgpImportExport .exportKeyRings(keyRingRowIds, keyType, outStream); + if(mIsCanceled){ + boolean isDeleted = new File(outputFile).delete(); + } + sendMessageToHandler(KeychainIntentServiceHandler.MESSAGE_OKAY, resultData); } catch (Exception e) { sendErrorToHandler(e); @@ -903,4 +908,9 @@ public class KeychainIntentService extends IntentService implements ProgressDial public void setProgress(int progress, int max) { setProgress(null, progress, max); } + + @Override + public boolean hasServiceStopped() { + return mIsCanceled; + } } -- cgit v1.2.3 From ccdf646c199b000ac12ad2ca7ecaaf90a01d79c7 Mon Sep 17 00:00:00 2001 From: grait Date: Tue, 11 Mar 2014 04:49:52 +0530 Subject: Export cancellable - minor changes --- .../java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java | 8 +++----- .../keychain/service/KeychainIntentService.java | 3 ++- .../sufficientlysecure/keychain/util/KeychainServiceListener.java | 5 +++++ 3 files changed, 10 insertions(+), 6 deletions(-) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 0315650eb..3ce9fa7c5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -42,6 +42,7 @@ import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; import org.sufficientlysecure.keychain.util.HkpKeyServer; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.KeyServer.AddKeyException; +import org.sufficientlysecure.keychain.util.KeychainServiceListener; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; @@ -51,9 +52,6 @@ import android.os.Environment; public class PgpImportExport { - public interface KeychainServiceListener{ - public boolean hasServiceStopped(); - } private Context mContext; private ProgressDialogUpdater mProgress; @@ -201,7 +199,7 @@ public class PgpImportExport { if (secretKeyRing != null) { secretKeyRing.encode(arOutStream); } - if(mKeychainServiceListener.hasServiceStopped()==true){ + if(mKeychainServiceListener.hasServiceStopped()){ arOutStream.close(); return null; } @@ -214,7 +212,7 @@ public class PgpImportExport { publicKeyRing.encode(arOutStream); } - if(mKeychainServiceListener.hasServiceStopped() == true){ + if(mKeychainServiceListener.hasServiceStopped()){ arOutStream.close(); return null; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 83531c8e2..23f489d35 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -56,6 +56,7 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; import org.sufficientlysecure.keychain.util.HkpKeyServer; import org.sufficientlysecure.keychain.util.InputData; +import org.sufficientlysecure.keychain.util.KeychainServiceListener; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; @@ -73,7 +74,7 @@ import android.os.RemoteException; * data from the activities or other apps, queues these intents, executes them, and stops itself * after doing them. */ -public class KeychainIntentService extends IntentService implements ProgressDialogUpdater, PgpImportExport.KeychainServiceListener { +public class KeychainIntentService extends IntentService implements ProgressDialogUpdater, KeychainServiceListener { /* extras that can be given by intent */ public static final String EXTRA_MESSENGER = "messenger"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java new file mode 100644 index 000000000..0d7513057 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java @@ -0,0 +1,5 @@ +package org.sufficientlysecure.keychain.util; + +public interface KeychainServiceListener { + boolean hasServiceStopped(); +} -- cgit v1.2.3 From 6af65a2a9b5f90b90bf8752820f40f89241d8014 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Thu, 13 Mar 2014 13:06:23 +0100 Subject: merge fixes as per comments in merge https://github.com/openpgp-keychain/openpgp-keychain/pull/403/files#r10540753 --- .../keychain/ui/KeyListFragment.java | 49 +++++++++------------- 1 file changed, 19 insertions(+), 30 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 72af24717..ea5c60c53 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -33,6 +33,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.ui.adapter.HighlightQueryCursorAdapter; import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; import org.sufficientlysecure.keychain.util.Log; @@ -203,6 +204,20 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL showDeleteKeyDialog(mode, ids); break; } + case R.id.menu_key_list_multi_export: { + // todo: public/secret needs to be handled differently here + ids = mStickyList.getWrappedList().getCheckedItemIds(); + ExportHelper mExportHelper = new ExportHelper((ActionBarActivity) getActivity()); + mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); + break; + } + case R.id.menu_key_list_multi_select_all: { + // select all + for (int i = 0; i < mStickyList.getCount(); i++) { + mStickyList.setItemChecked(i, true); + } + break; + } } return true; } @@ -455,7 +470,7 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL /** * Implements StickyListHeadersAdapter from library */ - private class KeyListAdapter extends CursorAdapter implements StickyListHeadersAdapter { + private class KeyListAdapter extends HighlightQueryCursorAdapter implements StickyListHeadersAdapter { private LayoutInflater mInflater; private int mIndexUserId; private int mIndexIsRevoked; @@ -698,42 +713,16 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL * Change color for multi-selection */ // default color - v.setBackgroundColor(Color.TRANSPARENT); if (mSelection.get(position) != null) { // this is a selected position, change color! v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); + } else { + v.setBackgroundColor(Color.TRANSPARENT); } - return v; - } - // search highlight methods - - public void setSearchQuery(String searchQuery) { - mCurQuery = searchQuery; - } - - public String getSearchQuery() { - return mCurQuery; + return v; } - protected Spannable highlightSearchQuery(String text) { - Spannable highlight = Spannable.Factory.getInstance().newSpannable(text); - - if (mCurQuery != null) { - Pattern pattern = Pattern.compile("(?i)" + mCurQuery); - Matcher matcher = pattern.matcher(text); - if (matcher.find()) { - highlight.setSpan( - new ForegroundColorSpan(mContext.getResources().getColor(R.color.emphasis)), - matcher.start(), - matcher.end(), - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); - } - return highlight; - } else { - return highlight; - } - } } } -- cgit v1.2.3 From be3828c89ee7cd4775ba6b442adb59f1007619ca Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Thu, 13 Mar 2014 14:34:07 +0100 Subject: drop unified uri in favor of generic /key_rings this works well in the uri schema, and we get notifications back with no effort. ....also remove a line I committed accidentally oO --- .../keychain/provider/KeychainContract.java | 3 +-- .../keychain/provider/KeychainProvider.java | 22 +++++++++------------- 2 files changed, 10 insertions(+), 15 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index 706b30d05..d9356951e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -78,7 +78,6 @@ public class KeychainContract { public static final String PATH_PUBLIC = "public"; public static final String PATH_SECRET = "secret"; - public static final String PATH_UNIFIED = "unified"; public static final String PATH_BY_MASTER_KEY_ID = "master_key_id"; public static final String PATH_BY_KEY_ID = "key_id"; @@ -102,7 +101,7 @@ public class KeychainContract { public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.key_ring"; public static Uri buildUnifiedKeyRingsUri() { - return CONTENT_URI.buildUpon().appendPath(PATH_UNIFIED).build(); + return CONTENT_URI; } public static Uri buildPublicKeyRingsUri() { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index cc08b26bd..1a131a689 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -96,6 +96,15 @@ public class KeychainProvider extends ContentProvider { String authority = KeychainContract.CONTENT_AUTHORITY; + /** + * unified key rings + * + *

+         * key_rings
+         * 
+ */ + matcher.addURI(authority, KeychainContract.BASE_KEY_RINGS, UNIFIED_KEY_RING); + /** * public key rings * @@ -228,16 +237,6 @@ public class KeychainProvider extends ContentProvider { matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_APPS_BY_PACKAGE_NAME); - /** - * unified key rings - *
-         *
-         * key_rings/unified
-         *
-         */
-        matcher.addURI(authority, KeychainContract.BASE_KEY_RINGS + "/"
-                + KeychainContract.PATH_UNIFIED, UNIFIED_KEY_RING);
-
         /**
          * data stream
          *
@@ -813,9 +812,6 @@ public class KeychainProvider extends ContentProvider {
 
         // notify of changes in db
         getContext().getContentResolver().notifyChange(uri, null);
-        getContext().getContentResolver().notifyChange(
-                KeyRings.buildUnifiedKeyRingsUri().buildUpon().appendPath("lulz").build(), null
-        );
 
         return count;
     }
-- 
cgit v1.2.3


From f055228e5bf9d43659238cef1652dc422d2690aa Mon Sep 17 00:00:00 2001
From: uberspot 
Date: Thu, 13 Mar 2014 16:09:37 +0200
Subject: add apg's change to colorizing, no more background changes needed

---
 .../keychain/ui/ViewKeyMainFragment.java           | 46 +++++++++++++++-------
 1 file changed, 31 insertions(+), 15 deletions(-)

(limited to 'OpenPGP-Keychain/src/main/java')

diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java
index d223a259f..a43e3f5b5 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java
@@ -283,31 +283,47 @@ public class ViewKeyMainFragment extends Fragment  implements
         try {
             // for each 4 characters of the fingerprint + 1 space
             for (int i = 0; i < fingerprint.length(); i += 5) {
-                int minFingLength = Math.min(i + 4, fingerprint.length());
-                String fourChars = fingerprint.substring(i, minFingLength);
+                int spanEnd = Math.min(i + 4, fingerprint.length());
+                String fourChars = fingerprint.substring(i, spanEnd);
 
                 int raw = Integer.parseInt(fourChars, 16);
                 byte[] bytes = {(byte) ((raw >> 8) & 0xff - 128), (byte) (raw & 0xff - 128)};
                 int[] color = OtherHelper.getRgbForData(bytes);
+                int r = color[0];
+                int g = color[1];
+                int b = color[2];
+
+                // we cannot change black by multiplication, so adjust it to an almost-black grey,
+                // which will then be brightened to the minimal brightness level
+                if (r == 0 && g == 0 && b == 0) {
+                    r = 1;
+                    g = 1;
+                    b = 1;
+                }
 
                 // Convert rgb to brightness
-                int brightness = (int) (0.2126*color[0] + 0.7152*color[1] + 0.0722*color[2]);
-
-                // Detect dark colors and invert their background to white to make them more distinguishable
-                if (brightness < 40) {
-                    sb.setSpan(new BackgroundColorSpan(Color.WHITE),
-                            i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
-
-                // Detect bright colors and invert their background to black to make them more distinguishable
-                } else if (brightness > 210) {
-                    sb.setSpan(new BackgroundColorSpan(Color.BLACK),
-                            i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
+                double brightness = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+
+                // If a color is too dark to be seen on black,
+                // then brighten it up to a minimal brightness.
+                if (brightness < 80) {
+                    double factor = 80.0 / brightness;
+                    r = Math.min(255, (int) (r * factor));
+                    g = Math.min(255, (int) (g * factor));
+                    b = Math.min(255, (int) (b * factor));
+
+                // If it is too light, then darken it to a respective maximal brightness.
+                } else if (brightness > 180) {
+                    double factor = 180.0 / brightness;
+                    r = (int) (r * factor);
+                    g = (int) (g * factor);
+                    b = (int) (b * factor);
                 }
 
                 // Create a foreground color with the 3 digest integers as RGB
                 // and then converting that int to hex to use as a color
-                sb.setSpan(new ForegroundColorSpan(Color.rgb(color[0], color[1], color[2])),
-                                            i, minFingLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
+                sb.setSpan(new ForegroundColorSpan(Color.rgb(r, g, b)),
+                                            i, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
             }
         } catch (Exception e) {
             Log.e(Constants.TAG, "Colorization failed", e);
-- 
cgit v1.2.3


From f4370b3ac8378a92192d8d84496aa6ea1fb27b0c Mon Sep 17 00:00:00 2001
From: gogowitczak 
Date: Thu, 13 Mar 2014 15:39:38 +0100
Subject: Added possibility to specify port for KeyServer.

---
 .../keychain/util/HkpKeyServer.java                | 54 ++++++++++++----------
 1 file changed, 30 insertions(+), 24 deletions(-)

(limited to 'OpenPGP-Keychain/src/main/java')

diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java
index 32266839c..b6ffa0ef0 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java
@@ -18,24 +18,7 @@
 
 package org.sufficientlysecure.keychain.util;
 
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.TimeZone;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.Locale;
-
+import android.text.Html;
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
@@ -51,7 +34,14 @@ import org.sufficientlysecure.keychain.pgp.PgpHelper;
 import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
 import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry;
 
-import android.text.Html;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.*;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * TODO:
@@ -82,7 +72,7 @@ public class HkpKeyServer extends KeyServer {
     }
 
     private String mHost;
-    private short mPort = 11371;
+    private short mPort;
 
     // example:
     // pub 2048R/9F5C9090 2009-08-17 hostname" (eg. "pool.sks-keyservers.net"), then it will
+	 *                connect using {@link #PORT_DEFAULT}. However, port may be specified after colon
+	 *                ("hostname:port", eg. "p80.pool.sks-keyservers.net:80").
+	 */
+	public HkpKeyServer(String hostAndPort) {
+		String host = hostAndPort;
+		short port = PORT_DEFAULT;
+		final int colonPosition = hostAndPort.lastIndexOf(':');
+		if (colonPosition > 0) {
+			host = hostAndPort.substring(0, colonPosition);
+			final String portStr = hostAndPort.substring(colonPosition + 1);
+			port = Short.decode(portStr);
+		}
+		mHost = host;
+		mPort = port;
+	}
 
     public HkpKeyServer(String host, short port) {
         mHost = host;
@@ -226,7 +232,7 @@ public class HkpKeyServer extends KeyServer {
         HttpClient client = new DefaultHttpClient();
         try {
             HttpGet get = new HttpGet("http://" + mHost + ":" + mPort
-                    + "/pks/lookup?op=get&search=" + PgpKeyHelper.convertKeyIdToHex(keyId));
+                    + "/pks/lookup?op=get&search=0x" + PgpKeyHelper.convertKeyIdToHex(keyId));
 
             HttpResponse response = client.execute(get);
             if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
-- 
cgit v1.2.3


From ccde4212e013ea5955cea26265423c84f4c74faf Mon Sep 17 00:00:00 2001
From: gogowitczak 
Date: Thu, 13 Mar 2014 15:53:43 +0100
Subject: Added possibility to specify port for KeyServer.

---
 .../main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java    | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

(limited to 'OpenPGP-Keychain/src/main/java')

diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java
index b6ffa0ef0..99cac1152 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java
@@ -232,7 +232,7 @@ public class HkpKeyServer extends KeyServer {
         HttpClient client = new DefaultHttpClient();
         try {
             HttpGet get = new HttpGet("http://" + mHost + ":" + mPort
-                    + "/pks/lookup?op=get&search=0x" + PgpKeyHelper.convertKeyIdToHex(keyId));
+                    + "/pks/lookup?op=get&search=" + PgpKeyHelper.convertKeyIdToHex(keyId));
 
             HttpResponse response = client.execute(get);
             if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
-- 
cgit v1.2.3


From 471cefa71f3ea91b07d1c5f94c95e9b17cecb7a6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= 
Date: Thu, 13 Mar 2014 18:27:08 +0100
Subject: Cleanup and simplification

---
 .../keychain/provider/KeychainProvider.java        |  2 +-
 .../keychain/ui/KeyListFragment.java               | 83 ++++++----------------
 2 files changed, 24 insertions(+), 61 deletions(-)

(limited to 'OpenPGP-Keychain/src/main/java')

diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java
index 1a131a689..fdc4b7bda 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java
@@ -414,7 +414,7 @@ public class KeychainProvider extends ContentProvider {
      * Builds default query for keyRings: KeyRings table is joined with UserIds and Keys
      */
     private SQLiteQueryBuilder buildKeyRingQuery(SQLiteQueryBuilder qb, int match) {
-        if(match != UNIFIED_KEY_RING) {
+        if (match != UNIFIED_KEY_RING) {
             // public or secret keyring
             qb.appendWhere(Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " = ");
             qb.appendWhereEscapeString(Integer.toString(getKeyType(match)));
diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java
index ea5c60c53..70ffe968d 100644
--- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java
+++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Dominik Schürmann 
+ * Copyright (C) 2013-2014 Dominik Schürmann 
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -19,8 +19,6 @@ package org.sufficientlysecure.keychain.ui;
 
 import java.util.HashMap;
 import java.util.ArrayList;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
 
 import org.sufficientlysecure.keychain.Constants;
 import org.sufficientlysecure.keychain.Id;
@@ -32,7 +30,6 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
 import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes;
 import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds;
 import org.sufficientlysecure.keychain.provider.KeychainDatabase;
-import org.sufficientlysecure.keychain.provider.ProviderHelper;
 import org.sufficientlysecure.keychain.ui.adapter.HighlightQueryCursorAdapter;
 import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment;
 import org.sufficientlysecure.keychain.util.Log;
@@ -57,13 +54,10 @@ import android.support.v4.app.Fragment;
 import android.support.v4.app.LoaderManager;
 import android.support.v4.content.CursorLoader;
 import android.support.v4.content.Loader;
-import android.support.v4.widget.CursorAdapter;
 import android.support.v4.view.MenuItemCompat;
 import android.support.v7.app.ActionBarActivity;
 import android.support.v7.widget.SearchView;
-import android.text.Spannable;
 import android.text.TextUtils;
-import android.text.style.ForegroundColorSpan;
 import android.view.ActionMode;
 import android.view.LayoutInflater;
 import android.view.Menu;
@@ -270,10 +264,13 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL
     };
 
     static final int INDEX_TYPE = 1;
-    static final int INDEX_UID = 3;
+    static final int INDEX_MASTER_KEY_ID = 2;
+    static final int INDEX_USER_ID = 3;
+    static final int INDEX_IS_REVOKED = 4;
+
     static final String SORT_ORDER =
-                // show secret before public key
-                KeychainDatabase.Tables.KEY_RINGS + "." + KeyRings.TYPE + " DESC, "
+            // show secret before public key
+            KeychainDatabase.Tables.KEY_RINGS + "." + KeyRings.TYPE + " DESC, "
                     // sort by user id otherwise
                     + UserIds.USER_ID + " ASC";
 
@@ -472,43 +469,20 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL
      */
     private class KeyListAdapter extends HighlightQueryCursorAdapter implements StickyListHeadersAdapter {
         private LayoutInflater mInflater;
-        private int mIndexUserId;
-        private int mIndexIsRevoked;
-        private int mMasterKeyId;
-
-        private String mCurQuery;
 
-        @SuppressLint("UseSparseArrays")
         private HashMap mSelection = new HashMap();
 
         public KeyListAdapter(Context context, Cursor c, int flags) {
             super(context, c, flags);
 
             mInflater = LayoutInflater.from(context);
-            initIndex(c);
         }
 
         @Override
         public Cursor swapCursor(Cursor newCursor) {
-            initIndex(newCursor);
-
             return super.swapCursor(newCursor);
         }
 
-        /**
-         * Get column indexes for performance reasons just once in constructor and swapCursor. For a
-         * performance comparison see http://stackoverflow.com/a/17999582
-         *
-         * @param cursor
-         */
-        private void initIndex(Cursor cursor) {
-            if (cursor != null) {
-                mIndexUserId = cursor.getColumnIndexOrThrow(KeychainContract.UserIds.USER_ID);
-                mIndexIsRevoked = cursor.getColumnIndexOrThrow(KeychainContract.Keys.IS_REVOKED);
-                mMasterKeyId = cursor.getColumnIndexOrThrow(KeychainContract.KeyRings.MASTER_KEY_ID);
-            }
-        }
-
         /**
          * Bind cursor data to the item list view
          * 

@@ -522,15 +496,15 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId); TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest); - String userId = cursor.getString(mIndexUserId); + String userId = cursor.getString(INDEX_USER_ID); String[] userIdSplit = PgpKeyHelper.splitUserId(userId); if (userIdSplit[0] != null) { - mainUserId.setText(highlightSearchQuery(userIdSplit[0])); + mainUserId.setText(highlightSearchQuery(userIdSplit[0])); } else { mainUserId.setText(R.string.user_id_no_name); } if (userIdSplit[1] != null) { - mainUserIdRest.setText(highlightSearchQuery(userIdSplit[1])); + mainUserIdRest.setText(highlightSearchQuery(userIdSplit[1])); mainUserIdRest.setVisibility(View.VISIBLE); } else { mainUserIdRest.setVisibility(View.GONE); @@ -541,12 +515,12 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL Button button = (Button) view.findViewById(R.id.edit); TextView revoked = (TextView) view.findViewById(R.id.revoked); - if(cursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { + if (cursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { // this is a secret key - show the edit button revoked.setVisibility(View.GONE); button.setVisibility(View.VISIBLE); - final long id = cursor.getLong(mMasterKeyId); + final long id = cursor.getLong(INDEX_MASTER_KEY_ID); button.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); @@ -559,7 +533,7 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL // this is a public key - hide the edit button, show if it's revoked button.setVisibility(View.GONE); - boolean isRevoked = cursor.getInt(mIndexIsRevoked) > 0; + boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0; revoked.setVisibility(isRevoked ? View.VISIBLE : View.GONE); } } @@ -567,23 +541,11 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL } public long getMasterKeyId(int id) { - if (!mCursor.moveToPosition(id)) { throw new IllegalStateException("couldn't move cursor to position " + id); } - return mCursor.getLong(mMasterKeyId); - - } - - public int getKeyType(int position) { - - if (!mCursor.moveToPosition(position)) { - throw new IllegalStateException("couldn't move cursor to position " + position); - } - - return mCursor.getInt(KeyListFragment.INDEX_TYPE); - + return mCursor.getLong(INDEX_MASTER_KEY_ID); } @Override @@ -621,7 +583,7 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL throw new IllegalStateException("couldn't move cursor to position " + position); } - if(mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { + if (mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { { // set contact count int num = mCursor.getCount(); String contactsTotal = getResources().getQuantityString(R.plurals.n_contacts, num, num); @@ -634,10 +596,10 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL } // set header text as first char in user id - String userId = mCursor.getString(KeyListFragment.INDEX_UID); + String userId = mCursor.getString(KeyListFragment.INDEX_USER_ID); String headerText = convertView.getResources().getString(R.string.user_id_no_name); if (userId != null && userId.length() > 0) { - headerText = "" + mCursor.getString(KeyListFragment.INDEX_UID).subSequence(0, 1).charAt(0); + headerText = "" + mCursor.getString(KeyListFragment.INDEX_USER_ID).subSequence(0, 1).charAt(0); } holder.text.setText(headerText); holder.count.setVisibility(View.GONE); @@ -660,11 +622,11 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL } // early breakout: all secret keys are assigned id 0 - if(mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) + if (mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) return 1L; // otherwise, return the first character of the name as ID - String userId = mCursor.getString(KeyListFragment.INDEX_UID); + String userId = mCursor.getString(KeyListFragment.INDEX_USER_ID); if (userId != null && userId.length() > 0) { return userId.charAt(0); } else { @@ -689,8 +651,9 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL long[] ids = new long[mSelection.size()]; int i = 0; // get master key ids - for (int pos : mSelection.keySet()) + for (int pos : mSelection.keySet()) { ids[i++] = mAdapter.getMasterKeyId(pos); + } return ids; } @@ -712,11 +675,11 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL /** * Change color for multi-selection */ - // default color if (mSelection.get(position) != null) { - // this is a selected position, change color! + // selected position color v.setBackgroundColor(parent.getResources().getColor(R.color.emphasis)); } else { + // default color v.setBackgroundColor(Color.TRANSPARENT); } -- cgit v1.2.3 From 4c5ae3cdaa525ca925b5e7229a7c02b89b8cefd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 13 Mar 2014 19:01:24 +0100 Subject: Readd create key menu items --- .../keychain/ui/KeyListActivity.java | 50 ++++++++++++++++------ 1 file changed, 38 insertions(+), 12 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 9eebbed64..684ee6959 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -53,19 +53,45 @@ public class KeyListActivity extends DrawerActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.menu_key_list_import: - Intent intentImport = new Intent(this, ImportKeysActivity.class); - startActivityForResult(intentImport, 0); - - return true; - case R.id.menu_key_list_export: - // TODO fix this for unified keylist - mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); - - return true; - default: - return super.onOptionsItemSelected(item); + case R.id.menu_key_list_import: + Intent intentImport = new Intent(this, ImportKeysActivity.class); + startActivityForResult(intentImport, 0); + + return true; + case R.id.menu_key_list_export: + // TODO fix this for unified keylist + mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); + + return true; + case R.id.menu_key_list_create: + createKey(); + + return true; + case R.id.menu_key_list_create_expert: + createKeyExpert(); + + return true; + case R.id.menu_key_list_secret_export: + mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); + + + default: + return super.onOptionsItemSelected(item); } } + private void createKey() { + Intent intent = new Intent(this, EditKeyActivity.class); + intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); + intent.putExtra(EditKeyActivity.EXTRA_GENERATE_DEFAULT_KEYS, true); + intent.putExtra(EditKeyActivity.EXTRA_USER_IDS, ""); // show user id view + startActivityForResult(intent, 0); + } + + private void createKeyExpert() { + Intent intent = new Intent(this, EditKeyActivity.class); + intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); + startActivityForResult(intent, 0); + } + } -- cgit v1.2.3 From 908cf8e7695b282760d7a790ae782346424e7ba8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 13 Mar 2014 19:08:03 +0100 Subject: Add FAQ tab to help --- .../sufficientlysecure/keychain/ui/HelpActivity.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java index ac8250bef..48068a6c4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2012-2014 Dominik Schürmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,8 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import java.util.ArrayList; - import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.ui.adapter.TabsAdapter; @@ -29,7 +27,7 @@ import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; public class HelpActivity extends ActionBarActivity { - public static final String EXTRA_SELECTED_TAB = "selectedTab"; + public static final String EXTRA_SELECTED_TAB = "selected_tab"; ViewPager mViewPager; TabsAdapter mTabsAdapter; @@ -59,19 +57,24 @@ public class HelpActivity extends ActionBarActivity { Bundle startBundle = new Bundle(); startBundle.putInt(HelpHtmlFragment.ARG_HTML_FILE, R.raw.help_start); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_start)), - HelpHtmlFragment.class, startBundle, (selectedTab == 0) ); + HelpHtmlFragment.class, startBundle, (selectedTab == 0)); + + Bundle faqBundle = new Bundle(); + faqBundle.putInt(HelpHtmlFragment.ARG_HTML_FILE, R.raw.help_faq); + mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_faq)), + HelpHtmlFragment.class, faqBundle, (selectedTab == 1)); Bundle nfcBundle = new Bundle(); nfcBundle.putInt(HelpHtmlFragment.ARG_HTML_FILE, R.raw.help_nfc_beam); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_nfc_beam)), - HelpHtmlFragment.class, nfcBundle, (selectedTab == 1) ); + HelpHtmlFragment.class, nfcBundle, (selectedTab == 2)); Bundle changelogBundle = new Bundle(); changelogBundle.putInt(HelpHtmlFragment.ARG_HTML_FILE, R.raw.help_changelog); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_changelog)), - HelpHtmlFragment.class, changelogBundle, (selectedTab == 2) ); + HelpHtmlFragment.class, changelogBundle, (selectedTab == 3)); mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_about)), - HelpAboutFragment.class, null, (selectedTab == 3) ); + HelpAboutFragment.class, null, (selectedTab == 4)); } } \ No newline at end of file -- cgit v1.2.3 From 79a8528a630d192566496a401abbbdabbbcf5d79 Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 19:29:21 +0200 Subject: Optimize imports in all files, remove useless whitespace in some and fix indentation --- .../keychain/service/KeychainIntentService.java | 61 +++++++--------------- .../service/KeychainIntentServiceHandler.java | 8 +-- .../keychain/service/PassphraseCacheService.java | 48 +++++++---------- .../service/remote/AppSettingsActivity.java | 23 ++++---- .../service/remote/AppSettingsFragment.java | 28 ++++------ .../keychain/service/remote/OpenPgpService.java | 1 - .../service/remote/RegisteredAppsAdapter.java | 5 +- .../service/remote/RegisteredAppsListActivity.java | 3 +- .../service/remote/RegisteredAppsListFragment.java | 9 ++-- .../keychain/service/remote/RemoteService.java | 21 ++++---- .../service/remote/RemoteServiceActivity.java | 1 - 11 files changed, 80 insertions(+), 128 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 23f489d35..f893e3488 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -17,57 +17,32 @@ package org.sufficientlysecure.keychain.service; -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.GregorianCalendar; -import java.util.List; - -import org.spongycastle.openpgp.PGPKeyRing; -import org.spongycastle.openpgp.PGPObjectFactory; -import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPUtil; +import android.app.IntentService; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import org.spongycastle.openpgp.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.FileHelper; import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.helper.Preferences; -import org.sufficientlysecure.keychain.pgp.PgpConversionHelper; -import org.sufficientlysecure.keychain.pgp.PgpDecryptVerify; -import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyResult; -import org.sufficientlysecure.keychain.pgp.PgpHelper; -import org.sufficientlysecure.keychain.pgp.PgpImportExport; -import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; -import org.sufficientlysecure.keychain.pgp.PgpSignEncrypt; +import org.sufficientlysecure.keychain.pgp.*; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; -import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainContract.DataStream; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; -import org.sufficientlysecure.keychain.util.HkpKeyServer; -import org.sufficientlysecure.keychain.util.InputData; -import org.sufficientlysecure.keychain.util.KeychainServiceListener; -import org.sufficientlysecure.keychain.util.Log; -import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; +import org.sufficientlysecure.keychain.util.*; -import android.app.IntentService; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; +import java.io.*; +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.List; /** * This Service contains all important long lasting operations for APG. It receives Intents with @@ -706,7 +681,7 @@ public class KeychainIntentService extends IntentService implements ProgressDial keyRingRowIds = ProviderHelper.getSecretKeyRingsRowIds(this); } } else { - for(long rowId : rowIds) { + for (long rowId : rowIds) { keyRingRowIds.add(rowId); } } @@ -718,8 +693,8 @@ public class KeychainIntentService extends IntentService implements ProgressDial resultData = pgpImportExport .exportKeyRings(keyRingRowIds, keyType, outStream); - if(mIsCanceled){ - boolean isDeleted = new File(outputFile).delete(); + if (mIsCanceled) { + boolean isDeleted = new File(outputFile).delete(); } sendMessageToHandler(KeychainIntentServiceHandler.MESSAGE_OKAY, resultData); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java index ebc002ceb..92d012c80 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentServiceHandler.java @@ -17,9 +17,6 @@ package org.sufficientlysecure.keychain.service; -import org.sufficientlysecure.keychain.ui.dialog.ProgressDialogFragment; -import org.sufficientlysecure.keychain.R; - import android.app.Activity; import android.content.DialogInterface.OnCancelListener; import android.os.Bundle; @@ -28,6 +25,8 @@ import android.os.Message; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.widget.Toast; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.dialog.ProgressDialogFragment; public class KeychainIntentServiceHandler extends Handler { @@ -73,7 +72,8 @@ public class KeychainIntentServiceHandler extends Handler { } public void showProgressDialog(FragmentActivity activity) { - // TODO: This is a hack!, see http://stackoverflow.com/questions/10114324/show-dialogfragment-from-onactivityresult + // TODO: This is a hack!, see + // http://stackoverflow.com/questions/10114324/show-dialogfragment-from-onactivityresult final FragmentManager manager = activity.getSupportFragmentManager(); Handler handler = new Handler(); handler.post(new Runnable() { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java index ce34d451d..134afbfdd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java @@ -17,10 +17,15 @@ package org.sufficientlysecure.keychain.service; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; - +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.*; +import android.util.Log; import android.util.LongSparseArray; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPPrivateKey; @@ -34,28 +39,13 @@ import org.sufficientlysecure.keychain.helper.Preferences; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.ProviderHelper; -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.app.Service; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.Binder; -import android.os.Bundle; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.IBinder; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; -import android.util.Log; +import java.util.Date; +import java.util.Iterator; /** * This service runs in its own process, but is available to all other processes as the main * passphrase cache. Use the static methods addCachedPassphrase and getCachedPassphrase for * convenience. - * */ public class PassphraseCacheService extends Service { public static final String TAG = Constants.TAG + ": PassphraseCacheService"; @@ -86,7 +76,7 @@ public class PassphraseCacheService extends Service { * This caches a new passphrase in memory by sending a new command to the service. An android * service is only run once. Thus, when the service is already started, new commands just add * new events to the alarm manager for new passphrases to let them timeout in the future. - * + * * @param context * @param keyId * @param passphrase @@ -106,7 +96,7 @@ public class PassphraseCacheService extends Service { /** * Gets a cached passphrase from memory by sending an intent to the service. This method is * designed to wait until the service returns the passphrase. - * + * * @param context * @param keyId * @return passphrase or null (if no passphrase is cached for this keyId) @@ -161,7 +151,7 @@ public class PassphraseCacheService extends Service { /** * Internal implementation to get cached passphrase. - * + * * @param keyId * @return */ @@ -205,7 +195,7 @@ public class PassphraseCacheService extends Service { /** * Checks if key has a passphrase. - * + * * @param secretKeyId * @return true if it has a passphrase */ @@ -216,8 +206,8 @@ public class PassphraseCacheService extends Service { .getPGPSecretKeyRingByKeyId(context, secretKeyId); PGPSecretKey secretKey = null; boolean foundValidKey = false; - for (Iterator keys = secRing.getSecretKeys(); keys.hasNext();) { - secretKey = (PGPSecretKey)keys.next(); + for (Iterator keys = secRing.getSecretKeys(); keys.hasNext(); ) { + secretKey = (PGPSecretKey) keys.next(); if (!secretKey.isPrivateKeyEmpty()) { foundValidKey = true; break; @@ -269,7 +259,7 @@ public class PassphraseCacheService extends Service { /** * Build pending intent that is executed by alarm manager to time out a specific passphrase - * + * * @param context * @param keyId * @return @@ -337,7 +327,7 @@ public class PassphraseCacheService extends Service { /** * Called when one specific passphrase for keyId timed out - * + * * @param context * @param keyId */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java index 178b2fc67..abdfb775c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java @@ -17,12 +17,6 @@ package org.sufficientlysecure.keychain.service.remote; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.util.Log; - import android.content.Intent; import android.net.Uri; import android.os.Bundle; @@ -30,6 +24,11 @@ import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ActionBarHelper; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.util.Log; public class AppSettingsActivity extends ActionBarActivity { private Uri mAppUri; @@ -77,12 +76,12 @@ public class AppSettingsActivity extends ActionBarActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.menu_api_settings_revoke: - revokeAccess(); - return true; - case R.id.menu_api_settings_cancel: - finish(); - return true; + case R.id.menu_api_settings_revoke: + revokeAccess(); + return true; + case R.id.menu_api_settings_cancel: + finish(); + return true; } return super.onOptionsItemSelected(item); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java index 64c4c5e96..a042e97d6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java @@ -17,17 +17,6 @@ package org.sufficientlysecure.keychain.service.remote; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import org.spongycastle.util.encoders.Hex; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; -import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; -import org.sufficientlysecure.keychain.util.AlgorithmNames; -import org.sufficientlysecure.keychain.util.Log; - import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; @@ -40,14 +29,19 @@ import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; -import android.widget.AdapterView; +import android.widget.*; import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.Spinner; -import android.widget.TextView; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.spongycastle.util.encoders.Hex; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; +import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; +import org.sufficientlysecure.keychain.util.AlgorithmNames; +import org.sufficientlysecure.keychain.util.Log; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; public class AppSettingsFragment extends Fragment implements SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java index f697faa6e..a94b19d44 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java @@ -23,7 +23,6 @@ import android.database.Cursor; import android.net.Uri; import android.os.IBinder; import android.os.ParcelFileDescriptor; - import org.openintents.openpgp.IOpenPgpService; import org.openintents.openpgp.OpenPgpError; import org.openintents.openpgp.OpenPgpSignatureResult; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java index 477ee04d0..7a49bfefa 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java @@ -17,9 +17,6 @@ package org.sufficientlysecure.keychain.service.remote; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; - import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; @@ -31,6 +28,8 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; public class RegisteredAppsAdapter extends CursorAdapter { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java index 3c553fff5..f6f216efd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java @@ -17,11 +17,10 @@ package org.sufficientlysecure.keychain.service.remote; +import android.os.Bundle; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.ui.DrawerActivity; -import android.os.Bundle; - public class RegisteredAppsListActivity extends DrawerActivity { @Override diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java index fed267a44..1a49e2e74 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java @@ -17,10 +17,6 @@ package org.sufficientlysecure.keychain.service.remote; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; - import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; @@ -33,6 +29,9 @@ import android.support.v4.content.Loader; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; public class RegisteredAppsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks { @@ -71,7 +70,7 @@ public class RegisteredAppsListFragment extends ListFragment implements } // These are the Contacts rows that we will retrieve. - static final String[] PROJECTION = new String[] { ApiApps._ID, ApiApps.PACKAGE_NAME }; + static final String[] PROJECTION = new String[]{ApiApps._ID, ApiApps.PACKAGE_NAME}; public Loader onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java index cb556be39..365008c01 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java @@ -17,17 +17,6 @@ package org.sufficientlysecure.keychain.service.remote; -import java.util.ArrayList; -import java.util.Arrays; - -import org.openintents.openpgp.OpenPgpError; -import org.openintents.openpgp.util.OpenPgpApi; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.util.Log; - import android.app.PendingIntent; import android.app.Service; import android.content.Context; @@ -38,6 +27,16 @@ import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.net.Uri; import android.os.Binder; +import org.openintents.openpgp.OpenPgpError; +import org.openintents.openpgp.util.OpenPgpApi; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.util.Log; + +import java.util.ArrayList; +import java.util.Arrays; /** * Abstract service class for remote APIs that handle app registration and user input. diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java index 8fb562884..88661c050 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java @@ -24,7 +24,6 @@ import android.os.Message; import android.os.Messenger; import android.support.v7.app.ActionBarActivity; import android.view.View; - import org.openintents.openpgp.util.OpenPgpApi; import org.sufficientlysecure.htmltextview.HtmlTextView; import org.sufficientlysecure.keychain.Constants; -- cgit v1.2.3 From 540aa044e242719cbcde4d8642bb918b79806bee Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 19:50:45 +0200 Subject: Fix code style in keychain/service/ --- .../keychain/service/KeychainIntentService.java | 41 ++++++++++++------- .../keychain/service/PassphraseCacheService.java | 4 +- .../keychain/service/remote/AppSettings.java | 46 +++++++++++----------- .../service/remote/AppSettingsActivity.java | 3 +- .../service/remote/AppSettingsFragment.java | 38 +++++++++--------- .../keychain/service/remote/OpenPgpService.java | 15 ++++--- .../service/remote/RegisteredAppsAdapter.java | 10 ++--- .../service/remote/RegisteredAppsListFragment.java | 2 +- .../keychain/service/remote/RemoteService.java | 14 ++++--- .../service/remote/RemoteServiceActivity.java | 24 ++++++----- .../remote/WrongPackageSignatureException.java | 19 ++++++++- 11 files changed, 129 insertions(+), 87 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index f893e3488..4e5812202 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -49,7 +49,8 @@ import java.util.List; * data from the activities or other apps, queues these intents, executes them, and stops itself * after doing them. */ -public class KeychainIntentService extends IntentService implements ProgressDialogUpdater, KeychainServiceListener { +public class KeychainIntentService extends IntentService + implements ProgressDialogUpdater, KeychainServiceListener { /* extras that can be given by intent */ public static final String EXTRA_MESSENGER = "messenger"; @@ -307,8 +308,10 @@ public class KeychainIntentService extends IntentService implements ProgressDial builder.enableAsciiArmorOutput(useAsciiArmor) .signatureForceV3(Preferences.getPreferences(this).getForceV3Signatures()) .signatureKeyId(secretKeyId) - .signatureHashAlgorithm(Preferences.getPreferences(this).getDefaultHashAlgorithm()) - .signaturePassphrase(PassphraseCacheService.getCachedPassphrase(this, secretKeyId)); + .signatureHashAlgorithm( + Preferences.getPreferences(this).getDefaultHashAlgorithm()) + .signaturePassphrase( + PassphraseCacheService.getCachedPassphrase(this, secretKeyId)); builder.build().generateSignature(); } else if (signOnly) { @@ -316,21 +319,26 @@ public class KeychainIntentService extends IntentService implements ProgressDial builder.enableAsciiArmorOutput(useAsciiArmor) .signatureForceV3(Preferences.getPreferences(this).getForceV3Signatures()) .signatureKeyId(secretKeyId) - .signatureHashAlgorithm(Preferences.getPreferences(this).getDefaultHashAlgorithm()) - .signaturePassphrase(PassphraseCacheService.getCachedPassphrase(this, secretKeyId)); + .signatureHashAlgorithm( + Preferences.getPreferences(this).getDefaultHashAlgorithm()) + .signaturePassphrase( + PassphraseCacheService.getCachedPassphrase(this, secretKeyId)); builder.build().execute(); } else { Log.d(Constants.TAG, "encrypt..."); builder.enableAsciiArmorOutput(useAsciiArmor) .compressionId(compressionId) - .symmetricEncryptionAlgorithm(Preferences.getPreferences(this).getDefaultEncryptionAlgorithm()) + .symmetricEncryptionAlgorithm( + Preferences.getPreferences(this).getDefaultEncryptionAlgorithm()) .signatureForceV3(Preferences.getPreferences(this).getForceV3Signatures()) .encryptionKeyIds(encryptionKeyIds) .encryptionPassphrase(encryptionPassphrase) .signatureKeyId(secretKeyId) - .signatureHashAlgorithm(Preferences.getPreferences(this).getDefaultHashAlgorithm()) - .signaturePassphrase(PassphraseCacheService.getCachedPassphrase(this, secretKeyId)); + .signatureHashAlgorithm( + Preferences.getPreferences(this).getDefaultHashAlgorithm()) + .signaturePassphrase( + PassphraseCacheService.getCachedPassphrase(this, secretKeyId)); builder.build().execute(); } @@ -522,7 +530,8 @@ public class KeychainIntentService extends IntentService implements ProgressDial ArrayList keys = PgpConversionHelper.BytesToPGPSecretKeyList(data .getByteArray(SAVE_KEYRING_KEYS)); ArrayList keysUsages = data.getIntegerArrayList(SAVE_KEYRING_KEYS_USAGES); - ArrayList keysExpiryDates = (ArrayList) data.getSerializable(SAVE_KEYRING_KEYS_EXPIRY_DATES); + ArrayList keysExpiryDates = + (ArrayList) data.getSerializable(SAVE_KEYRING_KEYS_EXPIRY_DATES); long masterKeyId = data.getLong(SAVE_KEYRING_MASTER_KEY_ID); @@ -577,7 +586,8 @@ public class KeychainIntentService extends IntentService implements ProgressDial int keysTotal = 2; int keysCreated = 0; setProgress( - getApplicationContext().getResources().getQuantityString(R.plurals.progress_generating, keysTotal), + getApplicationContext().getResources(). + getQuantityString(R.plurals.progress_generating, keysTotal), keysCreated, keysTotal); PgpKeyOperation keyOperations = new PgpKeyOperation(this, this); @@ -746,7 +756,8 @@ public class KeychainIntentService extends IntentService implements ProgressDial // need to have access to the bufferedInput, so we can reuse it for the possible // PGPObject chunks after the first one, e.g. files with several consecutive ASCII // armor blocks - BufferedInputStream bufferedInput = new BufferedInputStream(new ByteArrayInputStream(downloadedKey)); + BufferedInputStream bufferedInput = + new BufferedInputStream(new ByteArrayInputStream(downloadedKey)); try { // read all available blocks... (asc files can contain many blocks with BEGIN END) @@ -818,9 +829,9 @@ public class KeychainIntentService extends IntentService implements ProgressDial private void sendErrorToHandler(Exception e) { // Service was canceled. Do not send error to handler. - if (this.mIsCanceled) + if (this.mIsCanceled) { return; - + } Log.e(Constants.TAG, "ApgService Exception: ", e); e.printStackTrace(); @@ -831,9 +842,9 @@ public class KeychainIntentService extends IntentService implements ProgressDial private void sendMessageToHandler(Integer arg1, Integer arg2, Bundle data) { // Service was canceled. Do not send message to handler. - if (this.mIsCanceled) + if (this.mIsCanceled) { return; - + } Message msg = Message.obtain(); msg.arg1 = arg1; if (arg2 != null) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java index 134afbfdd..176d09c1a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java @@ -214,9 +214,9 @@ public class PassphraseCacheService extends Service { } } - if (!foundValidKey) + if (!foundValidKey) { return false; - + } PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( "SC").build("".toCharArray()); PGPPrivateKey testKey = secretKey.extractPrivateKey(keyDecryptor); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java index 9da4c8392..6f2d67efb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java @@ -22,12 +22,12 @@ import org.spongycastle.openpgp.PGPEncryptedData; import org.sufficientlysecure.keychain.Id; public class AppSettings { - private String packageName; - private byte[] packageSignature; - private long keyId = Id.key.none; - private int encryptionAlgorithm; - private int hashAlgorithm; - private int compression; + private String mPackageName; + private byte[] mPackageSignature; + private long mKeyId = Id.key.none; + private int mEncryptionAlgorithm; + private int mHashAlgorithm; + private int mCompression; public AppSettings() { @@ -35,60 +35,60 @@ public class AppSettings { public AppSettings(String packageName, byte[] packageSignature) { super(); - this.packageName = packageName; - this.packageSignature = packageSignature; + this.mPackageName = packageName; + this.mPackageSignature = packageSignature; // defaults: - this.encryptionAlgorithm = PGPEncryptedData.AES_256; - this.hashAlgorithm = HashAlgorithmTags.SHA512; - this.compression = Id.choice.compression.zlib; + this.mEncryptionAlgorithm = PGPEncryptedData.AES_256; + this.mHashAlgorithm = HashAlgorithmTags.SHA512; + this.mCompression = Id.choice.compression.zlib; } public String getPackageName() { - return packageName; + return mPackageName; } public void setPackageName(String packageName) { - this.packageName = packageName; + this.mPackageName = packageName; } public byte[] getPackageSignature() { - return packageSignature; + return mPackageSignature; } public void setPackageSignature(byte[] packageSignature) { - this.packageSignature = packageSignature; + this.mPackageSignature = packageSignature; } public long getKeyId() { - return keyId; + return mKeyId; } public void setKeyId(long scretKeyId) { - this.keyId = scretKeyId; + this.mKeyId = scretKeyId; } public int getEncryptionAlgorithm() { - return encryptionAlgorithm; + return mEncryptionAlgorithm; } public void setEncryptionAlgorithm(int encryptionAlgorithm) { - this.encryptionAlgorithm = encryptionAlgorithm; + this.mEncryptionAlgorithm = encryptionAlgorithm; } public int getHashAlgorithm() { - return hashAlgorithm; + return mHashAlgorithm; } public void setHashAlgorithm(int hashAlgorithm) { - this.hashAlgorithm = hashAlgorithm; + this.mHashAlgorithm = hashAlgorithm; } public int getCompression() { - return compression; + return mCompression; } public void setCompression(int compression) { - this.compression = compression; + this.mCompression = compression; } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java index abdfb775c..2ef170dec 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java @@ -40,7 +40,8 @@ public class AppSettingsActivity extends ActionBarActivity { super.onCreate(savedInstanceState); // Inflate a "Done" custom action bar - ActionBarHelper.setOneButtonView(getSupportActionBar(), R.string.api_settings_save, R.drawable.ic_action_done, + ActionBarHelper.setOneButtonView(getSupportActionBar(), + R.string.api_settings_save, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java index a042e97d6..837295018 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java @@ -47,7 +47,7 @@ public class AppSettingsFragment extends Fragment implements SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { // model - private AppSettings appSettings; + private AppSettings mAppSettings; // view private LinearLayout mAdvancedSettingsContainer; @@ -62,16 +62,16 @@ public class AppSettingsFragment extends Fragment implements private SelectSecretKeyLayoutFragment mSelectKeyFragment; - KeyValueSpinnerAdapter encryptionAdapter; - KeyValueSpinnerAdapter hashAdapter; - KeyValueSpinnerAdapter compressionAdapter; + KeyValueSpinnerAdapter mEncryptionAdapter; + KeyValueSpinnerAdapter mHashAdapter; + KeyValueSpinnerAdapter mCompressionAdapter; public AppSettings getAppSettings() { - return appSettings; + return mAppSettings; } public void setAppSettings(AppSettings appSettings) { - this.appSettings = appSettings; + this.mAppSettings = appSettings; setPackage(appSettings.getPackageName()); mPackageName.setText(appSettings.getPackageName()); @@ -87,10 +87,10 @@ public class AppSettingsFragment extends Fragment implements } mSelectKeyFragment.selectKey(appSettings.getKeyId()); - mEncryptionAlgorithm.setSelection(encryptionAdapter.getPosition(appSettings + mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(appSettings .getEncryptionAlgorithm())); - mHashAlgorithm.setSelection(hashAdapter.getPosition(appSettings.getHashAlgorithm())); - mCompression.setSelection(compressionAdapter.getPosition(appSettings.getCompression())); + mHashAlgorithm.setSelection(mHashAdapter.getPosition(appSettings.getHashAlgorithm())); + mCompression.setSelection(mCompressionAdapter.getPosition(appSettings.getCompression())); } /** @@ -133,14 +133,14 @@ public class AppSettingsFragment extends Fragment implements AlgorithmNames algorithmNames = new AlgorithmNames(getActivity()); - encryptionAdapter = new KeyValueSpinnerAdapter(getActivity(), + mEncryptionAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getEncryptionNames()); - mEncryptionAlgorithm.setAdapter(encryptionAdapter); + mEncryptionAlgorithm.setAdapter(mEncryptionAdapter); mEncryptionAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - appSettings.setEncryptionAlgorithm((int) id); + mAppSettings.setEncryptionAlgorithm((int) id); } @Override @@ -148,13 +148,13 @@ public class AppSettingsFragment extends Fragment implements } }); - hashAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getHashNames()); - mHashAlgorithm.setAdapter(hashAdapter); + mHashAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getHashNames()); + mHashAlgorithm.setAdapter(mHashAdapter); mHashAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - appSettings.setHashAlgorithm((int) id); + mAppSettings.setHashAlgorithm((int) id); } @Override @@ -162,14 +162,14 @@ public class AppSettingsFragment extends Fragment implements } }); - compressionAdapter = new KeyValueSpinnerAdapter(getActivity(), + mCompressionAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getCompressionNames()); - mCompression.setAdapter(compressionAdapter); + mCompression.setAdapter(mCompressionAdapter); mCompression.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - appSettings.setCompression((int) id); + mAppSettings.setCompression((int) id); } @Override @@ -231,7 +231,7 @@ public class AppSettingsFragment extends Fragment implements */ @Override public void onKeySelected(long secretKeyId) { - appSettings.setKeyId(secretKeyId); + mAppSettings.setKeyId(secretKeyId); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java index a94b19d44..95dc897f0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java @@ -99,7 +99,8 @@ public class OpenPgpService extends RemoteService { intent.putExtra(RemoteServiceActivity.EXTRA_DUBLICATE_USER_IDS, dublicateUserIds); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), PRIVATE_REQUEST_CODE_USER_IDS, intent, 0); + PendingIntent pi = PendingIntent.getActivity + (getBaseContext(), PRIVATE_REQUEST_CODE_USER_IDS, intent, 0); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -125,7 +126,8 @@ public class OpenPgpService extends RemoteService { intent.putExtra(RemoteServiceActivity.EXTRA_SECRET_KEY_ID, keyId); // pass params through to activity that it can be returned again later to repeat pgp operation intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), PRIVATE_REQUEST_CODE_PASSPHRASE, intent, 0); + PendingIntent pi = PendingIntent.getActivity + (getBaseContext(), PRIVATE_REQUEST_CODE_PASSPHRASE, intent, 0); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -207,7 +209,8 @@ public class OpenPgpService extends RemoteService { } else { Intent result = new Intent(); result.putExtra(OpenPgpApi.RESULT_ERROR, - new OpenPgpError(OpenPgpError.GENERIC_ERROR, "Missing parameter user_ids or key_ids!")); + new OpenPgpError(OpenPgpError.GENERIC_ERROR, + "Missing parameter user_ids or key_ids!")); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); return result; } @@ -288,7 +291,8 @@ public class OpenPgpService extends RemoteService { PgpDecryptVerify.Builder builder = new PgpDecryptVerify.Builder(this, inputData, os); builder.assumeSymmetric(false) // no support for symmetric encryption - .enforcedKeyId(appSettings.getKeyId()) // allow only the private key for this app for decryption + // allow only the private key for this app for decryption + .enforcedKeyId(appSettings.getKeyId()) .passphrase(passphrase); // TODO: currently does not support binary signed-only content @@ -402,7 +406,8 @@ public class OpenPgpService extends RemoteService { // version code is required and needs to correspond to version code of service! if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != OpenPgpApi.API_VERSION) { Intent result = new Intent(); - OpenPgpError error = new OpenPgpError(OpenPgpError.INCOMPATIBLE_API_VERSIONS, "Incompatible API versions!"); + OpenPgpError error = new OpenPgpError + (OpenPgpError.INCOMPATIBLE_API_VERSIONS, "Incompatible API versions!"); result.putExtra(OpenPgpApi.RESULT_ERROR, error); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); return result; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java index 7a49bfefa..e0dc4162f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java @@ -34,13 +34,13 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; public class RegisteredAppsAdapter extends CursorAdapter { private LayoutInflater mInflater; - private PackageManager pm; + private PackageManager mPM; public RegisteredAppsAdapter(Context context, Cursor c, int flags) { super(context, c, flags); mInflater = LayoutInflater.from(context); - pm = context.getApplicationContext().getPackageManager(); + mPM = context.getApplicationContext().getPackageManager(); } @Override @@ -52,10 +52,10 @@ public class RegisteredAppsAdapter extends CursorAdapter { if (packageName != null) { // get application name try { - ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); + ApplicationInfo ai = mPM.getApplicationInfo(packageName, 0); - text.setText(pm.getApplicationLabel(ai)); - icon.setImageDrawable(pm.getApplicationIcon(ai)); + text.setText(mPM.getApplicationLabel(ai)); + icon.setImageDrawable(mPM.getApplicationIcon(ai)); } catch (final NameNotFoundException e) { // fallback text.setText(packageName); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java index 1a49e2e74..25d0c7593 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java @@ -98,4 +98,4 @@ public class RegisteredAppsListFragment extends ListFragment implements mAdapter.swapCursor(null); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java index 365008c01..6a883316a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java @@ -83,7 +83,8 @@ public abstract class RemoteService extends Service { intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_SIGNATURE, packageSignature); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), PRIVATE_REQUEST_CODE_REGISTER, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), + PRIVATE_REQUEST_CODE_REGISTER, intent, 0); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -97,10 +98,12 @@ public abstract class RemoteService extends Service { Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); - intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, getString(R.string.api_error_wrong_signature)); + intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, + getString(R.string.api_error_wrong_signature)); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), PRIVATE_REQUEST_CODE_ERROR, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), + PRIVATE_REQUEST_CODE_ERROR, intent, 0); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -137,8 +140,9 @@ public abstract class RemoteService extends Service { AppSettings settings = ProviderHelper.getApiAppSettings(this, uri); - if (settings != null) + if (settings != null) { return settings; + } } return null; @@ -212,7 +216,7 @@ public abstract class RemoteService extends Service { return true; } else { throw new WrongPackageSignatureException( - "PACKAGE NOT ALLOWED! Signature wrong! (Signature not equals signature from database)"); + "PACKAGE NOT ALLOWED! Signature wrong! (Signature not equals signature from database)"); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java index 88661c050..e20114853 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java @@ -87,7 +87,8 @@ public class RemoteServiceActivity extends ActionBarActivity { final byte[] packageSignature = extras.getByteArray(EXTRA_PACKAGE_SIGNATURE); // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setTwoButtonView(getSupportActionBar(), R.string.api_register_allow, R.drawable.ic_action_done, + ActionBarHelper.setTwoButtonView(getSupportActionBar(), + R.string.api_register_allow, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { @@ -107,13 +108,14 @@ public class RemoteServiceActivity extends ActionBarActivity { RemoteServiceActivity.this.finish(); } } - }, R.string.api_register_disallow, R.drawable.ic_action_cancel, new View.OnClickListener() { - @Override - public void onClick(View v) { - // Disallow - RemoteServiceActivity.this.setResult(RESULT_CANCELED); - RemoteServiceActivity.this.finish(); - } + }, R.string.api_register_disallow, R.drawable.ic_action_cancel, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // Disallow + RemoteServiceActivity.this.setResult(RESULT_CANCELED); + RemoteServiceActivity.this.finish(); + } } ); @@ -160,7 +162,8 @@ public class RemoteServiceActivity extends ActionBarActivity { } // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setTwoButtonView(getSupportActionBar(), R.string.btn_okay, R.drawable.ic_action_done, + ActionBarHelper.setTwoButtonView(getSupportActionBar(), + R.string.btn_okay, R.drawable.ic_action_done, new View.OnClickListener() { @Override public void onClick(View v) { @@ -213,7 +216,8 @@ public class RemoteServiceActivity extends ActionBarActivity { String text = "" + errorMessage + ""; // Inflate a "Done" custom action bar view - ActionBarHelper.setOneButtonView(getSupportActionBar(), R.string.btn_okay, R.drawable.ic_action_done, + ActionBarHelper.setOneButtonView(getSupportActionBar(), + R.string.btn_okay, R.drawable.ic_action_done, new View.OnClickListener() { @Override diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java index cc08548e8..0b642086a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + package org.sufficientlysecure.keychain.service.remote; public class WrongPackageSignatureException extends Exception { @@ -7,4 +24,4 @@ public class WrongPackageSignatureException extends Exception { public WrongPackageSignatureException(String message) { super(message); } -} \ No newline at end of file +} -- cgit v1.2.3 From f26ba217e567aa35a6bcee2665c12c612440cbda Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 19:59:27 +0200 Subject: Fix code style in /helper --- .../keychain/helper/ActionBarHelper.java | 23 +++++----- .../keychain/helper/ExportHelper.java | 50 +++++++++++----------- .../keychain/helper/FileHelper.java | 37 +++++++--------- .../keychain/helper/OtherHelper.java | 16 +++---- .../keychain/helper/Preferences.java | 9 ++-- 5 files changed, 64 insertions(+), 71 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java index 24e8ff4c7..91e50637e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java @@ -17,24 +17,23 @@ package org.sufficientlysecure.keychain.helper; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.util.Log; - import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; import android.view.View.OnClickListener; +import android.view.ViewGroup; import android.widget.TextView; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.util.Log; public class ActionBarHelper { /** * Set actionbar without home button if called from another app - * + * * @param activity */ public static void setBackButton(ActionBarActivity activity) { @@ -54,7 +53,7 @@ public class ActionBarHelper { /** * Sets custom view on ActionBar for Done/Cancel activities - * + * * @param actionBar * @param firstText * @param firstDrawableId @@ -63,9 +62,9 @@ public class ActionBarHelper { * @param secondDrawableId * @param secondOnClickListener */ - public static void setTwoButtonView(ActionBar actionBar, int firstText, int firstDrawableId, - OnClickListener firstOnClickListener, int secondText, int secondDrawableId, - OnClickListener secondOnClickListener) { + public static void setTwoButtonView(ActionBar actionBar, + int firstText, int firstDrawableId, OnClickListener firstOnClickListener, + int secondText, int secondDrawableId, OnClickListener secondOnClickListener) { // Inflate the custom action bar view final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() @@ -94,13 +93,13 @@ public class ActionBarHelper { /** * Sets custom view on ActionBar for Done activities - * + * * @param actionBar * @param firstText * @param firstOnClickListener */ public static void setOneButtonView(ActionBar actionBar, int firstText, int firstDrawableId, - OnClickListener firstOnClickListener) { + OnClickListener firstOnClickListener) { // Inflate a "Done" custom action bar view to serve as the "Up" affordance. final LayoutInflater inflater = (LayoutInflater) actionBar.getThemedContext() .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 245c5fda1..557d75dbf 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -26,7 +26,6 @@ import android.os.Message; import android.os.Messenger; import android.support.v7.app.ActionBarActivity; import android.widget.Toast; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -41,11 +40,11 @@ public class ExportHelper { protected FileDialogFragment mFileDialog; protected String mExportFilename; - ActionBarActivity activity; + ActionBarActivity mActivity; public ExportHelper(ActionBarActivity activity) { super(); - this.activity = activity; + this.mActivity = activity; } public void deleteKey(Uri dataUri, final int keyType, Handler deleteHandler) { @@ -55,16 +54,16 @@ public class ExportHelper { Messenger messenger = new Messenger(deleteHandler); DeleteKeyDialogFragment deleteKeyDialog = DeleteKeyDialogFragment.newInstance(messenger, - new long[] { keyRingRowId }, keyType); + new long[]{keyRingRowId}, keyType); - deleteKeyDialog.show(activity.getSupportFragmentManager(), "deleteKeyDialog"); + deleteKeyDialog.show(mActivity.getSupportFragmentManager(), "deleteKeyDialog"); } /** * Show dialog where to export keys */ public void showExportKeysDialog(final long[] rowIds, final int keyType, - final String exportFilename) { + final String exportFilename) { mExportFilename = exportFilename; // Message is received after file is selected @@ -88,23 +87,23 @@ public class ExportHelper { String title = null; if (rowIds == null) { // export all keys - title = activity.getString(R.string.title_export_keys); + title = mActivity.getString(R.string.title_export_keys); } else { // export only key specified at data uri - title = activity.getString(R.string.title_export_key); + title = mActivity.getString(R.string.title_export_key); } String message = null; if (keyType == Id.type.public_key) { - message = activity.getString(R.string.specify_file_to_export_to); + message = mActivity.getString(R.string.specify_file_to_export_to); } else { - message = activity.getString(R.string.specify_file_to_export_secret_keys_to); + message = mActivity.getString(R.string.specify_file_to_export_secret_keys_to); } mFileDialog = FileDialogFragment.newInstance(messenger, title, message, exportFilename, null); - mFileDialog.show(activity.getSupportFragmentManager(), "fileDialog"); + mFileDialog.show(mActivity.getSupportFragmentManager(), "fileDialog"); } }); } @@ -116,7 +115,7 @@ public class ExportHelper { Log.d(Constants.TAG, "exportKeys started"); // Send all information needed to service to export key in other thread - final Intent intent = new Intent(activity, KeychainIntentService.class); + final Intent intent = new Intent(mActivity, KeychainIntentService.class); intent.setAction(KeychainIntentService.ACTION_EXPORT_KEYRING); @@ -135,12 +134,15 @@ public class ExportHelper { intent.putExtra(KeychainIntentService.EXTRA_DATA, data); // Message is received after exporting is done in ApgService - KeychainIntentServiceHandler exportHandler = new KeychainIntentServiceHandler(activity, - activity.getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL, true, new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialogInterface) { - activity.stopService(intent); - } + KeychainIntentServiceHandler exportHandler = new KeychainIntentServiceHandler(mActivity, + mActivity.getString(R.string.progress_exporting), + ProgressDialog.STYLE_HORIZONTAL, + true, + new DialogInterface.OnCancelListener() { + @Override + public void onCancel(DialogInterface dialogInterface) { + mActivity.stopService(intent); + } }) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first @@ -153,13 +155,13 @@ public class ExportHelper { int exported = returnData.getInt(KeychainIntentService.RESULT_EXPORT); String toastMessage; if (exported == 1) { - toastMessage = activity.getString(R.string.key_exported); + toastMessage = mActivity.getString(R.string.key_exported); } else if (exported > 0) { - toastMessage = activity.getString(R.string.keys_exported, exported); + toastMessage = mActivity.getString(R.string.keys_exported, exported); } else { - toastMessage = activity.getString(R.string.no_keys_exported); + toastMessage = mActivity.getString(R.string.no_keys_exported); } - Toast.makeText(activity, toastMessage, Toast.LENGTH_SHORT).show(); + Toast.makeText(mActivity, toastMessage, Toast.LENGTH_SHORT).show(); } } @@ -170,10 +172,10 @@ public class ExportHelper { intent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger); // show progress dialog - exportHandler.showProgressDialog(activity); + exportHandler.showProgressDialog(mActivity); // start service with intent - activity.startService(intent); + mActivity.startService(intent); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java index ec56fe912..d24aeca52 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java @@ -17,10 +17,6 @@ package org.sufficientlysecure.keychain.helper; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.util.Log; - import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; @@ -30,12 +26,15 @@ import android.net.Uri; import android.os.Environment; import android.support.v4.app.Fragment; import android.widget.Toast; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.util.Log; public class FileHelper { /** * Checks if external storage is mounted if file is located on external storage - * + * * @param file * @return true if storage is mounted */ @@ -52,15 +51,12 @@ public class FileHelper { /** * Opens the preferred installed file manager on Android and shows a toast if no manager is * installed. - * + * * @param activity - * @param filename - * default selected file, not supported by all file managers - * @param mimeType - * can be text/plain for example - * @param requestCode - * requestCode used to identify the result coming back from file manager to - * onActivityResult() in your activity + * @param filename default selected file, not supported by all file managers + * @param mimeType can be text/plain for example + * @param requestCode requestCode used to identify the result coming back from file manager to + * onActivityResult() in your activity */ public static void openFile(Activity activity, String filename, String mimeType, int requestCode) { Intent intent = buildFileIntent(filename, mimeType); @@ -97,14 +93,13 @@ public class FileHelper { /** * Get a file path from a Uri. - * + *

* from https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/ * afilechooser/utils/FileUtils.java - * + * * @param context * @param uri * @return - * * @author paulburke */ public static String getPath(Context context, Uri uri) { @@ -115,21 +110,19 @@ public class FileHelper { + uri.getPathSegments().toString()); if ("content".equalsIgnoreCase(uri.getScheme())) { - String[] projection = { "_data" }; + String[] projection = {"_data"}; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, null, null, null); - int column_index = cursor.getColumnIndexOrThrow("_data"); + int columnIndex = cursor.getColumnIndexOrThrow("_data"); if (cursor.moveToFirst()) { - return cursor.getString(column_index); + return cursor.getString(columnIndex); } } catch (Exception e) { // Eat it } - } - - else if ("file".equalsIgnoreCase(uri.getScheme())) { + } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java index 292b5bf3d..eb46a52e5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java @@ -17,22 +17,21 @@ package org.sufficientlysecure.keychain.helper; +import android.os.Bundle; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.util.Log; + import java.security.DigestException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Set; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.util.Log; - -import android.os.Bundle; - public class OtherHelper { /** * Logs bundle content to debug for inspecting the content - * + * * @param bundle * @param bundleName */ @@ -63,6 +62,7 @@ public class OtherHelper { /** * Converts the given bytes to a unique RGB color using SHA1 algorithm + * * @param bytes * @return an integer array containing 3 numeric color representations (Red, Green, Black) * @throws NoSuchAlgorithmException @@ -75,8 +75,8 @@ public class OtherHelper { byte[] digest = md.digest(); int[] result = {((int) digest[0] + 256) % 256, - ((int) digest[1] + 256) % 256, - ((int) digest[2] + 256) % 256}; + ((int) digest[1] + 256) % 256, + ((int) digest[2] + 256) % 256}; return result; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java index f18a290b3..82e181664 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java @@ -17,14 +17,13 @@ package org.sufficientlysecure.keychain.helper; +import android.content.Context; +import android.content.SharedPreferences; import org.spongycastle.bcpg.HashAlgorithmTags; import org.spongycastle.openpgp.PGPEncryptedData; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; -import android.content.Context; -import android.content.SharedPreferences; - import java.util.Vector; /** @@ -38,8 +37,8 @@ public class Preferences { return getPreferences(context, false); } - public static synchronized Preferences getPreferences(Context context, boolean force_new) { - if (mPreferences == null || force_new) { + public static synchronized Preferences getPreferences(Context context, boolean forceNew) { + if (mPreferences == null || forceNew) { mPreferences = new Preferences(context); } return mPreferences; -- cgit v1.2.3 From ad1e047aa926cc8aee68edd00917d06b297157b8 Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 20:25:01 +0200 Subject: First code style changes in ui --- .../keychain/ui/CertifyKeyActivity.java | 38 ++++---- .../keychain/ui/DecryptActivity.java | 50 ++++------ .../keychain/ui/DrawerActivity.java | 55 +++++------ .../keychain/ui/EditKeyActivity.java | 103 ++++++++++----------- .../keychain/ui/EncryptActivity.java | 46 ++++----- .../keychain/ui/HelpAboutFragment.java | 13 ++- .../keychain/ui/HelpActivity.java | 5 +- .../keychain/ui/HelpHtmlFragment.java | 13 ++- .../keychain/ui/ImportKeysActivity.java | 2 - .../keychain/ui/ImportKeysClipboardFragment.java | 6 +- .../keychain/ui/ImportKeysFileFragment.java | 10 +- .../keychain/ui/ImportKeysListFragment.java | 52 +++++------ .../keychain/ui/ImportKeysNFCFragment.java | 4 +- .../keychain/ui/ImportKeysQrCodeFragment.java | 84 ++++++++--------- .../keychain/ui/ImportKeysServerFragment.java | 10 +- .../keychain/ui/KeyListActivity.java | 9 +- .../keychain/ui/KeyListFragment.java | 79 +++++++--------- .../keychain/ui/PreferencesActivity.java | 68 +++++++------- .../keychain/ui/PreferencesKeyServerActivity.java | 18 ++-- .../keychain/ui/SelectPublicKeyActivity.java | 10 +- .../keychain/ui/SelectPublicKeyFragment.java | 32 +++---- .../keychain/ui/SelectSecretKeyActivity.java | 7 +- .../keychain/ui/SelectSecretKeyFragment.java | 29 +++--- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 17 ++-- .../keychain/ui/UploadKeyActivity.java | 16 ++-- .../keychain/ui/ViewKeyActivity.java | 3 +- .../keychain/ui/ViewKeyActivityJB.java | 17 ++-- .../keychain/ui/ViewKeyCertsFragment.java | 2 - .../keychain/ui/ViewKeyMainFragment.java | 15 +-- .../ui/adapter/AsyncTaskResultWrapper.java | 5 +- .../ui/adapter/HighlightQueryCursorAdapter.java | 1 - .../keychain/ui/adapter/ImportKeysAdapter.java | 22 ++--- .../keychain/ui/adapter/ImportKeysListEntry.java | 11 +-- .../keychain/ui/adapter/ImportKeysListLoader.java | 19 ++-- .../ui/adapter/ImportKeysListServerLoader.java | 1 - .../ui/adapter/KeyValueSpinnerAdapter.java | 8 +- .../ui/adapter/SelectKeyCursorAdapter.java | 16 ++-- .../keychain/ui/adapter/ViewKeyKeysAdapter.java | 9 +- .../keychain/ui/adapter/ViewKeyUserIdsAdapter.java | 7 +- .../ui/dialog/BadImportKeyDialogFragment.java | 1 - .../ui/dialog/CreateKeyDialogFragment.java | 2 - .../ui/dialog/DeleteFileDialogFragment.java | 7 +- .../ui/dialog/DeleteKeyDialogFragment.java | 3 +- .../keychain/ui/dialog/FileDialogFragment.java | 49 +++++----- .../ui/dialog/PassphraseDialogFragment.java | 50 +++++----- .../keychain/ui/dialog/ProgressDialogFragment.java | 1 - .../ui/dialog/SetPassphraseDialogFragment.java | 24 ++--- .../keychain/ui/dialog/ShareNfcDialogFragment.java | 5 +- .../ui/dialog/ShareQrCodeDialogFragment.java | 1 - .../keychain/ui/widget/FixedListView.java | 2 +- .../keychain/ui/widget/IntegerListPreference.java | 2 +- .../keychain/ui/widget/KeyEditor.java | 39 +++----- .../keychain/ui/widget/KeyServerEditor.java | 4 +- .../keychain/ui/widget/SectionView.java | 2 - .../keychain/ui/widget/UnderlineTextView.java | 2 +- .../keychain/ui/widget/UserIdEditor.java | 14 ++- 56 files changed, 486 insertions(+), 634 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index 029dda1a0..9a9911c94 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -17,8 +17,20 @@ package org.sufficientlysecure.keychain.ui; -import java.util.Iterator; - +import android.app.ProgressDialog; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.Messenger; +import android.support.v7.app.ActionBar; +import android.support.v7.app.ActionBarActivity; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.*; +import android.widget.CompoundButton.OnCheckedChangeListener; +import com.beardedhen.androidbootstrap.BootstrapButton; import org.spongycastle.openpgp.PGPPublicKeyRing; import org.spongycastle.openpgp.PGPSignature; import org.sufficientlysecure.keychain.Constants; @@ -33,25 +45,7 @@ import org.sufficientlysecure.keychain.service.PassphraseCacheService; import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; import org.sufficientlysecure.keychain.util.Log; -import android.app.ProgressDialog; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.support.v7.app.ActionBar; -import android.support.v7.app.ActionBarActivity; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.CompoundButton.OnCheckedChangeListener; -import android.widget.Spinner; -import android.widget.Toast; - -import com.beardedhen.androidbootstrap.BootstrapButton; +import java.util.Iterator; /** * Signs the specified public key with the specified secret master key @@ -87,7 +81,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements mSelectKeyserverSpinner = (Spinner) findViewById(R.id.sign_key_keyserver); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, Preferences.getPreferences(this) - .getKeyServers()); + .getKeyServers()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSelectKeyserverSpinner.setAdapter(adapter); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index 38d763ce4..42b20788f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -17,14 +17,20 @@ package org.sufficientlysecure.keychain.ui; -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.regex.Matcher; - +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.Messenger; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.animation.AnimationUtils; +import android.widget.*; +import com.beardedhen.androidbootstrap.BootstrapButton; +import com.devspark.appmsg.AppMsg; import org.openintents.openpgp.OpenPgpSignatureResult; import org.spongycastle.openpgp.PGPPublicKeyRing; import org.sufficientlysecure.keychain.Constants; @@ -33,10 +39,10 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.ClipboardReflection; import org.sufficientlysecure.keychain.helper.ActionBarHelper; import org.sufficientlysecure.keychain.helper.FileHelper; +import org.sufficientlysecure.keychain.pgp.PgpDecryptVerify; import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyResult; import org.sufficientlysecure.keychain.pgp.PgpHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.pgp.PgpDecryptVerify; import org.sufficientlysecure.keychain.pgp.exception.NoAsymmetricEncryptionException; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.provider.ProviderHelper; @@ -48,27 +54,8 @@ import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment; import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; import org.sufficientlysecure.keychain.util.Log; -import android.annotation.SuppressLint; -import android.app.ProgressDialog; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.animation.AnimationUtils; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.RelativeLayout; -import android.widget.TextView; -import android.widget.Toast; -import android.widget.ViewFlipper; - -import com.beardedhen.androidbootstrap.BootstrapButton; -import com.devspark.appmsg.AppMsg; +import java.io.*; +import java.util.regex.Matcher; @SuppressLint("NewApi") public class DecryptActivity extends DrawerActivity { @@ -533,7 +520,8 @@ public class DecryptActivity extends DrawerActivity { } finally { try { if (inStream != null) inStream.close(); - } catch (Exception e){ } + } catch (Exception e) { + } } } else { inStream = new ByteArrayInputStream(mMessage.getText().toString().getBytes()); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java index ebb520197..be22c8753 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java @@ -17,10 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.service.remote.RegisteredAppsListActivity; -import org.sufficientlysecure.keychain.util.Log; - import android.app.Activity; import android.content.Context; import android.content.Intent; @@ -30,17 +26,14 @@ import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; +import android.view.*; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; - import com.beardedhen.androidbootstrap.FontAwesomeText; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.service.remote.RegisteredAppsListActivity; public class DrawerActivity extends ActionBarActivity { private DrawerLayout mDrawerLayout; @@ -50,9 +43,9 @@ public class DrawerActivity extends ActionBarActivity { private CharSequence mDrawerTitle; private CharSequence mTitle; - private static Class[] mItemsClass = new Class[] { KeyListActivity.class, + private static Class[] mItemsClass = new Class[]{KeyListActivity.class, EncryptActivity.class, DecryptActivity.class, ImportKeysActivity.class, - RegisteredAppsListActivity.class }; + RegisteredAppsListActivity.class}; private Class mSelectedItem; private static final int MENU_ID_PREFERENCE = 222; @@ -67,12 +60,12 @@ public class DrawerActivity extends ActionBarActivity { // opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); - NavItem mItemIconTexts[] = new NavItem[] { + NavItem mItemIconTexts[] = new NavItem[]{ new NavItem("fa-user", getString(R.string.nav_contacts)), new NavItem("fa-lock", getString(R.string.nav_encrypt)), new NavItem("fa-unlock", getString(R.string.nav_decrypt)), new NavItem("fa-download", getString(R.string.nav_import)), - new NavItem("fa-android", getString(R.string.nav_apps)) }; + new NavItem("fa-android", getString(R.string.nav_apps))}; mDrawerList.setAdapter(new NavigationDrawerAdapter(this, R.layout.drawer_list_item, mItemIconTexts)); @@ -86,10 +79,10 @@ public class DrawerActivity extends ActionBarActivity { // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ - mDrawerLayout, /* DrawerLayout object */ - R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ - R.string.drawer_open, /* "open drawer" description for accessibility */ - R.string.drawer_close /* "close drawer" description for accessibility */ + mDrawerLayout, /* DrawerLayout object */ + R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ + R.string.drawer_open, /* "open drawer" description for accessibility */ + R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); @@ -97,7 +90,7 @@ public class DrawerActivity extends ActionBarActivity { supportInvalidateOptionsMenu(); // call intent activity if selected - if(mSelectedItem != null) { + if (mSelectedItem != null) { finish(); overridePendingTransition(0, 0); @@ -149,18 +142,18 @@ public class DrawerActivity extends ActionBarActivity { } switch (item.getItemId()) { - case MENU_ID_PREFERENCE: { - Intent intent = new Intent(this, PreferencesActivity.class); - startActivity(intent); - return true; - } - case MENU_ID_HELP: { - Intent intent = new Intent(this, HelpActivity.class); - startActivity(intent); - return true; - } - default: - return super.onOptionsItemSelected(item); + case MENU_ID_PREFERENCE: { + Intent intent = new Intent(this, PreferencesActivity.class); + startActivity(intent); + return true; + } + case MENU_ID_HELP: { + Intent intent = new Intent(this, HelpActivity.class); + startActivity(intent); + return true; + } + default: + return super.onOptionsItemSelected(item); } // Handle action buttons diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 0c35bb2b1..1dde4601b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -17,10 +17,25 @@ package org.sufficientlysecure.keychain.ui; -import java.util.ArrayList; -import java.util.GregorianCalendar; -import java.util.Vector; - +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.Messenger; +import android.support.v7.app.ActionBarActivity; +import android.view.*; +import android.view.View.OnClickListener; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.LinearLayout; +import android.widget.Toast; +import com.beardedhen.androidbootstrap.BootstrapButton; import org.spongycastle.openpgp.PGPSecretKey; import org.spongycastle.openpgp.PGPSecretKeyRing; import org.sufficientlysecure.keychain.Constants; @@ -44,30 +59,9 @@ import org.sufficientlysecure.keychain.ui.widget.UserIdEditor; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; -import android.app.Activity; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.support.v7.app.ActionBarActivity; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.CompoundButton.OnCheckedChangeListener; -import android.widget.LinearLayout; -import android.widget.Toast; - -import com.beardedhen.androidbootstrap.BootstrapButton; +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.Vector; public class EditKeyActivity extends ActionBarActivity { @@ -130,7 +124,7 @@ public class EditKeyActivity extends ActionBarActivity { /** * Handle intent action to create new key - * + * * @param intent */ private void handleActionCreateKey(Intent intent) { @@ -146,7 +140,8 @@ public class EditKeyActivity extends ActionBarActivity { public void onClick(View v) { cancelClicked(); } - }); + } + ); Bundle extras = intent.getExtras(); @@ -245,7 +240,7 @@ public class EditKeyActivity extends ActionBarActivity { /** * Handle intent action to edit existing key - * + * * @param intent */ private void handleActionEditKey(Intent intent) { @@ -323,28 +318,28 @@ public class EditKeyActivity extends ActionBarActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.menu_key_edit_cancel: - cancelClicked(); - return true; - case R.id.menu_key_edit_export_file: - long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; - mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); - return true; - case R.id.menu_key_edit_delete: { - // Message is received after key is deleted - Handler returnHandler = new Handler() { - @Override - public void handleMessage(Message message) { - if (message.what == DeleteKeyDialogFragment.MESSAGE_OKAY) { - setResult(RESULT_CANCELED); - finish(); + case R.id.menu_key_edit_cancel: + cancelClicked(); + return true; + case R.id.menu_key_edit_export_file: + long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; + mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); + return true; + case R.id.menu_key_edit_delete: { + // Message is received after key is deleted + Handler returnHandler = new Handler() { + @Override + public void handleMessage(Message message) { + if (message.what == DeleteKeyDialogFragment.MESSAGE_OKAY) { + setResult(RESULT_CANCELED); + finish(); + } } - } - }; + }; - mExportHelper.deleteKey(mDataUri, Id.type.secret_key, returnHandler); - return true; - } + mExportHelper.deleteKey(mDataUri, Id.type.secret_key, returnHandler); + return true; + } } return super.onOptionsItemSelected(item); } @@ -584,7 +579,7 @@ public class EditKeyActivity extends ActionBarActivity { /** * Returns user ids from the SectionView - * + * * @param userIdsView * @return */ @@ -633,7 +628,7 @@ public class EditKeyActivity extends ActionBarActivity { /** * Returns keys from the SectionView - * + * * @param keysView * @return */ @@ -656,7 +651,7 @@ public class EditKeyActivity extends ActionBarActivity { /** * Returns usage selections of keys from the SectionView - * + * * @param keysView * @return */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index 8f8952763..d2d662e40 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -17,9 +17,22 @@ package org.sufficientlysecure.keychain.ui; -import java.io.File; -import java.util.Vector; - +import android.app.ProgressDialog; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.Messenger; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.animation.AlphaAnimation; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.widget.*; +import com.beardedhen.androidbootstrap.BootstrapButton; +import com.beardedhen.androidbootstrap.FontAwesomeText; +import com.devspark.appmsg.AppMsg; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPPublicKeyRing; import org.spongycastle.openpgp.PGPSecretKey; @@ -43,31 +56,8 @@ import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; import org.sufficientlysecure.keychain.util.Choice; import org.sufficientlysecure.keychain.util.Log; -import android.app.ProgressDialog; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.animation.AlphaAnimation; -import android.view.animation.Animation; -import android.view.animation.AnimationUtils; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.Spinner; -import android.widget.TextView; -import android.widget.Toast; -import android.widget.ViewFlipper; - -import com.beardedhen.androidbootstrap.BootstrapButton; -import com.beardedhen.androidbootstrap.FontAwesomeText; -import com.devspark.appmsg.AppMsg; +import java.io.File; +import java.util.Vector; public class EncryptActivity extends DrawerActivity { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpAboutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpAboutFragment.java index 12d689274..a484b57de 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpAboutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpAboutFragment.java @@ -17,11 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.htmltextview.HtmlTextView; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.util.Log; - import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; @@ -31,6 +26,10 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; +import org.sufficientlysecure.htmltextview.HtmlTextView; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.util.Log; public class HelpAboutFragment extends Fragment { @@ -55,7 +54,7 @@ public class HelpAboutFragment extends Fragment { /** * Get the current package version. - * + * * @return The current version. */ private String getVersion() { @@ -73,4 +72,4 @@ public class HelpAboutFragment extends Fragment { return result; } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java index 48068a6c4..436d9291d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java @@ -17,14 +17,13 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.ui.adapter.TabsAdapter; - import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.adapter.TabsAdapter; public class HelpActivity extends ActionBarActivity { public static final String EXTRA_SELECTED_TAB = "selected_tab"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpHtmlFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpHtmlFragment.java index 3afb5bbe0..6b3c51b08 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpHtmlFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpHtmlFragment.java @@ -17,8 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.htmltextview.HtmlTextView; - import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -27,11 +25,12 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; +import org.sufficientlysecure.htmltextview.HtmlTextView; public class HelpHtmlFragment extends Fragment { private Activity mActivity; - private int htmlFile; + private int mHtmlFile; public static final String ARG_HTML_FILE = "htmlFile"; @@ -52,8 +51,8 @@ public class HelpHtmlFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mActivity = getActivity(); - - htmlFile = getArguments().getInt(ARG_HTML_FILE); + + mHtmlFile = getArguments().getInt(ARG_HTML_FILE); ScrollView scroller = new ScrollView(mActivity); HtmlTextView text = new HtmlTextView(mActivity); @@ -66,11 +65,11 @@ public class HelpHtmlFragment extends Fragment { scroller.addView(text); // load html from raw resource (Parsing handled by HtmlTextView library) - text.setHtmlFromRawResource(getActivity(), htmlFile); + text.setHtmlFromRawResource(getActivity(), mHtmlFile); // no flickering when clicking textview for Android < 4 text.setTextColor(getResources().getColor(android.R.color.black)); return scroller; } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index f04a0e227..aa0c127cf 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -34,10 +34,8 @@ import android.support.v7.app.ActionBar; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; - import com.beardedhen.androidbootstrap.BootstrapButton; import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java index 211fc1f44..c21271220 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java @@ -17,17 +17,15 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.compatibility.ClipboardReflection; - import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.compatibility.ClipboardReflection; public class ImportKeysClipboardFragment extends Fragment { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java index 60b33c8a2..cdfba894a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java @@ -17,11 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.FileHelper; - import android.app.Activity; import android.content.Intent; import android.os.Bundle; @@ -29,8 +24,11 @@ import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.FileHelper; public class ImportKeysFileFragment extends Fragment { private ImportKeysActivity mImportActivity; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java index a6917d6f4..346c009fb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java @@ -17,25 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.Preferences; -import org.sufficientlysecure.keychain.ui.adapter.AsyncTaskResultWrapper; -import org.sufficientlysecure.keychain.ui.adapter.ImportKeysAdapter; -import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; -import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListLoader; -import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListServerLoader; -import org.sufficientlysecure.keychain.util.InputData; -import org.sufficientlysecure.keychain.util.KeyServer; -import org.sufficientlysecure.keychain.util.Log; - import android.app.Activity; import android.net.Uri; import android.os.Bundle; @@ -44,8 +25,21 @@ import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.view.View; import android.widget.ListView; - import com.devspark.appmsg.AppMsg; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.Preferences; +import org.sufficientlysecure.keychain.ui.adapter.*; +import org.sufficientlysecure.keychain.util.InputData; +import org.sufficientlysecure.keychain.util.KeyServer; +import org.sufficientlysecure.keychain.util.Log; + +import java.io.ByteArrayInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; public class ImportKeysListFragment extends ListFragment implements LoaderManager.LoaderCallbacks>> { @@ -225,16 +219,16 @@ public class ImportKeysListFragment extends ListFragment implements switch (loader.getId()) { case LOADER_ID_BYTES: - if(error == null){ + if (error == null) { // No error - } else if(error instanceof ImportKeysListLoader.FileHasNoContent) { + } else if (error instanceof ImportKeysListLoader.FileHasNoContent) { AppMsg.makeText(getActivity(), R.string.error_import_file_no_content, AppMsg.STYLE_ALERT).show(); - } else if(error instanceof ImportKeysListLoader.NonPgpPart) { + } else if (error instanceof ImportKeysListLoader.NonPgpPart) { AppMsg.makeText(getActivity(), ((ImportKeysListLoader.NonPgpPart) error).getCount() + " " + getResources(). - getQuantityString(R.plurals.error_import_non_pgp_part, - ((ImportKeysListLoader.NonPgpPart) error).getCount()), + getQuantityString(R.plurals.error_import_non_pgp_part, + ((ImportKeysListLoader.NonPgpPart) error).getCount()), new AppMsg.Style(AppMsg.LENGTH_LONG, R.color.confirm)).show(); } else { AppMsg.makeText(getActivity(), R.string.error_generic_report_bug, @@ -244,19 +238,19 @@ public class ImportKeysListFragment extends ListFragment implements case LOADER_ID_SERVER_QUERY: - if(error == null) { + if (error == null) { AppMsg.makeText( getActivity(), getResources().getQuantityString(R.plurals.keys_found, mAdapter.getCount(), mAdapter.getCount()), AppMsg.STYLE_INFO ).show(); - } else if(error instanceof KeyServer.InsufficientQuery) { + } else if (error instanceof KeyServer.InsufficientQuery) { AppMsg.makeText(getActivity(), R.string.error_keyserver_insufficient_query, AppMsg.STYLE_ALERT).show(); - } else if(error instanceof KeyServer.QueryException) { + } else if (error instanceof KeyServer.QueryException) { AppMsg.makeText(getActivity(), R.string.error_keyserver_query, AppMsg.STYLE_ALERT).show(); - } else if(error instanceof KeyServer.TooManyResponses) { + } else if (error instanceof KeyServer.TooManyResponses) { AppMsg.makeText(getActivity(), R.string.error_keyserver_too_many_responses, AppMsg.STYLE_ALERT).show(); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java index 83af8cf48..44b5848d8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java @@ -17,8 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.R; - import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -26,8 +24,8 @@ import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.R; public class ImportKeysNFCFragment extends Fragment { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysQrCodeFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysQrCodeFragment.java index ee91b2434..10c0752b1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysQrCodeFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysQrCodeFragment.java @@ -17,14 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import java.util.ArrayList; -import java.util.Locale; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.util.IntentIntegratorSupportV4; -import org.sufficientlysecure.keychain.util.Log; - import android.content.Intent; import android.net.Uri; import android.os.Bundle; @@ -36,9 +28,15 @@ import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; - import com.beardedhen.androidbootstrap.BootstrapButton; import com.google.zxing.integration.android.IntentResult; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.util.IntentIntegratorSupportV4; +import org.sufficientlysecure.keychain.util.Log; + +import java.util.ArrayList; +import java.util.Locale; public class ImportKeysQrCodeFragment extends Fragment { @@ -94,45 +92,45 @@ public class ImportKeysQrCodeFragment extends Fragment { @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode & 0xFFFF) { - case IntentIntegratorSupportV4.REQUEST_CODE: { - IntentResult scanResult = IntentIntegratorSupportV4.parseActivityResult(requestCode, - resultCode, data); - if (scanResult != null && scanResult.getFormatName() != null) { - String scannedContent = scanResult.getContents(); - - Log.d(Constants.TAG, "scannedContent: " + scannedContent); - - // look if it's fingerprint only - if (scannedContent.toLowerCase(Locale.ENGLISH).startsWith(Constants.FINGERPRINT_SCHEME)) { - importFingerprint(Uri.parse(scanResult.getContents())); - return; + case IntentIntegratorSupportV4.REQUEST_CODE: { + IntentResult scanResult = IntentIntegratorSupportV4.parseActivityResult(requestCode, + resultCode, data); + if (scanResult != null && scanResult.getFormatName() != null) { + String scannedContent = scanResult.getContents(); + + Log.d(Constants.TAG, "scannedContent: " + scannedContent); + + // look if it's fingerprint only + if (scannedContent.toLowerCase(Locale.ENGLISH).startsWith(Constants.FINGERPRINT_SCHEME)) { + importFingerprint(Uri.parse(scanResult.getContents())); + return; + } + + // look if it is the whole key + String[] parts = scannedContent.split(","); + if (parts.length == 3) { + importParts(parts); + return; + } + + // is this a full key encoded as qr code? + if (scannedContent.startsWith("-----BEGIN PGP")) { + mImportActivity.loadCallback(scannedContent.getBytes(), null, null, null); + return; + } + + // fail... + Toast.makeText(getActivity(), R.string.import_qr_code_wrong, Toast.LENGTH_LONG) + .show(); } - // look if it is the whole key - String[] parts = scannedContent.split(","); - if (parts.length == 3) { - importParts(parts); - return; - } - - // is this a full key encoded as qr code? - if (scannedContent.startsWith("-----BEGIN PGP")) { - mImportActivity.loadCallback(scannedContent.getBytes(), null, null, null); - return; - } - - // fail... - Toast.makeText(getActivity(), R.string.import_qr_code_wrong, Toast.LENGTH_LONG) - .show(); + break; } - break; - } - - default: - super.onActivityResult(requestCode, resultCode, data); + default: + super.onActivityResult(requestCode, resultCode, data); - break; + break; } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java index d77015aa7..f2449fae1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java @@ -17,11 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.Preferences; -import org.sufficientlysecure.keychain.util.Log; - import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -36,8 +31,11 @@ import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.Preferences; +import org.sufficientlysecure.keychain.util.Log; public class ImportKeysServerFragment extends Fragment { public static final String ARG_QUERY = "query"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 684ee6959..a70688cdf 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -17,15 +17,14 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ExportHelper; - import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ExportHelper; public class KeyListActivity extends DrawerActivity { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 70ffe968d..6230abbed 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -17,27 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import java.util.HashMap; -import java.util.ArrayList; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.helper.ExportHelper; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; -import org.sufficientlysecure.keychain.provider.KeychainDatabase; -import org.sufficientlysecure.keychain.ui.adapter.HighlightQueryCursorAdapter; -import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; -import org.sufficientlysecure.keychain.util.Log; - -import se.emilsjolander.stickylistheaders.ApiLevelTooLowException; -import se.emilsjolander.stickylistheaders.StickyListHeadersListView; -import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; - import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; @@ -45,11 +24,7 @@ import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; +import android.os.*; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; @@ -58,23 +33,31 @@ import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.text.TextUtils; -import android.view.ActionMode; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; +import android.view.*; import android.view.View.OnClickListener; -import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.AbsListView.MultiChoiceModeListener; -import android.widget.AdapterView; -import android.widget.Button; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; - +import android.widget.*; import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ExportHelper; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; +import org.sufficientlysecure.keychain.provider.KeychainDatabase; +import org.sufficientlysecure.keychain.ui.adapter.HighlightQueryCursorAdapter; +import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; +import org.sufficientlysecure.keychain.util.Log; +import se.emilsjolander.stickylistheaders.ApiLevelTooLowException; +import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; +import se.emilsjolander.stickylistheaders.StickyListHeadersListView; + +import java.util.ArrayList; +import java.util.HashMap; /** * Public key list with sticky list headers. It does _not_ extend ListFragment because it uses @@ -566,8 +549,8 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL if (convertView == null) { holder = new HeaderViewHolder(); convertView = mInflater.inflate(R.layout.key_list_header, parent, false); - holder.text = (TextView) convertView.findViewById(R.id.stickylist_header_text); - holder.count = (TextView) convertView.findViewById(R.id.contacts_num); + holder.mText = (TextView) convertView.findViewById(R.id.stickylist_header_text); + holder.mCount = (TextView) convertView.findViewById(R.id.contacts_num); convertView.setTag(holder); } else { holder = (HeaderViewHolder) convertView.getTag(); @@ -587,11 +570,11 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL { // set contact count int num = mCursor.getCount(); String contactsTotal = getResources().getQuantityString(R.plurals.n_contacts, num, num); - holder.count.setText(contactsTotal); - holder.count.setVisibility(View.VISIBLE); + holder.mCount.setText(contactsTotal); + holder.mCount.setVisibility(View.VISIBLE); } - holder.text.setText(convertView.getResources().getString(R.string.my_keys)); + holder.mText.setText(convertView.getResources().getString(R.string.my_keys)); return convertView; } @@ -601,8 +584,8 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL if (userId != null && userId.length() > 0) { headerText = "" + mCursor.getString(KeyListFragment.INDEX_USER_ID).subSequence(0, 1).charAt(0); } - holder.text.setText(headerText); - holder.count.setVisibility(View.GONE); + holder.mText.setText(headerText); + holder.mCount.setVisibility(View.GONE); return convertView; } @@ -635,8 +618,8 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL } class HeaderViewHolder { - TextView text; - TextView count; + TextView mText; + TextView mCount; } /** diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java index 2e8f25890..5660850b2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java @@ -16,6 +16,11 @@ package org.sufficientlysecure.keychain.ui; +import android.annotation.SuppressLint; +import android.content.Intent; +import android.os.Build; +import android.os.Bundle; +import android.preference.*; import org.spongycastle.bcpg.HashAlgorithmTags; import org.spongycastle.openpgp.PGPEncryptedData; import org.sufficientlysecure.keychain.Constants; @@ -24,17 +29,6 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.Preferences; import org.sufficientlysecure.keychain.ui.widget.IntegerListPreference; -import android.annotation.SuppressLint; -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.Preference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceFragment; -import android.preference.PreferenceScreen; -import android.support.v7.app.ActionBarActivity; - import java.util.List; @SuppressLint("NewApi") @@ -86,13 +80,13 @@ public class PreferencesActivity extends PreferenceActivity { initializeEncryptionAlgorithm( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM)); - int[] valueIds = new int[] { Id.choice.compression.none, Id.choice.compression.zip, - Id.choice.compression.zlib, Id.choice.compression.bzip2, }; - String[] entries = new String[] { + int[] valueIds = new int[]{Id.choice.compression.none, Id.choice.compression.zip, + Id.choice.compression.zlib, Id.choice.compression.bzip2,}; + String[] entries = new String[]{ getString(R.string.choice_none) + " (" + getString(R.string.compression_fast) + ")", "ZIP (" + getString(R.string.compression_fast) + ")", "ZLIB (" + getString(R.string.compression_fast) + ")", - "BZIP2 (" + getString(R.string.compression_very_slow) + ")", }; + "BZIP2 (" + getString(R.string.compression_very_slow) + ")",}; String[] values = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; @@ -100,15 +94,15 @@ public class PreferencesActivity extends PreferenceActivity { initializeHashAlgorithm( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_HASH_ALGORITHM), - valueIds, entries, values); + valueIds, entries, values); initializeMessageCompression( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_MESSAGE_COMPRESSION), - valueIds, entries, values); + valueIds, entries, values); initializeFileCompression( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_FILE_COMPRESSION), - entries, values); + entries, values); initializeAsciiArmour((CheckBoxPreference) findPreference(Constants.pref.DEFAULT_ASCII_ARMOUR)); @@ -149,7 +143,9 @@ public class PreferencesActivity extends PreferenceActivity { loadHeadersFromResource(R.xml.preference_headers, target); } - /** This fragment shows the general preferences in android 3.0+ */ + /** + * This fragment shows the general preferences in android 3.0+ + */ public static class GeneralPrefsFragment extends PreferenceFragment { private PreferenceScreen mKeyServerPreference = null; @@ -204,7 +200,9 @@ public class PreferencesActivity extends PreferenceActivity { } } - /** This fragment shows the advanced preferences in android 3.0+ */ + /** + * This fragment shows the advanced preferences in android 3.0+ + */ public static class AdvancedPrefsFragment extends PreferenceFragment { @Override @@ -217,13 +215,13 @@ public class PreferencesActivity extends PreferenceActivity { initializeEncryptionAlgorithm( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM)); - int[] valueIds = new int[] { Id.choice.compression.none, Id.choice.compression.zip, - Id.choice.compression.zlib, Id.choice.compression.bzip2, }; - String[] entries = new String[] { + int[] valueIds = new int[]{Id.choice.compression.none, Id.choice.compression.zip, + Id.choice.compression.zlib, Id.choice.compression.bzip2,}; + String[] entries = new String[]{ getString(R.string.choice_none) + " (" + getString(R.string.compression_fast) + ")", "ZIP (" + getString(R.string.compression_fast) + ")", "ZLIB (" + getString(R.string.compression_fast) + ")", - "BZIP2 (" + getString(R.string.compression_very_slow) + ")", }; + "BZIP2 (" + getString(R.string.compression_very_slow) + ")",}; String[] values = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; @@ -231,11 +229,11 @@ public class PreferencesActivity extends PreferenceActivity { initializeHashAlgorithm( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_HASH_ALGORITHM), - valueIds, entries, values); + valueIds, entries, values); initializeMessageCompression( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_MESSAGE_COMPRESSION), - valueIds, entries, values); + valueIds, entries, values); initializeFileCompression( (IntegerListPreference) findPreference(Constants.pref.DEFAULT_FILE_COMPRESSION), @@ -247,7 +245,7 @@ public class PreferencesActivity extends PreferenceActivity { } } - protected boolean isValidFragment (String fragmentName) { + protected boolean isValidFragment(String fragmentName) { return AdvancedPrefsFragment.class.getName().equals(fragmentName) || GeneralPrefsFragment.class.getName().equals(fragmentName) || super.isValidFragment(fragmentName); @@ -268,12 +266,12 @@ public class PreferencesActivity extends PreferenceActivity { } private static void initializeEncryptionAlgorithm(final IntegerListPreference mEncryptionAlgorithm) { - int valueIds[] = { PGPEncryptedData.AES_128, PGPEncryptedData.AES_192, + int valueIds[] = {PGPEncryptedData.AES_128, PGPEncryptedData.AES_192, PGPEncryptedData.AES_256, PGPEncryptedData.BLOWFISH, PGPEncryptedData.TWOFISH, PGPEncryptedData.CAST5, PGPEncryptedData.DES, PGPEncryptedData.TRIPLE_DES, - PGPEncryptedData.IDEA, }; - String entries[] = { "AES-128", "AES-192", "AES-256", "Blowfish", "Twofish", "CAST5", - "DES", "Triple DES", "IDEA", }; + PGPEncryptedData.IDEA,}; + String entries[] = {"AES-128", "AES-192", "AES-256", "Blowfish", "Twofish", "CAST5", + "DES", "Triple DES", "IDEA",}; String values[] = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; @@ -296,11 +294,11 @@ public class PreferencesActivity extends PreferenceActivity { private static void initializeHashAlgorithm (final IntegerListPreference mHashAlgorithm, int[] valueIds, String[] entries, String[] values) { - valueIds = new int[] { HashAlgorithmTags.MD5, HashAlgorithmTags.RIPEMD160, + valueIds = new int[]{HashAlgorithmTags.MD5, HashAlgorithmTags.RIPEMD160, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA224, HashAlgorithmTags.SHA256, - HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, }; - entries = new String[] { "MD5", "RIPEMD-160", "SHA-1", "SHA-224", "SHA-256", "SHA-384", - "SHA-512", }; + HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512,}; + entries = new String[]{"MD5", "RIPEMD-160", "SHA-1", "SHA-224", "SHA-256", "SHA-384", + "SHA-512",}; values = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java index 50fec1ffc..d890f35cb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesKeyServerActivity.java @@ -16,14 +16,6 @@ package org.sufficientlysecure.keychain.ui; -import java.util.Vector; - -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; -import org.sufficientlysecure.keychain.ui.widget.Editor; -import org.sufficientlysecure.keychain.ui.widget.Editor.EditorListener; -import org.sufficientlysecure.keychain.ui.widget.KeyServerEditor; - import android.content.Context; import android.content.Intent; import android.os.Bundle; @@ -33,6 +25,13 @@ import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.TextView; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ActionBarHelper; +import org.sufficientlysecure.keychain.ui.widget.Editor; +import org.sufficientlysecure.keychain.ui.widget.Editor.EditorListener; +import org.sufficientlysecure.keychain.ui.widget.KeyServerEditor; + +import java.util.Vector; public class PreferencesKeyServerActivity extends ActionBarActivity implements OnClickListener, EditorListener { @@ -63,7 +62,8 @@ public class PreferencesKeyServerActivity extends ActionBarActivity implements O // cancel cancelClicked(); } - }); + } + ); setContentView(R.layout.key_server_preference); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java index 3c63628f7..7efb43cce 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java @@ -17,14 +17,13 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; - import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ActionBarHelper; public class SelectPublicKeyActivity extends ActionBarActivity { @@ -59,7 +58,8 @@ public class SelectPublicKeyActivity extends ActionBarActivity { // cancel cancelClicked(); } - }); + } + ); setContentView(R.layout.select_public_key_activity); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java index d320af451..7a30b11d2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java @@ -17,19 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import java.util.Date; -import java.util.Vector; - -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.compatibility.ListFragmentWorkaround; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; -import org.sufficientlysecure.keychain.provider.KeychainDatabase; -import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; -import org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter; - import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; @@ -45,12 +32,19 @@ import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.ProgressBar; -import android.widget.TextView; +import android.widget.*; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.compatibility.ListFragmentWorkaround; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; +import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; +import org.sufficientlysecure.keychain.provider.KeychainDatabase; +import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; +import org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter; + +import java.util.Date; +import java.util.Vector; public class SelectPublicKeyFragment extends ListFragmentWorkaround implements TextWatcher, LoaderManager.LoaderCallbacks { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java index cd3b2cf78..1509bc88c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java @@ -17,14 +17,13 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; - import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.Menu; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; public class SelectSecretKeyActivity extends ActionBarActivity { @@ -90,7 +89,7 @@ public class SelectSecretKeyActivity extends ActionBarActivity { /** * This is executed by SelectSecretKeyFragment after clicking on an item - * + * * @param masterKeyId * @param userId */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java index 8ee2d381e..9b3541c81 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java @@ -17,17 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import java.util.Date; - -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; -import org.sufficientlysecure.keychain.provider.KeychainDatabase; -import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; -import org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter; - import android.database.Cursor; import android.net.Uri; import android.os.Bundle; @@ -39,6 +28,16 @@ import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; +import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; +import org.sufficientlysecure.keychain.provider.KeychainDatabase; +import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; +import org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter; + +import java.util.Date; public class SelectSecretKeyFragment extends ListFragment implements LoaderManager.LoaderCallbacks { @@ -46,9 +45,9 @@ public class SelectSecretKeyFragment extends ListFragment implements private SelectSecretKeyActivity mActivity; private SelectKeyCursorAdapter mAdapter; private ListView mListView; - + private boolean mFilterCertify; - + private static final String ARG_FILTER_CERTIFY = "filter_certify"; /** @@ -122,7 +121,7 @@ public class SelectSecretKeyFragment extends ListFragment implements // These are the rows that we will retrieve. long now = new Date().getTime() / 1000; - String[] projection = new String[] { + String[] projection = new String[]{ KeyRings._ID, KeyRings.MASTER_KEY_ID, UserIds.USER_ID, @@ -142,7 +141,7 @@ public class SelectSecretKeyFragment extends ListFragment implements + Keys.IS_REVOKED + " = '0' AND valid_keys." + Keys.CAN_SIGN + " = '1' AND valid_keys." + Keys.CREATION + " <= '" + now + "' AND " + "(valid_keys." + Keys.EXPIRY + " IS NULL OR valid_keys." + Keys.EXPIRY - + " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID, }; + + " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID,}; String orderBy = UserIds.USER_ID + " ASC"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index c9129285e..b1de85973 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -17,27 +17,22 @@ package org.sufficientlysecure.keychain.ui; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.provider.ProviderHelper; - -import android.Manifest; import android.app.Activity; -import android.app.ActivityOptions; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; -import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.TextView; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.provider.ProviderHelper; public class SelectSecretKeyLayoutFragment extends Fragment { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java index 6f0aaa0f0..2c8f66488 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java @@ -17,13 +17,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.Preferences; -import org.sufficientlysecure.keychain.service.KeychainIntentService; -import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; -import org.sufficientlysecure.keychain.util.Log; - import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; @@ -36,8 +29,13 @@ import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.Preferences; +import org.sufficientlysecure.keychain.service.KeychainIntentService; +import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; +import org.sufficientlysecure.keychain.util.Log; /** * Sends the selected public key to a keyserver @@ -59,7 +57,7 @@ public class UploadKeyActivity extends ActionBarActivity { ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, Preferences.getPreferences(this) - .getKeyServers()); + .getKeyServers()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mKeyServerSpinner.setAdapter(adapter); if (adapter.getCount() > 0) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 581d14a22..2d47c7a92 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -29,7 +29,6 @@ import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -89,7 +88,7 @@ public class ViewKeyActivity extends ActionBarActivity { // given valid /public/ query long rowId = ProviderHelper.getRowId(this, getIntent().getData()); // TODO: handle (rowId == 0) with something else than a crash - mDataUri = KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(rowId)) ; + mDataUri = KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(rowId)); } Bundle mainBundle = new Bundle(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivityJB.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivityJB.java index 59037d9ff..997ff9c7a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivityJB.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivityJB.java @@ -18,10 +18,6 @@ package org.sufficientlysecure.keychain.ui; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.ProviderHelper; - import android.annotation.TargetApi; import android.net.Uri; import android.nfc.NdefMessage; @@ -35,6 +31,9 @@ import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.Toast; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.ProviderHelper; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class ViewKeyActivityJB extends ViewKeyActivity implements CreateNdefMessageCallback, @@ -66,7 +65,7 @@ public class ViewKeyActivityJB extends ViewKeyActivity implements CreateNdefMess // get public keyring as byte array long masterKeyId = ProviderHelper.getMasterKeyId(this, dataUri); mSharedKeyringBytes = ProviderHelper.getKeyRingsAsByteArray(this, dataUri, - new long[] { masterKeyId }); + new long[]{masterKeyId}); // Register callback to set NDEF message mNfcAdapter.setNdefPushMessageCallback(this, this); @@ -109,10 +108,10 @@ public class ViewKeyActivityJB extends ViewKeyActivity implements CreateNdefMess @Override public void handleMessage(Message msg) { switch (msg.what) { - case NFC_SENT: - Toast.makeText(getApplicationContext(), R.string.nfc_successfull, Toast.LENGTH_LONG) - .show(); - break; + case NFC_SENT: + Toast.makeText(getApplicationContext(), R.string.nfc_successfull, Toast.LENGTH_LONG) + .show(); + break; } } }; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java index 36d3e6ace..a08492aa5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java @@ -24,9 +24,7 @@ import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - import com.beardedhen.androidbootstrap.BootstrapButton; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.util.Log; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 0e73ad983..a4a811bbc 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -29,16 +29,13 @@ import android.support.v4.content.Loader; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.format.DateFormat; -import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; - import com.beardedhen.androidbootstrap.BootstrapButton; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.OtherHelper; @@ -49,13 +46,11 @@ import org.sufficientlysecure.keychain.ui.adapter.ViewKeyKeysAdapter; import org.sufficientlysecure.keychain.ui.adapter.ViewKeyUserIdsAdapter; import org.sufficientlysecure.keychain.util.Log; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Date; -public class ViewKeyMainFragment extends Fragment implements - LoaderManager.LoaderCallbacks{ +public class ViewKeyMainFragment extends Fragment implements + LoaderManager.LoaderCallbacks { public static final String ARG_DATA_URI = "uri"; @@ -130,7 +125,7 @@ public class ViewKeyMainFragment extends Fragment implements { // label whether secret key is available, and edit button if it is final long masterKeyId = ProviderHelper.getMasterKeyId(getActivity(), mDataUri); - if(ProviderHelper.hasSecretKeyByMasterKeyId(getActivity(), masterKeyId)) { + if (ProviderHelper.hasSecretKeyByMasterKeyId(getActivity(), masterKeyId)) { // set this attribute. this is a LITTLE unclean, but we have the info available // right here, so why not. mSecretKey.setTextColor(getResources().getColor(R.color.emphasis)); @@ -341,7 +336,7 @@ public class ViewKeyMainFragment extends Fragment implements g = Math.min(255, (int) (g * factor)); b = Math.min(255, (int) (b * factor)); - // If it is too light, then darken it to a respective maximal brightness. + // If it is too light, then darken it to a respective maximal brightness. } else if (brightness > 180) { double factor = 180.0 / brightness; r = (int) (r * factor); @@ -352,7 +347,7 @@ public class ViewKeyMainFragment extends Fragment implements // Create a foreground color with the 3 digest integers as RGB // and then converting that int to hex to use as a color sb.setSpan(new ForegroundColorSpan(Color.rgb(r, g, b)), - i, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE); + i, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } } catch (Exception e) { Log.e(Constants.TAG, "Colorization failed", e); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java index 2ac19c1d9..0285deb2e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java @@ -22,14 +22,15 @@ package org.sufficientlysecure.keychain.ui.adapter; * You can pass the result and an exception in it if an error occurred. * Concept found at: * https://stackoverflow.com/questions/19593577/how-to-handle-errors-in-custom-asynctaskloader + * * @param - Typ of the result which is wrapped */ -public class AsyncTaskResultWrapper { +public class AsyncTaskResultWrapper { private final T result; private final Exception error; - public AsyncTaskResultWrapper(T result, Exception error){ + public AsyncTaskResultWrapper(T result, Exception error) { this.result = result; this.error = error; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java index fd7a2dc30..a3ed08a4c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/HighlightQueryCursorAdapter.java @@ -22,7 +22,6 @@ import android.database.Cursor; import android.support.v4.widget.CursorAdapter; import android.text.Spannable; import android.text.style.ForegroundColorSpan; - import org.sufficientlysecure.keychain.R; import java.util.regex.Matcher; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index 4f7623bce..c0b6027cc 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -17,12 +17,6 @@ package org.sufficientlysecure.keychain.ui.adapter; -import java.util.ArrayList; -import java.util.List; - -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; - import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; @@ -36,13 +30,19 @@ import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; + +import java.util.ArrayList; +import java.util.List; public class ImportKeysAdapter extends ArrayAdapter { protected LayoutInflater mInflater; protected Activity mActivity; protected List data; - static class ViewHolder{ + + static class ViewHolder { private TextView mainUserId; private TextView mainUserIdRest; private TextView keyId; @@ -51,6 +51,7 @@ public class ImportKeysAdapter extends ArrayAdapter { private TextView status; } + public ImportKeysAdapter(Activity activity) { super(activity, -1); mActivity = activity; @@ -95,7 +96,7 @@ public class ImportKeysAdapter extends ArrayAdapter { public View getView(int position, View convertView, ViewGroup parent) { ImportKeysListEntry entry = data.get(position); ViewHolder holder; - if(convertView == null) { + if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.import_keys_list_entry, null); holder.mainUserId = (TextView) convertView.findViewById(R.id.mainUserId); @@ -105,9 +106,8 @@ public class ImportKeysAdapter extends ArrayAdapter { holder.algorithm = (TextView) convertView.findViewById(R.id.algorithm); holder.status = (TextView) convertView.findViewById(R.id.status); convertView.setTag(holder); - } - else{ - holder = (ViewHolder)convertView.getTag(); + } else { + holder = (ViewHolder) convertView.getTag(); } // main user id String userId = entry.userIds.get(0); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index a52e9b447..fbfaa29fb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -19,12 +19,6 @@ package org.sufficientlysecure.keychain.ui.adapter; import android.os.Parcel; import android.os.Parcelable; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; - import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPSecretKeyRing; @@ -33,6 +27,11 @@ import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; + public class ImportKeysListEntry implements Serializable, Parcelable { private static final long serialVersionUID = -7797972103284992662L; public ArrayList userIds; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java index 3eca99f15..d7544d1bb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java @@ -17,10 +17,8 @@ package org.sufficientlysecure.keychain.ui.adapter; -import java.io.BufferedInputStream; -import java.io.InputStream; -import java.util.ArrayList; - +import android.content.Context; +import android.support.v4.content.AsyncTaskLoader; import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPObjectFactory; import org.spongycastle.openpgp.PGPUtil; @@ -29,8 +27,9 @@ import org.sufficientlysecure.keychain.util.InputData; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.PositionAwareInputStream; -import android.content.Context; -import android.support.v4.content.AsyncTaskLoader; +import java.io.BufferedInputStream; +import java.io.InputStream; +import java.util.ArrayList; public class ImportKeysListLoader extends AsyncTaskLoader>> { @@ -40,9 +39,11 @@ public class ImportKeysListLoader extends AsyncTaskLoader> (data, new FileHasNoContent()); } - if(nonPgpCounter > 0) { + if (nonPgpCounter > 0) { entryListWrapper = new AsyncTaskResultWrapper> (data, new NonPgpPart(nonPgpCounter)); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java index 3a3b6e58b..0e1b83c81 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java @@ -19,7 +19,6 @@ package org.sufficientlysecure.keychain.ui.adapter; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.util.HkpKeyServer; import org.sufficientlysecure.keychain.util.KeyServer; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java index 78f7b1f7e..0a1dca751 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java @@ -17,15 +17,11 @@ package org.sufficientlysecure.keychain.ui.adapter; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - import android.content.Context; import android.widget.ArrayAdapter; +import java.util.*; + public class KeyValueSpinnerAdapter extends ArrayAdapter { private final HashMap mData; private final int[] mKeys; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java index 6d67a0e65..eaaa54376 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java @@ -17,12 +17,6 @@ package org.sufficientlysecure.keychain.ui.adapter; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; - import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; @@ -31,7 +25,11 @@ import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; - +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { @@ -50,7 +48,7 @@ public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { public final static String PROJECTION_ROW_VALID = "valid"; public SelectKeyCursorAdapter(Context context, Cursor c, int flags, ListView listView, - int keyType) { + int keyType) { super(context, c, flags); mInflater = LayoutInflater.from(context); @@ -69,7 +67,7 @@ public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { /** * Get column indexes for performance reasons just once in constructor and swapCursor. For a * performance comparison see http://stackoverflow.com/a/17999582 - * + * * @param cursor */ private void initIndex(Cursor cursor) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index 046a98883..153a3f266 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -17,10 +17,6 @@ package org.sufficientlysecure.keychain.ui.adapter; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; - import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; @@ -29,6 +25,9 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; public class ViewKeyKeysAdapter extends CursorAdapter { private LayoutInflater mInflater; @@ -59,7 +58,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { /** * Get column indexes for performance reasons just once in constructor and swapCursor. For a * performance comparison see http://stackoverflow.com/a/17999582 - * + * * @param cursor */ private void initIndex(Cursor cursor) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java index cf8699417..3ba291c3d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java @@ -17,9 +17,6 @@ package org.sufficientlysecure.keychain.ui.adapter; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; - import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; @@ -27,6 +24,8 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; public class ViewKeyUserIdsAdapter extends CursorAdapter { private LayoutInflater mInflater; @@ -51,7 +50,7 @@ public class ViewKeyUserIdsAdapter extends CursorAdapter { /** * Get column indexes for performance reasons just once in constructor and swapCursor. For a * performance comparison see http://stackoverflow.com/a/17999582 - * + * * @param cursor */ private void initIndex(Cursor cursor) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/BadImportKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/BadImportKeyDialogFragment.java index 2b8cba857..20b70658c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/BadImportKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/BadImportKeyDialogFragment.java @@ -23,7 +23,6 @@ import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; - import org.sufficientlysecure.keychain.R; public class BadImportKeyDialogFragment extends DialogFragment { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java index a47601c9b..140a33641 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java @@ -27,13 +27,11 @@ import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; - import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.util.Choice; import java.util.ArrayList; -import java.util.Vector; public class CreateKeyDialogFragment extends DialogFragment { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java index 162bf32fd..7f0c295ad 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java @@ -17,10 +17,6 @@ package org.sufficientlysecure.keychain.ui.dialog; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.service.KeychainIntentService; -import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; - import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; @@ -32,6 +28,9 @@ import android.os.Messenger; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.widget.Toast; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.service.KeychainIntentService; +import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; public class DeleteFileDialogFragment extends DialogFragment { private static final String ARG_DELETE_FILE = "delete_file"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java index dc40bab2a..c6751ec58 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java @@ -28,7 +28,6 @@ import android.os.Messenger; import android.os.RemoteException; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -118,7 +117,7 @@ public class DeleteKeyDialogFragment extends DialogFragment { String selectionIDs = ""; for (int i = 0; i < keyRingRowIds.length; i++) { selectionIDs += "'" + String.valueOf(keyRingRowIds[i]) + "'"; - if (i+1 < keyRingRowIds.length) + if (i + 1 < keyRingRowIds.length) selectionIDs += ","; } selection += selectionIDs + ")"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/FileDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/FileDialogFragment.java index 2a3a7508d..a4285c8e9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/FileDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/FileDialogFragment.java @@ -17,11 +17,6 @@ package org.sufficientlysecure.keychain.ui.dialog; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.FileHelper; -import org.sufficientlysecure.keychain.util.Log; - import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; @@ -38,8 +33,11 @@ import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.FileHelper; +import org.sufficientlysecure.keychain.util.Log; public class FileDialogFragment extends DialogFragment { private static final String ARG_MESSENGER = "messenger"; @@ -66,7 +64,7 @@ public class FileDialogFragment extends DialogFragment { * Creates new instance of this file dialog fragment */ public static FileDialogFragment newInstance(Messenger messenger, String title, String message, - String defaultFile, String checkboxText) { + String defaultFile, String checkboxText) { FileDialogFragment frag = new FileDialogFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_MESSENGER, messenger); @@ -176,34 +174,33 @@ public class FileDialogFragment extends DialogFragment { @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode & 0xFFFF) { - case REQUEST_CODE: { - if (resultCode == Activity.RESULT_OK && data != null) { - try { - String path = data.getData().getPath(); - Log.d(Constants.TAG, "path=" + path); - - // set filename used in export/import dialogs - setFilename(path); - } catch (NullPointerException e) { - Log.e(Constants.TAG, "Nullpointer while retrieving path!", e); + case REQUEST_CODE: { + if (resultCode == Activity.RESULT_OK && data != null) { + try { + String path = data.getData().getPath(); + Log.d(Constants.TAG, "path=" + path); + + // set filename used in export/import dialogs + setFilename(path); + } catch (NullPointerException e) { + Log.e(Constants.TAG, "Nullpointer while retrieving path!", e); + } } - } - break; - } + break; + } - default: - super.onActivityResult(requestCode, resultCode, data); + default: + super.onActivityResult(requestCode, resultCode, data); - break; + break; } } /** * Send message back to handler which is initialized in a activity - * - * @param what - * Message integer you want to send + * + * @param what Message integer you want to send */ private void sendMessageToHandler(Integer what, Bundle data) { Message msg = Message.obtain(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java index afa05cc91..fa74cbdc6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java @@ -17,20 +17,6 @@ package org.sufficientlysecure.keychain.ui.dialog; -import org.spongycastle.openpgp.PGPException; -import org.spongycastle.openpgp.PGPPrivateKey; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; -import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.service.PassphraseCacheService; -import org.sufficientlysecure.keychain.util.Log; - import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; @@ -52,6 +38,19 @@ import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPrivateKey; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.service.PassphraseCacheService; +import org.sufficientlysecure.keychain.util.Log; public class PassphraseDialogFragment extends DialogFragment implements OnEditorActionListener { private static final String ARG_MESSENGER = "messenger"; @@ -66,16 +65,14 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor /** * Creates new instance of this dialog fragment - * - * @param secretKeyId - * secret key id you want to use - * @param messenger - * to communicate back after caching the passphrase + * + * @param secretKeyId secret key id you want to use + * @param messenger to communicate back after caching the passphrase * @return * @throws PgpGeneralException */ public static PassphraseDialogFragment newInstance(Context context, Messenger messenger, - long secretKeyId) throws PgpGeneralException { + long secretKeyId) throws PgpGeneralException { // check if secret key has a passphrase if (!(secretKeyId == Id.key.symmetric || secretKeyId == Id.key.none)) { if (!PassphraseCacheService.hasPassphrase(context, secretKeyId)) { @@ -171,7 +168,7 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor Toast.makeText(activity, R.string.error_could_not_extract_private_key, Toast.LENGTH_SHORT).show(); - + sendMessageToHandler(MESSAGE_CANCEL); return; } else { @@ -187,14 +184,14 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor } catch (PGPException e) { Toast.makeText(activity, R.string.wrong_passphrase, Toast.LENGTH_SHORT).show(); - + sendMessageToHandler(MESSAGE_CANCEL); return; } } else { Toast.makeText(activity, R.string.error_could_not_extract_private_key, Toast.LENGTH_SHORT).show(); - + sendMessageToHandler(MESSAGE_CANCEL); return; // ran out of keys to try } @@ -207,7 +204,7 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor // cache the new passphrase Log.d(Constants.TAG, "Everything okay! Caching entered passphrase"); PassphraseCacheService.addCachedPassphrase(activity, keyId, passphrase); - if ( !keyOK && clickSecretKey.getKeyID() != keyId) { + if (!keyOK && clickSecretKey.getKeyID() != keyId) { PassphraseCacheService.addCachedPassphrase(activity, clickSecretKey.getKeyID(), passphrase); } @@ -265,9 +262,8 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor /** * Send message back to handler which is initialized in a activity - * - * @param what - * Message integer you want to send + * + * @param what Message integer you want to send */ private void sendMessageToHandler(Integer what) { Message msg = Message.obtain(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java index b7a1882ef..062eca3e5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java @@ -26,7 +26,6 @@ import android.content.DialogInterface.OnKeyListener; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.KeyEvent; - import org.sufficientlysecure.keychain.R; public class ProgressDialogFragment extends DialogFragment { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java index e406547b3..69723b804 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java @@ -17,10 +17,6 @@ package org.sufficientlysecure.keychain.ui.dialog; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.util.Log; - import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; @@ -40,6 +36,9 @@ import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.util.Log; public class SetPassphraseDialogFragment extends DialogFragment implements OnEditorActionListener { private static final String ARG_MESSENGER = "messenger"; @@ -55,11 +54,9 @@ public class SetPassphraseDialogFragment extends DialogFragment implements OnEdi /** * Creates new instance of this dialog fragment - * - * @param title - * title of dialog - * @param messenger - * to communicate back after setting the passphrase + * + * @param title title of dialog + * @param messenger to communicate back after setting the passphrase * @return */ public static SetPassphraseDialogFragment newInstance(Messenger messenger, int title) { @@ -96,7 +93,7 @@ public class SetPassphraseDialogFragment extends DialogFragment implements OnEdi mPassphraseAgainEditText = (EditText) view.findViewById(R.id.passphrase_passphrase_again); alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - + @Override public void onClick(DialogInterface dialog, int id) { dismiss(); @@ -130,7 +127,7 @@ public class SetPassphraseDialogFragment extends DialogFragment implements OnEdi }); alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - + @Override public void onClick(DialogInterface dialog, int id) { dismiss(); @@ -168,9 +165,8 @@ public class SetPassphraseDialogFragment extends DialogFragment implements OnEdi /** * Send message back to handler which is initialized in a activity - * - * @param what - * Message integer you want to send + * + * @param what Message integer you want to send */ private void sendMessageToHandler(Integer what, Bundle data) { Message msg = Message.obtain(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java index b850638a6..6b4de0334 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java @@ -17,9 +17,6 @@ package org.sufficientlysecure.keychain.ui.dialog; -import org.sufficientlysecure.htmltextview.HtmlTextView; -import org.sufficientlysecure.keychain.R; - import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.Dialog; @@ -31,6 +28,8 @@ import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; +import org.sufficientlysecure.htmltextview.HtmlTextView; +import org.sufficientlysecure.keychain.R; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class ShareNfcDialogFragment extends DialogFragment { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java index f26cd35c0..b501ba230 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java @@ -28,7 +28,6 @@ import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java index b9dcd0d25..6245fd95c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java @@ -24,7 +24,7 @@ import android.widget.ListView; /** * Automatically calculate height of ListView based on contained items. This enables to put this * ListView into a ScrollView without messing up. - * + *

* from * http://stackoverflow.com/questions/2419246/how-do-i-create-a-listview-thats-not-in-a-scrollview- * or-has-the-scrollview-dis diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/IntegerListPreference.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/IntegerListPreference.java index bc60b2adf..6e1e4c678 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/IntegerListPreference.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/IntegerListPreference.java @@ -25,7 +25,7 @@ import android.util.AttributeSet; * values should use {@link android.content.SharedPreferences#getInt}. When using XML-declared * arrays for entry values, the arrays should be regular string arrays containing valid integer * values. - * + * * @author Rodrigo Damazio */ public class IntegerListPreference extends ListPreference { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java index 9f25fac42..0d15de982 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java @@ -16,20 +16,6 @@ package org.sufficientlysecure.keychain.ui.widget; -import java.text.DateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; -import java.util.Vector; - -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPSecretKey; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.util.Choice; - import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.app.Dialog; @@ -40,13 +26,17 @@ import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.DatePicker; -import android.widget.LinearLayout; -import android.widget.Spinner; -import android.widget.TextView; - +import android.widget.*; import com.beardedhen.androidbootstrap.BootstrapButton; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPSecretKey; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; +import org.sufficientlysecure.keychain.util.Choice; + +import java.text.DateFormat; +import java.util.*; public class KeyEditor extends LinearLayout implements Editor, OnClickListener { private PGPSecretKey mKey; @@ -99,7 +89,7 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { new Choice(Id.choice.usage.encrypt_only, getResources().getString( R.string.choice_encrypt_only)), new Choice(Id.choice.usage.sign_and_encrypt, getResources().getString( - R.string.choice_sign_and_encrypt)), }; + R.string.choice_sign_and_encrypt)),}; ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, choices); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); @@ -144,11 +134,11 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { dialog.getDatePicker().setCalendarViewShown(false); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { - if ( dialog != null && mCreatedDate != null ) { - dialog.getDatePicker().setMinDate(mCreatedDate.getTime().getTime()+ DateUtils.DAY_IN_MILLIS); + if (dialog != null && mCreatedDate != null) { + dialog.getDatePicker().setMinDate(mCreatedDate.getTime().getTime() + DateUtils.DAY_IN_MILLIS); } else { //When created date isn't available - dialog.getDatePicker().setMinDate(date.getTime().getTime()+ DateUtils.DAY_IN_MILLIS); + dialog.getDatePicker().setMinDate(date.getTime().getTime() + DateUtils.DAY_IN_MILLIS); } } @@ -290,6 +280,7 @@ class ExpiryDatePickerDialog extends DatePickerDialog { public ExpiryDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, callBack, year, monthOfYear, dayOfMonth); } + //Set permanent title. public void setTitle(CharSequence title) { super.setTitle(getContext().getString(R.string.expiry_date_dialog_title)); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyServerEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyServerEditor.java index 01259ccd1..f92c7532a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyServerEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyServerEditor.java @@ -16,8 +16,6 @@ package org.sufficientlysecure.keychain.ui.widget; -import org.sufficientlysecure.keychain.R; - import android.content.Context; import android.util.AttributeSet; import android.view.View; @@ -25,8 +23,8 @@ import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; - import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.R; public class KeyServerEditor extends LinearLayout implements Editor, OnClickListener { private EditorListener mEditorListener = null; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java index 0acfe13bc..d6e44ee4e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java @@ -31,9 +31,7 @@ import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; - import com.beardedhen.androidbootstrap.BootstrapButton; - import org.spongycastle.openpgp.PGPSecretKey; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UnderlineTextView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UnderlineTextView.java index 752d44f89..937a48e48 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UnderlineTextView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UnderlineTextView.java @@ -26,7 +26,7 @@ import android.widget.TextView; /** * Copied from StickyListHeaders lib example - * + * * @author Eric Frohnhoefer */ public class UnderlineTextView extends TextView { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java index 71cd89ae8..039e87446 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java @@ -16,21 +16,19 @@ package org.sufficientlysecure.keychain.ui.widget; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import android.widget.*; -import org.sufficientlysecure.keychain.R; - import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; - +import android.widget.*; import com.beardedhen.androidbootstrap.BootstrapButton; +import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.ContactHelper; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class UserIdEditor extends LinearLayout implements Editor, OnClickListener { private EditorListener mEditorListener = null; @@ -109,7 +107,7 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene mEmail.setAdapter( new ArrayAdapter (this.getContext(), android.R.layout.simple_dropdown_item_1line, - ContactHelper.getMailAccounts(getContext()) + ContactHelper.getMailAccounts(getContext()) )); super.onFinishInflate(); -- cgit v1.2.3 From dc5c34ffc5e7e4f76f69f103d33b5a84616586fc Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 20:41:53 +0200 Subject: More code style fixes for /ui --- .../keychain/ui/EditKeyActivity.java | 19 +++++------ .../keychain/ui/HelpActivity.java | 2 +- .../keychain/ui/ImportKeysClipboardFragment.java | 3 +- .../keychain/ui/ImportKeysListFragment.java | 3 +- .../keychain/ui/KeyListFragment.java | 34 ++++++++++++++------ .../keychain/ui/SelectPublicKeyFragment.java | 5 +-- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 5 ++- .../keychain/ui/ViewKeyActivity.java | 3 +- .../keychain/ui/ViewKeyMainFragment.java | 37 ++++++++++++++-------- .../ui/dialog/CreateKeyDialogFragment.java | 2 +- .../ui/dialog/DeleteFileDialogFragment.java | 5 +-- .../ui/dialog/DeleteKeyDialogFragment.java | 9 ++++-- .../ui/dialog/PassphraseDialogFragment.java | 8 ++--- .../keychain/ui/dialog/ProgressDialogFragment.java | 5 +-- .../ui/dialog/SetPassphraseDialogFragment.java | 2 +- .../keychain/ui/dialog/ShareNfcDialogFragment.java | 2 +- 16 files changed, 91 insertions(+), 53 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 1dde4601b..f99e88e60 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -98,7 +98,7 @@ public class EditKeyActivity extends ActionBarActivity { Vector mUserIds; Vector mKeys; Vector mKeysUsages; - boolean masterCanSign = true; + boolean mMasterCanSign = true; ExportHelper mExportHelper; @@ -264,8 +264,8 @@ public class EditKeyActivity extends ActionBarActivity { // get master key id using row id long masterKeyId = ProviderHelper.getMasterKeyId(this, mDataUri); - masterCanSign = ProviderHelper.getMasterKeyCanSign(this, mDataUri); - finallyEdit(masterKeyId, masterCanSign); + mMasterCanSign = ProviderHelper.getMasterKeyCanSign(this, mDataUri); + finallyEdit(masterKeyId, mMasterCanSign); } } @@ -432,12 +432,12 @@ public class EditKeyActivity extends ActionBarActivity { LinearLayout container = (LinearLayout) findViewById(R.id.edit_key_container); mUserIdsView = (SectionView) inflater.inflate(R.layout.edit_key_section, container, false); mUserIdsView.setType(Id.type.user_id); - mUserIdsView.setCanEdit(masterCanSign); + mUserIdsView.setCanEdit(mMasterCanSign); mUserIdsView.setUserIds(mUserIds); container.addView(mUserIdsView); mKeysView = (SectionView) inflater.inflate(R.layout.edit_key_section, container, false); mKeysView.setType(Id.type.key); - mKeysView.setCanEdit(masterCanSign); + mKeysView.setCanEdit(mMasterCanSign); mKeysView.setKeys(mKeys, mKeysUsages); container.addView(mKeysView); @@ -493,12 +493,13 @@ public class EditKeyActivity extends ActionBarActivity { } String passphrase = null; - if (mIsPassPhraseSet) + if (mIsPassPhraseSet) { passphrase = PassphraseCacheService.getCachedPassphrase(this, masterKeyId); - else + } else { passphrase = ""; + } if (passphrase == null) { - showPassphraseDialog(masterKeyId, masterCanSign); + showPassphraseDialog(masterKeyId, mMasterCanSign); } else { mCurrentPassphrase = passphrase; finallySaveClicked(); @@ -531,7 +532,7 @@ public class EditKeyActivity extends ActionBarActivity { data.putSerializable(KeychainIntentService.SAVE_KEYRING_KEYS_EXPIRY_DATES, getKeysExpiryDates(mKeysView)); data.putLong(KeychainIntentService.SAVE_KEYRING_MASTER_KEY_ID, getMasterKeyId()); - data.putBoolean(KeychainIntentService.SAVE_KEYRING_CAN_SIGN, masterCanSign); + data.putBoolean(KeychainIntentService.SAVE_KEYRING_CAN_SIGN, mMasterCanSign); intent.putExtra(KeychainIntentService.EXTRA_DATA, data); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java index 436d9291d..32f37a0a5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/HelpActivity.java @@ -76,4 +76,4 @@ public class HelpActivity extends ActionBarActivity { mTabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.help_tab_about)), HelpAboutFragment.class, null, (selectedTab == 4)); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java index c21271220..3f0b4a46e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysClipboardFragment.java @@ -58,8 +58,9 @@ public class ImportKeysClipboardFragment extends Fragment { public void onClick(View v) { CharSequence clipboardText = ClipboardReflection.getClipboardText(getActivity()); String sendText = ""; - if (clipboardText != null) + if (clipboardText != null) { sendText = clipboardText.toString(); + } mImportActivity.loadCallback(sendText.getBytes(), null, null, null); } }); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java index 346c009fb..9e8506193 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysListFragment.java @@ -178,7 +178,8 @@ public class ImportKeysListFragment extends ListFragment implements } @Override - public Loader>> onCreateLoader(int id, Bundle args) { + public Loader>> + onCreateLoader(int id, Bundle args) { switch (id) { case LOADER_ID_BYTES: { InputData inputData = getInputData(mKeyBytes, mDataUri); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 6230abbed..e969c1af3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -36,8 +36,8 @@ import android.text.TextUtils; import android.view.*; import android.view.View.OnClickListener; import android.view.animation.AnimationUtils; -import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.*; +import android.widget.AbsListView.MultiChoiceModeListener; import com.beardedhen.androidbootstrap.BootstrapButton; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; @@ -63,7 +63,8 @@ import java.util.HashMap; * Public key list with sticky list headers. It does _not_ extend ListFragment because it uses * StickyListHeaders library which does not extend upon ListView. */ -public class KeyListFragment extends Fragment implements SearchView.OnQueryTextListener, AdapterView.OnItemClickListener, +public class KeyListFragment extends Fragment + implements SearchView.OnQueryTextListener, AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks { private KeyListAdapter mAdapter; @@ -185,7 +186,10 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL // todo: public/secret needs to be handled differently here ids = mStickyList.getWrappedList().getCheckedItemIds(); ExportHelper mExportHelper = new ExportHelper((ActionBarActivity) getActivity()); - mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); + mExportHelper + .showExportKeysDialog(ids, + Id.type.public_key, + Constants.path.APP_DIR_FILE_PUB); break; } case R.id.menu_key_list_multi_select_all: { @@ -310,7 +314,10 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL } else { viewIntent = new Intent(getActivity(), ViewKeyActivityJB.class); } - viewIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsByMasterKeyIdUri(Long.toString(mAdapter.getMasterKeyId(position)))); + viewIntent.setData( + KeychainContract + .KeyRings.buildPublicKeyRingsByMasterKeyIdUri( + Long.toString(mAdapter.getMasterKeyId(position)))); startActivity(viewIntent); } @@ -347,8 +354,12 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL for (String userId : notDeleted) { notDeletedMsg += userId + "\n"; } - Toast.makeText(getActivity(), getString(R.string.error_can_not_delete_contacts, notDeletedMsg) - + getResources().getQuantityString(R.plurals.error_can_not_delete_info, notDeleted.size()), + Toast.makeText(getActivity(), + getString(R.string.error_can_not_delete_contacts, notDeletedMsg) + + getResources() + .getQuantityString( + R.plurals.error_can_not_delete_info, + notDeleted.size()), Toast.LENGTH_LONG).show(); mode.finish(); @@ -507,7 +518,9 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL button.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); - editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(id))); + editIntent.setData( + KeychainContract.KeyRings + .buildSecretKeyRingsByMasterKeyIdUri(Long.toString(id))); editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); startActivityForResult(editIntent, 0); } @@ -582,7 +595,8 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL String userId = mCursor.getString(KeyListFragment.INDEX_USER_ID); String headerText = convertView.getResources().getString(R.string.user_id_no_name); if (userId != null && userId.length() > 0) { - headerText = "" + mCursor.getString(KeyListFragment.INDEX_USER_ID).subSequence(0, 1).charAt(0); + headerText = "" + + mCursor.getString(KeyListFragment.INDEX_USER_ID).subSequence(0, 1).charAt(0); } holder.mText.setText(headerText); holder.mCount.setVisibility(View.GONE); @@ -605,9 +619,9 @@ public class KeyListFragment extends Fragment implements SearchView.OnQueryTextL } // early breakout: all secret keys are assigned id 0 - if (mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) + if (mCursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { return 1L; - + } // otherwise, return the first character of the name as ID String userId = mCursor.getString(KeyListFragment.INDEX_USER_ID); if (userId != null && userId.length() > 0) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java index 7a30b11d2..6ab9f1c6e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyFragment.java @@ -132,7 +132,8 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T mSearchView = new EditText(context); mSearchView.setId(SEARCH_ID); mSearchView.setHint(R.string.menu_search); - mSearchView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ic_action_search), null, null, null); + mSearchView.setCompoundDrawablesWithIntrinsicBounds( + getResources().getDrawable(R.drawable.ic_action_search), null, null, null); linearLayout.addView(mSearchView, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); @@ -270,7 +271,7 @@ public class SelectPublicKeyFragment extends ListFragmentWorkaround implements T + Keys.CAN_ENCRYPT + " = '1' AND valid_keys." + Keys.CREATION + " <= '" + now + "' AND " + "(valid_keys." + Keys.EXPIRY + " IS NULL OR valid_keys." + Keys.EXPIRY + " >= '" + now + "')) AS " - + SelectKeyCursorAdapter.PROJECTION_ROW_VALID,}; + + SelectKeyCursorAdapter.PROJECTION_ROW_VALID, }; String inMasterKeyList = null; if (mSelectedMasterKeyIds != null && mSelectedMasterKeyIds.length > 0) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index b1de85973..beff8385e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -101,7 +101,10 @@ public class SelectSecretKeyLayoutFragment extends Fragment { mKeyUserIdRest.setVisibility(View.GONE); } } else { - mKeyMasterKeyIdHex.setText(getActivity().getResources().getString(R.string.no_keys_added_or_updated) + " for master id: " + secretKeyId); + mKeyMasterKeyIdHex.setText( + getActivity().getResources() + .getString(R.string.no_keys_added_or_updated) + + " for master id: " + secretKeyId); mKeyUserId.setVisibility(View.GONE); mKeyUserIdRest.setVisibility(View.GONE); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 2d47c7a92..32c0ea340 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -241,7 +241,8 @@ public class ViewKeyActivity extends ActionBarActivity { // we delete only this key, so MESSAGE_NOT_DELETED will solely contain this key Toast.makeText(ViewKeyActivity.this, getString(R.string.error_can_not_delete_contact) - + getResources().getQuantityString(R.plurals.error_can_not_delete_info, 1), + + getResources() + .getQuantityString(R.plurals.error_can_not_delete_info, 1), Toast.LENGTH_LONG).show(); } else { setResult(RESULT_CANCELED); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index a4a811bbc..eeb17fea2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -136,7 +136,10 @@ public class ViewKeyMainFragment extends Fragment implements mActionEdit.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent editIntent = new Intent(getActivity(), EditKeyActivity.class); - editIntent.setData(KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId))); + editIntent.setData( + KeychainContract + .KeyRings.buildSecretKeyRingsByMasterKeyIdUri( + Long.toString(masterKeyId))); editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); startActivityForResult(editIntent, 0); } @@ -169,21 +172,28 @@ public class ViewKeyMainFragment extends Fragment implements getActivity().getSupportLoaderManager().initLoader(LOADER_ID_KEYS, null, this); } - static final String[] KEYRING_PROJECTION = new String[]{KeychainContract.KeyRings._ID, KeychainContract.KeyRings.MASTER_KEY_ID, + static final String[] KEYRING_PROJECTION = + new String[]{KeychainContract.KeyRings._ID, KeychainContract.KeyRings.MASTER_KEY_ID, KeychainContract.UserIds.USER_ID}; static final int KEYRING_INDEX_ID = 0; static final int KEYRING_INDEX_MASTER_KEY_ID = 1; static final int KEYRING_INDEX_USER_ID = 2; - static final String[] USER_IDS_PROJECTION = new String[]{KeychainContract.UserIds._ID, KeychainContract.UserIds.USER_ID, - KeychainContract.UserIds.RANK,}; + static final String[] USER_IDS_PROJECTION = + new String[]{KeychainContract.UserIds._ID, KeychainContract.UserIds.USER_ID, + KeychainContract.UserIds.RANK, }; // not the main user id static final String USER_IDS_SELECTION = KeychainContract.UserIds.RANK + " > 0 "; - static final String USER_IDS_SORT_ORDER = KeychainContract.UserIds.USER_ID + " COLLATE LOCALIZED ASC"; - - static final String[] KEYS_PROJECTION = new String[]{KeychainContract.Keys._ID, KeychainContract.Keys.KEY_ID, - KeychainContract.Keys.IS_MASTER_KEY, KeychainContract.Keys.ALGORITHM, KeychainContract.Keys.KEY_SIZE, KeychainContract.Keys.CAN_CERTIFY, KeychainContract.Keys.CAN_SIGN, - KeychainContract.Keys.CAN_ENCRYPT, KeychainContract.Keys.CREATION, KeychainContract.Keys.EXPIRY, KeychainContract.Keys.FINGERPRINT}; + static final String USER_IDS_SORT_ORDER = + KeychainContract.UserIds.USER_ID + " COLLATE LOCALIZED ASC"; + + static final String[] KEYS_PROJECTION = + new String[]{KeychainContract.Keys._ID, KeychainContract.Keys.KEY_ID, + KeychainContract.Keys.IS_MASTER_KEY, KeychainContract.Keys.ALGORITHM, + KeychainContract.Keys.KEY_SIZE, KeychainContract.Keys.CAN_CERTIFY, + KeychainContract.Keys.CAN_SIGN, KeychainContract.Keys.CAN_ENCRYPT, + KeychainContract.Keys.CREATION, KeychainContract.Keys.EXPIRY, + KeychainContract.Keys.FINGERPRINT}; static final String KEYS_SORT_ORDER = KeychainContract.Keys.RANK + " ASC"; static final int KEYS_INDEX_ID = 0; static final int KEYS_INDEX_KEY_ID = 1; @@ -266,7 +276,8 @@ public class ViewKeyMainFragment extends Fragment implements } else { Date creationDate = new Date(data.getLong(KEYS_INDEX_CREATION) * 1000); - mCreation.setText(DateFormat.getDateFormat(getActivity().getApplicationContext()).format( + mCreation.setText( + DateFormat.getDateFormat(getActivity().getApplicationContext()).format( creationDate)); } @@ -276,7 +287,8 @@ public class ViewKeyMainFragment extends Fragment implements } else { Date expiryDate = new Date(data.getLong(KEYS_INDEX_EXPIRY) * 1000); - mExpiry.setText(DateFormat.getDateFormat(getActivity().getApplicationContext()).format( + mExpiry.setText( + DateFormat.getDateFormat(getActivity().getApplicationContext()).format( expiryDate)); } @@ -397,5 +409,4 @@ public class ViewKeyMainFragment extends Fragment implements startActivity(signIntent); } - -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java index 140a33641..a41bc2bee 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java @@ -148,4 +148,4 @@ public class CreateKeyDialogFragment extends DialogFragment { return dialog.create(); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java index 7f0c295ad..b067010df 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java @@ -88,7 +88,8 @@ public class DeleteFileDialogFragment extends DialogFragment { null); // Message is received after deleting is done in ApgService - KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(activity, deletingDialog) { + KeychainIntentServiceHandler saveHandler = + new KeychainIntentServiceHandler(activity, deletingDialog) { public void handleMessage(Message message) { // handle messages by standard ApgHandler first super.handleMessage(message); @@ -120,4 +121,4 @@ public class DeleteFileDialogFragment extends DialogFragment { return alert.create(); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java index c6751ec58..1bcf5b33c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java @@ -117,8 +117,9 @@ public class DeleteKeyDialogFragment extends DialogFragment { String selectionIDs = ""; for (int i = 0; i < keyRingRowIds.length; i++) { selectionIDs += "'" + String.valueOf(keyRingRowIds[i]) + "'"; - if (i + 1 < keyRingRowIds.length) + if (i + 1 < keyRingRowIds.length) { selectionIDs += ","; + } } selection += selectionIDs + ")"; @@ -139,7 +140,9 @@ public class DeleteKeyDialogFragment extends DialogFragment { // check if a corresponding secret key exists... Cursor secretCursor = activity.getContentResolver().query( - KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(String.valueOf(masterKeyId)), + KeychainContract.KeyRings + .buildSecretKeyRingsByMasterKeyIdUri( + String.valueOf(masterKeyId)), null, null, null, null ); if (secretCursor != null && secretCursor.getCount() > 0) { @@ -204,4 +207,4 @@ public class DeleteKeyDialogFragment extends DialogFragment { Log.w(Constants.TAG, "Messenger is null!", e); } } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java index fa74cbdc6..271219fa3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/PassphraseDialogFragment.java @@ -61,7 +61,7 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor private Messenger mMessenger; private EditText mPassphraseEditText; - private boolean canKB; + private boolean mCanKB; /** * Creates new instance of this dialog fragment @@ -128,7 +128,7 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor } }); alert.setCancelable(false); - canKB = false; + mCanKB = false; return alert.create(); } String userId = PgpKeyHelper.getMainUserIdSafe(activity, secretKey); @@ -221,14 +221,14 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor } }); - canKB = true; + mCanKB = true; return alert.create(); } @Override public void onActivityCreated(Bundle arg0) { super.onActivityCreated(arg0); - if (canKB) { + if (mCanKB) { // request focus and open soft keyboard mPassphraseEditText.requestFocus(); getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java index 062eca3e5..132a2ce86 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ProgressDialogFragment.java @@ -100,8 +100,9 @@ public class ProgressDialogFragment extends DialogFragment { public void onCancel(DialogInterface dialog) { super.onCancel(dialog); - if (this.mOnCancelListener != null) + if (this.mOnCancelListener != null) { this.mOnCancelListener.onCancel(dialog); + } } /** @@ -150,4 +151,4 @@ public class ProgressDialogFragment extends DialogFragment { return dialog; } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java index 69723b804..ae61c1470 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/SetPassphraseDialogFragment.java @@ -183,4 +183,4 @@ public class SetPassphraseDialogFragment extends DialogFragment implements OnEdi Log.w(Constants.TAG, "Messenger is null!", e); } } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java index 6b4de0334..741530b1d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareNfcDialogFragment.java @@ -96,4 +96,4 @@ public class ShareNfcDialogFragment extends DialogFragment { return alert.create(); } -} \ No newline at end of file +} -- cgit v1.2.3 From 4353ea37e223c0ed5b9f14c0226ce87ea992288c Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 21:07:21 +0200 Subject: more UI code style fixes --- .../keychain/ui/DecryptActivity.java | 6 ++-- .../keychain/ui/DrawerActivity.java | 32 +++++++++--------- .../keychain/ui/KeyListActivity.java | 2 +- .../keychain/ui/PreferencesActivity.java | 39 ++++++++++++---------- .../keychain/ui/SelectPublicKeyActivity.java | 6 ++-- .../keychain/ui/widget/FixedListView.java | 2 +- .../keychain/ui/widget/KeyEditor.java | 16 +++++---- .../keychain/ui/widget/SectionView.java | 33 +++++++++--------- .../keychain/ui/widget/UserIdEditor.java | 11 ++---- 9 files changed, 77 insertions(+), 70 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index 42b20788f..f805198f1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -351,7 +351,7 @@ public class DecryptActivity extends DrawerActivity { } } else { Log.e(Constants.TAG, - "Direct binary data without actual file in filesystem is not supported. Please use the Remote Service API!"); + "Direct binary data without actual file in filesystem is not supported. Please use the Remote Service API!"); Toast.makeText(this, R.string.error_only_files_are_supported, Toast.LENGTH_LONG) .show(); // end activity @@ -519,7 +519,9 @@ public class DecryptActivity extends DrawerActivity { AppMsg.STYLE_ALERT).show(); } finally { try { - if (inStream != null) inStream.close(); + if (inStream != null) { + inStream.close(); + } } catch (Exception e) { } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java index be22c8753..c0fd53007 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java @@ -221,15 +221,15 @@ public class DrawerActivity extends ActionBarActivity { } private class NavigationDrawerAdapter extends ArrayAdapter { - Context context; - int layoutResourceId; - NavItem data[] = null; + Context mContext; + int mLayoutResourceId; + NavItem mData[] = null; public NavigationDrawerAdapter(Context context, int layoutResourceId, NavItem[] data) { super(context, layoutResourceId, data); - this.layoutResourceId = layoutResourceId; - this.context = context; - this.data = data; + this.mLayoutResourceId = layoutResourceId; + this.mContext = context; + this.mData = data; } @Override @@ -238,21 +238,21 @@ public class DrawerActivity extends ActionBarActivity { NavItemHolder holder = null; if (row == null) { - LayoutInflater inflater = ((Activity) context).getLayoutInflater(); - row = inflater.inflate(layoutResourceId, parent, false); + LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); + row = inflater.inflate(mLayoutResourceId, parent, false); holder = new NavItemHolder(); - holder.img = (FontAwesomeText) row.findViewById(R.id.drawer_item_icon); - holder.txtTitle = (TextView) row.findViewById(R.id.drawer_item_text); + holder.mImg = (FontAwesomeText) row.findViewById(R.id.drawer_item_icon); + holder.mTxtTitle = (TextView) row.findViewById(R.id.drawer_item_text); row.setTag(holder); } else { holder = (NavItemHolder) row.getTag(); } - NavItem item = data[position]; - holder.txtTitle.setText(item.title); - holder.img.setIcon(item.icon); + NavItem item = mData[position]; + holder.mTxtTitle.setText(item.title); + holder.mImg.setIcon(item.icon); return row; } @@ -260,8 +260,8 @@ public class DrawerActivity extends ActionBarActivity { } static class NavItemHolder { - FontAwesomeText img; - TextView txtTitle; + FontAwesomeText mImg; + TextView mTxtTitle; } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index a70688cdf..0dda10c9c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -73,7 +73,7 @@ public class KeyListActivity extends DrawerActivity { case R.id.menu_key_list_secret_export: mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); - + return true; default: return super.onOptionsItemSelected(item); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java index 5660850b2..47372eb59 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java @@ -34,8 +34,8 @@ import java.util.List; @SuppressLint("NewApi") public class PreferencesActivity extends PreferenceActivity { - public final static String ACTION_PREFS_GEN = "org.sufficientlysecure.keychain.ui.PREFS_GEN"; - public final static String ACTION_PREFS_ADV = "org.sufficientlysecure.keychain.ui.PREFS_ADV"; + public static final String ACTION_PREFS_GEN = "org.sufficientlysecure.keychain.ui.PREFS_GEN"; + public static final String ACTION_PREFS_ADV = "org.sufficientlysecure.keychain.ui.PREFS_ADV"; private PreferenceScreen mKeyServerPreference = null; private static Preferences mPreferences; @@ -81,12 +81,12 @@ public class PreferencesActivity extends PreferenceActivity { (IntegerListPreference) findPreference(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM)); int[] valueIds = new int[]{Id.choice.compression.none, Id.choice.compression.zip, - Id.choice.compression.zlib, Id.choice.compression.bzip2,}; + Id.choice.compression.zlib, Id.choice.compression.bzip2, }; String[] entries = new String[]{ getString(R.string.choice_none) + " (" + getString(R.string.compression_fast) + ")", "ZIP (" + getString(R.string.compression_fast) + ")", "ZLIB (" + getString(R.string.compression_fast) + ")", - "BZIP2 (" + getString(R.string.compression_very_slow) + ")",}; + "BZIP2 (" + getString(R.string.compression_very_slow) + ")", }; String[] values = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; @@ -104,9 +104,11 @@ public class PreferencesActivity extends PreferenceActivity { (IntegerListPreference) findPreference(Constants.pref.DEFAULT_FILE_COMPRESSION), entries, values); - initializeAsciiArmour((CheckBoxPreference) findPreference(Constants.pref.DEFAULT_ASCII_ARMOUR)); + initializeAsciiArmour( + (CheckBoxPreference) findPreference(Constants.pref.DEFAULT_ASCII_ARMOUR)); - initializeForceV3Signatures((CheckBoxPreference) findPreference(Constants.pref.FORCE_V3_SIGNATURES)); + initializeForceV3Signatures( + (CheckBoxPreference) findPreference(Constants.pref.FORCE_V3_SIGNATURES)); } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // Load the legacy preferences headers @@ -216,12 +218,12 @@ public class PreferencesActivity extends PreferenceActivity { (IntegerListPreference) findPreference(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM)); int[] valueIds = new int[]{Id.choice.compression.none, Id.choice.compression.zip, - Id.choice.compression.zlib, Id.choice.compression.bzip2,}; + Id.choice.compression.zlib, Id.choice.compression.bzip2, }; String[] entries = new String[]{ getString(R.string.choice_none) + " (" + getString(R.string.compression_fast) + ")", "ZIP (" + getString(R.string.compression_fast) + ")", "ZLIB (" + getString(R.string.compression_fast) + ")", - "BZIP2 (" + getString(R.string.compression_very_slow) + ")",}; + "BZIP2 (" + getString(R.string.compression_very_slow) + ")", }; String[] values = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; @@ -239,9 +241,11 @@ public class PreferencesActivity extends PreferenceActivity { (IntegerListPreference) findPreference(Constants.pref.DEFAULT_FILE_COMPRESSION), entries, values); - initializeAsciiArmour((CheckBoxPreference) findPreference(Constants.pref.DEFAULT_ASCII_ARMOUR)); + initializeAsciiArmour( + (CheckBoxPreference) findPreference(Constants.pref.DEFAULT_ASCII_ARMOUR)); - initializeForceV3Signatures((CheckBoxPreference) findPreference(Constants.pref.FORCE_V3_SIGNATURES)); + initializeForceV3Signatures( + (CheckBoxPreference) findPreference(Constants.pref.FORCE_V3_SIGNATURES)); } } @@ -269,9 +273,9 @@ public class PreferencesActivity extends PreferenceActivity { int valueIds[] = {PGPEncryptedData.AES_128, PGPEncryptedData.AES_192, PGPEncryptedData.AES_256, PGPEncryptedData.BLOWFISH, PGPEncryptedData.TWOFISH, PGPEncryptedData.CAST5, PGPEncryptedData.DES, PGPEncryptedData.TRIPLE_DES, - PGPEncryptedData.IDEA,}; + PGPEncryptedData.IDEA, }; String entries[] = {"AES-128", "AES-192", "AES-256", "Blowfish", "Twofish", "CAST5", - "DES", "Triple DES", "IDEA",}; + "DES", "Triple DES", "IDEA", }; String values[] = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; @@ -296,9 +300,9 @@ public class PreferencesActivity extends PreferenceActivity { (final IntegerListPreference mHashAlgorithm, int[] valueIds, String[] entries, String[] values) { valueIds = new int[]{HashAlgorithmTags.MD5, HashAlgorithmTags.RIPEMD160, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA224, HashAlgorithmTags.SHA256, - HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512,}; + HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, }; entries = new String[]{"MD5", "RIPEMD-160", "SHA-1", "SHA-224", "SHA-256", "SHA-384", - "SHA-512",}; + "SHA-512", }; values = new String[valueIds.length]; for (int i = 0; i < values.length; ++i) { values[i] = "" + valueIds[i]; @@ -317,8 +321,9 @@ public class PreferencesActivity extends PreferenceActivity { }); } - private static void initializeMessageCompression - (final IntegerListPreference mMessageCompression, int[] valueIds, String[] entries, String[] values) { + private static void initializeMessageCompression( + final IntegerListPreference mMessageCompression, + int[] valueIds, String[] entries, String[] values) { mMessageCompression.setEntries(entries); mMessageCompression.setEntryValues(values); mMessageCompression.setValue("" + mPreferences.getDefaultMessageCompression()); @@ -373,4 +378,4 @@ public class PreferencesActivity extends PreferenceActivity { } }); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java index 7efb43cce..874703704 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectPublicKeyActivity.java @@ -38,7 +38,7 @@ public class SelectPublicKeyActivity extends ActionBarActivity { SelectPublicKeyFragment mSelectFragment; - long selectedMasterKeyIds[]; + long mSelectedMasterKeyIds[]; @Override protected void onCreate(Bundle savedInstanceState) { @@ -79,7 +79,7 @@ public class SelectPublicKeyActivity extends ActionBarActivity { } // Create an instance of the fragment - mSelectFragment = SelectPublicKeyFragment.newInstance(selectedMasterKeyIds); + mSelectFragment = SelectPublicKeyFragment.newInstance(mSelectedMasterKeyIds); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() @@ -124,7 +124,7 @@ public class SelectPublicKeyActivity extends ActionBarActivity { // } // preselected master keys - selectedMasterKeyIds = intent.getLongArrayExtra(EXTRA_SELECTED_MASTER_KEY_IDS); + mSelectedMasterKeyIds = intent.getLongArrayExtra(EXTRA_SELECTED_MASTER_KEY_IDS); } private void cancelClicked() { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java index 6245fd95c..da29f808a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FixedListView.java @@ -52,4 +52,4 @@ public class FixedListView extends ListView { super.onMeasure(widthMeasureSpec, expandSpec); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java index 0d15de982..7e0acfa28 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/KeyEditor.java @@ -54,7 +54,8 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { GregorianCalendar mExpiryDate; private int mDatePickerResultCount = 0; - private DatePickerDialog.OnDateSetListener mExpiryDateSetListener = new DatePickerDialog.OnDateSetListener() { + private DatePickerDialog.OnDateSetListener mExpiryDateSetListener = + new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // Note: Ignore results after the first one - android sends multiples. if (mDatePickerResultCount++ == 0) { @@ -89,7 +90,7 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { new Choice(Id.choice.usage.encrypt_only, getResources().getString( R.string.choice_encrypt_only)), new Choice(Id.choice.usage.sign_and_encrypt, getResources().getString( - R.string.choice_sign_and_encrypt)),}; + R.string.choice_sign_and_encrypt)), }; ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, choices); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); @@ -129,13 +130,15 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { }); // setCalendarViewShown() is supported from API 11 onwards. - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { // Hide calendarView in tablets because of the unix warparound bug. dialog.getDatePicker().setCalendarViewShown(false); - + } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { if (dialog != null && mCreatedDate != null) { - dialog.getDatePicker().setMinDate(mCreatedDate.getTime().getTime() + DateUtils.DAY_IN_MILLIS); + dialog.getDatePicker() + .setMinDate( + mCreatedDate.getTime().getTime() + DateUtils.DAY_IN_MILLIS); } else { //When created date isn't available dialog.getDatePicker().setMinDate(date.getTime().getTime() + DateUtils.DAY_IN_MILLIS); @@ -277,7 +280,8 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener { class ExpiryDatePickerDialog extends DatePickerDialog { - public ExpiryDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { + public ExpiryDatePickerDialog(Context context, OnDateSetListener callBack, + int year, int monthOfYear, int dayOfMonth) { super(context, callBack, year, monthOfYear, dayOfMonth); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java index d6e44ee4e..e5b6003b1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java @@ -55,7 +55,7 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor private Choice mNewKeyAlgorithmChoice; private int mNewKeySize; - private boolean canEdit = true; + private boolean mCanEdit = true; private ActionBarActivity mActivity; @@ -95,8 +95,8 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor } public void setCanEdit(boolean bCanEdit) { - canEdit = bCanEdit; - if (!canEdit) { + mCanEdit = bCanEdit; + if (!mCanEdit) { mPlusButton.setVisibility(View.INVISIBLE); } } @@ -137,7 +137,7 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor * {@inheritDoc} */ public void onClick(View v) { - if (canEdit) { + if (mCanEdit) { switch (mType) { case Id.type.user_id: { UserIdEditor view = (UserIdEditor) mInflater.inflate( @@ -151,15 +151,18 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor } case Id.type.key: { - CreateKeyDialogFragment mCreateKeyDialogFragment = CreateKeyDialogFragment.newInstance(mEditors.getChildCount()); - mCreateKeyDialogFragment.setOnAlgorithmSelectedListener(new CreateKeyDialogFragment.OnAlgorithmSelectedListener() { - @Override - public void onAlgorithmSelected(Choice algorithmChoice, int keySize) { - mNewKeyAlgorithmChoice = algorithmChoice; - mNewKeySize = keySize; - createKey(); - } - }); + CreateKeyDialogFragment mCreateKeyDialogFragment = + CreateKeyDialogFragment.newInstance(mEditors.getChildCount()); + mCreateKeyDialogFragment + .setOnAlgorithmSelectedListener( + new CreateKeyDialogFragment.OnAlgorithmSelectedListener() { + @Override + public void onAlgorithmSelected(Choice algorithmChoice, int keySize) { + mNewKeyAlgorithmChoice = algorithmChoice; + mNewKeySize = keySize; + createKey(); + } + }); mCreateKeyDialogFragment.show(mActivity.getSupportFragmentManager(), "createKeyDialog"); break; } @@ -186,7 +189,7 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor if (mEditors.getChildCount() == 0) { view.setIsMainUserId(true); } - view.setCanEdit(canEdit); + view.setCanEdit(mCanEdit); mEditors.addView(view); } @@ -207,7 +210,7 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor view.setEditorListener(this); boolean isMasterKey = (mEditors.getChildCount() == 0); view.setValue(list.get(i), isMasterKey, usages.get(i)); - view.setCanEdit(canEdit); + view.setCanEdit(mCanEdit); mEditors.addView(view); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java index 039e87446..d3c6f02fe 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java @@ -18,6 +18,7 @@ package org.sufficientlysecure.keychain.ui.widget; import android.content.Context; import android.util.AttributeSet; +import android.util.Patterns; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; @@ -38,14 +39,6 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene private AutoCompleteTextView mEmail; private EditText mComment; - // see http://www.regular-expressions.info/email.html - // RFC 2822 if we omit the syntax using double quotes and square brackets - // android.util.Patterns.EMAIL_ADDRESS is only available as of Android 2.2+ - private static final Pattern EMAIL_PATTERN = Pattern - .compile( - "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", - Pattern.CASE_INSENSITIVE); - public static class NoNameException extends Exception { static final long serialVersionUID = 0xf812773343L; @@ -142,7 +135,7 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene String comment = ("" + mComment.getText()).trim(); if (email.length() > 0) { - Matcher emailMatcher = EMAIL_PATTERN.matcher(email); + Matcher emailMatcher = Patterns.EMAIL_ADDRESS.matcher(email); if (!emailMatcher.matches()) { throw new InvalidEmailException(getContext().getString(R.string.error_invalid_email, email)); -- cgit v1.2.3 From 2ff6949c9510de64593c733172fdf345968e53f5 Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 21:30:47 +0200 Subject: more code style changes in /ui and /util --- .../keychain/ui/EncryptActivity.java | 2 +- .../keychain/ui/ImportKeysActivity.java | 8 +- .../keychain/ui/ImportKeysServerFragment.java | 4 +- .../keychain/ui/SelectSecretKeyFragment.java | 2 +- .../keychain/ui/ViewKeyCertsFragment.java | 2 +- .../ui/adapter/AsyncTaskResultWrapper.java | 12 +- .../keychain/ui/adapter/ImportKeysAdapter.java | 63 +++--- .../keychain/ui/adapter/ImportKeysListEntry.java | 36 +-- .../keychain/ui/adapter/ImportKeysListLoader.java | 31 +-- .../ui/adapter/ImportKeysListServerLoader.java | 23 +- .../ui/adapter/KeyValueSpinnerAdapter.java | 2 +- .../ui/adapter/SelectKeyCursorAdapter.java | 4 +- .../keychain/ui/adapter/TabsAdapter.java | 31 ++- .../keychain/util/AlgorithmNames.java | 7 +- .../sufficientlysecure/keychain/util/Choice.java | 2 +- .../keychain/util/HkpKeyServer.java | 36 +-- .../keychain/util/IntentIntegratorSupportV4.java | 12 +- .../keychain/util/KeyServer.java | 12 +- .../keychain/util/KeychainServiceListener.java | 13 ++ .../org/sufficientlysecure/keychain/util/Log.java | 1 - .../keychain/util/PRNGFixes.java | 51 ++--- .../keychain/util/PausableThreadPoolExecutor.java | 50 ++-- .../sufficientlysecure/keychain/util/Primes.java | 252 ++++++++++----------- .../keychain/util/QrCodeUtils.java | 12 +- 24 files changed, 345 insertions(+), 323 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index d2d662e40..1231b6209 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -848,7 +848,7 @@ public class EncryptActivity extends DrawerActivity { new Choice(Id.choice.compression.zlib, "ZLIB (" + getString(R.string.compression_fast) + ")"), new Choice(Id.choice.compression.bzip2, "BZIP2 (" - + getString(R.string.compression_very_slow) + ")"),}; + + getString(R.string.compression_very_slow) + ")"), }; ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, choices); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index aa0c127cf..05bfc613e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -167,7 +167,8 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa query = "0x" + fingerprint; } } else { - Log.e(Constants.TAG, "IMPORT_KEY_FROM_KEYSERVER action needs to contain the 'query', 'key_id', or 'fingerprint' extra!"); + Log.e(Constants.TAG, + "IMPORT_KEY_FROM_KEYSERVER action needs to contain the 'query', 'key_id', or 'fingerprint' extra!"); return; } @@ -336,7 +337,7 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa // } else { // status.putString( // EXTRA_ERROR, - // "Scanned fingerprint does NOT match the fingerprint of the received key. You shouldnt trust this key."); + // "Scanned fingerprint does NOT match the fingerprint of the received key. You shouldnt trust this key."); // } // } // } catch (QueryException e) { @@ -398,7 +399,8 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa AppMsg.makeText(ImportKeysActivity.this, toastMessage, AppMsg.STYLE_INFO) .show(); if (bad > 0) { - BadImportKeyDialogFragment badImportKeyDialogFragment = BadImportKeyDialogFragment.newInstance(bad); + BadImportKeyDialogFragment badImportKeyDialogFragment = + BadImportKeyDialogFragment.newInstance(bad); badImportKeyDialogFragment.show(getSupportFragmentManager(), "badKeyDialog"); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java index f2449fae1..0b2fff64e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysServerFragment.java @@ -94,7 +94,8 @@ public class ImportKeysServerFragment extends Fragment { search(query, keyServer); // close keyboard after pressing search - InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); + InputMethodManager imm = + (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mQueryEditText.getWindowToken(), 0); } }); @@ -108,7 +109,6 @@ public class ImportKeysServerFragment extends Fragment { search(query, keyServer); // Don't return true to let the keyboard close itself after pressing search - // http://stackoverflow.com/questions/2342620/how-to-hide-keyboard-after-typing-in-edittext-in-android return false; } return false; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java index 9b3541c81..47a3fbad3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java @@ -141,7 +141,7 @@ public class SelectSecretKeyFragment extends ListFragment implements + Keys.IS_REVOKED + " = '0' AND valid_keys." + Keys.CAN_SIGN + " = '1' AND valid_keys." + Keys.CREATION + " <= '" + now + "' AND " + "(valid_keys." + Keys.EXPIRY + " IS NULL OR valid_keys." + Keys.EXPIRY - + " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID,}; + + " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID, }; String orderBy = UserIds.USER_ID + " ASC"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java index a08492aa5..02c04c11d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyCertsFragment.java @@ -87,4 +87,4 @@ public class ViewKeyCertsFragment extends Fragment { startActivity(signIntent); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java index 0285deb2e..5f2aec4fe 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/AsyncTaskResultWrapper.java @@ -27,20 +27,20 @@ package org.sufficientlysecure.keychain.ui.adapter; */ public class AsyncTaskResultWrapper { - private final T result; - private final Exception error; + private final T mResult; + private final Exception mError; public AsyncTaskResultWrapper(T result, Exception error) { - this.result = result; - this.error = error; + this.mResult = result; + this.mError = error; } public T getResult() { - return result; + return mResult; } public Exception getError() { - return error; + return mError; } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index c0b6027cc..16776e121 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -40,15 +40,15 @@ public class ImportKeysAdapter extends ArrayAdapter { protected LayoutInflater mInflater; protected Activity mActivity; - protected List data; + protected List mData; static class ViewHolder { - private TextView mainUserId; - private TextView mainUserIdRest; - private TextView keyId; - private TextView fingerprint; - private TextView algorithm; - private TextView status; + private TextView mMainUserId; + private TextView mMainUserIdRest; + private TextView mKeyId; + private TextView mFingerprint; + private TextView mAlgorithm; + private TextView mStatus; } @@ -62,7 +62,7 @@ public class ImportKeysAdapter extends ArrayAdapter { public void setData(List data) { clear(); if (data != null) { - this.data = data; + this.mData = data; // add data to extended ArrayAdapter if (Build.VERSION.SDK_INT >= 11) { @@ -76,14 +76,15 @@ public class ImportKeysAdapter extends ArrayAdapter { } public List getData() { - return data; + return mData; } public ArrayList getSelectedData() { ArrayList selectedData = new ArrayList(); - for (ImportKeysListEntry entry : data) { - if (entry.isSelected()) + for (ImportKeysListEntry entry : mData) { + if (entry.isSelected()) { selectedData.add(entry); + } } return selectedData; } @@ -94,17 +95,17 @@ public class ImportKeysAdapter extends ArrayAdapter { } public View getView(int position, View convertView, ViewGroup parent) { - ImportKeysListEntry entry = data.get(position); + ImportKeysListEntry entry = mData.get(position); ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.import_keys_list_entry, null); - holder.mainUserId = (TextView) convertView.findViewById(R.id.mainUserId); - holder.mainUserIdRest = (TextView) convertView.findViewById(R.id.mainUserIdRest); - holder.keyId = (TextView) convertView.findViewById(R.id.keyId); - holder.fingerprint = (TextView) convertView.findViewById(R.id.fingerprint); - holder.algorithm = (TextView) convertView.findViewById(R.id.algorithm); - holder.status = (TextView) convertView.findViewById(R.id.status); + holder.mMainUserId = (TextView) convertView.findViewById(R.id.mainUserId); + holder.mMainUserIdRest = (TextView) convertView.findViewById(R.id.mainUserIdRest); + holder.mKeyId = (TextView) convertView.findViewById(R.id.keyId); + holder.mFingerprint = (TextView) convertView.findViewById(R.id.fingerprint); + holder.mAlgorithm = (TextView) convertView.findViewById(R.id.algorithm); + holder.mStatus = (TextView) convertView.findViewById(R.id.status); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); @@ -118,36 +119,36 @@ public class ImportKeysAdapter extends ArrayAdapter { // show red user id if it is a secret key if (entry.secretKey) { userIdSplit[0] = mActivity.getString(R.string.secret_key) + " " + userIdSplit[0]; - holder.mainUserId.setTextColor(Color.RED); + holder.mMainUserId.setTextColor(Color.RED); } - holder.mainUserId.setText(userIdSplit[0]); + holder.mMainUserId.setText(userIdSplit[0]); } else { - holder.mainUserId.setText(R.string.user_id_no_name); + holder.mMainUserId.setText(R.string.user_id_no_name); } // email if (userIdSplit[1] != null) { - holder.mainUserIdRest.setText(userIdSplit[1]); - holder.mainUserIdRest.setVisibility(View.VISIBLE); + holder.mMainUserIdRest.setText(userIdSplit[1]); + holder.mMainUserIdRest.setVisibility(View.VISIBLE); } else { - holder.mainUserIdRest.setVisibility(View.GONE); + holder.mMainUserIdRest.setVisibility(View.GONE); } - holder.keyId.setText(entry.hexKeyId); + holder.mKeyId.setText(entry.hexKeyId); if (entry.fingerPrint != null) { - holder.fingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrint); - holder.fingerprint.setVisibility(View.VISIBLE); + holder.mFingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrint); + holder.mFingerprint.setVisibility(View.VISIBLE); } else { - holder.fingerprint.setVisibility(View.GONE); + holder.mFingerprint.setVisibility(View.GONE); } - holder.algorithm.setText("" + entry.bitStrength + "/" + entry.algorithm); + holder.mAlgorithm.setText("" + entry.bitStrength + "/" + entry.algorithm); if (entry.revoked) { - holder.status.setText(R.string.revoked); + holder.mStatus.setText(R.string.revoked); } else { - holder.status.setVisibility(View.GONE); + holder.mStatus.setVisibility(View.GONE); } LinearLayout ll = (LinearLayout) convertView.findViewById(R.id.list); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index fbfaa29fb..19f0d1eaf 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -45,9 +45,9 @@ public class ImportKeysListEntry implements Serializable, Parcelable { public String algorithm; public boolean secretKey; - private boolean selected; + private boolean mSelected; - private byte[] bytes = new byte[]{}; + private byte[] mBytes = new byte[]{}; public ImportKeysListEntry(ImportKeysListEntry b) { this.userIds = b.userIds; @@ -59,8 +59,8 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.bitStrength = b.bitStrength; this.algorithm = b.algorithm; this.secretKey = b.secretKey; - this.selected = b.selected; - this.bytes = b.bytes; + this.mSelected = b.mSelected; + this.mBytes = b.mBytes; } public int describeContents() { @@ -78,9 +78,9 @@ public class ImportKeysListEntry implements Serializable, Parcelable { dest.writeInt(bitStrength); dest.writeString(algorithm); dest.writeByte((byte) (secretKey ? 1 : 0)); - dest.writeByte((byte) (selected ? 1 : 0)); - dest.writeInt(bytes.length); - dest.writeByteArray(bytes); + dest.writeByte((byte) (mSelected ? 1 : 0)); + dest.writeInt(mBytes.length); + dest.writeByteArray(mBytes); } public static final Creator CREATOR = new Creator() { @@ -96,9 +96,9 @@ public class ImportKeysListEntry implements Serializable, Parcelable { vr.bitStrength = source.readInt(); vr.algorithm = source.readString(); vr.secretKey = source.readByte() == 1; - vr.selected = source.readByte() == 1; - vr.bytes = new byte[source.readInt()]; - source.readByteArray(vr.bytes); + vr.mSelected = source.readByte() == 1; + vr.mBytes = new byte[source.readInt()]; + source.readByteArray(vr.mBytes); return vr; } @@ -113,11 +113,11 @@ public class ImportKeysListEntry implements Serializable, Parcelable { } public byte[] getBytes() { - return bytes; + return mBytes; } public void setBytes(byte[] bytes) { - this.bytes = bytes; + this.mBytes = bytes; } /** @@ -127,16 +127,16 @@ public class ImportKeysListEntry implements Serializable, Parcelable { // keys from keyserver are always public keys secretKey = false; // do not select by default - selected = false; + mSelected = false; userIds = new ArrayList(); } public boolean isSelected() { - return selected; + return mSelected; } public void setSelected(boolean selected) { - this.selected = selected; + this.mSelected = selected; } /** @@ -146,13 +146,13 @@ public class ImportKeysListEntry implements Serializable, Parcelable { public ImportKeysListEntry(PGPKeyRing pgpKeyRing) { // save actual key object into entry, used to import it later try { - this.bytes = pgpKeyRing.getEncoded(); + this.mBytes = pgpKeyRing.getEncoded(); } catch (IOException e) { Log.e(Constants.TAG, "IOException on pgpKeyRing.getEncoded()", e); } // selected is default - this.selected = true; + this.mSelected = true; if (pgpKeyRing instanceof PGPSecretKeyRing) { secretKey = true; @@ -187,4 +187,4 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.algorithm = "unknown"; } } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java index d7544d1bb..c9983213c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListLoader.java @@ -31,21 +31,22 @@ import java.io.BufferedInputStream; import java.io.InputStream; import java.util.ArrayList; -public class ImportKeysListLoader extends AsyncTaskLoader>> { +public class ImportKeysListLoader + extends AsyncTaskLoader>> { public static class FileHasNoContent extends Exception { } public static class NonPgpPart extends Exception { - private int count; + private int mCount; public NonPgpPart(int count) { - this.count = count; + this.mCount = count; } public int getCount() { - return count; + return mCount; } } @@ -53,8 +54,8 @@ public class ImportKeysListLoader extends AsyncTaskLoader data = new ArrayList(); - AsyncTaskResultWrapper> entryListWrapper; + ArrayList mData = new ArrayList(); + AsyncTaskResultWrapper> mEntryListWrapper; public ImportKeysListLoader(Context context, InputData inputData) { super(context); @@ -65,16 +66,16 @@ public class ImportKeysListLoader extends AsyncTaskLoader> loadInBackground() { - entryListWrapper = new AsyncTaskResultWrapper>(data, null); + mEntryListWrapper = new AsyncTaskResultWrapper>(mData, null); if (mInputData == null) { Log.e(Constants.TAG, "Input data is null!"); - return entryListWrapper; + return mEntryListWrapper; } generateListOfKeyrings(mInputData); - return entryListWrapper; + return mEntryListWrapper; } @Override @@ -142,25 +143,25 @@ public class ImportKeysListLoader extends AsyncTaskLoader>(data, e); + mEntryListWrapper = new AsyncTaskResultWrapper>(mData, e); nonPgpCounter = 0; } if (isEmpty) { Log.e(Constants.TAG, "File has no content!", new FileHasNoContent()); - entryListWrapper = new AsyncTaskResultWrapper> - (data, new FileHasNoContent()); + mEntryListWrapper = new AsyncTaskResultWrapper> + (mData, new FileHasNoContent()); } if (nonPgpCounter > 0) { - entryListWrapper = new AsyncTaskResultWrapper> - (data, new NonPgpPart(nonPgpCounter)); + mEntryListWrapper = new AsyncTaskResultWrapper> + (mData, new NonPgpPart(nonPgpCounter)); } } private void addToData(PGPKeyRing keyring) { ImportKeysListEntry item = new ImportKeysListEntry(keyring); - data.add(item); + mData.add(item); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java index 0e1b83c81..1e96606a6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java @@ -26,14 +26,15 @@ import org.sufficientlysecure.keychain.util.Log; import java.util.ArrayList; -public class ImportKeysListServerLoader extends AsyncTaskLoader>> { +public class ImportKeysListServerLoader + extends AsyncTaskLoader>> { Context mContext; String mServerQuery; String mKeyServer; - private ArrayList entryList = new ArrayList(); - private AsyncTaskResultWrapper> entryListWrapper; + private ArrayList mEntryList = new ArrayList(); + private AsyncTaskResultWrapper> mEntryListWrapper; public ImportKeysListServerLoader(Context context, String serverQuery, String keyServer) { super(context); @@ -45,16 +46,16 @@ public class ImportKeysListServerLoader extends AsyncTaskLoader> loadInBackground() { - entryListWrapper = new AsyncTaskResultWrapper>(entryList, null); + mEntryListWrapper = new AsyncTaskResultWrapper>(mEntryList, null); if (mServerQuery == null) { Log.e(Constants.TAG, "mServerQuery is null!"); - return entryListWrapper; + return mEntryListWrapper; } queryServer(mServerQuery, mKeyServer); - return entryListWrapper; + return mEntryListWrapper; } @Override @@ -89,17 +90,17 @@ public class ImportKeysListServerLoader extends AsyncTaskLoader searchResult = server.search(query); // add result to data - entryList.addAll(searchResult); - entryListWrapper = new AsyncTaskResultWrapper>(entryList, null); + mEntryList.addAll(searchResult); + mEntryListWrapper = new AsyncTaskResultWrapper>(mEntryList, null); } catch (KeyServer.InsufficientQuery e) { Log.e(Constants.TAG, "InsufficientQuery", e); - entryListWrapper = new AsyncTaskResultWrapper>(entryList, e); + mEntryListWrapper = new AsyncTaskResultWrapper>(mEntryList, e); } catch (KeyServer.QueryException e) { Log.e(Constants.TAG, "QueryException", e); - entryListWrapper = new AsyncTaskResultWrapper>(entryList, e); + mEntryListWrapper = new AsyncTaskResultWrapper>(mEntryList, e); } catch (KeyServer.TooManyResponses e) { Log.e(Constants.TAG, "TooManyResponses", e); - entryListWrapper = new AsyncTaskResultWrapper>(entryList, e); + mEntryListWrapper = new AsyncTaskResultWrapper>(mEntryList, e); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java index 0a1dca751..c997599bd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/KeyValueSpinnerAdapter.java @@ -94,4 +94,4 @@ public class KeyValueSpinnerAdapter extends ArrayAdapter { } return -1; } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java index eaaa54376..beb76fc10 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java @@ -44,8 +44,8 @@ public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { private int mIndexProjectionValid; private int mIndexProjectionAvailable; - public final static String PROJECTION_ROW_AVAILABLE = "available"; - public final static String PROJECTION_ROW_VALID = "valid"; + public static final String PROJECTION_ROW_AVAILABLE = "available"; + public static final String PROJECTION_ROW_VALID = "valid"; public SelectKeyCursorAdapter(Context context, Cursor c, int flags, ListView listView, int keyType) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/TabsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/TabsAdapter.java index 924a70897..f435d46ef 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/TabsAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/TabsAdapter.java @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2012-2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + package org.sufficientlysecure.keychain.ui.adapter; import android.content.Context; @@ -19,12 +36,12 @@ public class TabsAdapter extends FragmentStatePagerAdapter implements ActionBar. private final ArrayList mTabs = new ArrayList(); static final class TabInfo { - private final Class clss; - private final Bundle args; + private final Class mClss; + private final Bundle mArgs; - TabInfo(Class _class, Bundle _args) { - clss = _class; - args = _args; + TabInfo(Class mClss, Bundle mArgs) { + this.mClss = mClss; + this.mArgs = mArgs; } } @@ -54,7 +71,7 @@ public class TabsAdapter extends FragmentStatePagerAdapter implements ActionBar. @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); - return Fragment.instantiate(mContext, info.clss.getName(), info.args); + return Fragment.instantiate(mContext, info.mClss.getName(), info.mArgs); } public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { @@ -81,4 +98,4 @@ public class TabsAdapter extends FragmentStatePagerAdapter implements ActionBar. public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/AlgorithmNames.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/AlgorithmNames.java index d3c37edc6..d2f4cc003 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/AlgorithmNames.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/AlgorithmNames.java @@ -17,13 +17,14 @@ package org.sufficientlysecure.keychain.util; -import java.util.HashMap; +import android.annotation.SuppressLint; +import android.app.Activity; import org.spongycastle.bcpg.HashAlgorithmTags; import org.spongycastle.openpgp.PGPEncryptedData; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; -import android.annotation.SuppressLint; -import android.app.Activity; + +import java.util.HashMap; @SuppressLint("UseSparseArrays") public class AlgorithmNames { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Choice.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Choice.java index 9e0042c00..1a6184d9c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Choice.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Choice.java @@ -39,7 +39,7 @@ public class Choice { } @Override - public String toString() { + public String toString() { return mName; } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 99cac1152..c94917b60 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -85,25 +85,25 @@ public class HkpKeyServer extends KeyServer { public static Pattern USER_ID_LINE = Pattern.compile("^ +(.+)$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); - private static final short PORT_DEFAULT = 11371; + private static final short PORT_DEFAULT = 11371; - /** - * @param hostAndPort may be just "hostname" (eg. "pool.sks-keyservers.net"), then it will - * connect using {@link #PORT_DEFAULT}. However, port may be specified after colon - * ("hostname:port", eg. "p80.pool.sks-keyservers.net:80"). - */ - public HkpKeyServer(String hostAndPort) { - String host = hostAndPort; - short port = PORT_DEFAULT; - final int colonPosition = hostAndPort.lastIndexOf(':'); - if (colonPosition > 0) { - host = hostAndPort.substring(0, colonPosition); - final String portStr = hostAndPort.substring(colonPosition + 1); - port = Short.decode(portStr); - } - mHost = host; - mPort = port; - } + /** + * @param hostAndPort may be just "hostname" (eg. "pool.sks-keyservers.net"), then it will + * connect using {@link #PORT_DEFAULT}. However, port may be specified after colon + * ("hostname:port", eg. "p80.pool.sks-keyservers.net:80"). + */ + public HkpKeyServer(String hostAndPort) { + String host = hostAndPort; + short port = PORT_DEFAULT; + final int colonPosition = hostAndPort.lastIndexOf(':'); + if (colonPosition > 0) { + host = hostAndPort.substring(0, colonPosition); + final String portStr = hostAndPort.substring(colonPosition + 1); + port = Short.decode(portStr); + } + mHost = host; + mPort = port; + } public HkpKeyServer(String host, short port) { mHost = host; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IntentIntegratorSupportV4.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IntentIntegratorSupportV4.java index a43c03e3e..b95b3ee6a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IntentIntegratorSupportV4.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IntentIntegratorSupportV4.java @@ -18,30 +18,28 @@ package org.sufficientlysecure.keychain.util; import android.content.Intent; import android.support.v4.app.Fragment; - import com.google.zxing.integration.android.IntentIntegrator; /** * IntentIntegrator for the V4 Android compatibility package. - * + * * @author Lachezar Dobrev */ public final class IntentIntegratorSupportV4 extends IntentIntegrator { - private final Fragment fragment; + private final Fragment mFragment; /** - * @param fragment - * Fragment to handle activity response. + * @param fragment Fragment to handle activity response. */ public IntentIntegratorSupportV4(Fragment fragment) { super(fragment.getActivity()); - this.fragment = fragment; + this.mFragment = fragment; } @Override protected void startActivityForResult(Intent intent, int code) { - fragment.startActivityForResult(intent, code); + mFragment.startActivityForResult(intent, code); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java index 7049820e8..a31fdc5ae 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java @@ -18,12 +18,12 @@ package org.sufficientlysecure.keychain.util; -import java.util.List; - import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; +import java.util.List; + public abstract class KeyServer { - static public class QueryException extends Exception { + public static class QueryException extends Exception { private static final long serialVersionUID = 2703768928624654512L; public QueryException(String message) { @@ -31,15 +31,15 @@ public abstract class KeyServer { } } - static public class TooManyResponses extends Exception { + public static class TooManyResponses extends Exception { private static final long serialVersionUID = 2703768928624654513L; } - static public class InsufficientQuery extends Exception { + public static class InsufficientQuery extends Exception { private static final long serialVersionUID = 2703768928624654514L; } - static public class AddKeyException extends Exception { + public static class AddKeyException extends Exception { private static final long serialVersionUID = -507574859137295530L; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java index 0d7513057..14b2a2211 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeychainServiceListener.java @@ -1,3 +1,16 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.sufficientlysecure.keychain.util; public interface KeychainServiceListener { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Log.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Log.java index bcf275c32..f58f1757a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Log.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Log.java @@ -21,7 +21,6 @@ import org.sufficientlysecure.keychain.Constants; /** * Wraps Android Logging to enable or disable debug output using Constants - * */ public final class Log { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PRNGFixes.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PRNGFixes.java index 530a81044..2d8fbcd81 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PRNGFixes.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PRNGFixes.java @@ -14,48 +14,36 @@ import android.os.Build; import android.os.Process; import android.util.Log; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.SecureRandomSpi; -import java.security.Security; +import java.io.*; +import java.security.*; /** * Fixes for the output of the default PRNG having low entropy. - * + *

* The fixes need to be applied via {@link #apply()} before any use of Java Cryptography * Architecture primitives. A good place to invoke them is in the application's {@code onCreate}. - * + *

* copied from http://android-developers.blogspot.de/2013/08/some-securerandom-thoughts.html - * - * + *

+ *

* More information on these Android bugs: * http://blog.k3170makan.com/2013/08/more-details-on-android-jca-prng-flaw.html * Paper: "Randomly failed! Weaknesses in Java Pseudo Random Number Generators (PRNGs)" - * - * + *

+ *

* Sep 15, 2013: * On some devices /dev/urandom is non-writable! * No need to seed /dev/urandom. urandom should have enough seeds from the OS and kernel. * Only OpenSSL seeds are broken. See http://emboss.github.io/blog/2013/08/21/openssl-prng-is-not-really-fork-safe - * + *

* see also: * https://github.com/k9mail/k-9/commit/dda8f64276d4d29c43f86237cd77819c28f22f21 * In addition to a couple of custom ROMs linking /dev/urandom to a non-writable * random version, now Samsung's SELinux policy also prevents apps from opening * /dev/urandom for writing. Since we shouldn't need to write to /dev/urandom anyway * we now simply don't. - * - * + *

+ *

* Sep 17, 2013: * Updated from official blogpost: * Update: the original code sample below crashed on a small fraction of Android @@ -66,10 +54,13 @@ public final class PRNGFixes { private static final int VERSION_CODE_JELLY_BEAN = 16; private static final int VERSION_CODE_JELLY_BEAN_MR2 = 18; private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = - getBuildFingerprintAndDeviceSerial(); + getBuildFingerprintAndDeviceSerial(); - /** Hidden constructor to prevent instantiation. */ - private PRNGFixes() {} + /** + * Hidden constructor to prevent instantiation. + */ + private PRNGFixes() { + } /** * Applies all fixes. @@ -136,7 +127,7 @@ public final class PRNGFixes { if ((secureRandomProviders == null) || (secureRandomProviders.length < 1) || (!LinuxPRNGSecureRandomProvider.class.equals( - secureRandomProviders[0].getClass()))) { + secureRandomProviders[0].getClass()))) { Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1); } @@ -161,7 +152,7 @@ public final class PRNGFixes { rng2.getProvider().getClass())) { throw new SecurityException( "SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong" - + " Provider: " + rng2.getProvider().getClass()); + + " Provider: " + rng2.getProvider().getClass()); } } @@ -175,7 +166,7 @@ public final class PRNGFixes { super("LinuxPRNG", 1.0, "A Linux-specific random number provider that uses" - + " /dev/urandom"); + + " /dev/urandom"); // Although /dev/urandom is not a SHA-1 PRNG, some apps // explicitly request a SHA1PRNG SecureRandom and we thus need to // prevent them from getting the default implementation whose output @@ -358,4 +349,4 @@ public final class PRNGFixes { throw new RuntimeException("UTF-8 encoding not supported"); } } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PausableThreadPoolExecutor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PausableThreadPoolExecutor.java index aa21581c6..377a8d5d6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PausableThreadPoolExecutor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/PausableThreadPoolExecutor.java @@ -17,11 +17,7 @@ package org.sufficientlysecure.keychain.util; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; @@ -32,59 +28,63 @@ import java.util.concurrent.locks.ReentrantLock; public class PausableThreadPoolExecutor extends ThreadPoolExecutor { public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, - TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler) { + TimeUnit unit, BlockingQueue workQueue, + RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); } public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, - TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, - RejectedExecutionHandler handler) { + TimeUnit unit, BlockingQueue workQueue, + ThreadFactory threadFactory, + RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); } public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, - TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { + TimeUnit unit, BlockingQueue workQueue, + ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); } public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, - TimeUnit unit, BlockingQueue workQueue) { + TimeUnit unit, BlockingQueue workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } - private boolean isPaused; - private ReentrantLock pauseLock = new ReentrantLock(); - private Condition unpaused = pauseLock.newCondition(); + private boolean mIsPaused; + private ReentrantLock mPauseLock = new ReentrantLock(); + private Condition mUnPaused = mPauseLock.newCondition(); protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); - pauseLock.lock(); + mPauseLock.lock(); try { - while (isPaused) - unpaused.await(); + while (mIsPaused) { + mUnPaused.await(); + } } catch (InterruptedException ie) { t.interrupt(); } finally { - pauseLock.unlock(); + mPauseLock.unlock(); } } public void pause() { - pauseLock.lock(); + mPauseLock.lock(); try { - isPaused = true; + mIsPaused = true; } finally { - pauseLock.unlock(); + mPauseLock.unlock(); } } public void resume() { - pauseLock.lock(); + mPauseLock.lock(); try { - isPaused = false; - unpaused.signalAll(); + mIsPaused = false; + mUnPaused.signalAll(); } finally { - pauseLock.unlock(); + mPauseLock.unlock(); } } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Primes.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Primes.java index f503227a3..28a12bf37 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Primes.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/Primes.java @@ -25,147 +25,147 @@ public final class Primes { // taken from http://www.ietf.org/rfc/rfc3526.txt public static final String P1536 = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" + - "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + - "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + - "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + - "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + - "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + - "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + - "670C354E 4ABC9804 F1746C08 CA237327 FFFFFFFF FFFFFFFF"; + "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + + "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + + "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + + "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + + "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + + "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + + "670C354E 4ABC9804 F1746C08 CA237327 FFFFFFFF FFFFFFFF"; public static final String P2048 = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" + - "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + - "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + - "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + - "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + - "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + - "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + - "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + - "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + - "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + - "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"; + "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + + "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + + "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + + "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + + "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + + "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + + "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + + "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + + "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + + "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"; public static final String P3072 = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" + - "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + - "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + - "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + - "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + - "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + - "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + - "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + - "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + - "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + - "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + - "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + - "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + - "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + - "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + - "43DB5BFC E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF"; + "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + + "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + + "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + + "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + + "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + + "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + + "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + + "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + + "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + + "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + + "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + + "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + + "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + + "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + + "43DB5BFC E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF"; public static final String P4096 = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" + - "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + - "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + - "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + - "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + - "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + - "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + - "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + - "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + - "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + - "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + - "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + - "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + - "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + - "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + - "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" + - "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" + - "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" + - "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" + - "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" + - "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34063199" + - "FFFFFFFF FFFFFFFF"; + "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + + "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + + "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + + "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + + "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + + "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + + "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + + "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + + "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + + "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + + "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + + "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + + "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + + "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + + "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" + + "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" + + "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" + + "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" + + "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" + + "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34063199" + + "FFFFFFFF FFFFFFFF"; public static final String P6144 = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" + - "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + - "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + - "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + - "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + - "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + - "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + - "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + - "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + - "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + - "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + - "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + - "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + - "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + - "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + - "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" + - "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" + - "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" + - "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" + - "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" + - "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34028492" + - "36C3FAB4 D27C7026 C1D4DCB2 602646DE C9751E76 3DBA37BD" + - "F8FF9406 AD9E530E E5DB382F 413001AE B06A53ED 9027D831" + - "179727B0 865A8918 DA3EDBEB CF9B14ED 44CE6CBA CED4BB1B" + - "DB7F1447 E6CC254B 33205151 2BD7AF42 6FB8F401 378CD2BF" + - "5983CA01 C64B92EC F032EA15 D1721D03 F482D7CE 6E74FEF6" + - "D55E702F 46980C82 B5A84031 900B1C9E 59E7C97F BEC7E8F3" + - "23A97A7E 36CC88BE 0F1D45B7 FF585AC5 4BD407B2 2B4154AA" + - "CC8F6D7E BF48E1D8 14CC5ED2 0F8037E0 A79715EE F29BE328" + - "06A1D58B B7C5DA76 F550AA3D 8A1FBFF0 EB19CCB1 A313D55C" + - "DA56C9EC 2EF29632 387FE8D7 6E3C0468 043E8F66 3F4860EE" + - "12BF2D5B 0B7474D6 E694F91E 6DCC4024 FFFFFFFF FFFFFFFF"; + "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + + "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + + "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + + "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + + "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + + "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + + "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + + "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + + "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + + "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + + "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + + "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + + "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + + "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + + "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" + + "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" + + "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" + + "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" + + "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" + + "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34028492" + + "36C3FAB4 D27C7026 C1D4DCB2 602646DE C9751E76 3DBA37BD" + + "F8FF9406 AD9E530E E5DB382F 413001AE B06A53ED 9027D831" + + "179727B0 865A8918 DA3EDBEB CF9B14ED 44CE6CBA CED4BB1B" + + "DB7F1447 E6CC254B 33205151 2BD7AF42 6FB8F401 378CD2BF" + + "5983CA01 C64B92EC F032EA15 D1721D03 F482D7CE 6E74FEF6" + + "D55E702F 46980C82 B5A84031 900B1C9E 59E7C97F BEC7E8F3" + + "23A97A7E 36CC88BE 0F1D45B7 FF585AC5 4BD407B2 2B4154AA" + + "CC8F6D7E BF48E1D8 14CC5ED2 0F8037E0 A79715EE F29BE328" + + "06A1D58B B7C5DA76 F550AA3D 8A1FBFF0 EB19CCB1 A313D55C" + + "DA56C9EC 2EF29632 387FE8D7 6E3C0468 043E8F66 3F4860EE" + + "12BF2D5B 0B7474D6 E694F91E 6DCC4024 FFFFFFFF FFFFFFFF"; public static final String P8192 = "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" + - "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + - "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + - "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + - "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + - "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + - "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + - "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + - "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + - "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + - "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + - "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + - "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + - "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + - "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + - "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" + - "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" + - "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" + - "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" + - "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" + - "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34028492" + - "36C3FAB4 D27C7026 C1D4DCB2 602646DE C9751E76 3DBA37BD" + - "F8FF9406 AD9E530E E5DB382F 413001AE B06A53ED 9027D831" + - "179727B0 865A8918 DA3EDBEB CF9B14ED 44CE6CBA CED4BB1B" + - "DB7F1447 E6CC254B 33205151 2BD7AF42 6FB8F401 378CD2BF" + - "5983CA01 C64B92EC F032EA15 D1721D03 F482D7CE 6E74FEF6" + - "D55E702F 46980C82 B5A84031 900B1C9E 59E7C97F BEC7E8F3" + - "23A97A7E 36CC88BE 0F1D45B7 FF585AC5 4BD407B2 2B4154AA" + - "CC8F6D7E BF48E1D8 14CC5ED2 0F8037E0 A79715EE F29BE328" + - "06A1D58B B7C5DA76 F550AA3D 8A1FBFF0 EB19CCB1 A313D55C" + - "DA56C9EC 2EF29632 387FE8D7 6E3C0468 043E8F66 3F4860EE" + - "12BF2D5B 0B7474D6 E694F91E 6DBE1159 74A3926F 12FEE5E4" + - "38777CB6 A932DF8C D8BEC4D0 73B931BA 3BC832B6 8D9DD300" + - "741FA7BF 8AFC47ED 2576F693 6BA42466 3AAB639C 5AE4F568" + - "3423B474 2BF1C978 238F16CB E39D652D E3FDB8BE FC848AD9" + - "22222E04 A4037C07 13EB57A8 1A23F0C7 3473FC64 6CEA306B" + - "4BCBC886 2F8385DD FA9D4B7F A2C087E8 79683303 ED5BDD3A" + - "062B3CF5 B3A278A6 6D2A13F8 3F44F82D DF310EE0 74AB6A36" + - "4597E899 A0255DC1 64F31CC5 0846851D F9AB4819 5DED7EA1" + - "B1D510BD 7EE74D73 FAF36BC3 1ECFA268 359046F4 EB879F92" + - "4009438B 481C6CD7 889A002E D5EE382B C9190DA6 FC026E47" + - "9558E447 5677E9AA 9E3050E2 765694DF C81F56E8 80B96E71" + - "60C980DD 98EDD3DF FFFFFFFF FFFFFFFF"; + "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" + + "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" + + "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" + + "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" + + "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" + + "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" + + "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" + + "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" + + "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" + + "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64" + + "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7" + + "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B" + + "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C" + + "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31" + + "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7" + + "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA" + + "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6" + + "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED" + + "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9" + + "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34028492" + + "36C3FAB4 D27C7026 C1D4DCB2 602646DE C9751E76 3DBA37BD" + + "F8FF9406 AD9E530E E5DB382F 413001AE B06A53ED 9027D831" + + "179727B0 865A8918 DA3EDBEB CF9B14ED 44CE6CBA CED4BB1B" + + "DB7F1447 E6CC254B 33205151 2BD7AF42 6FB8F401 378CD2BF" + + "5983CA01 C64B92EC F032EA15 D1721D03 F482D7CE 6E74FEF6" + + "D55E702F 46980C82 B5A84031 900B1C9E 59E7C97F BEC7E8F3" + + "23A97A7E 36CC88BE 0F1D45B7 FF585AC5 4BD407B2 2B4154AA" + + "CC8F6D7E BF48E1D8 14CC5ED2 0F8037E0 A79715EE F29BE328" + + "06A1D58B B7C5DA76 F550AA3D 8A1FBFF0 EB19CCB1 A313D55C" + + "DA56C9EC 2EF29632 387FE8D7 6E3C0468 043E8F66 3F4860EE" + + "12BF2D5B 0B7474D6 E694F91E 6DBE1159 74A3926F 12FEE5E4" + + "38777CB6 A932DF8C D8BEC4D0 73B931BA 3BC832B6 8D9DD300" + + "741FA7BF 8AFC47ED 2576F693 6BA42466 3AAB639C 5AE4F568" + + "3423B474 2BF1C978 238F16CB E39D652D E3FDB8BE FC848AD9" + + "22222E04 A4037C07 13EB57A8 1A23F0C7 3473FC64 6CEA306B" + + "4BCBC886 2F8385DD FA9D4B7F A2C087E8 79683303 ED5BDD3A" + + "062B3CF5 B3A278A6 6D2A13F8 3F44F82D DF310EE0 74AB6A36" + + "4597E899 A0255DC1 64F31CC5 0846851D F9AB4819 5DED7EA1" + + "B1D510BD 7EE74D73 FAF36BC3 1ECFA268 359046F4 EB879F92" + + "4009438B 481C6CD7 889A002E D5EE382B C9190DA6 FC026E47" + + "9558E447 5677E9AA 9E3050E2 765694DF C81F56E8 80B96E71" + + "60C980DD 98EDD3DF FFFFFFFF FFFFFFFF"; public static BigInteger getBestPrime(int keySize) { String primeString; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/QrCodeUtils.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/QrCodeUtils.java index 9e8118e7a..8c3367bea 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/QrCodeUtils.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/QrCodeUtils.java @@ -18,26 +18,24 @@ package org.sufficientlysecure.keychain.util; -import java.util.Hashtable; - -import org.sufficientlysecure.keychain.Constants; - import android.graphics.Bitmap; import android.graphics.Color; - import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; +import org.sufficientlysecure.keychain.Constants; + +import java.util.Hashtable; public class QrCodeUtils { - public final static QRCodeWriter QR_CODE_WRITER = new QRCodeWriter(); + public static final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter(); /** * Generate Bitmap with QR Code based on input. - * + * * @param input * @param size * @return QR Code as Bitmap -- cgit v1.2.3 From 6ac4d6c2181aa1591494aab93ccef23bf8a7e09a Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 21:39:14 +0200 Subject: final ui code style changes --- .../org/sufficientlysecure/keychain/Constants.java | 10 +++--- .../keychain/KeychainApplication.java | 2 +- .../keychain/helper/Preferences.java | 38 +++++++++++----------- .../provider/KeychainServiceBlobProvider.java | 2 +- .../keychain/ui/DecryptActivity.java | 2 +- .../keychain/ui/EditKeyActivity.java | 2 +- .../keychain/ui/ImportKeysFileFragment.java | 2 +- .../keychain/ui/KeyListActivity.java | 4 +-- .../keychain/ui/KeyListFragment.java | 2 +- .../keychain/ui/PreferencesActivity.java | 32 +++++++++--------- .../keychain/ui/ViewKeyActivity.java | 2 +- .../keychain/util/HkpKeyServer.java | 9 ++--- 12 files changed, 54 insertions(+), 53 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java index 34a3de8d5..011cd9663 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java @@ -16,10 +16,10 @@ package org.sufficientlysecure.keychain; -import org.spongycastle.jce.provider.BouncyCastleProvider; - import android.os.Environment; +import org.spongycastle.jce.provider.BouncyCastleProvider; + public final class Constants { public static final boolean DEBUG = BuildConfig.DEBUG; @@ -40,14 +40,14 @@ public final class Constants { public static final String INTENT_PREFIX = PACKAGE_NAME + ".action."; - public static final class path { + public static final class Path { public static final String APP_DIR = Environment.getExternalStorageDirectory() + "/OpenPGP-Keychain"; public static final String APP_DIR_FILE_SEC = APP_DIR + "/secexport.asc"; public static final String APP_DIR_FILE_PUB = APP_DIR + "/pubexport.asc"; } - public static final class pref { + public static final class Pref { public static final String DEFAULT_ENCRYPTION_ALGORITHM = "defaultEncryptionAlgorithm"; public static final String DEFAULT_HASH_ALGORITHM = "defaultHashAlgorithm"; public static final String DEFAULT_ASCII_ARMOUR = "defaultAsciiArmour"; @@ -59,7 +59,7 @@ public final class Constants { public static final String KEY_SERVERS = "keyServers"; } - public static final class defaults { + public static final class Defaults { public static final String KEY_SERVERS = "pool.sks-keyservers.net, subkeys.pgp.net, pgp.mit.edu"; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java index 4a25f2df1..98b827542 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java @@ -64,7 +64,7 @@ public class KeychainApplication extends Application { // Create APG directory on sdcard if not existing if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { - File dir = new File(Constants.path.APP_DIR); + File dir = new File(Constants.Path.APP_DIR); if (!dir.exists() && !dir.mkdirs()) { // ignore this for now, it's not crucial // that the directory doesn't exist at this point diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java index 82e181664..515201b92 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java @@ -49,17 +49,17 @@ public class Preferences { } public String getLanguage() { - return mSharedPreferences.getString(Constants.pref.LANGUAGE, ""); + return mSharedPreferences.getString(Constants.Pref.LANGUAGE, ""); } public void setLanguage(String value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putString(Constants.pref.LANGUAGE, value); + editor.putString(Constants.Pref.LANGUAGE, value); editor.commit(); } public long getPassPhraseCacheTtl() { - int ttl = mSharedPreferences.getInt(Constants.pref.PASS_PHRASE_CACHE_TTL, 180); + int ttl = mSharedPreferences.getInt(Constants.Pref.PASS_PHRASE_CACHE_TTL, 180); // fix the value if it was set to "never" in previous versions, which currently is not // supported if (ttl == 0) { @@ -70,77 +70,77 @@ public class Preferences { public void setPassPhraseCacheTtl(int value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putInt(Constants.pref.PASS_PHRASE_CACHE_TTL, value); + editor.putInt(Constants.Pref.PASS_PHRASE_CACHE_TTL, value); editor.commit(); } public int getDefaultEncryptionAlgorithm() { - return mSharedPreferences.getInt(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM, + return mSharedPreferences.getInt(Constants.Pref.DEFAULT_ENCRYPTION_ALGORITHM, PGPEncryptedData.AES_256); } public void setDefaultEncryptionAlgorithm(int value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putInt(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM, value); + editor.putInt(Constants.Pref.DEFAULT_ENCRYPTION_ALGORITHM, value); editor.commit(); } public int getDefaultHashAlgorithm() { - return mSharedPreferences.getInt(Constants.pref.DEFAULT_HASH_ALGORITHM, + return mSharedPreferences.getInt(Constants.Pref.DEFAULT_HASH_ALGORITHM, HashAlgorithmTags.SHA512); } public void setDefaultHashAlgorithm(int value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putInt(Constants.pref.DEFAULT_HASH_ALGORITHM, value); + editor.putInt(Constants.Pref.DEFAULT_HASH_ALGORITHM, value); editor.commit(); } public int getDefaultMessageCompression() { - return mSharedPreferences.getInt(Constants.pref.DEFAULT_MESSAGE_COMPRESSION, + return mSharedPreferences.getInt(Constants.Pref.DEFAULT_MESSAGE_COMPRESSION, Id.choice.compression.zlib); } public void setDefaultMessageCompression(int value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putInt(Constants.pref.DEFAULT_MESSAGE_COMPRESSION, value); + editor.putInt(Constants.Pref.DEFAULT_MESSAGE_COMPRESSION, value); editor.commit(); } public int getDefaultFileCompression() { - return mSharedPreferences.getInt(Constants.pref.DEFAULT_FILE_COMPRESSION, + return mSharedPreferences.getInt(Constants.Pref.DEFAULT_FILE_COMPRESSION, Id.choice.compression.none); } public void setDefaultFileCompression(int value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putInt(Constants.pref.DEFAULT_FILE_COMPRESSION, value); + editor.putInt(Constants.Pref.DEFAULT_FILE_COMPRESSION, value); editor.commit(); } public boolean getDefaultAsciiArmour() { - return mSharedPreferences.getBoolean(Constants.pref.DEFAULT_ASCII_ARMOUR, false); + return mSharedPreferences.getBoolean(Constants.Pref.DEFAULT_ASCII_ARMOUR, false); } public void setDefaultAsciiArmour(boolean value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putBoolean(Constants.pref.DEFAULT_ASCII_ARMOUR, value); + editor.putBoolean(Constants.Pref.DEFAULT_ASCII_ARMOUR, value); editor.commit(); } public boolean getForceV3Signatures() { - return mSharedPreferences.getBoolean(Constants.pref.FORCE_V3_SIGNATURES, false); + return mSharedPreferences.getBoolean(Constants.Pref.FORCE_V3_SIGNATURES, false); } public void setForceV3Signatures(boolean value) { SharedPreferences.Editor editor = mSharedPreferences.edit(); - editor.putBoolean(Constants.pref.FORCE_V3_SIGNATURES, value); + editor.putBoolean(Constants.Pref.FORCE_V3_SIGNATURES, value); editor.commit(); } public String[] getKeyServers() { - String rawData = mSharedPreferences.getString(Constants.pref.KEY_SERVERS, - Constants.defaults.KEY_SERVERS); + String rawData = mSharedPreferences.getString(Constants.Pref.KEY_SERVERS, + Constants.Defaults.KEY_SERVERS); Vector servers = new Vector(); String chunks[] = rawData.split(","); for (String c : chunks) { @@ -165,7 +165,7 @@ public class Preferences { } rawData += tmp; } - editor.putString(Constants.pref.KEY_SERVERS, rawData); + editor.putString(Constants.Pref.KEY_SERVERS, rawData); editor.commit(); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java index 5693e6de2..86eccbe37 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java @@ -40,7 +40,7 @@ import java.util.List; import java.util.UUID; public class KeychainServiceBlobProvider extends ContentProvider { - private static final String STORE_PATH = Constants.path.APP_DIR + "/ApgBlobs"; + private static final String STORE_PATH = Constants.Path.APP_DIR + "/ApgBlobs"; private KeychainServiceBlobDatabase mBlobDatabase = null; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index f805198f1..3e389c034 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -370,7 +370,7 @@ public class DecryptActivity extends DrawerActivity { if (filename.endsWith(".asc") || filename.endsWith(".gpg") || filename.endsWith(".pgp")) { filename = filename.substring(0, filename.length() - 4); } - mOutputFilename = Constants.path.APP_DIR + "/" + filename; + mOutputFilename = Constants.Path.APP_DIR + "/" + filename; } private void updateSource() { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index f99e88e60..a0186f08c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -323,7 +323,7 @@ public class EditKeyActivity extends ActionBarActivity { return true; case R.id.menu_key_edit_export_file: long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; - mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); + mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC); return true; case R.id.menu_key_edit_delete: { // Message is received after key is deleted diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java index cdfba894a..31d5f3fd0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java @@ -60,7 +60,7 @@ public class ImportKeysFileFragment extends Fragment { // open .asc or .gpg files // setting it to text/plain prevents Cynaogenmod's file manager from selecting asc // or gpg types! - FileHelper.openFile(ImportKeysFileFragment.this, Constants.path.APP_DIR + "/", + FileHelper.openFile(ImportKeysFileFragment.this, Constants.Path.APP_DIR + "/", "*/*", Id.request.filename); } }); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 0dda10c9c..078b998e1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -59,7 +59,7 @@ public class KeyListActivity extends DrawerActivity { return true; case R.id.menu_key_list_export: // TODO fix this for unified keylist - mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); + mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.Path.APP_DIR_FILE_PUB); return true; case R.id.menu_key_list_create: @@ -71,7 +71,7 @@ public class KeyListActivity extends DrawerActivity { return true; case R.id.menu_key_list_secret_export: - mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.path.APP_DIR_FILE_SEC); + mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC); return true; default: diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index e969c1af3..5ac59965d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -189,7 +189,7 @@ public class KeyListFragment extends Fragment mExportHelper .showExportKeysDialog(ids, Id.type.public_key, - Constants.path.APP_DIR_FILE_PUB); + Constants.Path.APP_DIR_FILE_PUB); break; } case R.id.menu_key_list_multi_select_all: { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java index 47372eb59..04179cb80 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/PreferencesActivity.java @@ -56,9 +56,9 @@ public class PreferencesActivity extends PreferenceActivity { addPreferencesFromResource(R.xml.gen_preferences); initializePassPassPhraceCacheTtl( - (IntegerListPreference) findPreference(Constants.pref.PASS_PHRASE_CACHE_TTL)); + (IntegerListPreference) findPreference(Constants.Pref.PASS_PHRASE_CACHE_TTL)); - mKeyServerPreference = (PreferenceScreen) findPreference(Constants.pref.KEY_SERVERS); + mKeyServerPreference = (PreferenceScreen) findPreference(Constants.Pref.KEY_SERVERS); String servers[] = mPreferences.getKeyServers(); mKeyServerPreference.setSummary(getResources().getQuantityString(R.plurals.n_key_servers, servers.length, servers.length)); @@ -78,7 +78,7 @@ public class PreferencesActivity extends PreferenceActivity { addPreferencesFromResource(R.xml.adv_preferences); initializeEncryptionAlgorithm( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM)); + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_ENCRYPTION_ALGORITHM)); int[] valueIds = new int[]{Id.choice.compression.none, Id.choice.compression.zip, Id.choice.compression.zlib, Id.choice.compression.bzip2, }; @@ -93,22 +93,22 @@ public class PreferencesActivity extends PreferenceActivity { } initializeHashAlgorithm( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_HASH_ALGORITHM), + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_HASH_ALGORITHM), valueIds, entries, values); initializeMessageCompression( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_MESSAGE_COMPRESSION), + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_MESSAGE_COMPRESSION), valueIds, entries, values); initializeFileCompression( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_FILE_COMPRESSION), + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_FILE_COMPRESSION), entries, values); initializeAsciiArmour( - (CheckBoxPreference) findPreference(Constants.pref.DEFAULT_ASCII_ARMOUR)); + (CheckBoxPreference) findPreference(Constants.Pref.DEFAULT_ASCII_ARMOUR)); initializeForceV3Signatures( - (CheckBoxPreference) findPreference(Constants.pref.FORCE_V3_SIGNATURES)); + (CheckBoxPreference) findPreference(Constants.Pref.FORCE_V3_SIGNATURES)); } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // Load the legacy preferences headers @@ -160,9 +160,9 @@ public class PreferencesActivity extends PreferenceActivity { addPreferencesFromResource(R.xml.gen_preferences); initializePassPassPhraceCacheTtl( - (IntegerListPreference) findPreference(Constants.pref.PASS_PHRASE_CACHE_TTL)); + (IntegerListPreference) findPreference(Constants.Pref.PASS_PHRASE_CACHE_TTL)); - mKeyServerPreference = (PreferenceScreen) findPreference(Constants.pref.KEY_SERVERS); + mKeyServerPreference = (PreferenceScreen) findPreference(Constants.Pref.KEY_SERVERS); String servers[] = mPreferences.getKeyServers(); mKeyServerPreference.setSummary(getResources().getQuantityString(R.plurals.n_key_servers, servers.length, servers.length)); @@ -215,7 +215,7 @@ public class PreferencesActivity extends PreferenceActivity { addPreferencesFromResource(R.xml.adv_preferences); initializeEncryptionAlgorithm( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_ENCRYPTION_ALGORITHM)); + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_ENCRYPTION_ALGORITHM)); int[] valueIds = new int[]{Id.choice.compression.none, Id.choice.compression.zip, Id.choice.compression.zlib, Id.choice.compression.bzip2, }; @@ -230,22 +230,22 @@ public class PreferencesActivity extends PreferenceActivity { } initializeHashAlgorithm( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_HASH_ALGORITHM), + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_HASH_ALGORITHM), valueIds, entries, values); initializeMessageCompression( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_MESSAGE_COMPRESSION), + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_MESSAGE_COMPRESSION), valueIds, entries, values); initializeFileCompression( - (IntegerListPreference) findPreference(Constants.pref.DEFAULT_FILE_COMPRESSION), + (IntegerListPreference) findPreference(Constants.Pref.DEFAULT_FILE_COMPRESSION), entries, values); initializeAsciiArmour( - (CheckBoxPreference) findPreference(Constants.pref.DEFAULT_ASCII_ARMOUR)); + (CheckBoxPreference) findPreference(Constants.Pref.DEFAULT_ASCII_ARMOUR)); initializeForceV3Signatures( - (CheckBoxPreference) findPreference(Constants.pref.FORCE_V3_SIGNATURES)); + (CheckBoxPreference) findPreference(Constants.Pref.FORCE_V3_SIGNATURES)); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 32c0ea340..93bb83003 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -125,7 +125,7 @@ public class ViewKeyActivity extends ActionBarActivity { return true; case R.id.menu_key_view_export_file: long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; - mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.path.APP_DIR_FILE_PUB); + mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.Path.APP_DIR_FILE_PUB); return true; case R.id.menu_key_view_share_default_fingerprint: shareKey(mDataUri, true); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index c94917b60..42fb03a3e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -78,17 +78,18 @@ public class HkpKeyServer extends KeyServer { // pub 2048R/9F5C9090 2009-08-17 Jörg Runge // <joerg@joergrunge.de> - public static Pattern PUB_KEY_LINE = Pattern + public static final Pattern PUB_KEY_LINE = Pattern .compile( "pub +([0-9]+)([a-z]+)/.*?0x([0-9a-z]+).*? +([0-9-]+) +(.+)[\n\r]+((?: +.+[\n\r]+)*)", Pattern.CASE_INSENSITIVE); - public static Pattern USER_ID_LINE = Pattern.compile("^ +(.+)$", Pattern.MULTILINE + public static final Pattern USER_ID_LINE = Pattern.compile("^ +(.+)$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); private static final short PORT_DEFAULT = 11371; /** - * @param hostAndPort may be just "hostname" (eg. "pool.sks-keyservers.net"), then it will + * @param hostAndPort may be just + * "hostname" (eg. "pool.sks-keyservers.net"), then it will * connect using {@link #PORT_DEFAULT}. However, port may be specified after colon * ("hostname:port", eg. "p80.pool.sks-keyservers.net:80"). */ @@ -110,7 +111,7 @@ public class HkpKeyServer extends KeyServer { mPort = port; } - static private String readAll(InputStream in, String encoding) throws IOException { + private static String readAll(InputStream in, String encoding) throws IOException { ByteArrayOutputStream raw = new ByteArrayOutputStream(); byte buffer[] = new byte[1 << 16]; -- cgit v1.2.3 From 1c95970ea33db5cdf41fe0468a3f76cbc1303370 Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 22:08:13 +0200 Subject: fix code style in /pgp --- .../keychain/pgp/PgpConversionHelper.java | 32 +-- .../keychain/pgp/PgpDecryptVerify.java | 181 +++++++-------- .../keychain/pgp/PgpDecryptVerifyResult.java | 37 ++- .../sufficientlysecure/keychain/pgp/PgpHelper.java | 47 ++-- .../keychain/pgp/PgpImportExport.java | 41 ++-- .../keychain/pgp/PgpKeyHelper.java | 20 +- .../keychain/pgp/PgpKeyOperation.java | 160 ++++++------- .../keychain/pgp/PgpSignEncrypt.java | 256 ++++++++++----------- .../sufficientlysecure/keychain/pgp/PgpToX509.java | 115 +++++---- .../exception/NoAsymmetricEncryptionException.java | 19 +- .../pgp/exception/PgpGeneralException.java | 19 +- 11 files changed, 436 insertions(+), 491 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java index a30e0718f..08ac16ec4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConversionHelper.java @@ -17,11 +17,6 @@ package org.sufficientlysecure.keychain.pgp; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; - import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPObjectFactory; import org.spongycastle.openpgp.PGPSecretKey; @@ -29,12 +24,17 @@ import org.spongycastle.openpgp.PGPSecretKeyRing; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.util.Log; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; + public class PgpConversionHelper { /** * Convert from byte[] to PGPKeyRing - * + * * @param keysBytes * @return */ @@ -54,7 +54,7 @@ public class PgpConversionHelper { /** * Convert from byte[] to ArrayList - * + * * @param keysBytes * @return */ @@ -73,9 +73,9 @@ public class PgpConversionHelper { /** * Convert from byte[] to PGPSecretKey - * + *

* Singles keys are encoded as keyRings with one single key in it by Bouncy Castle - * + * * @param keyBytes * @return */ @@ -88,13 +88,13 @@ public class PgpConversionHelper { Log.e(Constants.TAG, "Error while converting to PGPSecretKey!", e); } PGPSecretKey secKey = null; - if(obj instanceof PGPSecretKey) { - if ((secKey = (PGPSecretKey)obj ) == null) { + if (obj instanceof PGPSecretKey) { + if ((secKey = (PGPSecretKey) obj) == null) { Log.e(Constants.TAG, "No keys given!"); } - } else if(obj instanceof PGPSecretKeyRing) { //master keys are sent as keyrings + } else if (obj instanceof PGPSecretKeyRing) { //master keys are sent as keyrings PGPSecretKeyRing keyRing = null; - if ((keyRing = (PGPSecretKeyRing)obj) == null) { + if ((keyRing = (PGPSecretKeyRing) obj) == null) { Log.e(Constants.TAG, "No keys given!"); } secKey = keyRing.getSecretKey(); @@ -105,7 +105,7 @@ public class PgpConversionHelper { /** * Convert from ArrayList to byte[] - * + * * @param keys * @return */ @@ -124,7 +124,7 @@ public class PgpConversionHelper { /** * Convert from PGPSecretKey to byte[] - * + * * @param key * @return */ @@ -140,7 +140,7 @@ public class PgpConversionHelper { /** * Convert from PGPSecretKeyRing to byte[] - * + * * @param keyRing * @return */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java index 252be1036..d4ce3d352 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java @@ -18,38 +18,16 @@ package org.sufficientlysecure.keychain.pgp; import android.content.Context; - import org.openintents.openpgp.OpenPgpSignatureResult; import org.spongycastle.bcpg.ArmoredInputStream; import org.spongycastle.bcpg.SignatureSubpacketTags; -import org.spongycastle.openpgp.PGPCompressedData; -import org.spongycastle.openpgp.PGPEncryptedData; -import org.spongycastle.openpgp.PGPEncryptedDataList; -import org.spongycastle.openpgp.PGPException; -import org.spongycastle.openpgp.PGPLiteralData; -import org.spongycastle.openpgp.PGPObjectFactory; -import org.spongycastle.openpgp.PGPOnePassSignature; -import org.spongycastle.openpgp.PGPOnePassSignatureList; -import org.spongycastle.openpgp.PGPPBEEncryptedData; -import org.spongycastle.openpgp.PGPPrivateKey; -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPPublicKeyEncryptedData; -import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPSignature; -import org.spongycastle.openpgp.PGPSignatureList; -import org.spongycastle.openpgp.PGPSignatureSubpacketVector; +import org.spongycastle.openpgp.*; import org.spongycastle.openpgp.PGPUtil; import org.spongycastle.openpgp.operator.PBEDataDecryptorFactory; import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; import org.spongycastle.openpgp.operator.PGPDigestCalculatorProvider; import org.spongycastle.openpgp.operator.PublicKeyDataDecryptorFactory; -import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider; -import org.spongycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; +import org.spongycastle.openpgp.operator.jcajce.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; @@ -59,12 +37,7 @@ import org.sufficientlysecure.keychain.util.InputData; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; import java.security.SignatureException; import java.util.Iterator; @@ -72,57 +45,57 @@ import java.util.Iterator; * This class uses a Builder pattern! */ public class PgpDecryptVerify { - private Context context; - private InputData data; - private OutputStream outStream; + private Context mContext; + private InputData mData; + private OutputStream mOutStream; - private ProgressDialogUpdater progressDialogUpdater; - private boolean assumeSymmetric; - private String passphrase; - private long enforcedKeyId; + private ProgressDialogUpdater mProgressDialogUpdater; + private boolean mAssumeSymmetric; + private String mPassphrase; + private long mEnforcedKeyId; private PgpDecryptVerify(Builder builder) { // private Constructor can only be called from Builder - this.context = builder.context; - this.data = builder.data; - this.outStream = builder.outStream; - - this.progressDialogUpdater = builder.progressDialogUpdater; - this.assumeSymmetric = builder.assumeSymmetric; - this.passphrase = builder.passphrase; - this.enforcedKeyId = builder.enforcedKeyId; + this.mContext = builder.mContext; + this.mData = builder.mData; + this.mOutStream = builder.mOutStream; + + this.mProgressDialogUpdater = builder.mProgressDialogUpdater; + this.mAssumeSymmetric = builder.mAssumeSymmetric; + this.mPassphrase = builder.mPassphrase; + this.mEnforcedKeyId = builder.mEnforcedKeyId; } public static class Builder { // mandatory parameter - private Context context; - private InputData data; - private OutputStream outStream; + private Context mContext; + private InputData mData; + private OutputStream mOutStream; // optional - private ProgressDialogUpdater progressDialogUpdater = null; - private boolean assumeSymmetric = false; - private String passphrase = ""; - private long enforcedKeyId = 0; + private ProgressDialogUpdater mProgressDialogUpdater = null; + private boolean mAssumeSymmetric = false; + private String mPassphrase = ""; + private long mEnforcedKeyId = 0; public Builder(Context context, InputData data, OutputStream outStream) { - this.context = context; - this.data = data; - this.outStream = outStream; + this.mContext = context; + this.mData = data; + this.mOutStream = outStream; } public Builder progressDialogUpdater(ProgressDialogUpdater progressDialogUpdater) { - this.progressDialogUpdater = progressDialogUpdater; + this.mProgressDialogUpdater = progressDialogUpdater; return this; } public Builder assumeSymmetric(boolean assumeSymmetric) { - this.assumeSymmetric = assumeSymmetric; + this.mAssumeSymmetric = assumeSymmetric; return this; } public Builder passphrase(String passphrase) { - this.passphrase = passphrase; + this.mPassphrase = passphrase; return this; } @@ -134,7 +107,7 @@ public class PgpDecryptVerify { * @return */ public Builder enforcedKeyId(long enforcedKeyId) { - this.enforcedKeyId = enforcedKeyId; + this.mEnforcedKeyId = enforcedKeyId; return this; } @@ -144,14 +117,14 @@ public class PgpDecryptVerify { } public void updateProgress(int message, int current, int total) { - if (progressDialogUpdater != null) { - progressDialogUpdater.setProgress(message, current, total); + if (mProgressDialogUpdater != null) { + mProgressDialogUpdater.setProgress(message, current, total); } } public void updateProgress(int current, int total) { - if (progressDialogUpdater != null) { - progressDialogUpdater.setProgress(current, total); + if (mProgressDialogUpdater != null) { + mProgressDialogUpdater.setProgress(current, total); } } @@ -196,7 +169,7 @@ public class PgpDecryptVerify { public PgpDecryptVerifyResult execute() throws IOException, PgpGeneralException, PGPException, SignatureException { // automatically works with ascii armor input and binary - InputStream in = PGPUtil.getDecoderStream(data.getInputStream()); + InputStream in = PGPUtil.getDecoderStream(mData.getInputStream()); if (in instanceof ArmoredInputStream) { ArmoredInputStream aIn = (ArmoredInputStream) in; // it is ascii armored @@ -240,7 +213,7 @@ public class PgpDecryptVerify { } if (enc == null) { - throw new PgpGeneralException(context.getString(R.string.error_invalid_data)); + throw new PgpGeneralException(mContext.getString(R.string.error_invalid_data)); } InputStream clear; @@ -250,7 +223,7 @@ public class PgpDecryptVerify { // TODO: currently we always only look at the first known key or symmetric encryption, // there might be more... - if (assumeSymmetric) { + if (mAssumeSymmetric) { PGPPBEEncryptedData pbe = null; Iterator it = enc.getEncryptedDataObjects(); // find secret key @@ -264,7 +237,7 @@ public class PgpDecryptVerify { if (pbe == null) { throw new PgpGeneralException( - context.getString(R.string.error_no_symmetric_encryption_packet)); + mContext.getString(R.string.error_no_symmetric_encryption_packet)); } updateProgress(R.string.progress_preparing_streams, currentProgress, 100); @@ -273,7 +246,7 @@ public class PgpDecryptVerify { .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(); PBEDataDecryptorFactory decryptorFactory = new JcePBEDataDecryptorFactoryBuilder( digestCalcProvider).setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build( - passphrase.toCharArray()); + mPassphrase.toCharArray()); clear = pbe.getDataStream(decryptorFactory); @@ -290,33 +263,35 @@ public class PgpDecryptVerify { Object obj = it.next(); if (obj instanceof PGPPublicKeyEncryptedData) { PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) obj; - secretKey = ProviderHelper.getPGPSecretKeyByKeyId(context, encData.getKeyID()); + secretKey = ProviderHelper.getPGPSecretKeyByKeyId(mContext, encData.getKeyID()); if (secretKey != null) { // secret key exists in database // allow only a specific key for decryption? - if (enforcedKeyId != 0) { + if (mEnforcedKeyId != 0) { // TODO: improve this code! get master key directly! - PGPSecretKeyRing secretKeyRing = ProviderHelper.getPGPSecretKeyRingByKeyId(context, encData.getKeyID()); + PGPSecretKeyRing secretKeyRing = + ProviderHelper.getPGPSecretKeyRingByKeyId(mContext, encData.getKeyID()); long masterKeyId = PgpKeyHelper.getMasterKey(secretKeyRing).getKeyID(); Log.d(Constants.TAG, "encData.getKeyID():" + encData.getKeyID()); - Log.d(Constants.TAG, "enforcedKeyId: " + enforcedKeyId); + Log.d(Constants.TAG, "enforcedKeyId: " + mEnforcedKeyId); Log.d(Constants.TAG, "masterKeyId: " + masterKeyId); - if (enforcedKeyId != masterKeyId) { - throw new PgpGeneralException(context.getString(R.string.error_no_secret_key_found)); + if (mEnforcedKeyId != masterKeyId) { + throw new PgpGeneralException( + mContext.getString(R.string.error_no_secret_key_found)); } } pbe = encData; // if no passphrase was explicitly set try to get it from the cache service - if (passphrase == null) { + if (mPassphrase == null) { // returns "" if key has no passphrase - passphrase = PassphraseCacheService.getCachedPassphrase(context, encData.getKeyID()); + mPassphrase = PassphraseCacheService.getCachedPassphrase(mContext, encData.getKeyID()); // if passphrase was not cached, return here indicating that a passphrase is missing! - if (passphrase == null) { + if (mPassphrase == null) { returnData.setKeyPassphraseNeeded(true); return returnData; } @@ -330,7 +305,7 @@ public class PgpDecryptVerify { } if (secretKey == null) { - throw new PgpGeneralException(context.getString(R.string.error_no_secret_key_found)); + throw new PgpGeneralException(mContext.getString(R.string.error_no_secret_key_found)); } currentProgress += 5; @@ -339,14 +314,14 @@ public class PgpDecryptVerify { try { PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder() .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build( - passphrase.toCharArray()); + mPassphrase.toCharArray()); privateKey = secretKey.extractPrivateKey(keyDecryptor); } catch (PGPException e) { - throw new PGPException(context.getString(R.string.error_wrong_passphrase)); + throw new PGPException(mContext.getString(R.string.error_wrong_passphrase)); } if (privateKey == null) { throw new PgpGeneralException( - context.getString(R.string.error_could_not_extract_private_key)); + mContext.getString(R.string.error_could_not_extract_private_key)); } currentProgress += 5; updateProgress(R.string.progress_preparing_streams, currentProgress, 100); @@ -386,7 +361,7 @@ public class PgpDecryptVerify { for (int i = 0; i < sigList.size(); ++i) { signature = sigList.get(i); signatureKey = ProviderHelper - .getPGPPublicKeyByKeyId(context, signature.getKeyID()); + .getPGPPublicKeyByKeyId(mContext, signature.getKeyID()); if (signatureKeyId == 0) { signatureKeyId = signature.getKeyID(); } @@ -397,7 +372,7 @@ public class PgpDecryptVerify { signatureKeyId = signature.getKeyID(); String userId = null; PGPPublicKeyRing signKeyRing = ProviderHelper.getPGPPublicKeyRingByKeyId( - context, signatureKeyId); + mContext, signatureKeyId); if (signKeyRing != null) { userId = PgpKeyHelper.getMainUserId(PgpKeyHelper.getMasterKey(signKeyRing)); } @@ -444,9 +419,9 @@ public class PgpDecryptVerify { int n; // TODO: progress calculation is broken here! Try to rework it based on commented code! // int progress = 0; - long startPos = data.getStreamPosition(); + long startPos = mData.getStreamPosition(); while ((n = dataIn.read(buffer)) > 0) { - outStream.write(buffer, 0, n); + mOutStream.write(buffer, 0, n); // progress += n; if (signature != null) { try { @@ -460,11 +435,11 @@ public class PgpDecryptVerify { // unknown size, but try to at least have a moving, slowing down progress bar // currentProgress = startProgress + (endProgress - startProgress) * progress // / (progress + 100000); - if (data.getSize() - startPos == 0) { + if (mData.getSize() - startPos == 0) { currentProgress = endProgress; } else { currentProgress = (int) (startProgress + (endProgress - startProgress) - * (data.getStreamPosition() - startPos) / (data.getSize() - startPos)); + * (mData.getStreamPosition() - startPos) / (mData.getSize() - startPos)); } updateProgress(currentProgress, 100); } @@ -480,7 +455,7 @@ public class PgpDecryptVerify { signatureResult.setSignatureOnly(false); //Now check binding signatures - boolean validKeyBinding = verifyKeyBinding(context, messageSignature, signatureKey); + boolean validKeyBinding = verifyKeyBinding(mContext, messageSignature, signatureKey); boolean validSignature = signature.verify(messageSignature); // TODO: implement CERTIFIED! @@ -499,7 +474,7 @@ public class PgpDecryptVerify { } else { // failed Log.d(Constants.TAG, "Integrity verification: failed!"); - throw new PgpGeneralException(context.getString(R.string.error_integrity_check_failed)); + throw new PgpGeneralException(mContext.getString(R.string.error_integrity_check_failed)); } } else { // no integrity check @@ -555,21 +530,21 @@ public class PgpDecryptVerify { out.close(); byte[] clearText = out.toByteArray(); - outStream.write(clearText); + mOutStream.write(clearText); updateProgress(R.string.progress_processing_signature, 60, 100); PGPObjectFactory pgpFact = new PGPObjectFactory(aIn); PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject(); if (sigList == null) { - throw new PgpGeneralException(context.getString(R.string.error_corrupt_data)); + throw new PgpGeneralException(mContext.getString(R.string.error_corrupt_data)); } PGPSignature signature = null; long signatureKeyId = 0; PGPPublicKey signatureKey = null; for (int i = 0; i < sigList.size(); ++i) { signature = sigList.get(i); - signatureKey = ProviderHelper.getPGPPublicKeyByKeyId(context, signature.getKeyID()); + signatureKey = ProviderHelper.getPGPPublicKeyByKeyId(mContext, signature.getKeyID()); if (signatureKeyId == 0) { signatureKeyId = signature.getKeyID(); } @@ -579,7 +554,7 @@ public class PgpDecryptVerify { } else { signatureKeyId = signature.getKeyID(); String userId = null; - PGPPublicKeyRing signKeyRing = ProviderHelper.getPGPPublicKeyRingByKeyId(context, + PGPPublicKeyRing signKeyRing = ProviderHelper.getPGPPublicKeyRingByKeyId(mContext, signatureKeyId); if (signKeyRing != null) { userId = PgpKeyHelper.getMainUserId(PgpKeyHelper.getMasterKey(signKeyRing)); @@ -623,7 +598,7 @@ public class PgpDecryptVerify { } //Now check binding signatures - boolean validKeyBinding = verifyKeyBinding(context, signature, signatureKey); + boolean validKeyBinding = verifyKeyBinding(mContext, signature, signatureKey); boolean validSignature = signature.verify(); if (validSignature & validKeyBinding) { @@ -684,24 +659,27 @@ public class PgpDecryptVerify { continue; } - if (validTempSubkeyBinding) + if (validTempSubkeyBinding) { validSubkeyBinding = true; + } if (validTempSubkeyBinding) { validPrimaryKeyBinding = verifyPrimaryKeyBinding(sig.getUnhashedSubPackets(), masterPublicKey, signingPublicKey); - if (validPrimaryKeyBinding) + if (validPrimaryKeyBinding) { break; + } validPrimaryKeyBinding = verifyPrimaryKeyBinding(sig.getHashedSubPackets(), masterPublicKey, signingPublicKey); - if (validPrimaryKeyBinding) + if (validPrimaryKeyBinding) { break; + } } } } return (validSubkeyBinding & validPrimaryKeyBinding); } - private static boolean verifyPrimaryKeyBinding(PGPSignatureSubpacketVector Pkts, + private static boolean verifyPrimaryKeyBinding(PGPSignatureSubpacketVector pkts, PGPPublicKey masterPublicKey, PGPPublicKey signingPublicKey) { boolean validPrimaryKeyBinding = false; JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider = @@ -709,9 +687,9 @@ public class PgpDecryptVerify { .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); PGPSignatureList eSigList; - if (Pkts.hasSubpacket(SignatureSubpacketTags.EMBEDDED_SIGNATURE)) { + if (pkts.hasSubpacket(SignatureSubpacketTags.EMBEDDED_SIGNATURE)) { try { - eSigList = Pkts.getEmbeddedSignatures(); + eSigList = pkts.getEmbeddedSignatures(); } catch (IOException e) { return false; } catch (PGPException e) { @@ -723,8 +701,9 @@ public class PgpDecryptVerify { try { emSig.init(contentVerifierBuilderProvider, signingPublicKey); validPrimaryKeyBinding = emSig.verifyCertification(masterPublicKey, signingPublicKey); - if (validPrimaryKeyBinding) + if (validPrimaryKeyBinding) { break; + } } catch (PGPException e) { continue; } catch (SignatureException e) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyResult.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyResult.java index 0477c4fdf..d4a4f6075 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyResult.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyResult.java @@ -19,36 +19,35 @@ package org.sufficientlysecure.keychain.pgp; import android.os.Parcel; import android.os.Parcelable; - import org.openintents.openpgp.OpenPgpSignatureResult; public class PgpDecryptVerifyResult implements Parcelable { - boolean symmetricPassphraseNeeded; - boolean keyPassphraseNeeded; - OpenPgpSignatureResult signatureResult; + boolean mSymmetricPassphraseNeeded; + boolean mKeyPassphraseNeeded; + OpenPgpSignatureResult mSignatureResult; public boolean isSymmetricPassphraseNeeded() { - return symmetricPassphraseNeeded; + return mSymmetricPassphraseNeeded; } public void setSymmetricPassphraseNeeded(boolean symmetricPassphraseNeeded) { - this.symmetricPassphraseNeeded = symmetricPassphraseNeeded; + this.mSymmetricPassphraseNeeded = symmetricPassphraseNeeded; } public boolean isKeyPassphraseNeeded() { - return keyPassphraseNeeded; + return mKeyPassphraseNeeded; } public void setKeyPassphraseNeeded(boolean keyPassphraseNeeded) { - this.keyPassphraseNeeded = keyPassphraseNeeded; + this.mKeyPassphraseNeeded = keyPassphraseNeeded; } public OpenPgpSignatureResult getSignatureResult() { - return signatureResult; + return mSignatureResult; } public void setSignatureResult(OpenPgpSignatureResult signatureResult) { - this.signatureResult = signatureResult; + this.mSignatureResult = signatureResult; } public PgpDecryptVerifyResult() { @@ -56,9 +55,9 @@ public class PgpDecryptVerifyResult implements Parcelable { } public PgpDecryptVerifyResult(PgpDecryptVerifyResult b) { - this.symmetricPassphraseNeeded = b.symmetricPassphraseNeeded; - this.keyPassphraseNeeded = b.keyPassphraseNeeded; - this.signatureResult = b.signatureResult; + this.mSymmetricPassphraseNeeded = b.mSymmetricPassphraseNeeded; + this.mKeyPassphraseNeeded = b.mKeyPassphraseNeeded; + this.mSignatureResult = b.mSignatureResult; } @@ -67,17 +66,17 @@ public class PgpDecryptVerifyResult implements Parcelable { } public void writeToParcel(Parcel dest, int flags) { - dest.writeByte((byte) (symmetricPassphraseNeeded ? 1 : 0)); - dest.writeByte((byte) (keyPassphraseNeeded ? 1 : 0)); - dest.writeParcelable(signatureResult, 0); + dest.writeByte((byte) (mSymmetricPassphraseNeeded ? 1 : 0)); + dest.writeByte((byte) (mKeyPassphraseNeeded ? 1 : 0)); + dest.writeParcelable(mSignatureResult, 0); } public static final Creator CREATOR = new Creator() { public PgpDecryptVerifyResult createFromParcel(final Parcel source) { PgpDecryptVerifyResult vr = new PgpDecryptVerifyResult(); - vr.symmetricPassphraseNeeded = source.readByte() == 1; - vr.keyPassphraseNeeded = source.readByte() == 1; - vr.signatureResult = source.readParcelable(OpenPgpSignatureResult.class.getClassLoader()); + vr.mSymmetricPassphraseNeeded = source.readByte() == 1; + vr.mKeyPassphraseNeeded = source.readByte() == 1; + vr.mSignatureResult = source.readParcelable(OpenPgpSignatureResult.class.getClassLoader()); return vr; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java index 1db4f98b1..2680d77af 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpHelper.java @@ -17,22 +17,10 @@ package org.sufficientlysecure.keychain.pgp; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.security.SecureRandom; -import java.util.Iterator; -import java.util.regex.Pattern; - -import org.spongycastle.openpgp.PGPEncryptedDataList; -import org.spongycastle.openpgp.PGPObjectFactory; -import org.spongycastle.openpgp.PGPPublicKeyEncryptedData; -import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPUtil; +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager.NameNotFoundException; +import org.spongycastle.openpgp.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -42,21 +30,25 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; -import android.content.Context; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager.NameNotFoundException; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.security.SecureRandom; +import java.util.Iterator; +import java.util.regex.Pattern; public class PgpHelper { - public static Pattern PGP_MESSAGE = Pattern.compile( + public static final Pattern PGP_MESSAGE = Pattern.compile( ".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*", Pattern.DOTALL); - public static Pattern PGP_SIGNED_MESSAGE = Pattern + public static final Pattern PGP_SIGNED_MESSAGE = Pattern .compile( ".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*", Pattern.DOTALL); - public static Pattern PGP_PUBLIC_KEY = Pattern.compile( + public static final Pattern PGP_PUBLIC_KEY = Pattern.compile( ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*", Pattern.DOTALL); @@ -140,7 +132,7 @@ public class PgpHelper { /** * Generate a random filename - * + * * @param length * @return */ @@ -170,7 +162,7 @@ public class PgpHelper { /** * Go once through stream to get length of stream. The length is later used to display progress * when encrypting/decrypting - * + * * @param in * @return * @throws IOException @@ -187,9 +179,9 @@ public class PgpHelper { /** * Deletes file securely by overwriting it with random data before deleting it. - * + *

* TODO: Does this really help on flash storage? - * + * * @param context * @param progress * @param file @@ -206,8 +198,9 @@ public class PgpHelper { int pos = 0; String msg = context.getString(R.string.progress_deleting_securely, file.getName()); while (pos < length) { - if (progress != null) + if (progress != null) { progress.setProgress(msg, (int) (100 * pos / length), 100); + } random.nextBytes(data); raf.write(data); pos += data.length; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 3ce9fa7c5..4a97eb825 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -17,20 +17,11 @@ package org.sufficientlysecure.keychain.pgp; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - +import android.content.Context; +import android.os.Bundle; +import android.os.Environment; import org.spongycastle.bcpg.ArmoredOutputStream; -import org.spongycastle.openpgp.PGPException; -import org.spongycastle.openpgp.PGPKeyRing; -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.*; import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; @@ -39,16 +30,14 @@ import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; -import org.sufficientlysecure.keychain.util.HkpKeyServer; -import org.sufficientlysecure.keychain.util.IterableIterator; +import org.sufficientlysecure.keychain.util.*; import org.sufficientlysecure.keychain.util.KeyServer.AddKeyException; -import org.sufficientlysecure.keychain.util.KeychainServiceListener; -import org.sufficientlysecure.keychain.util.Log; -import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; -import android.content.Context; -import android.os.Bundle; -import android.os.Environment; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; public class PgpImportExport { @@ -63,7 +52,7 @@ public class PgpImportExport { this.mProgress = progress; } - public PgpImportExport(Context context, ProgressDialogUpdater progress, KeychainServiceListener keychainListener){ + public PgpImportExport(Context context, ProgressDialogUpdater progress, KeychainServiceListener keychainListener) { super(); this.mContext = context; this.mProgress = progress; @@ -107,8 +96,8 @@ public class PgpImportExport { return false; } finally { try { - if (aos != null) aos.close(); - if (bos != null) bos.close(); + if (aos != null) { aos.close(); } + if (bos != null) { bos.close(); } } catch (IOException e) { } } @@ -199,7 +188,7 @@ public class PgpImportExport { if (secretKeyRing != null) { secretKeyRing.encode(arOutStream); } - if(mKeychainServiceListener.hasServiceStopped()){ + if (mKeychainServiceListener.hasServiceStopped()) { arOutStream.close(); return null; } @@ -212,7 +201,7 @@ public class PgpImportExport { publicKeyRing.encode(arOutStream); } - if(mKeychainServiceListener.hasServiceStopped()){ + if (mKeychainServiceListener.hasServiceStopped()) { arOutStream.close(); return null; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index 71c921c33..436c26700 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -17,21 +17,9 @@ package org.sufficientlysecure.keychain.pgp; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.Vector; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - +import android.content.Context; import org.spongycastle.bcpg.sig.KeyFlags; -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPSignature; -import org.spongycastle.openpgp.PGPSignatureSubpacketVector; +import org.spongycastle.openpgp.*; import org.spongycastle.util.encoders.Hex; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; @@ -39,7 +27,9 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; -import android.content.Context; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class PgpKeyHelper { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index 5ebb53f20..84d772846 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -17,48 +17,20 @@ package org.sufficientlysecure.keychain.pgp; -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - +import android.content.Context; import org.spongycastle.bcpg.CompressionAlgorithmTags; import org.spongycastle.bcpg.HashAlgorithmTags; import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags; import org.spongycastle.bcpg.sig.KeyFlags; import org.spongycastle.jce.provider.BouncyCastleProvider; import org.spongycastle.jce.spec.ElGamalParameterSpec; -import org.spongycastle.openpgp.PGPEncryptedData; -import org.spongycastle.openpgp.PGPException; -import org.spongycastle.openpgp.PGPKeyPair; -import org.spongycastle.openpgp.PGPKeyRingGenerator; -import org.spongycastle.openpgp.PGPPrivateKey; -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPSignature; -import org.spongycastle.openpgp.PGPSignatureGenerator; -import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; -import org.spongycastle.openpgp.PGPSignatureSubpacketVector; +import org.spongycastle.openpgp.*; import org.spongycastle.openpgp.PGPUtil; import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; import org.spongycastle.openpgp.operator.PBESecretKeyEncryptor; import org.spongycastle.openpgp.operator.PGPContentSignerBuilder; import org.spongycastle.openpgp.operator.PGPDigestCalculator; -import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcaPGPKeyPair; -import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder; +import org.spongycastle.openpgp.operator.jcajce.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -68,21 +40,27 @@ import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.Primes; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; -import android.content.Context; +import java.io.IOException; +import java.math.BigInteger; +import java.security.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; public class PgpKeyOperation { private Context mContext; private ProgressDialogUpdater mProgress; - private static final int[] PREFERRED_SYMMETRIC_ALGORITHMS = new int[] { + private static final int[] PREFERRED_SYMMETRIC_ALGORITHMS = new int[]{ SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128, SymmetricKeyAlgorithmTags.CAST5, - SymmetricKeyAlgorithmTags.TRIPLE_DES }; - private static final int[] PREFERRED_HASH_ALGORITHMS = new int[] { HashAlgorithmTags.SHA1, - HashAlgorithmTags.SHA256, HashAlgorithmTags.RIPEMD160 }; - private static final int[] PREFERRED_COMPRESSION_ALGORITHMS = new int[] { + SymmetricKeyAlgorithmTags.TRIPLE_DES}; + private static final int[] PREFERRED_HASH_ALGORITHMS = new int[]{HashAlgorithmTags.SHA1, + HashAlgorithmTags.SHA256, HashAlgorithmTags.RIPEMD160}; + private static final int[] PREFERRED_COMPRESSION_ALGORITHMS = new int[]{ CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2, - CompressionAlgorithmTags.ZIP }; + CompressionAlgorithmTags.ZIP}; public PgpKeyOperation(Context context, ProgressDialogUpdater progress) { super(); @@ -104,7 +82,7 @@ public class PgpKeyOperation { /** * Creates new secret key. - * + * * @param algorithmChoice * @param keySize * @param passphrase @@ -119,8 +97,9 @@ public class PgpKeyOperation { // TODO: key flags? public PGPSecretKey createKey(int algorithmChoice, int keySize, String passphrase, - boolean isMasterKey) throws NoSuchAlgorithmException, PGPException, NoSuchProviderException, - PgpGeneralException, InvalidAlgorithmParameterException { + boolean isMasterKey) + throws NoSuchAlgorithmException, PGPException, NoSuchProviderException, + PgpGeneralException, InvalidAlgorithmParameterException { if (keySize < 512) { throw new PgpGeneralException(mContext.getString(R.string.error_key_size_minimum512bit)); @@ -134,41 +113,41 @@ public class PgpKeyOperation { KeyPairGenerator keyGen = null; switch (algorithmChoice) { - case Id.choice.algorithm.dsa: { - keyGen = KeyPairGenerator.getInstance("DSA", Constants.BOUNCY_CASTLE_PROVIDER_NAME); - keyGen.initialize(keySize, new SecureRandom()); - algorithm = PGPPublicKey.DSA; - break; - } - - case Id.choice.algorithm.elgamal: { - if (isMasterKey) { - throw new PgpGeneralException( - mContext.getString(R.string.error_master_key_must_not_be_el_gamal)); + case Id.choice.algorithm.dsa: { + keyGen = KeyPairGenerator.getInstance("DSA", Constants.BOUNCY_CASTLE_PROVIDER_NAME); + keyGen.initialize(keySize, new SecureRandom()); + algorithm = PGPPublicKey.DSA; + break; } - keyGen = KeyPairGenerator.getInstance("ElGamal", Constants.BOUNCY_CASTLE_PROVIDER_NAME); - BigInteger p = Primes.getBestPrime(keySize); - BigInteger g = new BigInteger("2"); - ElGamalParameterSpec elParams = new ElGamalParameterSpec(p, g); + case Id.choice.algorithm.elgamal: { + if (isMasterKey) { + throw new PgpGeneralException( + mContext.getString(R.string.error_master_key_must_not_be_el_gamal)); + } + keyGen = KeyPairGenerator.getInstance("ElGamal", Constants.BOUNCY_CASTLE_PROVIDER_NAME); + BigInteger p = Primes.getBestPrime(keySize); + BigInteger g = new BigInteger("2"); - keyGen.initialize(elParams); - algorithm = PGPPublicKey.ELGAMAL_ENCRYPT; - break; - } + ElGamalParameterSpec elParams = new ElGamalParameterSpec(p, g); - case Id.choice.algorithm.rsa: { - keyGen = KeyPairGenerator.getInstance("RSA", Constants.BOUNCY_CASTLE_PROVIDER_NAME); - keyGen.initialize(keySize, new SecureRandom()); + keyGen.initialize(elParams); + algorithm = PGPPublicKey.ELGAMAL_ENCRYPT; + break; + } - algorithm = PGPPublicKey.RSA_GENERAL; - break; - } + case Id.choice.algorithm.rsa: { + keyGen = KeyPairGenerator.getInstance("RSA", Constants.BOUNCY_CASTLE_PROVIDER_NAME); + keyGen.initialize(keySize, new SecureRandom()); - default: { - throw new PgpGeneralException( - mContext.getString(R.string.error_unknown_algorithm_choice)); - } + algorithm = PGPPublicKey.RSA_GENERAL; + break; + } + + default: { + throw new PgpGeneralException( + mContext.getString(R.string.error_unknown_algorithm_choice)); + } } // build new key pair @@ -184,13 +163,13 @@ public class PgpKeyOperation { .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(passphrase.toCharArray()); PGPSecretKey secKey = new PGPSecretKey(keyPair.getPrivateKey(), keyPair.getPublicKey(), - sha1Calc, isMasterKey, keyEncryptor); + sha1Calc, isMasterKey, keyEncryptor); return secKey; } public void changeSecretKeyPassphrase(PGPSecretKeyRing keyRing, String oldPassPhrase, - String newPassPhrase) throws IOException, PGPException, + String newPassPhrase) throws IOException, PGPException, NoSuchProviderException { updateProgress(R.string.progress_building_key, 0, 100); @@ -218,9 +197,9 @@ public class PgpKeyOperation { } public void buildSecretKey(ArrayList userIds, ArrayList keys, - ArrayList keysUsages, ArrayList keysExpiryDates, - long masterKeyId, String oldPassPhrase, - String newPassPhrase) throws PgpGeneralException, NoSuchProviderException, + ArrayList keysUsages, ArrayList keysExpiryDates, + long masterKeyId, String oldPassPhrase, + String newPassPhrase) throws PgpGeneralException, NoSuchProviderException, PGPException, NoSuchAlgorithmException, SignatureException, IOException { Log.d(Constants.TAG, "userIds: " + userIds.toString()); @@ -237,8 +216,10 @@ public class PgpKeyOperation { updateProgress(R.string.progress_preparing_master_key, 10, 100); int usageId = keysUsages.get(0); - boolean canSign = (usageId == Id.choice.usage.sign_only || usageId == Id.choice.usage.sign_and_encrypt); - boolean canEncrypt = (usageId == Id.choice.usage.encrypt_only || usageId == Id.choice.usage.sign_and_encrypt); + boolean canSign = + (usageId == Id.choice.usage.sign_only || usageId == Id.choice.usage.sign_and_encrypt); + boolean canEncrypt = + (usageId == Id.choice.usage.encrypt_only || usageId == Id.choice.usage.sign_and_encrypt); String mainUserId = userIds.get(0); @@ -303,13 +284,16 @@ public class PgpKeyOperation { GregorianCalendar expiryDate = keysExpiryDates.get(0); //note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c //here we purposefully ignore partial days in each date - long type has no fractional part! - long numDays = (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000); - if (numDays <= 0) + long numDays = + (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000); + if (numDays <= 0) { throw new PgpGeneralException(mContext.getString(R.string.error_expiry_must_come_after_creation)); + } hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400); } else { - hashedPacketsGen.setKeyExpirationTime(false, 0); //do this explicitly, although since we're rebuilding, - //this happens anyway + //do this explicitly, although since we're rebuilding, + hashedPacketsGen.setKeyExpirationTime(false, 0); + //this happens anyway } updateProgress(R.string.progress_building_master_key, 30, 100); @@ -382,13 +366,17 @@ public class PgpKeyOperation { GregorianCalendar expiryDate = keysExpiryDates.get(i); //note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c //here we purposefully ignore partial days in each date - long type has no fractional part! - long numDays = (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000); - if (numDays <= 0) - throw new PgpGeneralException(mContext.getString(R.string.error_expiry_must_come_after_creation)); + long numDays = + (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000); + if (numDays <= 0) { + throw new PgpGeneralException + (mContext.getString(R.string.error_expiry_must_come_after_creation)); + } hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400); } else { - hashedPacketsGen.setKeyExpirationTime(false, 0); //do this explicitly, although since we're rebuilding, - //this happens anyway + //do this explicitly, although since we're rebuilding, + hashedPacketsGen.setKeyExpirationTime(false, 0); + //this happens anyway } keyGen.addSubKey(subKeyPair, hashedPacketsGen.generate(), unhashedPacketsGen.generate()); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpSignEncrypt.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpSignEncrypt.java index ba1182c1b..737e9c75d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpSignEncrypt.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpSignEncrypt.java @@ -18,28 +18,11 @@ package org.sufficientlysecure.keychain.pgp; import android.content.Context; - import org.spongycastle.bcpg.ArmoredOutputStream; import org.spongycastle.bcpg.BCPGOutputStream; -import org.spongycastle.openpgp.PGPCompressedDataGenerator; -import org.spongycastle.openpgp.PGPEncryptedDataGenerator; -import org.spongycastle.openpgp.PGPException; -import org.spongycastle.openpgp.PGPLiteralData; -import org.spongycastle.openpgp.PGPLiteralDataGenerator; -import org.spongycastle.openpgp.PGPPrivateKey; -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPSignature; -import org.spongycastle.openpgp.PGPSignatureGenerator; -import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; -import org.spongycastle.openpgp.PGPV3SignatureGenerator; +import org.spongycastle.openpgp.*; import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; -import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePBEKeyEncryptionMethodGenerator; -import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; +import org.spongycastle.openpgp.operator.jcajce.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -49,11 +32,7 @@ import org.sufficientlysecure.keychain.util.InputData; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; +import java.io.*; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SignatureException; @@ -63,110 +42,110 @@ import java.util.Date; * This class uses a Builder pattern! */ public class PgpSignEncrypt { - private Context context; - private InputData data; - private OutputStream outStream; - - private ProgressDialogUpdater progress; - private boolean enableAsciiArmorOutput; - private int compressionId; - private long[] encryptionKeyIds; - private String encryptionPassphrase; - private int symmetricEncryptionAlgorithm; - private long signatureKeyId; - private int signatureHashAlgorithm; - private boolean signatureForceV3; - private String signaturePassphrase; + private Context mContext; + private InputData mData; + private OutputStream mOutStream; + + private ProgressDialogUpdater mProgress; + private boolean mEnableAsciiArmorOutput; + private int mCompressionId; + private long[] mEncryptionKeyIds; + private String mEncryptionPassphrase; + private int mSymmetricEncryptionAlgorithm; + private long mSignatureKeyId; + private int mSignatureHashAlgorithm; + private boolean mSignatureForceV3; + private String mSignaturePassphrase; private PgpSignEncrypt(Builder builder) { // private Constructor can only be called from Builder - this.context = builder.context; - this.data = builder.data; - this.outStream = builder.outStream; - - this.progress = builder.progress; - this.enableAsciiArmorOutput = builder.enableAsciiArmorOutput; - this.compressionId = builder.compressionId; - this.encryptionKeyIds = builder.encryptionKeyIds; - this.encryptionPassphrase = builder.encryptionPassphrase; - this.symmetricEncryptionAlgorithm = builder.symmetricEncryptionAlgorithm; - this.signatureKeyId = builder.signatureKeyId; - this.signatureHashAlgorithm = builder.signatureHashAlgorithm; - this.signatureForceV3 = builder.signatureForceV3; - this.signaturePassphrase = builder.signaturePassphrase; + this.mContext = builder.mContext; + this.mData = builder.mData; + this.mOutStream = builder.mOutStream; + + this.mProgress = builder.mProgress; + this.mEnableAsciiArmorOutput = builder.mEnableAsciiArmorOutput; + this.mCompressionId = builder.mCompressionId; + this.mEncryptionKeyIds = builder.mEncryptionKeyIds; + this.mEncryptionPassphrase = builder.mEncryptionPassphrase; + this.mSymmetricEncryptionAlgorithm = builder.mSymmetricEncryptionAlgorithm; + this.mSignatureKeyId = builder.mSignatureKeyId; + this.mSignatureHashAlgorithm = builder.mSignatureHashAlgorithm; + this.mSignatureForceV3 = builder.mSignatureForceV3; + this.mSignaturePassphrase = builder.mSignaturePassphrase; } public static class Builder { // mandatory parameter - private Context context; - private InputData data; - private OutputStream outStream; + private Context mContext; + private InputData mData; + private OutputStream mOutStream; // optional - private ProgressDialogUpdater progress = null; - private boolean enableAsciiArmorOutput = false; - private int compressionId = Id.choice.compression.none; - private long[] encryptionKeyIds = new long[0]; - private String encryptionPassphrase = null; - private int symmetricEncryptionAlgorithm = 0; - private long signatureKeyId = Id.key.none; - private int signatureHashAlgorithm = 0; - private boolean signatureForceV3 = false; - private String signaturePassphrase = null; + private ProgressDialogUpdater mProgress = null; + private boolean mEnableAsciiArmorOutput = false; + private int mCompressionId = Id.choice.compression.none; + private long[] mEncryptionKeyIds = new long[0]; + private String mEncryptionPassphrase = null; + private int mSymmetricEncryptionAlgorithm = 0; + private long mSignatureKeyId = Id.key.none; + private int mSignatureHashAlgorithm = 0; + private boolean mSignatureForceV3 = false; + private String mSignaturePassphrase = null; public Builder(Context context, InputData data, OutputStream outStream) { - this.context = context; - this.data = data; - this.outStream = outStream; + this.mContext = context; + this.mData = data; + this.mOutStream = outStream; } public Builder progress(ProgressDialogUpdater progress) { - this.progress = progress; + this.mProgress = progress; return this; } public Builder enableAsciiArmorOutput(boolean enableAsciiArmorOutput) { - this.enableAsciiArmorOutput = enableAsciiArmorOutput; + this.mEnableAsciiArmorOutput = enableAsciiArmorOutput; return this; } public Builder compressionId(int compressionId) { - this.compressionId = compressionId; + this.mCompressionId = compressionId; return this; } public Builder encryptionKeyIds(long[] encryptionKeyIds) { - this.encryptionKeyIds = encryptionKeyIds; + this.mEncryptionKeyIds = encryptionKeyIds; return this; } public Builder encryptionPassphrase(String encryptionPassphrase) { - this.encryptionPassphrase = encryptionPassphrase; + this.mEncryptionPassphrase = encryptionPassphrase; return this; } public Builder symmetricEncryptionAlgorithm(int symmetricEncryptionAlgorithm) { - this.symmetricEncryptionAlgorithm = symmetricEncryptionAlgorithm; + this.mSymmetricEncryptionAlgorithm = symmetricEncryptionAlgorithm; return this; } public Builder signatureKeyId(long signatureKeyId) { - this.signatureKeyId = signatureKeyId; + this.mSignatureKeyId = signatureKeyId; return this; } public Builder signatureHashAlgorithm(int signatureHashAlgorithm) { - this.signatureHashAlgorithm = signatureHashAlgorithm; + this.mSignatureHashAlgorithm = signatureHashAlgorithm; return this; } public Builder signatureForceV3(boolean signatureForceV3) { - this.signatureForceV3 = signatureForceV3; + this.mSignatureForceV3 = signatureForceV3; return this; } public Builder signaturePassphrase(String signaturePassphrase) { - this.signaturePassphrase = signaturePassphrase; + this.mSignaturePassphrase = signaturePassphrase; return this; } @@ -176,14 +155,14 @@ public class PgpSignEncrypt { } public void updateProgress(int message, int current, int total) { - if (progress != null) { - progress.setProgress(message, current, total); + if (mProgress != null) { + mProgress.setProgress(message, current, total); } } public void updateProgress(int current, int total) { - if (progress != null) { - progress.setProgress(current, total); + if (mProgress != null) { + mProgress.setProgress(current, total); } } @@ -201,17 +180,17 @@ public class PgpSignEncrypt { throws IOException, PgpGeneralException, PGPException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException { - boolean enableSignature = signatureKeyId != Id.key.none; - boolean enableEncryption = (encryptionKeyIds.length != 0 || encryptionPassphrase != null); - boolean enableCompression = (enableEncryption && compressionId != Id.choice.compression.none); + boolean enableSignature = mSignatureKeyId != Id.key.none; + boolean enableEncryption = (mEncryptionKeyIds.length != 0 || mEncryptionPassphrase != null); + boolean enableCompression = (enableEncryption && mCompressionId != Id.choice.compression.none); Log.d(Constants.TAG, "enableSignature:" + enableSignature + "\nenableEncryption:" + enableEncryption + "\nenableCompression:" + enableCompression - + "\nenableAsciiArmorOutput:" + enableAsciiArmorOutput); + + "\nenableAsciiArmorOutput:" + mEnableAsciiArmorOutput); int signatureType; - if (enableAsciiArmorOutput && enableSignature && !enableEncryption && !enableCompression) { + if (mEnableAsciiArmorOutput && enableSignature && !enableEncryption && !enableCompression) { // for sign-only ascii text signatureType = PGPSignature.CANONICAL_TEXT_DOCUMENT; } else { @@ -220,12 +199,12 @@ public class PgpSignEncrypt { ArmoredOutputStream armorOut = null; OutputStream out; - if (enableAsciiArmorOutput) { - armorOut = new ArmoredOutputStream(outStream); - armorOut.setHeader("Version", PgpHelper.getFullVersion(context)); + if (mEnableAsciiArmorOutput) { + armorOut = new ArmoredOutputStream(mOutStream); + armorOut.setHeader("Version", PgpHelper.getFullVersion(mContext)); out = armorOut; } else { - out = outStream; + out = mOutStream; } /* Get keys for signature generation for later usage */ @@ -233,25 +212,25 @@ public class PgpSignEncrypt { PGPSecretKeyRing signingKeyRing = null; PGPPrivateKey signaturePrivateKey = null; if (enableSignature) { - signingKeyRing = ProviderHelper.getPGPSecretKeyRingByKeyId(context, signatureKeyId); - signingKey = PgpKeyHelper.getSigningKey(context, signatureKeyId); + signingKeyRing = ProviderHelper.getPGPSecretKeyRingByKeyId(mContext, mSignatureKeyId); + signingKey = PgpKeyHelper.getSigningKey(mContext, mSignatureKeyId); if (signingKey == null) { - throw new PgpGeneralException(context.getString(R.string.error_signature_failed)); + throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed)); } - if (signaturePassphrase == null) { + if (mSignaturePassphrase == null) { throw new PgpGeneralException( - context.getString(R.string.error_no_signature_passphrase)); + mContext.getString(R.string.error_no_signature_passphrase)); } updateProgress(R.string.progress_extracting_signature_key, 0, 100); PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( - Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(signaturePassphrase.toCharArray()); + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(mSignaturePassphrase.toCharArray()); signaturePrivateKey = signingKey.extractPrivateKey(keyDecryptor); if (signaturePrivateKey == null) { throw new PgpGeneralException( - context.getString(R.string.error_could_not_extract_private_key)); + mContext.getString(R.string.error_could_not_extract_private_key)); } } updateProgress(R.string.progress_preparing_streams, 5, 100); @@ -261,23 +240,23 @@ public class PgpSignEncrypt { if (enableEncryption) { // has Integrity packet enabled! JcePGPDataEncryptorBuilder encryptorBuilder = - new JcePGPDataEncryptorBuilder(symmetricEncryptionAlgorithm) + new JcePGPDataEncryptorBuilder(mSymmetricEncryptionAlgorithm) .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME) .setWithIntegrityPacket(true); cPk = new PGPEncryptedDataGenerator(encryptorBuilder); - if (encryptionKeyIds.length == 0) { + if (mEncryptionKeyIds.length == 0) { // Symmetric encryption Log.d(Constants.TAG, "encryptionKeyIds length is 0 -> symmetric encryption"); JcePBEKeyEncryptionMethodGenerator symmetricEncryptionGenerator = - new JcePBEKeyEncryptionMethodGenerator(encryptionPassphrase.toCharArray()); + new JcePBEKeyEncryptionMethodGenerator(mEncryptionPassphrase.toCharArray()); cPk.addMethod(symmetricEncryptionGenerator); } else { // Asymmetric encryption - for (long id : encryptionKeyIds) { - PGPPublicKey key = PgpKeyHelper.getEncryptPublicKey(context, id); + for (long id : mEncryptionKeyIds) { + PGPPublicKey key = PgpKeyHelper.getEncryptPublicKey(mContext, id); if (key != null) { JcePublicKeyKeyEncryptionMethodGenerator pubKeyEncryptionGenerator = new JcePublicKeyKeyEncryptionMethodGenerator(key); @@ -295,10 +274,10 @@ public class PgpSignEncrypt { // content signer based on signing key algorithm and chosen hash algorithm JcaPGPContentSignerBuilder contentSignerBuilder = new JcaPGPContentSignerBuilder( - signingKey.getPublicKey().getAlgorithm(), signatureHashAlgorithm) + signingKey.getPublicKey().getAlgorithm(), mSignatureHashAlgorithm) .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); - if (signatureForceV3) { + if (mSignatureForceV3) { signatureV3Generator = new PGPV3SignatureGenerator(contentSignerBuilder); signatureV3Generator.init(signatureType, signaturePrivateKey); } else { @@ -322,14 +301,14 @@ public class PgpSignEncrypt { encryptionOut = cPk.open(out, new byte[1 << 16]); if (enableCompression) { - compressGen = new PGPCompressedDataGenerator(compressionId); + compressGen = new PGPCompressedDataGenerator(mCompressionId); bcpgOut = new BCPGOutputStream(compressGen.open(encryptionOut)); } else { bcpgOut = new BCPGOutputStream(encryptionOut); } if (enableSignature) { - if (signatureForceV3) { + if (mSignatureForceV3) { signatureV3Generator.generateOnePassVersion(false).encode(bcpgOut); } else { signatureGenerator.generateOnePassVersion(false).encode(bcpgOut); @@ -345,13 +324,13 @@ public class PgpSignEncrypt { long progress = 0; int n; byte[] buffer = new byte[1 << 16]; - InputStream in = data.getInputStream(); + InputStream in = mData.getInputStream(); while ((n = in.read(buffer)) > 0) { pOut.write(buffer, 0, n); // update signature buffer if signature is requested if (enableSignature) { - if (signatureForceV3) { + if (mSignatureForceV3) { signatureV3Generator.update(buffer, 0, n); } else { signatureGenerator.update(buffer, 0, n); @@ -359,26 +338,26 @@ public class PgpSignEncrypt { } progress += n; - if (data.getSize() != 0) { - updateProgress((int) (20 + (95 - 20) * progress / data.getSize()), 100); + if (mData.getSize() != 0) { + updateProgress((int) (20 + (95 - 20) * progress / mData.getSize()), 100); } } literalGen.close(); - } else if (enableAsciiArmorOutput && enableSignature && !enableEncryption && !enableCompression) { + } else if (mEnableAsciiArmorOutput && enableSignature && !enableEncryption && !enableCompression) { /* sign-only of ascii text */ updateProgress(R.string.progress_signing, 40, 100); // write directly on armor output stream - armorOut.beginClearText(signatureHashAlgorithm); + armorOut.beginClearText(mSignatureHashAlgorithm); - InputStream in = data.getInputStream(); + InputStream in = mData.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); final byte[] newline = "\r\n".getBytes("UTF-8"); - if (signatureForceV3) { + if (mSignatureForceV3) { processLine(reader.readLine(), armorOut, signatureV3Generator); } else { processLine(reader.readLine(), armorOut, signatureGenerator); @@ -395,7 +374,7 @@ public class PgpSignEncrypt { armorOut.write(newline); // update signature buffer with input line - if (signatureForceV3) { + if (mSignatureForceV3) { signatureV3Generator.update(newline); processLine(line, armorOut, signatureV3Generator); } else { @@ -415,7 +394,7 @@ public class PgpSignEncrypt { if (enableSignature) { updateProgress(R.string.progress_generating_signature, 95, 100); - if (signatureForceV3) { + if (mSignatureForceV3) { signatureV3Generator.generate().encode(pOut); } else { signatureGenerator.generate().encode(pOut); @@ -432,12 +411,12 @@ public class PgpSignEncrypt { encryptionOut.close(); } - if (enableAsciiArmorOutput) { + if (mEnableAsciiArmorOutput) { armorOut.close(); } out.close(); - outStream.close(); + mOutStream.close(); updateProgress(R.string.progress_done, 100, 100); } @@ -449,35 +428,36 @@ public class PgpSignEncrypt { SignatureException { OutputStream out; - if (enableAsciiArmorOutput) { + if (mEnableAsciiArmorOutput) { // Ascii Armor (Radix-64) - ArmoredOutputStream armorOut = new ArmoredOutputStream(outStream); - armorOut.setHeader("Version", PgpHelper.getFullVersion(context)); + ArmoredOutputStream armorOut = new ArmoredOutputStream(mOutStream); + armorOut.setHeader("Version", PgpHelper.getFullVersion(mContext)); out = armorOut; } else { - out = outStream; + out = mOutStream; } - if (signatureKeyId == 0) { - throw new PgpGeneralException(context.getString(R.string.error_no_signature_key)); + if (mSignatureKeyId == 0) { + throw new PgpGeneralException(mContext.getString(R.string.error_no_signature_key)); } - PGPSecretKeyRing signingKeyRing = ProviderHelper.getPGPSecretKeyRingByKeyId(context, signatureKeyId); - PGPSecretKey signingKey = PgpKeyHelper.getSigningKey(context, signatureKeyId); + PGPSecretKeyRing signingKeyRing = + ProviderHelper.getPGPSecretKeyRingByKeyId(mContext, mSignatureKeyId); + PGPSecretKey signingKey = PgpKeyHelper.getSigningKey(mContext, mSignatureKeyId); if (signingKey == null) { - throw new PgpGeneralException(context.getString(R.string.error_signature_failed)); + throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed)); } - if (signaturePassphrase == null) { - throw new PgpGeneralException(context.getString(R.string.error_no_signature_passphrase)); + if (mSignaturePassphrase == null) { + throw new PgpGeneralException(mContext.getString(R.string.error_no_signature_passphrase)); } PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( - Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(signaturePassphrase.toCharArray()); + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(mSignaturePassphrase.toCharArray()); PGPPrivateKey signaturePrivateKey = signingKey.extractPrivateKey(keyDecryptor); if (signaturePrivateKey == null) { throw new PgpGeneralException( - context.getString(R.string.error_could_not_extract_private_key)); + mContext.getString(R.string.error_could_not_extract_private_key)); } updateProgress(R.string.progress_preparing_streams, 0, 100); @@ -490,12 +470,12 @@ public class PgpSignEncrypt { // content signer based on signing key algorithm and chosen hash algorithm JcaPGPContentSignerBuilder contentSignerBuilder = new JcaPGPContentSignerBuilder(signingKey - .getPublicKey().getAlgorithm(), signatureHashAlgorithm) + .getPublicKey().getAlgorithm(), mSignatureHashAlgorithm) .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); PGPSignatureGenerator signatureGenerator = null; PGPV3SignatureGenerator signatureV3Generator = null; - if (signatureForceV3) { + if (mSignatureForceV3) { signatureV3Generator = new PGPV3SignatureGenerator(contentSignerBuilder); signatureV3Generator.init(type, signaturePrivateKey); } else { @@ -510,7 +490,7 @@ public class PgpSignEncrypt { updateProgress(R.string.progress_signing, 40, 100); - InputStream inStream = data.getInputStream(); + InputStream inStream = mData.getInputStream(); // if (binary) { // byte[] buffer = new byte[1 << 16]; // int n = 0; @@ -527,7 +507,7 @@ public class PgpSignEncrypt { String line; while ((line = reader.readLine()) != null) { - if (signatureForceV3) { + if (mSignatureForceV3) { processLine(line, null, signatureV3Generator); signatureV3Generator.update(newline); } else { @@ -538,13 +518,13 @@ public class PgpSignEncrypt { // } BCPGOutputStream bOut = new BCPGOutputStream(out); - if (signatureForceV3) { + if (mSignatureForceV3) { signatureV3Generator.generate().encode(bOut); } else { signatureGenerator.generate().encode(bOut); } out.close(); - outStream.close(); + mOutStream.close(); updateProgress(R.string.progress_done, 100, 100); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java index e18eb0d6d..309f1dc15 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java @@ -1,33 +1,24 @@ -package org.sufficientlysecure.keychain.pgp; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.text.DateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.Vector; +/* + * Copyright (C) 2012-2014 Dominik Schürmann + * Copyright (C) 2010 Thialfihar + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; +package org.sufficientlysecure.keychain.pgp; import org.spongycastle.asn1.DERObjectIdentifier; -import org.spongycastle.asn1.x509.AuthorityKeyIdentifier; -import org.spongycastle.asn1.x509.BasicConstraints; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.SubjectKeyIdentifier; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509Name; +import org.spongycastle.asn1.x509.*; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPPrivateKey; import org.spongycastle.openpgp.PGPPublicKey; @@ -38,30 +29,38 @@ import org.spongycastle.x509.extension.SubjectKeyIdentifierStructure; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.util.Log; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import java.io.IOException; +import java.math.BigInteger; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.text.DateFormat; +import java.util.Date; +import java.util.Iterator; +import java.util.Vector; + public class PgpToX509 { - public final static String DN_COMMON_PART_O = "OpenPGP to X.509 Bridge"; - public final static String DN_COMMON_PART_OU = "OpenPGP Keychain cert"; + public static final String DN_COMMON_PART_O = "OpenPGP to X.509 Bridge"; + public static final String DN_COMMON_PART_OU = "OpenPGP Keychain cert"; /** * Creates a self-signed certificate from a public and private key. The (critical) key-usage * extension is set up with: digital signature, non-repudiation, key-encipherment, key-agreement * and certificate-signing. The (non-critical) Netscape extension is set up with: SSL client and * S/MIME. A URI subjectAltName may also be set up. - * - * @param pubKey - * public key - * @param privKey - * private key - * @param subject - * subject (and issuer) DN for this certificate, RFC 2253 format preferred. - * @param startDate - * date from which the certificate will be valid (defaults to current date and time - * if null) - * @param endDate - * date until which the certificate will be valid (defaults to current date and time - * if null) * - * @param subjAltNameURI - * URI to be placed in subjectAltName + * + * @param pubKey public key + * @param privKey private key + * @param subject subject (and issuer) DN for this certificate, RFC 2253 format preferred. + * @param startDate date from which the certificate will be valid (defaults to current date and time + * if null) + * @param endDate date until which the certificate will be valid (defaults to current date and time + * if null) * + * @param subjAltNameURI URI to be placed in subjectAltName * @return self-signed certificate * @throws InvalidKeyException * @throws SignatureException @@ -70,11 +69,10 @@ public class PgpToX509 { * @throws NoSuchProviderException * @throws CertificateException * @throws Exception - * * @author Bruno Harbulot */ public static X509Certificate createSelfSignedCert(PublicKey pubKey, PrivateKey privKey, - X509Name subject, Date startDate, Date endDate, String subjAltNameURI) + X509Name subject, Date startDate, Date endDate, String subjAltNameURI) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException { @@ -171,15 +169,12 @@ public class PgpToX509 { /** * Creates a self-signed certificate from a PGP Secret Key. - * - * @param pgpSecKey - * PGP Secret Key (from which one can extract the public and private keys and other - * attributes). - * @param pgpPrivKey - * PGP Private Key corresponding to the Secret Key (password callbacks should be done - * before calling this method) - * @param subjAltNameURI - * optional URI to embed in the subject alternative-name + * + * @param pgpSecKey PGP Secret Key (from which one can extract the public and private keys and other + * attributes). + * @param pgpPrivKey PGP Private Key corresponding to the Secret Key (password callbacks should be done + * before calling this method) + * @param subjAltNameURI optional URI to embed in the subject alternative-name * @return self-signed certificate * @throws PGPException * @throws NoSuchProviderException @@ -187,11 +182,10 @@ public class PgpToX509 { * @throws NoSuchAlgorithmException * @throws SignatureException * @throws CertificateException - * * @author Bruno Harbulot */ public static X509Certificate createSelfSignedCert(PGPSecretKey pgpSecKey, - PGPPrivateKey pgpPrivKey, String subjAltNameURI) throws PGPException, + PGPPrivateKey pgpPrivKey, String subjAltNameURI) throws PGPException, NoSuchProviderException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException { // get public key from secret key @@ -213,7 +207,7 @@ public class PgpToX509 { x509NameValues.add(DN_COMMON_PART_OU); for (@SuppressWarnings("unchecked") - Iterator it = (Iterator) pgpSecKey.getUserIDs(); it.hasNext();) { + Iterator it = (Iterator) pgpSecKey.getUserIDs(); it.hasNext(); ) { Object attrib = it.next(); x509NameOids.add(X509Name.CN); x509NameValues.add("CryptoCall"); @@ -225,7 +219,7 @@ public class PgpToX509 { */ Log.d(Constants.TAG, "User attributes: "); for (@SuppressWarnings("unchecked") - Iterator it = (Iterator) pgpSecKey.getUserAttributes(); it.hasNext();) { + Iterator it = (Iterator) pgpSecKey.getUserAttributes(); it.hasNext(); ) { Object attrib = it.next(); Log.d(Constants.TAG, " - " + attrib + " -- " + attrib.getClass()); } @@ -261,9 +255,8 @@ public class PgpToX509 { * This is a password callback handler that will fill in a password automatically. Useful to * configure passwords in advance, but should be used with caution depending on how much you * allow passwords to be stored within your application. - * + * * @author Bruno Harbulot. - * */ public final static class PredefinedPasswordCallbackHandler implements CallbackHandler { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/NoAsymmetricEncryptionException.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/NoAsymmetricEncryptionException.java index 92542fa35..23c4bbbd9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/NoAsymmetricEncryptionException.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/NoAsymmetricEncryptionException.java @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2010 Thialfihar + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.sufficientlysecure.keychain.pgp.exception; public class NoAsymmetricEncryptionException extends Exception { @@ -6,4 +23,4 @@ public class NoAsymmetricEncryptionException extends Exception { public NoAsymmetricEncryptionException() { super(); } -} \ No newline at end of file +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/PgpGeneralException.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/PgpGeneralException.java index 36c663727..bb80d27ee 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/PgpGeneralException.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/exception/PgpGeneralException.java @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2010 Thialfihar + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.sufficientlysecure.keychain.pgp.exception; public class PgpGeneralException extends Exception { @@ -6,4 +23,4 @@ public class PgpGeneralException extends Exception { public PgpGeneralException(String message) { super(message); } -} \ No newline at end of file +} -- cgit v1.2.3 From 2d0817bd742e43cd69ece46bfaee0c62962993c9 Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 23:03:08 +0200 Subject: final code style changes --- .../compatibility/DialogFragmentWorkaround.java | 5 +- .../keychain/pgp/PgpDecryptVerify.java | 17 ++++-- .../keychain/pgp/PgpImportExport.java | 6 +- .../keychain/pgp/PgpKeyOperation.java | 9 ++- .../sufficientlysecure/keychain/pgp/PgpToX509.java | 14 ++--- .../keychain/provider/KeychainContract.java | 35 ++++++++--- .../keychain/provider/KeychainDatabase.java | 9 ++- .../keychain/provider/KeychainProvider.java | 28 ++++----- .../provider/KeychainServiceBlobContract.java | 3 +- .../provider/KeychainServiceBlobDatabase.java | 1 - .../provider/KeychainServiceBlobProvider.java | 40 +++++++----- .../keychain/provider/ProviderHelper.java | 71 +++++++++++----------- 12 files changed, 132 insertions(+), 106 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/DialogFragmentWorkaround.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/DialogFragmentWorkaround.java index a209f16cf..36f7fd23b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/DialogFragmentWorkaround.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/compatibility/DialogFragmentWorkaround.java @@ -37,8 +37,9 @@ import android.os.Handler; * */ public class DialogFragmentWorkaround { - public static final SDKLevel17Interface INTERFACE = ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) ? new SDKLevel17Impl() - : new SDKLevelPriorLevel17Impl()); + public static final SDKLevel17Interface INTERFACE = + ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) ? new SDKLevel17Impl() + : new SDKLevelPriorLevel17Impl()); private static final int RUNNABLE_DELAY = 300; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java index d4ce3d352..571729bc5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerify.java @@ -288,9 +288,11 @@ public class PgpDecryptVerify { // if no passphrase was explicitly set try to get it from the cache service if (mPassphrase == null) { // returns "" if key has no passphrase - mPassphrase = PassphraseCacheService.getCachedPassphrase(mContext, encData.getKeyID()); + mPassphrase = + PassphraseCacheService.getCachedPassphrase(mContext, encData.getKeyID()); - // if passphrase was not cached, return here indicating that a passphrase is missing! + // if passphrase was not cached, return here + // indicating that a passphrase is missing! if (mPassphrase == null) { returnData.setKeyPassphraseNeeded(true); return returnData; @@ -384,7 +386,8 @@ public class PgpDecryptVerify { signatureResult.setKeyId(signatureKeyId); if (signature != null) { - JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider = new JcaPGPContentVerifierBuilderProvider() + JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider = + new JcaPGPContentVerifierBuilderProvider() .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); signature.init(contentVerifierBuilderProvider, signatureKey); @@ -613,7 +616,8 @@ public class PgpDecryptVerify { return returnData; } - private static boolean verifyKeyBinding(Context context, PGPSignature signature, PGPPublicKey signatureKey) { + private static boolean verifyKeyBinding(Context context, + PGPSignature signature, PGPPublicKey signatureKey) { long signatureKeyId = signature.getKeyID(); boolean validKeyBinding = false; @@ -648,7 +652,8 @@ public class PgpDecryptVerify { //about keys without subkey signing. Can't get it to import a slightly broken one //either, so we will err on bad subkey binding here. PGPSignature sig = itr.next(); - if (sig.getKeyID() == masterPublicKey.getKeyID() && sig.getSignatureType() == PGPSignature.SUBKEY_BINDING) { + if (sig.getKeyID() == masterPublicKey.getKeyID() && + sig.getSignatureType() == PGPSignature.SUBKEY_BINDING) { //check and if ok, check primary key binding. try { sig.init(contentVerifierBuilderProvider, masterPublicKey); @@ -680,7 +685,7 @@ public class PgpDecryptVerify { } private static boolean verifyPrimaryKeyBinding(PGPSignatureSubpacketVector pkts, - PGPPublicKey masterPublicKey, PGPPublicKey signingPublicKey) { + PGPPublicKey masterPublicKey, PGPPublicKey signingPublicKey) { boolean validPrimaryKeyBinding = false; JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider = new JcaPGPContentVerifierBuilderProvider() diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 4a97eb825..dbfa521e5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -52,7 +52,8 @@ public class PgpImportExport { this.mProgress = progress; } - public PgpImportExport(Context context, ProgressDialogUpdater progress, KeychainServiceListener keychainListener) { + public PgpImportExport(Context context, + ProgressDialogUpdater progress, KeychainServiceListener keychainListener) { super(); this.mContext = context; this.mProgress = progress; @@ -252,8 +253,9 @@ public class PgpImportExport { } newPubRing = PGPPublicKeyRing.insertPublicKey(newPubRing, key); } - if (newPubRing != null) + if (newPubRing != null) { ProviderHelper.saveKeyRing(mContext, newPubRing); + } // TODO: remove status returns, use exceptions! status = Id.return_value.ok; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index 84d772846..c7ec02d7d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -287,7 +287,8 @@ public class PgpKeyOperation { long numDays = (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000); if (numDays <= 0) { - throw new PgpGeneralException(mContext.getString(R.string.error_expiry_must_come_after_creation)); + throw new PgpGeneralException( + mContext.getString(R.string.error_expiry_must_come_after_creation)); } hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400); } else { @@ -336,8 +337,10 @@ public class PgpKeyOperation { keyFlags = 0; usageId = keysUsages.get(i); - canSign = (usageId == Id.choice.usage.sign_only || usageId == Id.choice.usage.sign_and_encrypt); - canEncrypt = (usageId == Id.choice.usage.encrypt_only || usageId == Id.choice.usage.sign_and_encrypt); + canSign = + (usageId == Id.choice.usage.sign_only || usageId == Id.choice.usage.sign_and_encrypt); + canEncrypt = + (usageId == Id.choice.usage.encrypt_only || usageId == Id.choice.usage.sign_and_encrypt); if (canSign) { Date todayDate = new Date(); //both sig times the same keyFlags |= KeyFlags.SIGN_DATA; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java index 309f1dc15..54601173d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpToX509.java @@ -258,10 +258,10 @@ public class PgpToX509 { * * @author Bruno Harbulot. */ - public final static class PredefinedPasswordCallbackHandler implements CallbackHandler { + public static final class PredefinedPasswordCallbackHandler implements CallbackHandler { - private char[] password; - private String prompt; + private char[] mPassword; + private String mPrompt; public PredefinedPasswordCallbackHandler(String password) { this(password == null ? null : password.toCharArray(), null); @@ -276,16 +276,16 @@ public class PgpToX509 { } public PredefinedPasswordCallbackHandler(char[] password, String prompt) { - this.password = password; - this.prompt = prompt; + this.mPassword = password; + this.mPrompt = prompt; } public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof PasswordCallback) { PasswordCallback pwCallback = (PasswordCallback) callback; - if ((this.prompt == null) || (this.prompt.equals(pwCallback.getPrompt()))) { - pwCallback.setPassword(this.password); + if ((this.mPrompt == null) || (this.mPrompt.equals(pwCallback.getPrompt()))) { + pwCallback.setPassword(this.mPassword); } } else { throw new UnsupportedCallbackException(callback, "Unrecognised callback."); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index d9356951e..5f2354c24 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -17,10 +17,9 @@ package org.sufficientlysecure.keychain.provider; -import org.sufficientlysecure.keychain.Constants; - import android.net.Uri; import android.provider.BaseColumns; +import org.sufficientlysecure.keychain.Constants; public class KeychainContract { @@ -94,10 +93,14 @@ public class KeychainContract { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() .appendPath(BASE_KEY_RINGS).build(); - /** Use if multiple items get returned */ + /** + * Use if multiple items get returned + */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.key_ring"; - /** Use if a single item is returned */ + /** + * Use if a single item is returned + */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.key_ring"; public static Uri buildUnifiedKeyRingsUri() { @@ -165,10 +168,14 @@ public class KeychainContract { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() .appendPath(BASE_KEY_RINGS).build(); - /** Use if multiple items get returned */ + /** + * Use if multiple items get returned + */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.key"; - /** Use if a single item is returned */ + /** + * Use if a single item is returned + */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.key"; public static Uri buildPublicKeysUri(String keyRingRowId) { @@ -204,10 +211,14 @@ public class KeychainContract { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() .appendPath(BASE_KEY_RINGS).build(); - /** Use if multiple items get returned */ + /** + * Use if multiple items get returned + */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.user_id"; - /** Use if a single item is returned */ + /** + * Use if a single item is returned + */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.user_id"; public static Uri buildPublicUserIdsUri(String keyRingRowId) { @@ -243,10 +254,14 @@ public class KeychainContract { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() .appendPath(BASE_API_APPS).build(); - /** Use if multiple items get returned */ + /** + * Use if multiple items get returned + */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api_apps"; - /** Use if a single item is returned */ + /** + * Use if a single item is returned + */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api_apps"; public static Uri buildIdUri(String rowId) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java index 5f18ed6f9..031a7d5ae 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java @@ -17,6 +17,10 @@ package org.sufficientlysecure.keychain.provider; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.provider.BaseColumns; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingsColumns; @@ -24,11 +28,6 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeysColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIdsColumns; import org.sufficientlysecure.keychain.util.Log; -import android.content.Context; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.provider.BaseColumns; - public class KeychainDatabase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "apg.db"; private static final int DATABASE_VERSION = 7; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index fdc4b7bda..748aaeb1b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -17,21 +17,6 @@ package org.sufficientlysecure.keychain.provider; -import java.util.Arrays; -import java.util.HashMap; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingsColumns; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; -import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeysColumns; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; -import org.sufficientlysecure.keychain.provider.KeychainContract.UserIdsColumns; -import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; -import org.sufficientlysecure.keychain.util.Log; - import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; @@ -43,6 +28,13 @@ import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.provider.KeychainContract.*; +import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; +import org.sufficientlysecure.keychain.util.Log; + +import java.util.Arrays; +import java.util.HashMap; public class KeychainProvider extends ContentProvider { // public static final String ACTION_BROADCAST_DATABASE_CHANGE = Constants.PACKAGE_NAME @@ -367,7 +359,8 @@ public class KeychainProvider extends ContentProvider { projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID); projectionMap.put(KeyRingsColumns.KEY_RING_DATA, Tables.KEY_RINGS + "." + KeyRingsColumns.KEY_RING_DATA); - projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID); + projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." + + KeyRingsColumns.MASTER_KEY_ID); // TODO: deprecated master key id //projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEYS + "." + KeysColumns.KEY_ID); @@ -483,7 +476,8 @@ public class KeychainProvider extends ContentProvider { groupBy = Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID; if (TextUtils.isEmpty(sortOrder)) { - sortOrder = KeyRings.TYPE + " DESC, " + Tables.USER_IDS + "." + UserIdsColumns.USER_ID + " ASC"; + sortOrder = KeyRings.TYPE + " DESC, " + + Tables.USER_IDS + "." + UserIdsColumns.USER_ID + " ASC"; } break; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobContract.java index a879d60a8..701ffc6af 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobContract.java @@ -17,10 +17,9 @@ package org.sufficientlysecure.keychain.provider; -import org.sufficientlysecure.keychain.Constants; - import android.net.Uri; import android.provider.BaseColumns; +import org.sufficientlysecure.keychain.Constants; public class KeychainServiceBlobContract { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobDatabase.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobDatabase.java index fcee76fd7..da1bcb2d9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobDatabase.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobDatabase.java @@ -22,7 +22,6 @@ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; - import org.sufficientlysecure.keychain.provider.KeychainServiceBlobContract.BlobsColumns; public class KeychainServiceBlobDatabase extends SQLiteOpenHelper { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java index 86eccbe37..6ac61e157 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java @@ -18,11 +18,6 @@ package org.sufficientlysecure.keychain.provider; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.provider.KeychainServiceBlobContract.Blobs; -import org.sufficientlysecure.keychain.provider.KeychainServiceBlobContract.BlobsColumns; -import org.sufficientlysecure.keychain.util.Log; - import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; @@ -31,7 +26,10 @@ import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; - +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.provider.KeychainServiceBlobContract.Blobs; +import org.sufficientlysecure.keychain.provider.KeychainServiceBlobContract.BlobsColumns; +import org.sufficientlysecure.keychain.util.Log; import java.io.File; import java.io.FileNotFoundException; @@ -55,7 +53,9 @@ public class KeychainServiceBlobProvider extends ContentProvider { return true; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public Uri insert(Uri uri, ContentValues ignored) { // ContentValues are actually ignored, because we want to store a blob with no more @@ -74,7 +74,9 @@ public class KeychainServiceBlobProvider extends ContentProvider { return Uri.withAppendedPath(insertedUri, password); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws SecurityException, FileNotFoundException { @@ -91,9 +93,9 @@ public class KeychainServiceBlobProvider extends ContentProvider { // get the data SQLiteDatabase db = mBlobDatabase.getReadableDatabase(); - Cursor result = db.query(KeychainServiceBlobDatabase.TABLE, new String[] { BaseColumns._ID }, + Cursor result = db.query(KeychainServiceBlobDatabase.TABLE, new String[]{BaseColumns._ID}, BaseColumns._ID + " = ? and " + BlobsColumns.KEY + " = ?", - new String[] { id, key }, null, null, null); + new String[]{id, key}, null, null, null); if (result.getCount() == 0) { // either the key is wrong or no id exists @@ -124,26 +126,34 @@ public class KeychainServiceBlobProvider extends ContentProvider { return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public String getType(Uri uri) { return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, - String sortOrder) { + String sortOrder) { return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 1c05344d6..db2c57207 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -17,18 +17,13 @@ package org.sufficientlysecure.keychain.provider; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; - +import android.content.*; +import android.database.Cursor; +import android.database.DatabaseUtils; +import android.net.Uri; +import android.os.RemoteException; import org.spongycastle.bcpg.ArmoredOutputStream; -import org.spongycastle.openpgp.PGPKeyRing; -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPSignature; +import org.spongycastle.openpgp.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.pgp.PgpConversionHelper; import org.sufficientlysecure.keychain.pgp.PgpHelper; @@ -42,15 +37,10 @@ import org.sufficientlysecure.keychain.service.remote.AppSettings; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; -import android.content.ContentProviderOperation; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.content.OperationApplicationException; -import android.database.Cursor; -import android.database.DatabaseUtils; -import android.net.Uri; -import android.os.RemoteException; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; public class ProviderHelper { @@ -111,7 +101,7 @@ public class ProviderHelper { public static PGPPublicKey getPGPPublicKeyByKeyId(Context context, long keyId) { PGPPublicKeyRing keyRing = getPGPPublicKeyRingByKeyId(context, keyId); - return (keyRing == null)? null : keyRing.getPublicKey(keyId); + return (keyRing == null) ? null : keyRing.getPublicKey(keyId); } /** @@ -162,7 +152,8 @@ public class ProviderHelper { // get current _ID of key long currentRowId = -1; - Cursor oldQuery = context.getContentResolver().query(deleteUri, new String[]{KeyRings._ID}, null, null, null); + Cursor oldQuery = context.getContentResolver() + .query(deleteUri, new String[]{KeyRings._ID}, null, null, null); if (oldQuery != null && oldQuery.moveToFirst()) { currentRowId = oldQuery.getLong(0); } else { @@ -178,10 +169,12 @@ public class ProviderHelper { ContentValues values = new ContentValues(); // use exactly the same _ID again to replace key in-place. - // NOTE: If we would not use the same _ID again, getting back to the ViewKeyActivity would result in Nullpointer, + // NOTE: If we would not use the same _ID again, + // getting back to the ViewKeyActivity would result in Nullpointer, // because the currently loaded key would be gone from the database - if (currentRowId != -1) + if (currentRowId != -1) { values.put(KeyRings._ID, currentRowId); + } values.put(KeyRings.MASTER_KEY_ID, masterKeyId); values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded()); @@ -205,8 +198,11 @@ public class ProviderHelper { ++userIdRank; } - for (PGPSignature certification : new IterableIterator(masterKey.getSignaturesOfType(PGPSignature.POSITIVE_CERTIFICATION))) { - //TODO: how to do this?? we need to verify the signatures again and again when they are displayed... + for (PGPSignature certification : + new IterableIterator( + masterKey.getSignaturesOfType(PGPSignature.POSITIVE_CERTIFICATION))) { + // TODO: how to do this?? + // we need to verify the signatures again and again when they are displayed... // if (certification.verify // operations.add(buildPublicKeyOperations(context, keyRingRowId, key, rank)); } @@ -233,7 +229,8 @@ public class ProviderHelper { // get current _ID of key long currentRowId = -1; - Cursor oldQuery = context.getContentResolver().query(deleteUri, new String[]{KeyRings._ID}, null, null, null); + Cursor oldQuery = context.getContentResolver() + .query(deleteUri, new String[]{KeyRings._ID}, null, null, null); if (oldQuery != null && oldQuery.moveToFirst()) { currentRowId = oldQuery.getLong(0); } else { @@ -249,10 +246,12 @@ public class ProviderHelper { ContentValues values = new ContentValues(); // use exactly the same _ID again to replace key in-place. - // NOTE: If we would not use the same _ID again, getting back to the ViewKeyActivity would result in Nullpointer, + // NOTE: If we would not use the same _ID again, + // getting back to the ViewKeyActivity would result in Nullpointer, // because the currently loaded key would be gone from the database - if (currentRowId != -1) + if (currentRowId != -1) { values.put(KeyRings._ID, currentRowId); + } values.put(KeyRings.MASTER_KEY_ID, masterKeyId); values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded()); @@ -289,7 +288,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing */ private static ContentProviderOperation buildPublicKeyOperations(Context context, - long keyRingRowId, PGPPublicKey key, int rank) throws IOException { + long keyRingRowId, PGPPublicKey key, int rank) throws IOException { ContentValues values = new ContentValues(); values.put(Keys.KEY_ID, key.getKeyID()); values.put(Keys.IS_MASTER_KEY, key.isMasterKey()); @@ -317,7 +316,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add PublicUserIds to database corresponding to a keyRing */ private static ContentProviderOperation buildPublicUserIdOperations(Context context, - long keyRingRowId, String userId, int rank) { + long keyRingRowId, String userId, int rank) { ContentValues values = new ContentValues(); values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId); values.put(UserIds.USER_ID, userId); @@ -332,7 +331,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add PGPSecretKey to database corresponding to a keyRing */ private static ContentProviderOperation buildSecretKeyOperations(Context context, - long keyRingRowId, PGPSecretKey key, int rank) throws IOException { + long keyRingRowId, PGPSecretKey key, int rank) throws IOException { ContentValues values = new ContentValues(); boolean hasPrivate = true; @@ -369,7 +368,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add SecretUserIds to database corresponding to a keyRing */ private static ContentProviderOperation buildSecretUserIdOperations(Context context, - long keyRingRowId, String userId, int rank) { + long keyRingRowId, String userId, int rank) { ContentValues values = new ContentValues(); values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId); values.put(UserIds.USER_ID, userId); @@ -413,10 +412,10 @@ public class ProviderHelper { ArrayList rowIds = new ArrayList(); if (cursor != null) { - int IdCol = cursor.getColumnIndex(KeyRings._ID); + int idCol = cursor.getColumnIndex(KeyRings._ID); if (cursor.moveToFirst()) { do { - rowIds.add(cursor.getLong(IdCol)); + rowIds.add(cursor.getLong(idCol)); } while (cursor.moveToNext()); } } @@ -496,7 +495,7 @@ public class ProviderHelper { + " AS sign_keys WHERE sign_keys." + Keys.KEY_RING_ROW_ID + " = " + KeychainDatabase.Tables.KEY_RINGS + "." + KeyRings._ID + " AND sign_keys." + Keys.CAN_SIGN + " = '1' AND " + Keys.IS_MASTER_KEY - + " = 1) AS sign",}; + + " = 1) AS sign", }; ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(queryUri, projection, null, null, null); -- cgit v1.2.3 From b12392594f54cac1ef8812c80decc315f70866db Mon Sep 17 00:00:00 2001 From: uberspot Date: Thu, 13 Mar 2014 23:52:21 +0200 Subject: Make email address less restrictive and add icon to show when it's correct --- .../keychain/ui/EditKeyActivity.java | 2 -- .../keychain/ui/widget/UserIdEditor.java | 37 ++++++++++++++++------ 2 files changed, 28 insertions(+), 11 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index a0186f08c..edf980773 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -600,8 +600,6 @@ public class EditKeyActivity extends ActionBarActivity { } catch (UserIdEditor.NoEmailException e) { throw new PgpGeneralException( this.getString(R.string.error_user_id_needs_an_email_address)); - } catch (UserIdEditor.InvalidEmailException e) { - throw new PgpGeneralException(e.getMessage()); } if (userId.equals("")) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java index d3c6f02fe..ed81b162e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java @@ -17,6 +17,8 @@ package org.sufficientlysecure.keychain.ui.widget; import android.content.Context; +import android.text.Editable; +import android.text.TextWatcher; import android.util.AttributeSet; import android.util.Patterns; import android.view.View; @@ -102,6 +104,31 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene (this.getContext(), android.R.layout.simple_dropdown_item_1line, ContactHelper.getMailAccounts(getContext()) )); + mEmail.addTextChangedListener(new TextWatcher(){ + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } + + @Override + public void afterTextChanged(Editable editable) { + String email = editable.toString(); + if (email.length() > 0) { + Matcher emailMatcher = Patterns.EMAIL_ADDRESS.matcher(email); + if (emailMatcher.matches()) { + mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, + android.R.drawable.presence_online, 0); + } else { + mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, + android.R.drawable.presence_offline, 0); + } + } else { + // remove drawable if email is empty + mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); + } + } + }); super.onFinishInflate(); } @@ -129,19 +156,11 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene } } - public String getValue() throws NoNameException, NoEmailException, InvalidEmailException { + public String getValue() throws NoNameException, NoEmailException { String name = ("" + mName.getText()).trim(); String email = ("" + mEmail.getText()).trim(); String comment = ("" + mComment.getText()).trim(); - if (email.length() > 0) { - Matcher emailMatcher = Patterns.EMAIL_ADDRESS.matcher(email); - if (!emailMatcher.matches()) { - throw new InvalidEmailException(getContext().getString(R.string.error_invalid_email, - email)); - } - } - String userId = name; if (comment.length() > 0) { userId += " (" + comment + ")"; -- cgit v1.2.3 From 985a6793c0fb8c5f28c229c9432303263704015e Mon Sep 17 00:00:00 2001 From: uberspot Date: Fri, 14 Mar 2014 00:59:10 +0200 Subject: Fix two bugs in ImportKeys screen (issue #416) --- .../org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java | 1 + .../keychain/ui/adapter/ImportKeysListServerLoader.java | 1 + 2 files changed, 2 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index 16776e121..0f05af447 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -152,6 +152,7 @@ public class ImportKeysAdapter extends ArrayAdapter { } LinearLayout ll = (LinearLayout) convertView.findViewById(R.id.list); + ll.removeAllViews(); if (entry.userIds.size() == 1) { ll.setVisibility(View.GONE); } else { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java index 1e96606a6..a4dd06e40 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListServerLoader.java @@ -89,6 +89,7 @@ public class ImportKeysListServerLoader try { ArrayList searchResult = server.search(query); + mEntryList.clear(); // add result to data mEntryList.addAll(searchResult); mEntryListWrapper = new AsyncTaskResultWrapper>(mEntryList, null); -- cgit v1.2.3 From e387dd7c54ddfdbe8379b57e00fed567510fd863 Mon Sep 17 00:00:00 2001 From: uberspot Date: Sat, 15 Mar 2014 01:51:01 +0200 Subject: Fix export for new unified key list #409 --- .../java/org/sufficientlysecure/keychain/Id.java | 1 + .../keychain/helper/ExportHelper.java | 34 ++++++----- .../keychain/pgp/PgpImportExport.java | 69 ++++++++++++---------- .../keychain/service/KeychainIntentService.java | 50 ++++++++-------- .../keychain/ui/EditKeyActivity.java | 6 +- .../keychain/ui/KeyListActivity.java | 5 +- .../keychain/ui/KeyListFragment.java | 18 ++++-- .../keychain/ui/ViewKeyActivity.java | 7 ++- 8 files changed, 111 insertions(+), 79 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Id.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Id.java index 1d79edd43..784ec340e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Id.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Id.java @@ -119,6 +119,7 @@ public final class Id { public static final int secret_key = 0x21070002; public static final int user_id = 0x21070003; public static final int key = 0x21070004; + public static final int public_secret_key = 0x21070005; } public static final class choice { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 557d75dbf..03cf936ee 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -30,12 +30,18 @@ import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment; import org.sufficientlysecure.keychain.util.Log; +import java.lang.reflect.Array; +import java.security.Provider; +import java.util.ArrayList; + public class ExportHelper { protected FileDialogFragment mFileDialog; protected String mExportFilename; @@ -62,8 +68,8 @@ public class ExportHelper { /** * Show dialog where to export keys */ - public void showExportKeysDialog(final long[] rowIds, final int keyType, - final String exportFilename) { + public void showExportKeysDialog(final long[] masterKeyIds, final int keyType, + final String exportFilename, final String checkboxString) { mExportFilename = exportFilename; // Message is received after file is selected @@ -72,9 +78,14 @@ public class ExportHelper { public void handleMessage(Message message) { if (message.what == FileDialogFragment.MESSAGE_OKAY) { Bundle data = message.getData(); + int type = keyType; mExportFilename = data.getString(FileDialogFragment.MESSAGE_DATA_FILENAME); - exportKeys(rowIds, keyType); + if( data.getBoolean(FileDialogFragment.MESSAGE_DATA_CHECKED) ) { + type = Id.type.public_secret_key; + } + + exportKeys(masterKeyIds, type); } } }; @@ -85,7 +96,7 @@ public class ExportHelper { DialogFragmentWorkaround.INTERFACE.runnableRunDelayed(new Runnable() { public void run() { String title = null; - if (rowIds == null) { + if (masterKeyIds == null) { // export all keys title = mActivity.getString(R.string.title_export_keys); } else { @@ -93,15 +104,10 @@ public class ExportHelper { title = mActivity.getString(R.string.title_export_key); } - String message = null; - if (keyType == Id.type.public_key) { - message = mActivity.getString(R.string.specify_file_to_export_to); - } else { - message = mActivity.getString(R.string.specify_file_to_export_secret_keys_to); - } + String message = mActivity.getString(R.string.specify_file_to_export_to); mFileDialog = FileDialogFragment.newInstance(messenger, title, message, - exportFilename, null); + exportFilename, checkboxString); mFileDialog.show(mActivity.getSupportFragmentManager(), "fileDialog"); } @@ -111,7 +117,7 @@ public class ExportHelper { /** * Export keys */ - public void exportKeys(long[] rowIds, int keyType) { + public void exportKeys(long[] masterKeyIds, int keyType) { Log.d(Constants.TAG, "exportKeys started"); // Send all information needed to service to export key in other thread @@ -125,10 +131,10 @@ public class ExportHelper { data.putString(KeychainIntentService.EXPORT_FILENAME, mExportFilename); data.putInt(KeychainIntentService.EXPORT_KEY_TYPE, keyType); - if (rowIds == null) { + if (masterKeyIds == null) { data.putBoolean(KeychainIntentService.EXPORT_ALL, true); } else { - data.putLongArray(KeychainIntentService.EXPORT_KEY_RING_ROW_ID, rowIds); + data.putLongArray(KeychainIntentService.EXPORT_KEY_RING_MASTER_KEY_ID, masterKeyIds); } intent.putExtra(KeychainIntentService.EXTRA_DATA, data); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index dbfa521e5..0e0fdec83 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -36,6 +36,7 @@ import org.sufficientlysecure.keychain.util.KeyServer.AddKeyException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.security.Provider; import java.util.ArrayList; import java.util.List; @@ -158,60 +159,68 @@ public class PgpImportExport { return returnData; } - public Bundle exportKeyRings(ArrayList keyRingRowIds, int keyType, + public Bundle exportKeyRings(ArrayList publicKeyRingMasterIds, ArrayList secretKeyRingMasterIds, OutputStream outStream) throws PgpGeneralException, PGPException, IOException { Bundle returnData = new Bundle(); - int rowIdsSize = keyRingRowIds.size(); + int masterKeyIdsSize = publicKeyRingMasterIds.size() + secretKeyRingMasterIds.size(); + int progress = 0; updateProgress( mContext.getResources().getQuantityString(R.plurals.progress_exporting_key, - rowIdsSize), 0, 100); + masterKeyIdsSize), 0, 100); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { throw new PgpGeneralException( mContext.getString(R.string.error_external_storage_not_ready)); } - // For each row id - for (int i = 0; i < rowIdsSize; ++i) { + // For each public masterKey id + for (long pubKeyMasterId : publicKeyRingMasterIds) { + progress++; // Create an output stream ArmoredOutputStream arOutStream = new ArmoredOutputStream(outStream); arOutStream.setHeader("Version", PgpHelper.getFullVersion(mContext)); - // If the keyType is secret get the PGPSecretKeyRing - // based on the row id and encode it to the output - if (keyType == Id.type.secret_key) { - updateProgress(i * 100 / rowIdsSize / 2, 100); - PGPSecretKeyRing secretKeyRing = - ProviderHelper.getPGPSecretKeyRingByRowId(mContext, keyRingRowIds.get(i)); + updateProgress(progress * 100 / masterKeyIdsSize, 100); + PGPPublicKeyRing publicKeyRing = + ProviderHelper.getPGPPublicKeyRingByMasterKeyId(mContext, pubKeyMasterId); - if (secretKeyRing != null) { - secretKeyRing.encode(arOutStream); - } - if (mKeychainServiceListener.hasServiceStopped()) { - arOutStream.close(); - return null; - } - } else { - updateProgress(i * 100 / rowIdsSize, 100); - PGPPublicKeyRing publicKeyRing = - ProviderHelper.getPGPPublicKeyRingByRowId(mContext, keyRingRowIds.get(i)); + if (publicKeyRing != null) { + publicKeyRing.encode(arOutStream); + } - if (publicKeyRing != null) { - publicKeyRing.encode(arOutStream); - } + if (mKeychainServiceListener.hasServiceStopped()) { + arOutStream.close(); + return null; + } - if (mKeychainServiceListener.hasServiceStopped()) { - arOutStream.close(); - return null; - } + arOutStream.close(); + } + + // For each secret masterKey id + for (long secretKeyMasterId : secretKeyRingMasterIds) { + progress++; + // Create an output stream + ArmoredOutputStream arOutStream = new ArmoredOutputStream(outStream); + arOutStream.setHeader("Version", PgpHelper.getFullVersion(mContext)); + + updateProgress(progress * 100 / masterKeyIdsSize, 100); + PGPSecretKeyRing secretKeyRing = + ProviderHelper.getPGPSecretKeyRingByMasterKeyId(mContext, secretKeyMasterId); + + if (secretKeyRing != null) { + secretKeyRing.encode(arOutStream); + } + if (mKeychainServiceListener.hasServiceStopped()) { + arOutStream.close(); + return null; } arOutStream.close(); } - returnData.putInt(KeychainIntentService.RESULT_EXPORT, rowIdsSize); + returnData.putInt(KeychainIntentService.RESULT_EXPORT, masterKeyIdsSize); updateProgress(R.string.progress_done, 100, 100); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 4e5812202..a44b121ec 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -131,7 +131,6 @@ public class KeychainIntentService extends IntentService public static final String EXPORT_KEY_TYPE = "export_key_type"; public static final String EXPORT_ALL = "export_all"; public static final String EXPORT_KEY_RING_MASTER_KEY_ID = "export_key_ring_id"; - public static final String EXPORT_KEY_RING_ROW_ID = "export_key_rind_row_id"; // upload key public static final String UPLOAD_KEY_SERVER = "upload_key_server"; @@ -660,16 +659,11 @@ public class KeychainIntentService extends IntentService if (data.containsKey(EXPORT_KEY_TYPE)) { keyType = data.getInt(EXPORT_KEY_TYPE); } - + long[] masterKeyIds = data.getLongArray(EXPORT_KEY_RING_MASTER_KEY_ID); String outputFile = data.getString(EXPORT_FILENAME); - long[] rowIds = new long[0]; - - // If not exporting all keys get the rowIds of the keys to export from the intent + // If not exporting all keys get the masterKeyIds of the keys to export from the intent boolean exportAll = data.getBoolean(EXPORT_ALL); - if (!exportAll) { - rowIds = data.getLongArray(EXPORT_KEY_RING_ROW_ID); - } /* Operation */ @@ -678,30 +672,38 @@ public class KeychainIntentService extends IntentService throw new PgpGeneralException(getString(R.string.error_external_storage_not_ready)); } - // OutputStream - FileOutputStream outStream = new FileOutputStream(outputFile); + ArrayList publicMasterKeyIds = new ArrayList(); + ArrayList secretMasterKeyIds = new ArrayList(); + ArrayList allPublicMasterKeyIds = ProviderHelper.getPublicKeyRingsMasterKeyIds(this); + ArrayList allSecretMasterKeyIds = ProviderHelper.getSecretKeyRingsMasterKeyIds(this); - ArrayList keyRingRowIds = new ArrayList(); if (exportAll) { - - // get all key ring row ids based on export type - if (keyType == Id.type.public_key) { - keyRingRowIds = ProviderHelper.getPublicKeyRingsRowIds(this); - } else { - keyRingRowIds = ProviderHelper.getSecretKeyRingsRowIds(this); + // get all public key ring MasterKey ids + if (keyType == Id.type.public_key || keyType == Id.type.public_secret_key) { + publicMasterKeyIds = allPublicMasterKeyIds; + } + // get all secret key ring MasterKey ids + if (keyType == Id.type.secret_key || keyType == Id.type.public_secret_key) { + secretMasterKeyIds = allSecretMasterKeyIds; } } else { - for (long rowId : rowIds) { - keyRingRowIds.add(rowId); + + for (long masterKeyId : masterKeyIds) { + if ((keyType == Id.type.public_key || keyType == Id.type.public_secret_key) + && allPublicMasterKeyIds.contains(masterKeyId)) { + publicMasterKeyIds.add(masterKeyId); + } + if ((keyType == Id.type.secret_key || keyType == Id.type.public_secret_key) + && allSecretMasterKeyIds.contains(masterKeyId)) { + secretMasterKeyIds.add(masterKeyId); + } } } - Bundle resultData; - PgpImportExport pgpImportExport = new PgpImportExport(this, this, this); - - resultData = pgpImportExport - .exportKeyRings(keyRingRowIds, keyType, outStream); + Bundle resultData = pgpImportExport + .exportKeyRings(publicMasterKeyIds, secretMasterKeyIds, + new FileOutputStream(outputFile)); if (mIsCanceled) { boolean isDeleted = new File(outputFile).delete(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index edf980773..7edb61b09 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -322,8 +322,10 @@ public class EditKeyActivity extends ActionBarActivity { cancelClicked(); return true; case R.id.menu_key_edit_export_file: - long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; - mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC); + long masterKeyId = ProviderHelper.getMasterKeyId(this, mDataUri); + long[] ids = new long[]{masterKeyId}; + mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC, + null); return true; case R.id.menu_key_edit_delete: { // Message is received after key is deleted diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 078b998e1..5ff4dbdeb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -58,8 +58,7 @@ public class KeyListActivity extends DrawerActivity { return true; case R.id.menu_key_list_export: - // TODO fix this for unified keylist - mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.Path.APP_DIR_FILE_PUB); + mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.Path.APP_DIR_FILE_PUB, null); return true; case R.id.menu_key_list_create: @@ -71,7 +70,7 @@ public class KeyListActivity extends DrawerActivity { return true; case R.id.menu_key_list_secret_export: - mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC); + mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC, null); return true; default: diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 5ac59965d..cac8b7046 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -49,6 +49,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; import org.sufficientlysecure.keychain.provider.KeychainDatabase; +import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.adapter.HighlightQueryCursorAdapter; import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; import org.sufficientlysecure.keychain.util.Log; @@ -183,13 +184,22 @@ public class KeyListFragment extends Fragment break; } case R.id.menu_key_list_multi_export: { - // todo: public/secret needs to be handled differently here ids = mStickyList.getWrappedList().getCheckedItemIds(); + long[] masterKeyIds = new long[2*ids.length]; + ArrayList allPubRowIds = + ProviderHelper.getPublicKeyRingsRowIds(getActivity()); + for (int i = 0; i < ids.length; i++) { + if (allPubRowIds.contains(ids[i])) { + masterKeyIds[i] = ProviderHelper.getPublicMasterKeyId(getActivity(), ids[i]); + } else { + masterKeyIds[i] = ProviderHelper.getSecretMasterKeyId(getActivity(), ids[i]); + } + } ExportHelper mExportHelper = new ExportHelper((ActionBarActivity) getActivity()); mExportHelper - .showExportKeysDialog(ids, - Id.type.public_key, - Constants.Path.APP_DIR_FILE_PUB); + .showExportKeysDialog(masterKeyIds, Id.type.public_key, + Constants.Path.APP_DIR_FILE_PUB, + getString(R.string.also_export_secret_keys)); break; } case R.id.menu_key_list_multi_select_all: { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index 93bb83003..c4097403c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -124,8 +124,11 @@ public class ViewKeyActivity extends ActionBarActivity { uploadToKeyserver(mDataUri); return true; case R.id.menu_key_view_export_file: - long[] ids = new long[]{Long.valueOf(mDataUri.getLastPathSegment())}; - mExportHelper.showExportKeysDialog(ids, Id.type.public_key, Constants.Path.APP_DIR_FILE_PUB); + long masterKeyId = + ProviderHelper.getPublicMasterKeyId(this, Long.valueOf(mDataUri.getLastPathSegment())); + long[] ids = new long[]{masterKeyId}; + mExportHelper.showExportKeysDialog(ids, Id.type.public_key, + Constants.Path.APP_DIR_FILE_PUB, null); return true; case R.id.menu_key_view_share_default_fingerprint: shareKey(mDataUri, true); -- cgit v1.2.3 From 0922a8cf0410fb7ea3e6cca131d834b71caaf22f Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 02:20:28 +0100 Subject: move fingerprint coloring into helper --- .../keychain/helper/OtherHelper.java | 62 ++++++++++++++++++++++ .../keychain/ui/CertifyKeyActivity.java | 1 + .../keychain/ui/ViewKeyMainFragment.java | 62 +--------------------- 3 files changed, 64 insertions(+), 61 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java index eb46a52e5..736bff02d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java @@ -17,7 +17,12 @@ package org.sufficientlysecure.keychain.helper; +import android.graphics.Color; import android.os.Bundle; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.style.ForegroundColorSpan; + import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.util.Log; @@ -60,6 +65,63 @@ public class OtherHelper { } } + public static SpannableStringBuilder colorizeFingerprint(String fingerprint) { + SpannableStringBuilder sb = new SpannableStringBuilder(fingerprint); + try { + // for each 4 characters of the fingerprint + 1 space + for (int i = 0; i < fingerprint.length(); i += 5) { + int spanEnd = Math.min(i + 4, fingerprint.length()); + String fourChars = fingerprint.substring(i, spanEnd); + + int raw = Integer.parseInt(fourChars, 16); + byte[] bytes = {(byte) ((raw >> 8) & 0xff - 128), (byte) (raw & 0xff - 128)}; + int[] color = OtherHelper.getRgbForData(bytes); + int r = color[0]; + int g = color[1]; + int b = color[2]; + + // we cannot change black by multiplication, so adjust it to an almost-black grey, + // which will then be brightened to the minimal brightness level + if (r == 0 && g == 0 && b == 0) { + r = 1; + g = 1; + b = 1; + } + + // Convert rgb to brightness + double brightness = 0.2126 * r + 0.7152 * g + 0.0722 * b; + + // If a color is too dark to be seen on black, + // then brighten it up to a minimal brightness. + if (brightness < 80) { + double factor = 80.0 / brightness; + r = Math.min(255, (int) (r * factor)); + g = Math.min(255, (int) (g * factor)); + b = Math.min(255, (int) (b * factor)); + + // If it is too light, then darken it to a respective maximal brightness. + } else if (brightness > 180) { + double factor = 180.0 / brightness; + r = (int) (r * factor); + g = (int) (g * factor); + b = (int) (b * factor); + } + + // Create a foreground color with the 3 digest integers as RGB + // and then converting that int to hex to use as a color + sb.setSpan(new ForegroundColorSpan(Color.rgb(r, g, b)), + i, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE); + } + } catch (Exception e) { + Log.e(Constants.TAG, "Colorization failed", e); + // if anything goes wrong, then just display the fingerprint without colour, + // instead of partially correct colour or wrong colours + return new SpannableStringBuilder(fingerprint); + } + + return sb; + } + /** * Converts the given bytes to a unique RGB color using SHA1 algorithm * diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index 9a9911c94..ecf8ff09e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -35,6 +35,7 @@ import org.spongycastle.openpgp.PGPPublicKeyRing; import org.spongycastle.openpgp.PGPSignature; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.helper.Preferences; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index eeb17fea2..a361b24b6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -26,10 +26,7 @@ import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; -import android.text.Spannable; -import android.text.SpannableStringBuilder; import android.text.format.DateFormat; -import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -303,7 +300,7 @@ public class ViewKeyMainFragment extends Fragment implements } String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); - mFingerprint.setText(colorizeFingerprint(fingerprint)); + mFingerprint.setText(OtherHelper.colorizeFingerprint(fingerprint)); } mKeysAdapter.swapCursor(data); @@ -314,63 +311,6 @@ public class ViewKeyMainFragment extends Fragment implements } } - private SpannableStringBuilder colorizeFingerprint(String fingerprint) { - SpannableStringBuilder sb = new SpannableStringBuilder(fingerprint); - try { - // for each 4 characters of the fingerprint + 1 space - for (int i = 0; i < fingerprint.length(); i += 5) { - int spanEnd = Math.min(i + 4, fingerprint.length()); - String fourChars = fingerprint.substring(i, spanEnd); - - int raw = Integer.parseInt(fourChars, 16); - byte[] bytes = {(byte) ((raw >> 8) & 0xff - 128), (byte) (raw & 0xff - 128)}; - int[] color = OtherHelper.getRgbForData(bytes); - int r = color[0]; - int g = color[1]; - int b = color[2]; - - // we cannot change black by multiplication, so adjust it to an almost-black grey, - // which will then be brightened to the minimal brightness level - if (r == 0 && g == 0 && b == 0) { - r = 1; - g = 1; - b = 1; - } - - // Convert rgb to brightness - double brightness = 0.2126 * r + 0.7152 * g + 0.0722 * b; - - // If a color is too dark to be seen on black, - // then brighten it up to a minimal brightness. - if (brightness < 80) { - double factor = 80.0 / brightness; - r = Math.min(255, (int) (r * factor)); - g = Math.min(255, (int) (g * factor)); - b = Math.min(255, (int) (b * factor)); - - // If it is too light, then darken it to a respective maximal brightness. - } else if (brightness > 180) { - double factor = 180.0 / brightness; - r = (int) (r * factor); - g = (int) (g * factor); - b = (int) (b * factor); - } - - // Create a foreground color with the 3 digest integers as RGB - // and then converting that int to hex to use as a color - sb.setSpan(new ForegroundColorSpan(Color.rgb(r, g, b)), - i, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE); - } - } catch (Exception e) { - Log.e(Constants.TAG, "Colorization failed", e); - // if anything goes wrong, then just display the fingerprint without colour, - // instead of partially correct colour or wrong colours - return new SpannableStringBuilder(fingerprint); - } - - return sb; - } - /** * This is called when the last Cursor provided to onLoadFinished() above is about to be closed. * We need to make sure we are no longer using it. -- cgit v1.2.3 From db25c56b6479a3679a8abe01e865ad5231be73ee Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Wed, 12 Mar 2014 02:58:42 +0100 Subject: certify: add certify action button to viewkeymainfragment --- .../keychain/ui/ViewKeyMainFragment.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index a361b24b6..0915fa2e2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -62,6 +62,7 @@ public class ViewKeyMainFragment extends Fragment implements private TextView mSecretKey; private BootstrapButton mActionEdit; private BootstrapButton mActionEncrypt; + private BootstrapButton mActionCertify; private ListView mUserIds; private ListView mKeys; @@ -92,6 +93,7 @@ public class ViewKeyMainFragment extends Fragment implements mKeys = (ListView) view.findViewById(R.id.keys); mActionEdit = (BootstrapButton) view.findViewById(R.id.action_edit); mActionEncrypt = (BootstrapButton) view.findViewById(R.id.action_encrypt); + mActionCertify = (BootstrapButton) view.findViewById(R.id.action_certify); return view; } @@ -128,6 +130,11 @@ public class ViewKeyMainFragment extends Fragment implements mSecretKey.setTextColor(getResources().getColor(R.color.emphasis)); mSecretKey.setText(R.string.secret_key_yes); + // certify button + // TODO this button MIGHT be useful if the user wants to + // certify a private key with another... + // mActionCertify.setVisibility(View.GONE); + // edit button mActionEdit.setVisibility(View.VISIBLE); mActionEdit.setOnClickListener(new View.OnClickListener() { @@ -144,8 +151,22 @@ public class ViewKeyMainFragment extends Fragment implements } else { mSecretKey.setTextColor(Color.BLACK); mSecretKey.setText(getResources().getString(R.string.secret_key_no)); + + // certify button + mActionCertify.setVisibility(View.VISIBLE); + // edit button mActionEdit.setVisibility(View.GONE); } + + // TODO see todo note above, doing this here for now + mActionCertify.setOnClickListener(new View.OnClickListener() { + public void onClick(View view) { + certifyKey(KeychainContract.KeyRings.buildPublicKeyRingsByMasterKeyIdUri( + Long.toString(masterKeyId) + )); + } + }); + } mActionEncrypt.setOnClickListener(new View.OnClickListener() { -- cgit v1.2.3 From 9920196f70a67301117770421526a6e5c4cc1332 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 13:18:52 +0100 Subject: certify: selectsecretkeyfragment cosmetics --- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index beff8385e..3d22ca9f6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -39,6 +39,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment { private TextView mKeyUserId; private TextView mKeyUserIdRest; private TextView mKeyMasterKeyIdHex; + private TextView mNoKeySelected; private BootstrapButton mSelectKeyButton; private Boolean mFilterCertify; @@ -60,10 +61,10 @@ public class SelectSecretKeyLayoutFragment extends Fragment { public void selectKey(long secretKeyId) { if (secretKeyId == Id.key.none) { - mKeyMasterKeyIdHex.setText(R.string.api_settings_no_key); - mKeyUserIdRest.setText(""); + mNoKeySelected.setVisibility(View.VISIBLE); mKeyUserId.setVisibility(View.GONE); mKeyUserIdRest.setVisibility(View.GONE); + mKeyMasterKeyIdHex.setVisibility(View.GONE); } else { PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRingByMasterKeyId( @@ -93,20 +94,25 @@ public class SelectSecretKeyLayoutFragment extends Fragment { mKeyMasterKeyIdHex.setText(masterkeyIdHex); mKeyUserId.setText(userName); mKeyUserIdRest.setText(userEmail); + mKeyMasterKeyIdHex.setVisibility(View.VISIBLE); mKeyUserId.setVisibility(View.VISIBLE); mKeyUserIdRest.setVisibility(View.VISIBLE); + mNoKeySelected.setVisibility(View.GONE); } else { - mKeyMasterKeyIdHex.setText(getActivity().getResources().getString(R.string.no_key)); + mKeyMasterKeyIdHex.setVisibility(View.GONE); mKeyUserId.setVisibility(View.GONE); mKeyUserIdRest.setVisibility(View.GONE); + mNoKeySelected.setVisibility(View.VISIBLE); } } else { mKeyMasterKeyIdHex.setText( getActivity().getResources() .getString(R.string.no_keys_added_or_updated) + " for master id: " + secretKeyId); + mKeyMasterKeyIdHex.setVisibility(View.VISIBLE); mKeyUserId.setVisibility(View.GONE); mKeyUserIdRest.setVisibility(View.GONE); + mNoKeySelected.setVisibility(View.GONE); } } @@ -124,6 +130,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.select_secret_key_layout_fragment, container, false); + mNoKeySelected = (TextView) view.findViewById(R.id.no_key_selected); mKeyUserId = (TextView) view.findViewById(R.id.select_secret_key_user_id); mKeyUserIdRest = (TextView) view.findViewById(R.id.select_secret_key_user_id_rest); mKeyMasterKeyIdHex = (TextView) view.findViewById(R.id.select_secret_key_master_key_hex); -- cgit v1.2.3 From efc8252598ef4e5e198b9572648e7af62573cffb Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 13:22:02 +0100 Subject: certify: viewkeyuseridsadapter cosmetics and checkbox capability --- .../keychain/ui/ViewKeyMainFragment.java | 13 ++-- .../keychain/ui/adapter/ViewKeyUserIdsAdapter.java | 81 ++++++++++++++++++++-- 2 files changed, 82 insertions(+), 12 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 0915fa2e2..a828a4405 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -198,12 +198,13 @@ public class ViewKeyMainFragment extends Fragment implements static final int KEYRING_INDEX_USER_ID = 2; static final String[] USER_IDS_PROJECTION = - new String[]{KeychainContract.UserIds._ID, KeychainContract.UserIds.USER_ID, - KeychainContract.UserIds.RANK, }; - // not the main user id - static final String USER_IDS_SELECTION = KeychainContract.UserIds.RANK + " > 0 "; + new String[]{ + KeychainContract.UserIds._ID, + KeychainContract.UserIds.USER_ID, + KeychainContract.UserIds.RANK, + }; static final String USER_IDS_SORT_ORDER = - KeychainContract.UserIds.USER_ID + " COLLATE LOCALIZED ASC"; + KeychainContract.UserIds.RANK + " COLLATE LOCALIZED ASC"; static final String[] KEYS_PROJECTION = new String[]{KeychainContract.Keys._ID, KeychainContract.Keys.KEY_ID, @@ -239,7 +240,7 @@ public class ViewKeyMainFragment extends Fragment implements // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. - return new CursorLoader(getActivity(), baseUri, USER_IDS_PROJECTION, USER_IDS_SELECTION, null, + return new CursorLoader(getActivity(), baseUri, USER_IDS_PROJECTION, null, null, USER_IDS_SORT_ORDER); } case LOADER_ID_KEYS: { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java index 3ba291c3d..61572b9ce 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyUserIdsAdapter.java @@ -23,26 +23,48 @@ import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.CheckBox; +import android.widget.CompoundButton; import android.widget.TextView; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; +import java.util.ArrayList; + public class ViewKeyUserIdsAdapter extends CursorAdapter { private LayoutInflater mInflater; - private int mIndexUserId; + private int mIndexUserId, mIndexRank; - public ViewKeyUserIdsAdapter(Context context, Cursor c, int flags) { + final private ArrayList mCheckStates; + + public ViewKeyUserIdsAdapter(Context context, Cursor c, int flags, boolean showCheckBoxes) { super(context, c, flags); mInflater = LayoutInflater.from(context); + mCheckStates = showCheckBoxes ? new ArrayList() : null; + initIndex(c); } + public ViewKeyUserIdsAdapter(Context context, Cursor c, int flags) { + this(context, c, flags, false); + } @Override public Cursor swapCursor(Cursor newCursor) { initIndex(newCursor); + if(mCheckStates != null) { + mCheckStates.clear(); + if(newCursor != null) { + int count = newCursor.getCount(); + mCheckStates.ensureCapacity(count); + // initialize to true (use case knowledge: we usually want to sign all uids) + for(int i = 0; i < count; i++) + mCheckStates.add(true); + } + } return super.swapCursor(newCursor); } @@ -56,20 +78,67 @@ public class ViewKeyUserIdsAdapter extends CursorAdapter { private void initIndex(Cursor cursor) { if (cursor != null) { mIndexUserId = cursor.getColumnIndexOrThrow(UserIds.USER_ID); + mIndexRank = cursor.getColumnIndexOrThrow(UserIds.RANK); } } @Override public void bindView(View view, Context context, Cursor cursor) { - String userIdStr = cursor.getString(mIndexUserId); - TextView userId = (TextView) view.findViewById(R.id.userId); - userId.setText(userIdStr); + TextView vRank = (TextView) view.findViewById(R.id.rank); + TextView vUserId = (TextView) view.findViewById(R.id.userId); + TextView vAddress = (TextView) view.findViewById(R.id.address); + + vRank.setText(Integer.toString(cursor.getInt(mIndexRank))); + + String[] userId = PgpKeyHelper.splitUserId(cursor.getString(mIndexUserId)); + if (userId[0] != null) { + vUserId.setText(userId[0]); + } else { + vUserId.setText(R.string.user_id_no_name); + } + vAddress.setText(userId[1]); + + // don't care further if checkboxes aren't shown + if(mCheckStates == null) + return; + + final CheckBox vCheckBox = (CheckBox) view.findViewById(R.id.checkBox); + final int position = cursor.getPosition(); + vCheckBox.setClickable(false); + vCheckBox.setChecked(mCheckStates.get(position)); + vCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton compoundButton, boolean b) { + mCheckStates.set(position, b); + } + }); + view.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + vCheckBox.toggle(); + } + }); + + } + + public ArrayList getSelectedUserIds() { + ArrayList result = new ArrayList(); + for(int i = 0; i < mCheckStates.size(); i++) { + if(mCheckStates.get(i)) { + mCursor.moveToPosition(i); + result.add(mCursor.getString(mIndexUserId)); + } + } + return result; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { - return mInflater.inflate(R.layout.view_key_userids_item, null); + View view = mInflater.inflate(R.layout.view_key_userids_item, null); + // only need to do this once ever, since mShowCheckBoxes is final + view.findViewById(R.id.checkBox).setVisibility(mCheckStates != null ? View.VISIBLE : View.GONE); + return view; } } -- cgit v1.2.3 From 49984846d5955e29b1edd7aad5b1474a0eebfcfc Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 13:22:48 +0100 Subject: certify: support PUBLIC_KEY_RING_BY_MASTER_KEY_ID_USER_ID uri (haha) --- .../keychain/provider/KeychainProvider.java | 36 ++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 748aaeb1b..b963ceb39 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -55,6 +55,7 @@ public class KeychainProvider extends ContentProvider { private static final int PUBLIC_KEY_RING_USER_ID = 121; private static final int PUBLIC_KEY_RING_USER_ID_BY_ROW_ID = 122; + private static final int PUBLIC_KEY_RING_BY_MASTER_KEY_ID_USER_ID = 123; private static final int SECRET_KEY_RING = 201; private static final int SECRET_KEY_RING_BY_ROW_ID = 202; @@ -150,6 +151,7 @@ public class KeychainProvider extends ContentProvider { *
          * key_rings/public/#/user_ids
          * key_rings/public/#/user_ids/#
+         * key_rings/public/master_key_id/#/user_ids
          * 
*/ matcher.addURI(authority, KeychainContract.BASE_KEY_RINGS + "/" @@ -158,6 +160,10 @@ public class KeychainProvider extends ContentProvider { matcher.addURI(authority, KeychainContract.BASE_KEY_RINGS + "/" + KeychainContract.PATH_PUBLIC + "/#/" + KeychainContract.PATH_USER_IDS + "/#", PUBLIC_KEY_RING_USER_ID_BY_ROW_ID); + matcher.addURI(authority, KeychainContract.BASE_KEY_RINGS + "/" + + KeychainContract.PATH_PUBLIC + "/" + + KeychainContract.PATH_BY_MASTER_KEY_ID + "/*/" + KeychainContract.PATH_USER_IDS, + PUBLIC_KEY_RING_BY_MASTER_KEY_ID_USER_ID); /** * secret key rings @@ -285,6 +291,7 @@ public class KeychainProvider extends ContentProvider { return Keys.CONTENT_ITEM_TYPE; case PUBLIC_KEY_RING_USER_ID: + case PUBLIC_KEY_RING_BY_MASTER_KEY_ID_USER_ID: case SECRET_KEY_RING_USER_ID: return UserIds.CONTENT_TYPE; @@ -322,6 +329,7 @@ public class KeychainProvider extends ContentProvider { case PUBLIC_KEY_RING_KEY: case PUBLIC_KEY_RING_KEY_BY_ROW_ID: case PUBLIC_KEY_RING_USER_ID: + case PUBLIC_KEY_RING_BY_MASTER_KEY_ID_USER_ID: case PUBLIC_KEY_RING_USER_ID_BY_ROW_ID: type = KeyTypes.PUBLIC; break; @@ -364,6 +372,11 @@ public class KeychainProvider extends ContentProvider { // TODO: deprecated master key id //projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEYS + "." + KeysColumns.KEY_ID); + projectionMap.put(KeysColumns.ALGORITHM, Tables.KEYS + "." + KeysColumns.ALGORITHM); + projectionMap.put(KeysColumns.KEY_SIZE, Tables.KEYS + "." + KeysColumns.KEY_SIZE); + projectionMap.put(KeysColumns.CREATION, Tables.KEYS + "." + KeysColumns.CREATION); + projectionMap.put(KeysColumns.EXPIRY, Tables.KEYS + "." + KeysColumns.EXPIRY); + projectionMap.put(KeysColumns.KEY_RING_ROW_ID, Tables.KEYS + "." + KeysColumns.KEY_RING_ROW_ID); projectionMap.put(KeysColumns.FINGERPRINT, Tables.KEYS + "." + KeysColumns.FINGERPRINT); projectionMap.put(KeysColumns.IS_REVOKED, Tables.KEYS + "." + KeysColumns.IS_REVOKED); @@ -403,6 +416,18 @@ public class KeychainProvider extends ContentProvider { return projectionMap; } + private HashMap getProjectionMapForUserIds() { + HashMap projectionMap = new HashMap(); + + projectionMap.put(BaseColumns._ID, Tables.USER_IDS + "." + BaseColumns._ID); + projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." + UserIdsColumns.USER_ID); + projectionMap.put(UserIdsColumns.RANK, Tables.USER_IDS + "." + UserIdsColumns.RANK); + projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." + + KeyRingsColumns.MASTER_KEY_ID); + + return projectionMap; + } + /** * Builds default query for keyRings: KeyRings table is joined with UserIds and Keys */ @@ -606,6 +631,17 @@ public class KeychainProvider extends ContentProvider { break; + case PUBLIC_KEY_RING_BY_MASTER_KEY_ID_USER_ID: + qb.setTables(Tables.USER_IDS + " INNER JOIN " + Tables.KEY_RINGS + " ON " + "(" + + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.USER_IDS + "." + + KeysColumns.KEY_RING_ROW_ID + " )"); + qb.appendWhere(Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID + " = "); + qb.appendWhereEscapeString(uri.getPathSegments().get(3)); + + qb.setProjectionMap(getProjectionMapForUserIds()); + + break; + case PUBLIC_KEY_RING_USER_ID: case SECRET_KEY_RING_USER_ID: qb.setTables(Tables.USER_IDS); -- cgit v1.2.3 From 1de0312bb53935f8b48e4e7437169e72a154edbf Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 13:24:49 +0100 Subject: certify: revamp certifykeyactivity show info on the key to be certified, along with a list of (selectable) user ids. user ids are handed through to the signing service, but not yet handled. --- .../keychain/service/KeychainIntentService.java | 2 + .../keychain/ui/CertifyKeyActivity.java | 97 +++++++++++++++++++++- 2 files changed, 98 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 4e5812202..eb2367061 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -143,6 +143,7 @@ public class KeychainIntentService extends IntentService // sign key public static final String CERTIFY_KEY_MASTER_KEY_ID = "sign_key_master_key_id"; public static final String CERTIFY_KEY_PUB_KEY_ID = "sign_key_pub_key_id"; + public static final String CERTIFY_KEY_UIDS = "sign_key_uids"; /* * possible data keys as result send over messenger @@ -804,6 +805,7 @@ public class KeychainIntentService extends IntentService /* Input */ long masterKeyId = data.getLong(CERTIFY_KEY_MASTER_KEY_ID); long pubKeyId = data.getLong(CERTIFY_KEY_PUB_KEY_ID); + // String[] userIds = data.getStringArray(CERTIFY_KEY_PUB_KEY_ID); /* Operation */ String signaturePassPhrase = PassphraseCacheService.getCachedPassphrase(this, diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index ecf8ff09e..3590baa76 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -19,13 +19,18 @@ package org.sufficientlysecure.keychain.ui; import android.app.ProgressDialog; import android.content.Intent; +import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Messenger; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; +import android.text.format.DateFormat; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; @@ -39,20 +44,23 @@ import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.helper.Preferences; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; import org.sufficientlysecure.keychain.service.PassphraseCacheService; +import org.sufficientlysecure.keychain.ui.adapter.ViewKeyUserIdsAdapter; import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; import org.sufficientlysecure.keychain.util.Log; +import java.util.Date; import java.util.Iterator; /** * Signs the specified public key with the specified secret master key */ public class CertifyKeyActivity extends ActionBarActivity implements - SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { + SelectSecretKeyLayoutFragment.SelectSecretKeyCallback, LoaderManager.LoaderCallbacks { private BootstrapButton mSignButton; private CheckBox mUploadKeyCheckbox; private Spinner mSelectKeyserverSpinner; @@ -63,6 +71,12 @@ public class CertifyKeyActivity extends ActionBarActivity implements private long mPubKeyId = 0; private long mMasterKeyId = 0; + private ListView mUserIds; + private ViewKeyUserIdsAdapter mUserIdsAdapter; + + private static final int LOADER_ID_KEYRING = 0; + private static final int LOADER_ID_USER_IDS = 1; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -126,9 +140,18 @@ public class CertifyKeyActivity extends ActionBarActivity implements finish(); return; } + Log.e(Constants.TAG, "uri: " + mDataUri); PGPPublicKeyRing signKey = (PGPPublicKeyRing) ProviderHelper.getPGPKeyRing(this, mDataUri); + mUserIds = (ListView) findViewById(R.id.user_ids); + + mUserIdsAdapter = new ViewKeyUserIdsAdapter(this, null, 0, true); + mUserIds.setAdapter(mUserIdsAdapter); + + getSupportLoaderManager().initLoader(LOADER_ID_KEYRING, null, this); + getSupportLoaderManager().initLoader(LOADER_ID_USER_IDS, null, this); + if (signKey != null) { mPubKeyId = PgpKeyHelper.getMasterKey(signKey).getKeyID(); } @@ -139,6 +162,76 @@ public class CertifyKeyActivity extends ActionBarActivity implements } } + static final String[] KEYRING_PROJECTION = + new String[] { + KeychainContract.KeyRings._ID, + KeychainContract.KeyRings.MASTER_KEY_ID, + KeychainContract.Keys.FINGERPRINT, + KeychainContract.UserIds.USER_ID + }; + static final int INDEX_MASTER_KEY_ID = 1; + static final int INDEX_FINGERPRINT = 2; + static final int INDEX_USER_ID = 3; + + static final String[] USER_IDS_PROJECTION = + new String[]{ + KeychainContract.UserIds._ID, + KeychainContract.UserIds.USER_ID, + KeychainContract.UserIds.RANK + }; + static final String USER_IDS_SORT_ORDER = + KeychainContract.UserIds.RANK + " ASC"; + + @Override + public Loader onCreateLoader(int id, Bundle args) { + switch(id) { + case LOADER_ID_KEYRING: + return new CursorLoader(this, mDataUri, KEYRING_PROJECTION, null, null, null); + case LOADER_ID_USER_IDS: { + Uri baseUri = KeychainContract.UserIds.buildUserIdsUri(mDataUri); + return new CursorLoader(this, baseUri, USER_IDS_PROJECTION, null, null, USER_IDS_SORT_ORDER); + } + } + return null; + } + + @Override + public void onLoadFinished(Loader loader, Cursor data) { + switch(loader.getId()) { + case LOADER_ID_KEYRING: + // the first key here is our master key + if (data.moveToFirst()) { + long keyId = data.getLong(INDEX_MASTER_KEY_ID); + String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId); + ((TextView) findViewById(R.id.key_id)).setText(keyIdStr); + + String mainUserId = data.getString(INDEX_USER_ID); + ((TextView) findViewById(R.id.main_user_id)).setText(mainUserId); + + byte[] fingerprintBlob = data.getBlob(INDEX_FINGERPRINT); + if (fingerprintBlob == null) { + // FALLBACK for old database entries + fingerprintBlob = ProviderHelper.getFingerprint(this, mDataUri); + } + String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); + ((TextView) findViewById(R.id.fingerprint)).setText(OtherHelper.colorizeFingerprint(fingerprint)); + } + break; + case LOADER_ID_USER_IDS: + mUserIdsAdapter.swapCursor(data); + break; + } + } + + @Override + public void onLoaderReset(Loader loader) { + switch(loader.getId()) { + case LOADER_ID_USER_IDS: + mUserIdsAdapter.swapCursor(null); + break; + } + } + private void showPassphraseDialog(final long secretKeyId) { // Message is received after passphrase is cached Handler returnHandler = new Handler() { @@ -220,6 +313,8 @@ public class CertifyKeyActivity extends ActionBarActivity implements data.putLong(KeychainIntentService.CERTIFY_KEY_MASTER_KEY_ID, mMasterKeyId); data.putLong(KeychainIntentService.CERTIFY_KEY_PUB_KEY_ID, mPubKeyId); + data.putStringArray(KeychainIntentService.CERTIFY_KEY_UIDS, + (String[]) mUserIdsAdapter.getSelectedUserIds().toArray()); intent.putExtra(KeychainIntentService.EXTRA_DATA, data); -- cgit v1.2.3 From a3224687f6d94ce36acb0b5d70087e9af8eb24c6 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 15:28:26 +0100 Subject: certify: add some subscopes in PgpKeyOperation for readability note this commit introduces NO semantical changes whatsoever! --- .../keychain/pgp/PgpKeyOperation.java | 240 +++++++++++---------- 1 file changed, 128 insertions(+), 112 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index c7ec02d7d..fe09ea525 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -215,105 +215,117 @@ public class PgpKeyOperation { updateProgress(R.string.progress_preparing_master_key, 10, 100); - int usageId = keysUsages.get(0); - boolean canSign = - (usageId == Id.choice.usage.sign_only || usageId == Id.choice.usage.sign_and_encrypt); - boolean canEncrypt = - (usageId == Id.choice.usage.encrypt_only || usageId == Id.choice.usage.sign_and_encrypt); + // prepare keyring generator with given master public and secret key + PGPKeyRingGenerator keyGen; + PGPPublicKey masterPublicKey; { - String mainUserId = userIds.get(0); + String mainUserId = userIds.get(0); - PGPSecretKey masterKey = keys.get(0); + // prepare the master key pair + PGPKeyPair masterKeyPair; { - // this removes all userIds and certifications previously attached to the masterPublicKey - PGPPublicKey tmpKey = masterKey.getPublicKey(); - PGPPublicKey masterPublicKey = new PGPPublicKey(tmpKey.getAlgorithm(), - tmpKey.getKey(new BouncyCastleProvider()), tmpKey.getCreationTime()); + PGPSecretKey masterKey = keys.get(0); - // already done by code above: - // PGPPublicKey masterPublicKey = masterKey.getPublicKey(); - // // Somehow, the PGPPublicKey already has an empty certification attached to it when the - // // keyRing is generated the first time, we remove that when it exists, before adding the - // new - // // ones - // PGPPublicKey masterPublicKeyRmCert = PGPPublicKey.removeCertification(masterPublicKey, - // ""); - // if (masterPublicKeyRmCert != null) { - // masterPublicKey = masterPublicKeyRmCert; - // } + // this removes all userIds and certifications previously attached to the masterPublicKey + PGPPublicKey tmpKey = masterKey.getPublicKey(); + masterPublicKey = new PGPPublicKey(tmpKey.getAlgorithm(), + tmpKey.getKey(new BouncyCastleProvider()), tmpKey.getCreationTime()); - PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( - Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(oldPassPhrase.toCharArray()); - PGPPrivateKey masterPrivateKey = masterKey.extractPrivateKey(keyDecryptor); + // already done by code above: + // PGPPublicKey masterPublicKey = masterKey.getPublicKey(); + // // Somehow, the PGPPublicKey already has an empty certification attached to it when the + // // keyRing is generated the first time, we remove that when it exists, before adding the + // new + // // ones + // PGPPublicKey masterPublicKeyRmCert = PGPPublicKey.removeCertification(masterPublicKey, + // ""); + // if (masterPublicKeyRmCert != null) { + // masterPublicKey = masterPublicKeyRmCert; + // } - updateProgress(R.string.progress_certifying_master_key, 20, 100); + PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(oldPassPhrase.toCharArray()); + PGPPrivateKey masterPrivateKey = masterKey.extractPrivateKey(keyDecryptor); - // TODO: if we are editing a key, keep old certs, don't remake certs we don't have to. + updateProgress(R.string.progress_certifying_master_key, 20, 100); - for (String userId : userIds) { - PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder( - masterPublicKey.getAlgorithm(), HashAlgorithmTags.SHA1) - .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); - PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); + // TODO: if we are editing a key, keep old certs, don't remake certs we don't have to. - sGen.init(PGPSignature.POSITIVE_CERTIFICATION, masterPrivateKey); + for (String userId : userIds) { + PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder( + masterPublicKey.getAlgorithm(), HashAlgorithmTags.SHA1) + .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); + PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); - PGPSignature certification = sGen.generateCertification(userId, masterPublicKey); + sGen.init(PGPSignature.POSITIVE_CERTIFICATION, masterPrivateKey); - masterPublicKey = PGPPublicKey.addCertification(masterPublicKey, userId, certification); - } + PGPSignature certification = sGen.generateCertification(userId, masterPublicKey); - PGPKeyPair masterKeyPair = new PGPKeyPair(masterPublicKey, masterPrivateKey); + masterPublicKey = PGPPublicKey.addCertification(masterPublicKey, userId, certification); + } - PGPSignatureSubpacketGenerator hashedPacketsGen = new PGPSignatureSubpacketGenerator(); - PGPSignatureSubpacketGenerator unhashedPacketsGen = new PGPSignatureSubpacketGenerator(); + masterKeyPair = new PGPKeyPair(masterPublicKey, masterPrivateKey); + } - int keyFlags = KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA; - if (canEncrypt) { - keyFlags |= KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE; - } - hashedPacketsGen.setKeyFlags(true, keyFlags); - - hashedPacketsGen.setPreferredSymmetricAlgorithms(true, PREFERRED_SYMMETRIC_ALGORITHMS); - hashedPacketsGen.setPreferredHashAlgorithms(true, PREFERRED_HASH_ALGORITHMS); - hashedPacketsGen.setPreferredCompressionAlgorithms(true, PREFERRED_COMPRESSION_ALGORITHMS); - - if (keysExpiryDates.get(0) != null) { - GregorianCalendar creationDate = new GregorianCalendar(TimeZone.getTimeZone("UTC")); - creationDate.setTime(masterPublicKey.getCreationTime()); - GregorianCalendar expiryDate = keysExpiryDates.get(0); - //note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c - //here we purposefully ignore partial days in each date - long type has no fractional part! - long numDays = - (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000); - if (numDays <= 0) { - throw new PgpGeneralException( - mContext.getString(R.string.error_expiry_must_come_after_creation)); + PGPSignatureSubpacketGenerator hashedPacketsGen; + PGPSignatureSubpacketGenerator unhashedPacketsGen; { + + hashedPacketsGen = new PGPSignatureSubpacketGenerator(); + unhashedPacketsGen = new PGPSignatureSubpacketGenerator(); + + int usageId = keysUsages.get(0); + boolean canEncrypt = + (usageId == Id.choice.usage.encrypt_only || usageId == Id.choice.usage.sign_and_encrypt); + + int keyFlags = KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA; + if (canEncrypt) { + keyFlags |= KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE; + } + hashedPacketsGen.setKeyFlags(true, keyFlags); + + hashedPacketsGen.setPreferredSymmetricAlgorithms(true, PREFERRED_SYMMETRIC_ALGORITHMS); + hashedPacketsGen.setPreferredHashAlgorithms(true, PREFERRED_HASH_ALGORITHMS); + hashedPacketsGen.setPreferredCompressionAlgorithms(true, PREFERRED_COMPRESSION_ALGORITHMS); + + if (keysExpiryDates.get(0) != null) { + GregorianCalendar creationDate = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + creationDate.setTime(masterPublicKey.getCreationTime()); + GregorianCalendar expiryDate = keysExpiryDates.get(0); + //note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c + //here we purposefully ignore partial days in each date - long type has no fractional part! + long numDays = + (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000); + if (numDays <= 0) { + throw new PgpGeneralException( + mContext.getString(R.string.error_expiry_must_come_after_creation)); + } + hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400); + } else { + //do this explicitly, although since we're rebuilding, + hashedPacketsGen.setKeyExpirationTime(false, 0); + //this happens anyway + } } - hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400); - } else { - //do this explicitly, although since we're rebuilding, - hashedPacketsGen.setKeyExpirationTime(false, 0); - //this happens anyway - } - updateProgress(R.string.progress_building_master_key, 30, 100); + updateProgress(R.string.progress_building_master_key, 30, 100); - // define hashing and signing algos - PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get( - HashAlgorithmTags.SHA1); - PGPContentSignerBuilder certificationSignerBuilder = new JcaPGPContentSignerBuilder( - masterKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1); + // define hashing and signing algos + PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get( + HashAlgorithmTags.SHA1); + PGPContentSignerBuilder certificationSignerBuilder = new JcaPGPContentSignerBuilder( + masterKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1); - // Build key encrypter based on passphrase - PBESecretKeyEncryptor keyEncryptor = new JcePBESecretKeyEncryptorBuilder( - PGPEncryptedData.CAST5, sha1Calc) - .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build( - newPassPhrase.toCharArray()); + // Build key encrypter based on passphrase + PBESecretKeyEncryptor keyEncryptor = new JcePBESecretKeyEncryptorBuilder( + PGPEncryptedData.CAST5, sha1Calc) + .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build( + newPassPhrase.toCharArray()); + + keyGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, + masterKeyPair, mainUserId, sha1Calc, hashedPacketsGen.generate(), + unhashedPacketsGen.generate(), certificationSignerBuilder, keyEncryptor); - PGPKeyRingGenerator keyGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, - masterKeyPair, mainUserId, sha1Calc, hashedPacketsGen.generate(), - unhashedPacketsGen.generate(), certificationSignerBuilder, keyEncryptor); + } updateProgress(R.string.progress_adding_sub_keys, 40, 100); @@ -323,23 +335,23 @@ public class PgpKeyOperation { PGPSecretKey subKey = keys.get(i); PGPPublicKey subPublicKey = subKey.getPublicKey(); - PBESecretKeyDecryptor keyDecryptor2 = new JcePBESecretKeyDecryptorBuilder() + PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder() .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build( oldPassPhrase.toCharArray()); - PGPPrivateKey subPrivateKey = subKey.extractPrivateKey(keyDecryptor2); + PGPPrivateKey subPrivateKey = subKey.extractPrivateKey(keyDecryptor); // TODO: now used without algorithm and creation time?! (APG 1) PGPKeyPair subKeyPair = new PGPKeyPair(subPublicKey, subPrivateKey); - hashedPacketsGen = new PGPSignatureSubpacketGenerator(); - unhashedPacketsGen = new PGPSignatureSubpacketGenerator(); + PGPSignatureSubpacketGenerator hashedPacketsGen = new PGPSignatureSubpacketGenerator(); + PGPSignatureSubpacketGenerator unhashedPacketsGen = new PGPSignatureSubpacketGenerator(); - keyFlags = 0; + int keyFlags = 0; - usageId = keysUsages.get(i); - canSign = + int usageId = keysUsages.get(i); + boolean canSign = (usageId == Id.choice.usage.sign_only || usageId == Id.choice.usage.sign_and_encrypt); - canEncrypt = + boolean canEncrypt = (usageId == Id.choice.usage.encrypt_only || usageId == Id.choice.usage.sign_and_encrypt); if (canSign) { Date todayDate = new Date(); //both sig times the same @@ -402,37 +414,41 @@ public class PgpKeyOperation { if (passphrase == null) { throw new PgpGeneralException("Unable to obtain passphrase"); } else { - PGPPublicKeyRing pubring = ProviderHelper - .getPGPPublicKeyRingByKeyId(mContext, pubKeyId); - PGPSecretKey certificationKey = PgpKeyHelper.getCertificationKey(mContext, masterKeyId); - if (certificationKey == null) { - throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed)); - } - - PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( - Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(passphrase.toCharArray()); - PGPPrivateKey signaturePrivateKey = certificationKey.extractPrivateKey(keyDecryptor); - if (signaturePrivateKey == null) { - throw new PgpGeneralException( - mContext.getString(R.string.error_could_not_extract_private_key)); - } + // create a signatureGenerator from the supplied masterKeyId and passphrase + PGPSignatureGenerator signatureGenerator; { - // TODO: SHA256 fixed? - JcaPGPContentSignerBuilder contentSignerBuilder = new JcaPGPContentSignerBuilder( - certificationKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256) - .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); + PGPSecretKey certificationKey = PgpKeyHelper.getCertificationKey(mContext, masterKeyId); + if (certificationKey == null) { + throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed)); + } - PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( - contentSignerBuilder); + PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(passphrase.toCharArray()); + PGPPrivateKey signaturePrivateKey = certificationKey.extractPrivateKey(keyDecryptor); + if (signaturePrivateKey == null) { + throw new PgpGeneralException( + mContext.getString(R.string.error_could_not_extract_private_key)); + } - signatureGenerator.init(PGPSignature.DIRECT_KEY, signaturePrivateKey); + // TODO: SHA256 fixed? + JcaPGPContentSignerBuilder contentSignerBuilder = new JcaPGPContentSignerBuilder( + certificationKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256) + .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); - PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); + signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder); + signatureGenerator.init(PGPSignature.DIRECT_KEY, signaturePrivateKey); + } - PGPSignatureSubpacketVector packetVector = spGen.generate(); - signatureGenerator.setHashedSubpackets(packetVector); + { // supply signatureGenerator with a SubpacketVector + PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); + PGPSignatureSubpacketVector packetVector = spGen.generate(); + signatureGenerator.setHashedSubpackets(packetVector); + } + // fetch public key ring, add the certification and return it + PGPPublicKeyRing pubring = ProviderHelper + .getPGPPublicKeyRingByKeyId(mContext, pubKeyId); PGPPublicKey signedKey = PGPPublicKey.addCertification(pubring.getPublicKey(pubKeyId), signatureGenerator.generate()); pubring = PGPPublicKeyRing.insertPublicKey(pubring, signedKey); -- cgit v1.2.3 From 95be228b474c31a47743e84cf2abc1dff1d63079 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 18:12:44 +0100 Subject: certify: sign individual UIDs direct signing of pubkeys is out for now. not sure how this should be handled, but it's trivial to re-add so leaving this up for discussion for now. --- .../keychain/pgp/PgpKeyOperation.java | 20 ++++++++++++++++---- .../keychain/service/KeychainIntentService.java | 4 ++-- .../keychain/ui/CertifyKeyActivity.java | 19 +++++++++++++------ 3 files changed, 31 insertions(+), 12 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index fe09ea525..78e48b4ab 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -408,7 +408,16 @@ public class PgpKeyOperation { updateProgress(R.string.progress_done, 100, 100); } - public PGPPublicKeyRing certifyKey(long masterKeyId, long pubKeyId, String passphrase) + /** + * Certify the given pubkeyid with the given masterkeyid. + * + * @param masterKeyId Certifying key, must be available as secret key + * @param pubKeyId ID of public key to certify + * @param userIds User IDs to certify, must not be null or empty + * @param passphrase Passphrase of the secret key + * @return A keyring with added certifications + */ + public PGPPublicKeyRing certifyKey(long masterKeyId, long pubKeyId, List userIds, String passphrase) throws PgpGeneralException, NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException { if (passphrase == null) { @@ -437,7 +446,7 @@ public class PgpKeyOperation { .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder); - signatureGenerator.init(PGPSignature.DIRECT_KEY, signaturePrivateKey); + signatureGenerator.init(PGPSignature.DEFAULT_CERTIFICATION, signaturePrivateKey); } { // supply signatureGenerator with a SubpacketVector @@ -449,8 +458,11 @@ public class PgpKeyOperation { // fetch public key ring, add the certification and return it PGPPublicKeyRing pubring = ProviderHelper .getPGPPublicKeyRingByKeyId(mContext, pubKeyId); - PGPPublicKey signedKey = PGPPublicKey.addCertification(pubring.getPublicKey(pubKeyId), - signatureGenerator.generate()); + PGPPublicKey signedKey = pubring.getPublicKey(pubKeyId); + for(String userId : new IterableIterator(userIds.iterator())) { + PGPSignature sig = signatureGenerator.generateCertification(userId, signedKey); + signedKey = PGPPublicKey.addCertification(signedKey, userId, sig); + } pubring = PGPPublicKeyRing.insertPublicKey(pubring, signedKey); return pubring; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index eb2367061..506ff2735 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -805,7 +805,7 @@ public class KeychainIntentService extends IntentService /* Input */ long masterKeyId = data.getLong(CERTIFY_KEY_MASTER_KEY_ID); long pubKeyId = data.getLong(CERTIFY_KEY_PUB_KEY_ID); - // String[] userIds = data.getStringArray(CERTIFY_KEY_PUB_KEY_ID); + ArrayList userIds = data.getStringArrayList(CERTIFY_KEY_UIDS); /* Operation */ String signaturePassPhrase = PassphraseCacheService.getCachedPassphrase(this, @@ -813,7 +813,7 @@ public class KeychainIntentService extends IntentService PgpKeyOperation keyOperation = new PgpKeyOperation(this, this); PGPPublicKeyRing signedPubKeyRing = keyOperation.certifyKey(masterKeyId, pubKeyId, - signaturePassPhrase); + userIds, signaturePassPhrase); // store the signed key in our local cache PgpImportExport pgpImportExport = new PgpImportExport(this, null); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index 3590baa76..d8df5ced3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -30,14 +30,12 @@ import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; -import android.text.format.DateFormat; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; import android.widget.CompoundButton.OnCheckedChangeListener; import com.beardedhen.androidbootstrap.BootstrapButton; import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.spongycastle.openpgp.PGPSignature; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.OtherHelper; @@ -53,8 +51,7 @@ import org.sufficientlysecure.keychain.ui.adapter.ViewKeyUserIdsAdapter; import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; import org.sufficientlysecure.keychain.util.Log; -import java.util.Date; -import java.util.Iterator; +import java.util.ArrayList; /** * Signs the specified public key with the specified secret master key @@ -267,6 +264,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements // if we have already signed this key, dont bother doing it again boolean alreadySigned = false; + /* todo: reconsider this at a later point when certs are in the db @SuppressWarnings("unchecked") Iterator itr = pubring.getPublicKey(mPubKeyId).getSignatures(); while (itr.hasNext()) { @@ -276,6 +274,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements break; } } + */ if (!alreadySigned) { /* @@ -303,6 +302,15 @@ public class CertifyKeyActivity extends ActionBarActivity implements * kicks off the actual signing process on a background thread */ private void startSigning() { + + // Bail out if there is not at least one user id selected + ArrayList userIds = mUserIdsAdapter.getSelectedUserIds(); + if(userIds.isEmpty()) { + Toast.makeText(CertifyKeyActivity.this, "No User IDs to sign selected!", + Toast.LENGTH_SHORT).show(); + return; + } + // Send all information needed to service to sign key in other thread Intent intent = new Intent(this, KeychainIntentService.class); @@ -313,8 +321,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements data.putLong(KeychainIntentService.CERTIFY_KEY_MASTER_KEY_ID, mMasterKeyId); data.putLong(KeychainIntentService.CERTIFY_KEY_PUB_KEY_ID, mPubKeyId); - data.putStringArray(KeychainIntentService.CERTIFY_KEY_UIDS, - (String[]) mUserIdsAdapter.getSelectedUserIds().toArray()); + data.putStringArrayList(KeychainIntentService.CERTIFY_KEY_UIDS, userIds); intent.putExtra(KeychainIntentService.EXTRA_DATA, data); -- cgit v1.2.3 From 207010dd86c11db2db04f426d434b68784baacbe Mon Sep 17 00:00:00 2001 From: gogowitczak Date: Sat, 15 Mar 2014 21:16:34 +0100 Subject: Keyserver query now uses machine readable output for search and get. Added separate function for converting algorithm integer ID to String. --- .../keychain/pgp/PgpKeyHelper.java | 4 +- .../keychain/ui/adapter/ImportKeysListEntry.java | 45 +++-- .../keychain/util/HkpKeyServer.java | 193 +++++++++++++-------- 3 files changed, 150 insertions(+), 92 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index 436c26700..b93c68677 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -477,7 +477,7 @@ public class PgpKeyHelper { * @return */ public static String convertKeyIdToHex(long keyId) { - return "0x" + convertKeyIdToHex32bit(keyId >> 32) + convertKeyIdToHex32bit(keyId); + return "0x" + ((keyId >> 32) > 0 ? convertKeyIdToHex32bit(keyId >> 32) : "") + convertKeyIdToHex32bit(keyId); } private static String convertKeyIdToHex32bit(long keyId) { @@ -498,7 +498,7 @@ public class PgpKeyHelper { int len = hexString.length(); String s2 = hexString.substring(len - 8); String s1 = hexString.substring(0, len - 8); - return (Long.parseLong(s1, 16) << 32) | Long.parseLong(s2, 16); + return ((!s1.isEmpty() ? Long.parseLong(s1, 16) << 32 : 0) | Long.parseLong(s2, 16)); } /** diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index 19f0d1eaf..13309435d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -19,6 +19,7 @@ package org.sufficientlysecure.keychain.ui.adapter; import android.os.Parcel; import android.os.Parcelable; +import android.util.SparseArray; import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPSecretKeyRing; @@ -171,20 +172,34 @@ public class ImportKeysListEntry implements Serializable, Parcelable { .getFingerprint(), true); this.hexKeyId = PgpKeyHelper.convertKeyIdToHex(keyId); this.bitStrength = pgpKeyRing.getPublicKey().getBitStrength(); - int algorithm = pgpKeyRing.getPublicKey().getAlgorithm(); - if (algorithm == PGPPublicKey.RSA_ENCRYPT || algorithm == PGPPublicKey.RSA_GENERAL - || algorithm == PGPPublicKey.RSA_SIGN) { - this.algorithm = "RSA"; - } else if (algorithm == PGPPublicKey.DSA) { - this.algorithm = "DSA"; - } else if (algorithm == PGPPublicKey.ELGAMAL_ENCRYPT - || algorithm == PGPPublicKey.ELGAMAL_GENERAL) { - this.algorithm = "ElGamal"; - } else if (algorithm == PGPPublicKey.EC || algorithm == PGPPublicKey.ECDSA) { - this.algorithm = "ECC"; - } else { - // TODO: with resources - this.algorithm = "unknown"; - } + final int algorithm = pgpKeyRing.getPublicKey().getAlgorithm(); + this.algorithm = getAlgorithmFromId(algorithm); } + + /** + * Based on OpenPGP Message Format + */ + private final static SparseArray ALGORITHM_IDS = new SparseArray() {{ + put(-1, "unknown"); // TODO: with resources + put(0, "unencrypted"); + put(PGPPublicKey.RSA_GENERAL, "RSA"); + put(PGPPublicKey.RSA_ENCRYPT, "RSA"); + put(PGPPublicKey.RSA_SIGN, "RSA"); + put(PGPPublicKey.ELGAMAL_ENCRYPT, "ElGamal"); + put(PGPPublicKey.ELGAMAL_GENERAL, "ElGamal"); + put(PGPPublicKey.DSA, "DSA"); + put(PGPPublicKey.EC, "ECC"); + put(PGPPublicKey.ECDSA, "ECC"); + put(PGPPublicKey.ECDH, "ECC"); + }}; + + /** + * Based on OpenPGP Message Format + */ + public static String getAlgorithmFromId(int algorithmId) { + return (ALGORITHM_IDS.get(algorithmId) != null ? ALGORITHM_IDS.get(algorithmId) : ALGORITHM_IDS.get(-1)); + } + } + + diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 42fb03a3e..7ec532f5b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -43,6 +43,8 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry.getAlgorithmFromId; + /** * TODO: * rewrite to use machine readable output. @@ -74,16 +76,55 @@ public class HkpKeyServer extends KeyServer { private String mHost; private short mPort; - // example: - // pub 2048R/9F5C9090 2009-08-17 Jörg Runge - // <joerg@joergrunge.de> - public static final Pattern PUB_KEY_LINE = Pattern - .compile( - "pub +([0-9]+)([a-z]+)/.*?0x([0-9a-z]+).*? +([0-9-]+) +(.+)[\n\r]+((?: +.+[\n\r]+)*)", - Pattern.CASE_INSENSITIVE); - public static final Pattern USER_ID_LINE = Pattern.compile("^ +(.+)$", Pattern.MULTILINE - | Pattern.CASE_INSENSITIVE); + /** + * pub:%keyid%:%algo%:%keylen%:%creationdate%:%expirationdate%:%flags% + *
    + *
  • %keyid% = this is either the fingerprint or the key ID of the key. + * Either the 16-digit or 8-digit key IDs are acceptable, but obviously the fingerprint is best.
  • + *
  • %algo% = the algorithm number, (i.e. 1==RSA, 17==DSA, etc). See RFC-2440
  • + *
  • %keylen% = the key length (i.e. 1024, 2048, 4096, etc.)
  • + *
  • %creationdate% = creation date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • + *
  • %expirationdate% = expiration date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • + *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The + * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so + * the absence of a given flag does not necessarily mean the absence of the detail. + *
      + *
    • r == revoked
    • + *
    • d == disabled
    • + *
    • e == expired
    • + *
    + *
  • + *
+ * + * + * @see 5.2. Machine Readable Indexes in Internet-Draft OpenPGP HTTP Keyserver Protocol Document + */ + public static final Pattern PUB_KEY_LINE = Pattern + .compile("pub:([0-9a-fA-F]+):([0-9]+):([0-9]+):([0-9]+):([0-9]*):([rde]*)[ \n\r]*" // pub line + + "(uid:(.*):([0-9]+):([0-9]*):([rde]*))+", // one or more uid lines + Pattern.CASE_INSENSITIVE); + + /** + * uid:%escaped uid string%:%creationdate%:%expirationdate%:%flags% + *
    + *
  • %escaped uid string% = the user ID string, with HTTP %-escaping for anything that isn't 7-bit + * safe as well as for the ":" character. Any other characters may be escaped, as desired.
  • + *
  • %creationdate% = creation date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • + *
  • %expirationdate% = expiration date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • + *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The + * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so + * the absence of a given flag does not necessarily mean the absence of the detail. + *
      + *
    • r == revoked
    • + *
    • d == disabled
    • + *
    • e == expired
    • + *
    + *
  • + *
+ */ + public static final Pattern UID_LINE = Pattern + .compile("uid:(.*):([0-9]+):([0-9]*):([rde]*)", + Pattern.CASE_INSENSITIVE); private static final short PORT_DEFAULT = 11371; @@ -158,82 +199,84 @@ public class HkpKeyServer extends KeyServer { throw new QueryException("querying server(s) for '" + mHost + "' failed"); } - @Override - public ArrayList search(String query) throws QueryException, TooManyResponses, - InsufficientQuery { - ArrayList results = new ArrayList(); + @Override + public ArrayList search(String query) throws QueryException, TooManyResponses, + InsufficientQuery { + ArrayList results = new ArrayList(); - if (query.length() < 3) { - throw new InsufficientQuery(); - } + if (query.length() < 3) { + throw new InsufficientQuery(); + } - String encodedQuery; - try { - encodedQuery = URLEncoder.encode(query, "utf8"); - } catch (UnsupportedEncodingException e) { - return null; - } - String request = "/pks/lookup?op=index&search=" + encodedQuery; + String encodedQuery; + try { + encodedQuery = URLEncoder.encode(query, "utf8"); + } catch (UnsupportedEncodingException e) { + return null; + } + String request = "/pks/lookup?op=index&search=" + encodedQuery + "&options=mr"; - String data = null; - try { - data = query(request); - } catch (HttpError e) { - if (e.getCode() == 404) { - return results; - } else { - if (e.getData().toLowerCase(Locale.US).contains("no keys found")) { - return results; - } else if (e.getData().toLowerCase(Locale.US).contains("too many")) { - throw new TooManyResponses(); - } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) { - throw new InsufficientQuery(); - } - } - throw new QueryException("querying server(s) for '" + mHost + "' failed"); - } + String data = null; + try { + data = query(request); + } catch (HttpError e) { + if (e.getCode() == 404) { + return results; + } else { + if (e.getData().toLowerCase(Locale.US).contains("no keys found")) { + return results; + } else if (e.getData().toLowerCase(Locale.US).contains("too many")) { + throw new TooManyResponses(); + } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) { + throw new InsufficientQuery(); + } + } + throw new QueryException("querying server(s) for '" + mHost + "' failed"); + } - Matcher matcher = PUB_KEY_LINE.matcher(data); - while (matcher.find()) { - ImportKeysListEntry info = new ImportKeysListEntry(); - info.bitStrength = Integer.parseInt(matcher.group(1)); - info.algorithm = matcher.group(2); - info.hexKeyId = "0x" + matcher.group(3); - info.keyId = PgpKeyHelper.convertHexToKeyId(matcher.group(3)); - String chunks[] = matcher.group(4).split("-"); - - GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); - tmpGreg.set(Integer.parseInt(chunks[0]), Integer.parseInt(chunks[1]), - Integer.parseInt(chunks[2])); - info.date = tmpGreg.getTime(); - info.userIds = new ArrayList(); - if (matcher.group(5).startsWith("*** KEY")) { - info.revoked = true; - } else { - String tmp = matcher.group(5).replaceAll("<.*?>", ""); - tmp = Html.fromHtml(tmp).toString(); - info.userIds.add(tmp); - } - if (matcher.group(6).length() > 0) { - Matcher matcher2 = USER_ID_LINE.matcher(matcher.group(6)); - while (matcher2.find()) { - String tmp = matcher2.group(1).replaceAll("<.*?>", ""); - tmp = Html.fromHtml(tmp).toString(); - info.userIds.add(tmp); - } - } - results.add(info); - } + final Matcher matcher = PUB_KEY_LINE.matcher(data); + while (matcher.find()) { + final ImportKeysListEntry info = new ImportKeysListEntry(); + info.bitStrength = Integer.parseInt(matcher.group(3)); + final int algorithmId = Integer.decode(matcher.group(2)); + info.algorithm = getAlgorithmFromId(algorithmId); - return results; - } + info.hexKeyId = "0x" + matcher.group(1); + info.keyId = PgpKeyHelper.convertHexToKeyId(matcher.group(1)); + + final long creationDate = Long.parseLong(matcher.group(4)); + final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + tmpGreg.setTimeInMillis(creationDate*1000); + info.date = tmpGreg.getTime(); + + info.revoked = matcher.group(6).contains("r"); + info.userIds = new ArrayList(); + + final String uidLines = matcher.group(7); + final Matcher uidMatcher = UID_LINE.matcher(uidLines); + while (uidMatcher.find()) { + String tmp = uidMatcher.group(1).replaceAll("<.*?>", ""); + tmp = Html.fromHtml(tmp).toString().trim(); + if (tmp.contains("%")) + { + try { + tmp = (URLDecoder.decode(tmp, "UTF8")); // converts String like "Universit%C3%A4t" to a proper form "Universität". + } catch (UnsupportedEncodingException ignored) { + } + } + info.userIds.add(tmp); + } + results.add(info); + } + return results; + } @Override public String get(long keyId) throws QueryException { HttpClient client = new DefaultHttpClient(); try { HttpGet get = new HttpGet("http://" + mHost + ":" + mPort - + "/pks/lookup?op=get&search=" + PgpKeyHelper.convertKeyIdToHex(keyId)); + + "/pks/lookup?op=get&search=" + PgpKeyHelper.convertKeyIdToHex(keyId) + "&options=mr"); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { -- cgit v1.2.3 From 5277e4c1e76e185132716b0a807066c5abbf340c Mon Sep 17 00:00:00 2001 From: gogowitczak Date: Sat, 15 Mar 2014 22:01:37 +0100 Subject: removed TODO comment --- .../java/org/sufficientlysecure/keychain/util/HkpKeyServer.java | 7 ------- 1 file changed, 7 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 7ec532f5b..0839fc494 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -45,13 +45,6 @@ import java.util.regex.Pattern; import static org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry.getAlgorithmFromId; -/** - * TODO: - * rewrite to use machine readable output. - *

- * see http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00#section-5 - * https://github.com/openpgp-keychain/openpgp-keychain/issues/259 - */ public class HkpKeyServer extends KeyServer { private static class HttpError extends Exception { private static final long serialVersionUID = 1718783705229428893L; -- cgit v1.2.3 From cea62b1857a9b5dbade8dcff6009f72e309b7469 Mon Sep 17 00:00:00 2001 From: uberspot Date: Sun, 16 Mar 2014 23:35:14 +0200 Subject: Lock drawer as open in tablets --- .../keychain/helper/ActionBarHelper.java | 1 - .../keychain/ui/DrawerActivity.java | 86 +++++++++++++++------- .../keychain/ui/KeyListActivity.java | 3 + 3 files changed, 64 insertions(+), 26 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java index 91e50637e..a26df556d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ActionBarHelper.java @@ -37,7 +37,6 @@ public class ActionBarHelper { * @param activity */ public static void setBackButton(ActionBarActivity activity) { - // set actionbar without home button if called from another app final ActionBar actionBar = activity.getSupportActionBar(); Log.d(Constants.TAG, "calling package (only set when using startActivityForResult)=" + activity.getCallingPackage()); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java index c0fd53007..985f6c309 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java @@ -21,18 +21,17 @@ import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; +import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.view.*; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.widget.TextView; +import android.widget.*; import com.beardedhen.androidbootstrap.FontAwesomeText; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ActionBarHelper; import org.sufficientlysecure.keychain.service.remote.RegisteredAppsListActivity; public class DrawerActivity extends ActionBarActivity { @@ -42,6 +41,7 @@ public class DrawerActivity extends ActionBarActivity { private CharSequence mDrawerTitle; private CharSequence mTitle; + private boolean mIsDrawerLocked = false; private static Class[] mItemsClass = new Class[]{KeyListActivity.class, EncryptActivity.class, DecryptActivity.class, ImportKeysActivity.class, @@ -55,10 +55,22 @@ public class DrawerActivity extends ActionBarActivity { mDrawerTitle = getString(R.string.app_name); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); - - // set a custom shadow that overlays the main content when the drawer - // opens - mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); + ViewGroup viewGroup = (ViewGroup) findViewById(R.id.content_frame); + int leftMarginLoaded = ((ViewGroup.MarginLayoutParams) viewGroup.getLayoutParams()).leftMargin; + int leftMarginInTablets = (int) getResources().getDimension(R.dimen.drawer_size); + int errorInMarginAllowed = 5; + + // if the left margin of the loaded layout is close to the + // one used in tablets then set drawer as open and locked + if( Math.abs(leftMarginLoaded - leftMarginInTablets) < errorInMarginAllowed) { + mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, mDrawerList); + mDrawerLayout.setScrimColor(Color.TRANSPARENT); + mIsDrawerLocked = true; + } else { + // set a custom shadow that overlays the main content when the drawer opens + mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); + mIsDrawerLocked = false; + } NavItem mItemIconTexts[] = new NavItem[]{ new NavItem("fa-user", getString(R.string.nav_contacts)), @@ -73,8 +85,11 @@ public class DrawerActivity extends ActionBarActivity { mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // enable ActionBar app icon to behave as action to toggle nav drawer - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeButtonEnabled(true); + // if the drawer is not locked + if ( !mIsDrawerLocked ) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setHomeButtonEnabled(true); + } // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon @@ -86,19 +101,8 @@ public class DrawerActivity extends ActionBarActivity { ) { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); - // creates call to onPrepareOptionsMenu() - supportInvalidateOptionsMenu(); - // call intent activity if selected - if (mSelectedItem != null) { - finish(); - overridePendingTransition(0, 0); - - Intent intent = new Intent(DrawerActivity.this, mSelectedItem); - startActivity(intent); - // disable animation of activity start - overridePendingTransition(0, 0); - } + callIntentForSelectedItem(); } public void onDrawerOpened(View drawerView) { @@ -108,13 +112,37 @@ public class DrawerActivity extends ActionBarActivity { supportInvalidateOptionsMenu(); } }; - mDrawerLayout.setDrawerListener(mDrawerToggle); + if ( !mIsDrawerLocked ) { + mDrawerLayout.setDrawerListener(mDrawerToggle); + } + if ( mIsDrawerLocked ) { + // If the drawer is locked open make it un-focusable + // so that it doesn't consume all the Back button presses + mDrawerLayout.setFocusableInTouchMode(false); + } // if (savedInstanceState == null) { // selectItem(0); // } } + private void callIntentForSelectedItem() { + // creates call to onPrepareOptionsMenu() + supportInvalidateOptionsMenu(); + + // call intent activity if selected + if (mSelectedItem != null) { + finish(); + overridePendingTransition(0, 0); + + Intent intent = new Intent(this, mSelectedItem); + startActivity(intent); + + // disable animation of activity start + overridePendingTransition(0, 0); + } + } + @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(42, MENU_ID_PREFERENCE, 100, R.string.menu_preferences); @@ -185,10 +213,18 @@ public class DrawerActivity extends ActionBarActivity { private void selectItem(int position) { // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); - // setTitle(mDrawerTitles[position]); - mDrawerLayout.closeDrawer(mDrawerList); // set selected class mSelectedItem = mItemsClass[position]; + + // setTitle(mDrawerTitles[position]); + // If drawer isn't locked just close the drawer and + // it will move to the selected item by itself (via drawer toggle listener) + if ( !mIsDrawerLocked ) { + mDrawerLayout.closeDrawer(mDrawerList); + // else move to the selected item yourself + } else { + callIntentForSelectedItem(); + } } /** diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 5ff4dbdeb..57709350e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -53,8 +53,11 @@ public class KeyListActivity extends DrawerActivity { public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_key_list_import: + + overridePendingTransition(0, 0); Intent intentImport = new Intent(this, ImportKeysActivity.class); startActivityForResult(intentImport, 0); + overridePendingTransition(0, 0); return true; case R.id.menu_key_list_export: -- cgit v1.2.3 From e01c99a193528df717d5cf5bd9fe20c649297375 Mon Sep 17 00:00:00 2001 From: uberspot Date: Mon, 17 Mar 2014 00:27:52 +0200 Subject: make loading of drawer items a bit more dynamic --- .../org/sufficientlysecure/keychain/Constants.java | 14 +++++++++++ .../keychain/ui/DrawerActivity.java | 27 +++++++++++----------- .../keychain/ui/KeyListActivity.java | 6 +---- 3 files changed, 28 insertions(+), 19 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java index 011cd9663..ff4abe56a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java @@ -19,6 +19,11 @@ package org.sufficientlysecure.keychain; import android.os.Environment; import org.spongycastle.jce.provider.BouncyCastleProvider; +import org.sufficientlysecure.keychain.service.remote.RegisteredAppsListActivity; +import org.sufficientlysecure.keychain.ui.DecryptActivity; +import org.sufficientlysecure.keychain.ui.EncryptActivity; +import org.sufficientlysecure.keychain.ui.ImportKeysActivity; +import org.sufficientlysecure.keychain.ui.KeyListActivity; public final class Constants { @@ -63,4 +68,13 @@ public final class Constants { public static final String KEY_SERVERS = "pool.sks-keyservers.net, subkeys.pgp.net, pgp.mit.edu"; } + public static final class DrawerItems { + public static final Class KEY_LIST = KeyListActivity.class; + public static final Class ENCRYPT = EncryptActivity.class; + public static final Class DECRYPT = DecryptActivity.class; + public static final Class IMPORT_KEYS = ImportKeysActivity.class; + public static final Class REGISTERED_APPS_LIST = RegisteredAppsListActivity.class; + public static final Class[] ARRAY = new Class[]{KEY_LIST, ENCRYPT, DECRYPT, + IMPORT_KEYS, REGISTERED_APPS_LIST}; + } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java index 985f6c309..f01e67449 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DrawerActivity.java @@ -30,9 +30,8 @@ import android.support.v7.app.ActionBarActivity; import android.view.*; import android.widget.*; import com.beardedhen.androidbootstrap.FontAwesomeText; +import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; -import org.sufficientlysecure.keychain.service.remote.RegisteredAppsListActivity; public class DrawerActivity extends ActionBarActivity { private DrawerLayout mDrawerLayout; @@ -43,9 +42,6 @@ public class DrawerActivity extends ActionBarActivity { private CharSequence mTitle; private boolean mIsDrawerLocked = false; - private static Class[] mItemsClass = new Class[]{KeyListActivity.class, - EncryptActivity.class, DecryptActivity.class, ImportKeysActivity.class, - RegisteredAppsListActivity.class}; private Class mSelectedItem; private static final int MENU_ID_PREFERENCE = 222; @@ -102,7 +98,7 @@ public class DrawerActivity extends ActionBarActivity { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); - callIntentForSelectedItem(); + callIntentForDrawerItem(mSelectedItem); } public void onDrawerOpened(View drawerView) { @@ -112,11 +108,10 @@ public class DrawerActivity extends ActionBarActivity { supportInvalidateOptionsMenu(); } }; + if ( !mIsDrawerLocked ) { mDrawerLayout.setDrawerListener(mDrawerToggle); - } - - if ( mIsDrawerLocked ) { + } else { // If the drawer is locked open make it un-focusable // so that it doesn't consume all the Back button presses mDrawerLayout.setFocusableInTouchMode(false); @@ -126,16 +121,20 @@ public class DrawerActivity extends ActionBarActivity { // } } - private void callIntentForSelectedItem() { + /** + * Uses startActivity to call the Intent of the given class + * @param drawerItem the class of the drawer item you want to load. Based on Constants.DrawerItems.* + */ + public void callIntentForDrawerItem(Class drawerItem) { // creates call to onPrepareOptionsMenu() supportInvalidateOptionsMenu(); // call intent activity if selected - if (mSelectedItem != null) { + if (drawerItem != null) { finish(); overridePendingTransition(0, 0); - Intent intent = new Intent(this, mSelectedItem); + Intent intent = new Intent(this, drawerItem); startActivity(intent); // disable animation of activity start @@ -214,7 +213,7 @@ public class DrawerActivity extends ActionBarActivity { // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); // set selected class - mSelectedItem = mItemsClass[position]; + mSelectedItem = Constants.DrawerItems.ARRAY[position]; // setTitle(mDrawerTitles[position]); // If drawer isn't locked just close the drawer and @@ -223,7 +222,7 @@ public class DrawerActivity extends ActionBarActivity { mDrawerLayout.closeDrawer(mDrawerList); // else move to the selected item yourself } else { - callIntentForSelectedItem(); + callIntentForDrawerItem(mSelectedItem); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 57709350e..06df6f12d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -53,11 +53,7 @@ public class KeyListActivity extends DrawerActivity { public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_key_list_import: - - overridePendingTransition(0, 0); - Intent intentImport = new Intent(this, ImportKeysActivity.class); - startActivityForResult(intentImport, 0); - overridePendingTransition(0, 0); + callIntentForDrawerItem(Constants.DrawerItems.IMPORT_KEYS); return true; case R.id.menu_key_list_export: -- cgit v1.2.3 From 87004fd0ca3a5178fba3050599a445ba9c64662c Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 15 Mar 2014 18:15:39 +0100 Subject: certify: preserve user id certificates when saving secret keys --- .../keychain/pgp/PgpKeyOperation.java | 64 ++++++++++++++++++++-- .../keychain/service/KeychainIntentService.java | 5 +- .../keychain/util/IterableIterator.java | 10 +++- 3 files changed, 72 insertions(+), 7 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index 78e48b4ab..40a0b72ce 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -36,6 +36,7 @@ import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.Primes; import org.sufficientlysecure.keychain.util.ProgressDialogUpdater; @@ -46,6 +47,8 @@ import java.security.*; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; +import java.util.Iterator; +import java.util.List; import java.util.TimeZone; public class PgpKeyOperation { @@ -198,7 +201,7 @@ public class PgpKeyOperation { public void buildSecretKey(ArrayList userIds, ArrayList keys, ArrayList keysUsages, ArrayList keysExpiryDates, - long masterKeyId, String oldPassPhrase, + PGPPublicKey oldPublicKey, String oldPassPhrase, String newPassPhrase) throws PgpGeneralException, NoSuchProviderException, PGPException, NoSuchAlgorithmException, SignatureException, IOException { @@ -249,9 +252,32 @@ public class PgpKeyOperation { updateProgress(R.string.progress_certifying_master_key, 20, 100); - // TODO: if we are editing a key, keep old certs, don't remake certs we don't have to. - + // re-add old certificates, or create new ones for new uids for (String userId : userIds) { + // re-add certs for this uid, take a note if self-signed cert is in there + boolean foundSelfSign = false; + Iterator it = tmpKey.getSignaturesForID(userId); + if(it != null) for(PGPSignature sig : new IterableIterator(it)) { + if(sig.getKeyID() == masterPublicKey.getKeyID()) { + // already have a self sign? skip this other one, then. + // note: PGPKeyRingGenerator adds one cert for the main user id, which + // will lead to duplicates. unfortunately, if we add any other here + // first, that will change the main user id order... + if(foundSelfSign) + continue; + foundSelfSign = true; + } + Log.d(Constants.TAG, "adding old sig for " + userId + " from " + + PgpKeyHelper.convertKeyIdToHex(sig.getKeyID())); + masterPublicKey = PGPPublicKey.addCertification(masterPublicKey, userId, sig); + } + + // there was an old self-signed certificate for this uid + if(foundSelfSign) + continue; + + Log.d(Constants.TAG, "generating self-signed cert for " + userId); + PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder( masterPublicKey.getAlgorithm(), HashAlgorithmTags.SHA1) .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); @@ -330,7 +356,7 @@ public class PgpKeyOperation { updateProgress(R.string.progress_adding_sub_keys, 40, 100); for (int i = 1; i < keys.size(); ++i) { - updateProgress(40 + 50 * (i - 1) / (keys.size() - 1), 100); + updateProgress(40 + 40 * (i - 1) / (keys.size() - 1), 100); PGPSecretKey subKey = keys.get(i); PGPPublicKey subPublicKey = subKey.getPublicKey(); @@ -400,8 +426,38 @@ public class PgpKeyOperation { PGPSecretKeyRing secretKeyRing = keyGen.generateSecretKeyRing(); PGPPublicKeyRing publicKeyRing = keyGen.generatePublicKeyRing(); + updateProgress(R.string.progress_re_adding_certs, 80, 100); + + // re-add certificates from old public key + // TODO: this only takes care of user id certificates, what about others? + PGPPublicKey pubkey = publicKeyRing.getPublicKey(); + for(String uid : new IterableIterator(pubkey.getUserIDs())) { + for(PGPSignature sig : new IterableIterator(oldPublicKey.getSignaturesForID(uid), true)) { + // but skip self certificates + if(sig.getKeyID() == pubkey.getKeyID()) + continue; + pubkey = PGPPublicKey.addCertification(pubkey, uid, sig); + } + } + publicKeyRing = PGPPublicKeyRing.insertPublicKey(publicKeyRing, pubkey); + updateProgress(R.string.progress_saving_key_ring, 90, 100); + /* additional handy debug info + Log.d(Constants.TAG, " ------- in private key -------"); + for(String uid : new IterableIterator(secretKeyRing.getPublicKey().getUserIDs())) { + for(PGPSignature sig : new IterableIterator(secretKeyRing.getPublicKey().getSignaturesForID(uid))) { + Log.d(Constants.TAG, "sig: " + PgpKeyHelper.convertKeyIdToHex(sig.getKeyID()) + " for " + uid); + } + } + Log.d(Constants.TAG, " ------- in public key -------"); + for(String uid : new IterableIterator(publicKeyRing.getPublicKey().getUserIDs())) { + for(PGPSignature sig : new IterableIterator(publicKeyRing.getPublicKey().getSignaturesForID(uid))) { + Log.d(Constants.TAG, "sig: " + PgpKeyHelper.convertKeyIdToHex(sig.getKeyID()) + " for " + uid); + } + } + */ + ProviderHelper.saveKeyRing(mContext, secretKeyRing); ProviderHelper.saveKeyRing(mContext, publicKeyRing); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 506ff2735..daaff5d54 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -543,8 +543,9 @@ public class KeychainIntentService extends IntentService ProviderHelper.getPGPSecretKeyRingByKeyId(this, masterKeyId), oldPassPhrase, newPassPhrase); } else { - keyOperations.buildSecretKey(userIds, keys, keysUsages, keysExpiryDates, masterKeyId, - oldPassPhrase, newPassPhrase); + PGPPublicKey pubkey = ProviderHelper.getPGPPublicKeyByKeyId(this, masterKeyId); + keyOperations.buildSecretKey(userIds, keys, keysUsages, keysExpiryDates, + pubkey, oldPassPhrase, newPassPhrase); } PassphraseCacheService.addCachedPassphrase(this, masterKeyId, newPassPhrase); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IterableIterator.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IterableIterator.java index caaa07524..40105df4f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IterableIterator.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/IterableIterator.java @@ -16,13 +16,21 @@ package org.sufficientlysecure.keychain.util; +import java.util.ArrayList; import java.util.Iterator; public class IterableIterator implements Iterable { private Iterator mIter; - public IterableIterator(Iterator iter) { + public IterableIterator(Iterator iter, boolean failsafe) { mIter = iter; + if(failsafe && mIter == null) { + // is there a better way? + mIter = new ArrayList().iterator(); + } + } + public IterableIterator(Iterator iter) { + this(iter, false); } public Iterator iterator() { -- cgit v1.2.3 From fee18bd33e56a90f3d0df9d39dc70b3a2bf30132 Mon Sep 17 00:00:00 2001 From: gogowitczak Date: Tue, 18 Mar 2014 15:44:20 +0100 Subject: Fixed coding style. --- .../keychain/ui/adapter/ImportKeysListEntry.java | 49 ++-- .../keychain/util/HkpKeyServer.java | 250 +++++++++++---------- 2 files changed, 153 insertions(+), 146 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index 13309435d..05521b0c9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -173,33 +173,30 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.hexKeyId = PgpKeyHelper.convertKeyIdToHex(keyId); this.bitStrength = pgpKeyRing.getPublicKey().getBitStrength(); final int algorithm = pgpKeyRing.getPublicKey().getAlgorithm(); - this.algorithm = getAlgorithmFromId(algorithm); + this.algorithm = getAlgorithmFromId(algorithm); } - /** - * Based on OpenPGP Message Format - */ - private final static SparseArray ALGORITHM_IDS = new SparseArray() {{ - put(-1, "unknown"); // TODO: with resources - put(0, "unencrypted"); - put(PGPPublicKey.RSA_GENERAL, "RSA"); - put(PGPPublicKey.RSA_ENCRYPT, "RSA"); - put(PGPPublicKey.RSA_SIGN, "RSA"); - put(PGPPublicKey.ELGAMAL_ENCRYPT, "ElGamal"); - put(PGPPublicKey.ELGAMAL_GENERAL, "ElGamal"); - put(PGPPublicKey.DSA, "DSA"); - put(PGPPublicKey.EC, "ECC"); - put(PGPPublicKey.ECDSA, "ECC"); - put(PGPPublicKey.ECDH, "ECC"); - }}; - - /** - * Based on OpenPGP Message Format - */ - public static String getAlgorithmFromId(int algorithmId) { - return (ALGORITHM_IDS.get(algorithmId) != null ? ALGORITHM_IDS.get(algorithmId) : ALGORITHM_IDS.get(-1)); - } + /** + * Based on OpenPGP Message Format + */ + private final static SparseArray ALGORITHM_IDS = new SparseArray() {{ + put(-1, "unknown"); // TODO: with resources + put(0, "unencrypted"); + put(PGPPublicKey.RSA_GENERAL, "RSA"); + put(PGPPublicKey.RSA_ENCRYPT, "RSA"); + put(PGPPublicKey.RSA_SIGN, "RSA"); + put(PGPPublicKey.ELGAMAL_ENCRYPT, "ElGamal"); + put(PGPPublicKey.ELGAMAL_GENERAL, "ElGamal"); + put(PGPPublicKey.DSA, "DSA"); + put(PGPPublicKey.EC, "ECC"); + put(PGPPublicKey.ECDSA, "ECC"); + put(PGPPublicKey.ECDH, "ECC"); + }}; + /** + * Based on OpenPGP Message Format + */ + public static String getAlgorithmFromId(int algorithmId) { + return (ALGORITHM_IDS.get(algorithmId) != null ? ALGORITHM_IDS.get(algorithmId) : ALGORITHM_IDS.get(-1)); + } } - - diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 0839fc494..a354d19e8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -69,55 +69,64 @@ public class HkpKeyServer extends KeyServer { private String mHost; private short mPort; - /** - * pub:%keyid%:%algo%:%keylen%:%creationdate%:%expirationdate%:%flags% - *

    - *
  • %keyid% = this is either the fingerprint or the key ID of the key. - * Either the 16-digit or 8-digit key IDs are acceptable, but obviously the fingerprint is best.
  • - *
  • %algo% = the algorithm number, (i.e. 1==RSA, 17==DSA, etc). See RFC-2440
  • - *
  • %keylen% = the key length (i.e. 1024, 2048, 4096, etc.)
  • - *
  • %creationdate% = creation date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • - *
  • %expirationdate% = expiration date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • - *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The - * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so - * the absence of a given flag does not necessarily mean the absence of the detail. - *
      - *
    • r == revoked
    • - *
    • d == disabled
    • - *
    • e == expired
    • - *
    - *
  • - *
- * - * - * @see 5.2. Machine Readable Indexes in Internet-Draft OpenPGP HTTP Keyserver Protocol Document - */ - public static final Pattern PUB_KEY_LINE = Pattern - .compile("pub:([0-9a-fA-F]+):([0-9]+):([0-9]+):([0-9]+):([0-9]*):([rde]*)[ \n\r]*" // pub line - + "(uid:(.*):([0-9]+):([0-9]*):([rde]*))+", // one or more uid lines - Pattern.CASE_INSENSITIVE); - - /** - * uid:%escaped uid string%:%creationdate%:%expirationdate%:%flags% - *
    - *
  • %escaped uid string% = the user ID string, with HTTP %-escaping for anything that isn't 7-bit - * safe as well as for the ":" character. Any other characters may be escaped, as desired.
  • - *
  • %creationdate% = creation date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • - *
  • %expirationdate% = expiration date of the key in standard RFC-2440 form (i.e. number of seconds since 1/1/1970 UTC time)
  • - *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The - * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so - * the absence of a given flag does not necessarily mean the absence of the detail. - *
      - *
    • r == revoked
    • - *
    • d == disabled
    • - *
    • e == expired
    • - *
    - *
  • - *
- */ - public static final Pattern UID_LINE = Pattern - .compile("uid:(.*):([0-9]+):([0-9]*):([rde]*)", - Pattern.CASE_INSENSITIVE); + /** + * pub:%keyid%:%algo%:%keylen%:%creationdate%:%expirationdate%:%flags% + *
    + *
  • %keyid% = this is either the fingerprint or the key ID of the key. Either the 16-digit or 8-digit + * key IDs are acceptable, but obviously the fingerprint is best.
  • + *
  • %algo% = the algorithm number, (i.e. 1==RSA, 17==DSA, etc). + * See RFC-2440
  • + *
  • %keylen% = the key length (i.e. 1024, 2048, 4096, etc.)
  • + *
  • %creationdate% = creation date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %expirationdate% = expiration date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The + * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so + * the absence of a given flag does not necessarily mean the absence of the detail. + *
      + *
    • r == revoked
    • + *
    • d == disabled
    • + *
    • e == expired
    • + *
    + *
  • + *
+ * + * @see 5.2. Machine Readable Indexes + * in Internet-Draft OpenPGP HTTP Keyserver Protocol Document + */ + public static final Pattern PUB_KEY_LINE = Pattern + .compile("pub:([0-9a-fA-F]+):([0-9]+):([0-9]+):([0-9]+):([0-9]*):([rde]*)[ \n\r]*" // pub line + + "(uid:(.*):([0-9]+):([0-9]*):([rde]*))+", // one or more uid lines + Pattern.CASE_INSENSITIVE); + + /** + * uid:%escaped uid string%:%creationdate%:%expirationdate%:%flags% + *
    + *
  • %escaped uid string% = the user ID string, with HTTP %-escaping for anything that isn't 7-bit + * safe as well as for the ":" character. Any other characters may be escaped, as desired.
  • + *
  • %creationdate% = creation date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %expirationdate% = expiration date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The + * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so + * the absence of a given flag does not necessarily mean the absence of the detail. + *
      + *
    • r == revoked
    • + *
    • d == disabled
    • + *
    • e == expired
    • + *
    + *
  • + *
+ */ + public static final Pattern UID_LINE = Pattern + .compile("uid:(.*):([0-9]+):([0-9]*):([rde]*)", + Pattern.CASE_INSENSITIVE); private static final short PORT_DEFAULT = 11371; @@ -192,77 +201,78 @@ public class HkpKeyServer extends KeyServer { throw new QueryException("querying server(s) for '" + mHost + "' failed"); } - @Override - public ArrayList search(String query) throws QueryException, TooManyResponses, - InsufficientQuery { - ArrayList results = new ArrayList(); - - if (query.length() < 3) { - throw new InsufficientQuery(); - } - - String encodedQuery; - try { - encodedQuery = URLEncoder.encode(query, "utf8"); - } catch (UnsupportedEncodingException e) { - return null; - } - String request = "/pks/lookup?op=index&search=" + encodedQuery + "&options=mr"; - - String data = null; - try { - data = query(request); - } catch (HttpError e) { - if (e.getCode() == 404) { - return results; - } else { - if (e.getData().toLowerCase(Locale.US).contains("no keys found")) { - return results; - } else if (e.getData().toLowerCase(Locale.US).contains("too many")) { - throw new TooManyResponses(); - } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) { - throw new InsufficientQuery(); - } - } - throw new QueryException("querying server(s) for '" + mHost + "' failed"); - } - - final Matcher matcher = PUB_KEY_LINE.matcher(data); - while (matcher.find()) { - final ImportKeysListEntry info = new ImportKeysListEntry(); - info.bitStrength = Integer.parseInt(matcher.group(3)); - final int algorithmId = Integer.decode(matcher.group(2)); - info.algorithm = getAlgorithmFromId(algorithmId); - - info.hexKeyId = "0x" + matcher.group(1); - info.keyId = PgpKeyHelper.convertHexToKeyId(matcher.group(1)); - - final long creationDate = Long.parseLong(matcher.group(4)); - final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); - tmpGreg.setTimeInMillis(creationDate*1000); - info.date = tmpGreg.getTime(); - - info.revoked = matcher.group(6).contains("r"); - info.userIds = new ArrayList(); - - final String uidLines = matcher.group(7); - final Matcher uidMatcher = UID_LINE.matcher(uidLines); - while (uidMatcher.find()) { - String tmp = uidMatcher.group(1).replaceAll("<.*?>", ""); - tmp = Html.fromHtml(tmp).toString().trim(); - if (tmp.contains("%")) - { - try { - tmp = (URLDecoder.decode(tmp, "UTF8")); // converts String like "Universit%C3%A4t" to a proper form "Universität". - } catch (UnsupportedEncodingException ignored) { - } - } - info.userIds.add(tmp); - } - results.add(info); - } - return results; - } + @Override + public ArrayList search(String query) throws QueryException, TooManyResponses, + InsufficientQuery { + ArrayList results = new ArrayList(); + + if (query.length() < 3) { + throw new InsufficientQuery(); + } + + String encodedQuery; + try { + encodedQuery = URLEncoder.encode(query, "utf8"); + } catch (UnsupportedEncodingException e) { + return null; + } + String request = "/pks/lookup?op=index&search=" + encodedQuery + "&options=mr"; + + String data = null; + try { + data = query(request); + } catch (HttpError e) { + if (e.getCode() == 404) { + return results; + } else { + if (e.getData().toLowerCase(Locale.US).contains("no keys found")) { + return results; + } else if (e.getData().toLowerCase(Locale.US).contains("too many")) { + throw new TooManyResponses(); + } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) { + throw new InsufficientQuery(); + } + } + throw new QueryException("querying server(s) for '" + mHost + "' failed"); + } + + final Matcher matcher = PUB_KEY_LINE.matcher(data); + while (matcher.find()) { + final ImportKeysListEntry info = new ImportKeysListEntry(); + info.bitStrength = Integer.parseInt(matcher.group(3)); + final int algorithmId = Integer.decode(matcher.group(2)); + info.algorithm = getAlgorithmFromId(algorithmId); + + info.hexKeyId = "0x" + matcher.group(1); + info.keyId = PgpKeyHelper.convertHexToKeyId(matcher.group(1)); + + final long creationDate = Long.parseLong(matcher.group(4)); + final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + tmpGreg.setTimeInMillis(creationDate * 1000); + info.date = tmpGreg.getTime(); + + info.revoked = matcher.group(6).contains("r"); + info.userIds = new ArrayList(); + + final String uidLines = matcher.group(7); + final Matcher uidMatcher = UID_LINE.matcher(uidLines); + while (uidMatcher.find()) { + String tmp = uidMatcher.group(1).replaceAll("<.*?>", ""); + tmp = Html.fromHtml(tmp).toString().trim(); + if (tmp.contains("%")) { + try { + // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universität". + tmp = (URLDecoder.decode(tmp, "UTF8")); + } catch (UnsupportedEncodingException ignored) { + // will never happen, because "UTF8" is supported + } + } + info.userIds.add(tmp); + } + results.add(info); + } + return results; + } @Override public String get(long keyId) throws QueryException { -- cgit v1.2.3 From fa439c1a721320eb6c4bb17532ff96937bbb4a17 Mon Sep 17 00:00:00 2001 From: Sreeram Boyapati Date: Tue, 18 Mar 2014 07:17:05 +0530 Subject: Can_Encrypt Check added to hide Button --- .../java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index eeb17fea2..b2f9c9f40 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -266,7 +266,10 @@ public class ViewKeyMainFragment extends Fragment implements if (data.moveToFirst()) { // get key id from MASTER_KEY_ID long keyId = data.getLong(KEYS_INDEX_KEY_ID); - + long can_encrypt = data.getLong(KEYS_INDEX_CAN_ENCRYPT); + if(can_encrypt == 0){ + mActionEncrypt.setVisibility(View.GONE); + } String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId); mKeyId.setText(keyIdStr); -- cgit v1.2.3 From f34b3ee5316b95bbef9c9ac30b753d1708c4dbc4 Mon Sep 17 00:00:00 2001 From: Sreeram Boyapati Date: Tue, 18 Mar 2014 20:40:09 +0530 Subject: Button Text changes to Change Passphrase if Passphrase is set --- .../java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index edf980773..93099427d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -368,9 +368,8 @@ public class EditKeyActivity extends ActionBarActivity { } mCurrentPassphrase = ""; - - buildLayout(); mIsPassPhraseSet = PassphraseCacheService.hasPassphrase(this, masterKeyId); + buildLayout(); if (!mIsPassPhraseSet) { // check "no passphrase" checkbox and remove button mNoPassphrase.setChecked(true); @@ -425,11 +424,14 @@ public class EditKeyActivity extends ActionBarActivity { // find views mChangePassphrase = (BootstrapButton) findViewById(R.id.edit_key_btn_change_passphrase); mNoPassphrase = (CheckBox) findViewById(R.id.edit_key_no_passphrase); - // Build layout based on given userIds and keys + LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout container = (LinearLayout) findViewById(R.id.edit_key_container); + if(mIsPassPhraseSet){ + mChangePassphrase.setText(getString(R.string.btn_change_passphrase)); + } mUserIdsView = (SectionView) inflater.inflate(R.layout.edit_key_section, container, false); mUserIdsView.setType(Id.type.user_id); mUserIdsView.setCanEdit(mMasterCanSign); -- cgit v1.2.3 From eebf1c171a0ba70a92d76f5affb93476f6813e30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 18 Mar 2014 16:29:40 +0100 Subject: add mr option in keyserver class before query (code simplification) --- .../java/org/sufficientlysecure/keychain/util/HkpKeyServer.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index a354d19e8..0c07e9b06 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -216,9 +216,9 @@ public class HkpKeyServer extends KeyServer { } catch (UnsupportedEncodingException e) { return null; } - String request = "/pks/lookup?op=index&search=" + encodedQuery + "&options=mr"; + String request = "/pks/lookup?op=index&options=mr&search=" + encodedQuery; - String data = null; + String data; try { data = query(request); } catch (HttpError e) { @@ -279,7 +279,7 @@ public class HkpKeyServer extends KeyServer { HttpClient client = new DefaultHttpClient(); try { HttpGet get = new HttpGet("http://" + mHost + ":" + mPort - + "/pks/lookup?op=get&search=" + PgpKeyHelper.convertKeyIdToHex(keyId) + "&options=mr"); + + "/pks/lookup?op=get&options=mr&search=" + PgpKeyHelper.convertKeyIdToHex(keyId)); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { -- cgit v1.2.3 From 2d3f47eb99c18b188ed6e4f396605d6b0340de16 Mon Sep 17 00:00:00 2001 From: Daniel Hammann Date: Tue, 18 Mar 2014 16:07:17 +0100 Subject: Show revocation status in SelectPublicKeyFragment #375 Added revocation status in Key List View (graphical symbol and red coloring) --- .../sufficientlysecure/keychain/ui/ViewKeyMainFragment.java | 11 ++++++----- .../keychain/ui/adapter/ViewKeyKeysAdapter.java | 13 ++++++++++++- 2 files changed, 18 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index eeb17fea2..7ff4e0c57 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -192,8 +192,8 @@ public class ViewKeyMainFragment extends Fragment implements KeychainContract.Keys.IS_MASTER_KEY, KeychainContract.Keys.ALGORITHM, KeychainContract.Keys.KEY_SIZE, KeychainContract.Keys.CAN_CERTIFY, KeychainContract.Keys.CAN_SIGN, KeychainContract.Keys.CAN_ENCRYPT, - KeychainContract.Keys.CREATION, KeychainContract.Keys.EXPIRY, - KeychainContract.Keys.FINGERPRINT}; + KeychainContract.Keys.IS_REVOKED, KeychainContract.Keys.CREATION, + KeychainContract.Keys.EXPIRY, KeychainContract.Keys.FINGERPRINT}; static final String KEYS_SORT_ORDER = KeychainContract.Keys.RANK + " ASC"; static final int KEYS_INDEX_ID = 0; static final int KEYS_INDEX_KEY_ID = 1; @@ -203,9 +203,10 @@ public class ViewKeyMainFragment extends Fragment implements static final int KEYS_INDEX_CAN_CERTIFY = 5; static final int KEYS_INDEX_CAN_SIGN = 6; static final int KEYS_INDEX_CAN_ENCRYPT = 7; - static final int KEYS_INDEX_CREATION = 8; - static final int KEYS_INDEX_EXPIRY = 9; - static final int KEYS_INDEX_FINGERPRINT = 10; + static final int KEYS_INDEX_IS_REVOKED = 8; + static final int KEYS_INDEX_CREATION = 9; + static final int KEYS_INDEX_EXPIRY = 10; + static final int KEYS_INDEX_FINGERPRINT = 11; public Loader onCreateLoader(int id, Bundle args) { switch (id) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index 153a3f266..5f911275d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -19,6 +19,7 @@ package org.sufficientlysecure.keychain.ui.adapter; import android.content.Context; import android.database.Cursor; +import android.graphics.Color; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; @@ -39,6 +40,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { private int mIndexCanCertify; private int mIndexCanEncrypt; private int mIndexCanSign; + private int mIndexRevokedKey; public ViewKeyKeysAdapter(Context context, Cursor c, int flags) { super(context, c, flags); @@ -70,6 +72,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { mIndexCanCertify = cursor.getColumnIndexOrThrow(Keys.CAN_CERTIFY); mIndexCanEncrypt = cursor.getColumnIndexOrThrow(Keys.CAN_ENCRYPT); mIndexCanSign = cursor.getColumnIndexOrThrow(Keys.CAN_SIGN); + mIndexRevokedKey = cursor.getColumnIndexOrThrow(Keys.IS_REVOKED); } } @@ -81,13 +84,13 @@ public class ViewKeyKeysAdapter extends CursorAdapter { ImageView certifyIcon = (ImageView) view.findViewById(R.id.ic_certifyKey); ImageView encryptIcon = (ImageView) view.findViewById(R.id.ic_encryptKey); ImageView signIcon = (ImageView) view.findViewById(R.id.ic_signKey); + ImageView revokedKeyIcon = (ImageView) view.findViewById(R.id.ic_revokedKey); String keyIdStr = PgpKeyHelper.convertKeyIdToHex(cursor.getLong(mIndexKeyId)); String algorithmStr = PgpKeyHelper.getAlgorithmInfo(cursor.getInt(mIndexAlgorithm), cursor.getInt(mIndexKeySize)); keyId.setText(keyIdStr); - keyDetails.setText("(" + algorithmStr + ")"); if (cursor.getInt(mIndexIsMasterKey) != 1) { @@ -113,6 +116,14 @@ public class ViewKeyKeysAdapter extends CursorAdapter { } else { signIcon.setVisibility(View.VISIBLE); } + + if (cursor.getInt(mIndexRevokedKey) > 0) { + revokedKeyIcon.setVisibility(View.VISIBLE); + keyId.setTextColor(Color.RED); + keyDetails.setTextColor(Color.RED); + } else { + revokedKeyIcon.setVisibility(View.GONE); + } } @Override -- cgit v1.2.3 From 163e9fddb9f16d50efe2f936c096bcfec1de2117 Mon Sep 17 00:00:00 2001 From: Sreeram Boyapati Date: Tue, 18 Mar 2014 21:10:09 +0530 Subject: Code Style fix --- .../java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index b2f9c9f40..4844c4028 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -266,8 +266,8 @@ public class ViewKeyMainFragment extends Fragment implements if (data.moveToFirst()) { // get key id from MASTER_KEY_ID long keyId = data.getLong(KEYS_INDEX_KEY_ID); - long can_encrypt = data.getLong(KEYS_INDEX_CAN_ENCRYPT); - if(can_encrypt == 0){ + long canEncrypt = data.getLong(KEYS_INDEX_CAN_ENCRYPT); + if(canEncrypt == 0){ mActionEncrypt.setVisibility(View.GONE); } String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId); -- cgit v1.2.3 From ea648e5a431e20bf7a49ff7e6f41ae89465db8c1 Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 18 Mar 2014 19:24:04 +0200 Subject: fix emails not showing up in import keyserver search --- .../main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 0c07e9b06..9d6850027 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -257,8 +257,7 @@ public class HkpKeyServer extends KeyServer { final String uidLines = matcher.group(7); final Matcher uidMatcher = UID_LINE.matcher(uidLines); while (uidMatcher.find()) { - String tmp = uidMatcher.group(1).replaceAll("<.*?>", ""); - tmp = Html.fromHtml(tmp).toString().trim(); + String tmp = uidMatcher.group(1).trim(); if (tmp.contains("%")) { try { // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universität". -- cgit v1.2.3 From 4aa24413deaa46fc5a583d6e380231a8ce630e00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 18 Mar 2014 18:35:59 +0100 Subject: revert ca_necrypt patch --- .../java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java | 4 ---- 1 file changed, 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 1958d3bb8..e140cb21e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -286,10 +286,6 @@ public class ViewKeyMainFragment extends Fragment implements if (data.moveToFirst()) { // get key id from MASTER_KEY_ID long keyId = data.getLong(KEYS_INDEX_KEY_ID); - long canEncrypt = data.getLong(KEYS_INDEX_CAN_ENCRYPT); - if(canEncrypt == 0){ - mActionEncrypt.setVisibility(View.GONE); - } String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId); mKeyId.setText(keyIdStr); -- cgit v1.2.3 From 654c3029610f932d3d3396ce70e4bf2702427b38 Mon Sep 17 00:00:00 2001 From: uberspot Date: Tue, 18 Mar 2014 20:13:33 +0200 Subject: CertifyKeyActivity sets error if no key is selected --- .../sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 3d22ca9f6..6b57fc568 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -119,8 +119,8 @@ public class SelectSecretKeyLayoutFragment extends Fragment { } public void setError(String error) { - mKeyUserId.requestFocus(); - mKeyUserId.setError(error); + mNoKeySelected.requestFocus(); + mNoKeySelected.setError(error); } /** -- cgit v1.2.3 From 9d60224980e33552993baa20e99c656b1203ab55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 18 Mar 2014 19:36:59 +0100 Subject: Cleanup SelectSecretKeyActivity and also return Uri --- .../keychain/ui/SelectSecretKeyActivity.java | 89 +++++----------------- .../keychain/ui/SelectSecretKeyFragment.java | 12 +-- 2 files changed, 26 insertions(+), 75 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java index 1509bc88c..40771b90d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java @@ -1,36 +1,32 @@ /* - * Copyright (C) 2012 Dominik Schürmann - * Copyright (C) 2010 Thialfihar + * Copyright (C) 2012-2014 Dominik Schürmann * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * - * http://www.apache.org/licenses/LICENSE-2.0 + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package org.sufficientlysecure.keychain.ui; import android.content.Intent; +import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; -import android.view.Menu; -import org.sufficientlysecure.keychain.Constants; + import org.sufficientlysecure.keychain.R; public class SelectSecretKeyActivity extends ActionBarActivity { - // Actions for internal use only: - public static final String ACTION_SELECT_SECRET_KEY = Constants.INTENT_PREFIX - + "SELECT_SECRET_KEYRING"; - public static final String EXTRA_FILTER_CERTIFY = "filter_certify"; public static final String RESULT_EXTRA_MASTER_KEY_ID = "master_key_id"; @@ -50,23 +46,8 @@ public class SelectSecretKeyActivity extends ActionBarActivity { actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setHomeButtonEnabled(false); - setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); - - // TODO: reimplement! - // mFilterLayout = findViewById(R.id.layout_filter); - // mFilterInfo = (TextView) mFilterLayout.findViewById(R.id.filterInfo); - // mClearFilterButton = (Button) mFilterLayout.findViewById(R.id.btn_clear); - // - // mClearFilterButton.setOnClickListener(new OnClickListener() { - // public void onClick(View v) { - // handleIntent(new Intent()); - // } - // }); - mFilterCertify = getIntent().getBooleanExtra(EXTRA_FILTER_CERTIFY, false); - handleIntent(getIntent()); - // Check that the activity is using the layout version with // the fragment_container FrameLayout if (findViewById(R.id.select_secret_key_fragment_container) != null) { @@ -90,48 +71,18 @@ public class SelectSecretKeyActivity extends ActionBarActivity { /** * This is executed by SelectSecretKeyFragment after clicking on an item * - * @param masterKeyId - * @param userId + * @param selectedUri */ - public void afterListSelection(long masterKeyId, String userId) { + public void afterListSelection(Uri selectedUri) { Intent data = new Intent(); + data.setData(selectedUri); + + // TODO: deprecate RESULT_EXTRA_MASTER_KEY_ID! + long masterKeyId = Long.valueOf(selectedUri.getLastPathSegment()); data.putExtra(RESULT_EXTRA_MASTER_KEY_ID, masterKeyId); - data.putExtra(RESULT_EXTRA_USER_ID, (String) userId); + setResult(RESULT_OK, data); finish(); } - @Override - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - handleIntent(intent); - } - - private void handleIntent(Intent intent) { - // TODO: reimplement! - - // String searchString = null; - // if (Intent.ACTION_SEARCH.equals(intent.getAction())) { - // searchString = intent.getStringExtra(SearchManager.QUERY); - // if (searchString != null && searchString.trim().length() == 0) { - // searchString = null; - // } - // } - - // if (searchString == null) { - // mFilterLayout.setVisibility(View.GONE); - // } else { - // mFilterLayout.setVisibility(View.VISIBLE); - // mFilterInfo.setText(getString(R.string.filterInfo, searchString)); - // } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // TODO: reimplement! - // menu.add(0, Id.menu.option.search, 0, R.string.menu_search).setIcon( - // android.R.drawable.ic_menu_search); - return true; - } - } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java index 47a3fbad3..2efa7d33a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2012-2014 Dominik Schürmann * Copyright (C) 2010 Thialfihar * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -28,6 +28,7 @@ import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; + import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; @@ -55,10 +56,9 @@ public class SelectSecretKeyFragment extends ListFragment implements */ public static SelectSecretKeyFragment newInstance(boolean filterCertify) { SelectSecretKeyFragment frag = new SelectSecretKeyFragment(); - Bundle args = new Bundle(); + Bundle args = new Bundle(); args.putBoolean(ARG_FILTER_CERTIFY, filterCertify); - frag.setArguments(args); return frag; @@ -85,10 +85,10 @@ public class SelectSecretKeyFragment extends ListFragment implements @Override public void onItemClick(AdapterView adapterView, View view, int position, long id) { long masterKeyId = mAdapter.getMasterKeyId(position); - String userId = mAdapter.getUserId(position); + Uri result = KeyRings.buildSecretKeyRingsByMasterKeyIdUri(String.valueOf(masterKeyId)); // return data to activity, which results in finishing it - mActivity.afterListSelection(masterKeyId, userId); + mActivity.afterListSelection(result); } }); @@ -141,7 +141,7 @@ public class SelectSecretKeyFragment extends ListFragment implements + Keys.IS_REVOKED + " = '0' AND valid_keys." + Keys.CAN_SIGN + " = '1' AND valid_keys." + Keys.CREATION + " <= '" + now + "' AND " + "(valid_keys." + Keys.EXPIRY + " IS NULL OR valid_keys." + Keys.EXPIRY - + " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID, }; + + " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID,}; String orderBy = UserIds.USER_ID + " ASC"; -- cgit v1.2.3 From 2435794279bbf8ee8775f4a2629c91827b0a278e Mon Sep 17 00:00:00 2001 From: gogowitczak Date: Tue, 18 Mar 2014 21:52:44 +0100 Subject: Blocked ok button for generating weak (<1024) RSA key. --- .../ui/dialog/CreateKeyDialogFragment.java | 39 +++++++++++++--------- 1 file changed, 23 insertions(+), 16 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java index a41bc2bee..ffb45afc5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/CreateKeyDialogFragment.java @@ -25,6 +25,7 @@ import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; +import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import org.sufficientlysecure.keychain.Id; @@ -113,21 +114,8 @@ public class CreateKeyDialogFragment extends DialogFragment { public void onClick(DialogInterface di, int id) { di.dismiss(); try { - int nKeyIndex = keySize.getSelectedItemPosition(); - switch (nKeyIndex) { - case 0: - mNewKeySize = 512; - break; - case 1: - mNewKeySize = 1024; - break; - case 2: - mNewKeySize = 2048; - break; - case 3: - mNewKeySize = 4096; - break; - } + final String selectedItem = (String) keySize.getSelectedItem(); + mNewKeySize = Integer.parseInt(selectedItem); } catch (NumberFormatException e) { mNewKeySize = 0; } @@ -145,7 +133,26 @@ public class CreateKeyDialogFragment extends DialogFragment { } }); - return dialog.create(); + final AlertDialog alertDialog = dialog.create(); + + final AdapterView.OnItemSelectedListener weakRsaListener = new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + final Choice selectedAlgorithm = (Choice)algorithm.getSelectedItem(); + final int selectedKeySize = Integer.parseInt((String)keySize.getSelectedItem()); + final boolean isWeakRsa = (selectedAlgorithm.getId() == Id.choice.algorithm.rsa && selectedKeySize <= 1024); + alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(!isWeakRsa); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }; + + keySize.setOnItemSelectedListener(weakRsaListener); + algorithm.setOnItemSelectedListener(weakRsaListener); + + return alertDialog; } } -- cgit v1.2.3 From 69d26496a22dbc341fc9e646c13516626007aa08 Mon Sep 17 00:00:00 2001 From: Alexander Sulfrian Date: Wed, 19 Mar 2014 03:32:09 +0100 Subject: use correct LongSparseArray for minimum api level --- .../org/sufficientlysecure/keychain/service/PassphraseCacheService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java index 176d09c1a..5825db01b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/PassphraseCacheService.java @@ -26,7 +26,7 @@ import android.content.Intent; import android.content.IntentFilter; import android.os.*; import android.util.Log; -import android.util.LongSparseArray; +import android.support.v4.util.LongSparseArray; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPPrivateKey; import org.spongycastle.openpgp.PGPSecretKey; -- cgit v1.2.3 From 12b97d251a345cbea644c830fb323b90fa24fdbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 19 Mar 2014 16:22:10 +0100 Subject: Cleanup --- .../org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java index 40771b90d..82a3c2e8e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java @@ -30,9 +30,8 @@ public class SelectSecretKeyActivity extends ActionBarActivity { public static final String EXTRA_FILTER_CERTIFY = "filter_certify"; public static final String RESULT_EXTRA_MASTER_KEY_ID = "master_key_id"; - public static final String RESULT_EXTRA_USER_ID = "user_id"; - private boolean mFilterCertify = false; + private boolean mFilterCertify; private SelectSecretKeyFragment mSelectFragment; @Override -- cgit v1.2.3 From 977e76e7e4589162436e2d82978b0d1189d20297 Mon Sep 17 00:00:00 2001 From: uberspot Date: Wed, 19 Mar 2014 18:28:34 +0200 Subject: add apg's fix for Key id display --- .../main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java | 6 +++++- .../java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java | 2 +- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 2 +- .../keychain/ui/adapter/SelectKeyCursorAdapter.java | 2 +- .../sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java | 2 +- 5 files changed, 9 insertions(+), 5 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index b93c68677..5b00d163a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -477,7 +477,11 @@ public class PgpKeyHelper { * @return */ public static String convertKeyIdToHex(long keyId) { - return "0x" + ((keyId >> 32) > 0 ? convertKeyIdToHex32bit(keyId >> 32) : "") + convertKeyIdToHex32bit(keyId); + return "0x" + convertKeyIdToHex32bit(keyId >> 32) + convertKeyIdToHex32bit(keyId); + } + + public static String convertKeyIdToHexShort(long keyId) { + return "0x" + convertKeyIdToHex32bit(keyId); } private static String convertKeyIdToHex32bit(long keyId) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index d8df5ced3..bd14369b0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -199,7 +199,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements // the first key here is our master key if (data.moveToFirst()) { long keyId = data.getLong(INDEX_MASTER_KEY_ID); - String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId); + String keyIdStr = PgpKeyHelper.convertKeyIdToHexShort(keyId); ((TextView) findViewById(R.id.key_id)).setText(keyIdStr); String mainUserId = data.getString(INDEX_USER_ID); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 6b57fc568..960b4aafb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -71,7 +71,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment { getActivity(), secretKeyId); if (keyRing != null) { PGPSecretKey key = PgpKeyHelper.getMasterKey(keyRing); - String masterkeyIdHex = PgpKeyHelper.convertKeyIdToHex(secretKeyId); + String masterkeyIdHex = PgpKeyHelper.convertKeyIdToHexShort(secretKeyId); if (key != null) { String userId = PgpKeyHelper.getMainUserIdSafe(getActivity(), key); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java index beb76fc10..fbbb9caa4 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SelectKeyCursorAdapter.java @@ -115,7 +115,7 @@ public class SelectKeyCursorAdapter extends HighlightQueryCursorAdapter { // TODO: needed to key id to no? keyId.setText(R.string.no_key); long masterKeyId = cursor.getLong(mIndexMasterKeyId); - keyId.setText(PgpKeyHelper.convertKeyIdToHex(masterKeyId)); + keyId.setText(PgpKeyHelper.convertKeyIdToHexShort(masterKeyId)); // TODO: needed to set unknown_status? status.setText(R.string.unknown_status); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index 5f911275d..0064e9f13 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -86,7 +86,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { ImageView signIcon = (ImageView) view.findViewById(R.id.ic_signKey); ImageView revokedKeyIcon = (ImageView) view.findViewById(R.id.ic_revokedKey); - String keyIdStr = PgpKeyHelper.convertKeyIdToHex(cursor.getLong(mIndexKeyId)); + String keyIdStr = PgpKeyHelper.convertKeyIdToHexShort(cursor.getLong(mIndexKeyId)); String algorithmStr = PgpKeyHelper.getAlgorithmInfo(cursor.getInt(mIndexAlgorithm), cursor.getInt(mIndexKeySize)); -- cgit v1.2.3 From 62fb1fb57931626e73e9928cc44f6eb60f3c101e Mon Sep 17 00:00:00 2001 From: Thialfihar Date: Thu, 20 Mar 2014 00:29:40 +0100 Subject: Fix key list views in main key view Since the views are being reused, a revoked key might set the text color of a view and when the view is being reused for a non-revoked key it is still red. So grab the default text colour and set it explicitly when the key is not revoked. --- .../keychain/ui/adapter/ViewKeyKeysAdapter.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index 0064e9f13..068d6e6e9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -18,6 +18,7 @@ package org.sufficientlysecure.keychain.ui.adapter; import android.content.Context; +import android.content.res.ColorStateList; import android.database.Cursor; import android.graphics.Color; import android.support.v4.widget.CursorAdapter; @@ -42,6 +43,8 @@ public class ViewKeyKeysAdapter extends CursorAdapter { private int mIndexCanSign; private int mIndexRevokedKey; + private ColorStateList mDefaultTextColor; + public ViewKeyKeysAdapter(Context context, Cursor c, int flags) { super(context, c, flags); @@ -122,13 +125,20 @@ public class ViewKeyKeysAdapter extends CursorAdapter { keyId.setTextColor(Color.RED); keyDetails.setTextColor(Color.RED); } else { + keyId.setTextColor(mDefaultTextColor); + keyDetails.setTextColor(mDefaultTextColor); revokedKeyIcon.setVisibility(View.GONE); } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { - return mInflater.inflate(R.layout.view_key_keys_item, null); + View view = mInflater.inflate(R.layout.view_key_keys_item, null); + if (mDefaultTextColor == null) { + TextView keyId = (TextView) view.findViewById(R.id.keyId); + mDefaultTextColor = keyId.getTextColors(); + } + return view; } } -- cgit v1.2.3 From 16ae9c899949b5443c06226993ca2efc23591e72 Mon Sep 17 00:00:00 2001 From: Thialfihar Date: Thu, 20 Mar 2014 14:09:35 +0100 Subject: Let convertKeyIdToHex handle short key IDs If a short key ID is given, then it should only be displayed as such. --- .../main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index 5b00d163a..d201a1426 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -477,6 +477,11 @@ public class PgpKeyHelper { * @return */ public static String convertKeyIdToHex(long keyId) { + long upper = keyId >> 32; + if (upper == 0) { + // this is a short key id + return convertKeyIdToHexShort(keyId); + } return "0x" + convertKeyIdToHex32bit(keyId >> 32) + convertKeyIdToHex32bit(keyId); } -- cgit v1.2.3 From 3fa3fc444bf8a0f21d5bd2949d2141e555077f50 Mon Sep 17 00:00:00 2001 From: Thialfihar Date: Thu, 20 Mar 2014 14:14:02 +0100 Subject: Add debug logging for hkp keyserver actions --- .../sufficientlysecure/keychain/util/HkpKeyServer.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 9d6850027..43b40a4db 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -30,9 +30,11 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; +import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.pgp.PgpHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; +import org.sufficientlysecure.keychain.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -179,6 +181,7 @@ public class HkpKeyServer extends KeyServer { for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; + Log.d(Constants.TAG, "hkp keyserver query: " + url); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); @@ -277,9 +280,10 @@ public class HkpKeyServer extends KeyServer { public String get(long keyId) throws QueryException { HttpClient client = new DefaultHttpClient(); try { - HttpGet get = new HttpGet("http://" + mHost + ":" + mPort - + "/pks/lookup?op=get&options=mr&search=" + PgpKeyHelper.convertKeyIdToHex(keyId)); - + String query = "http://" + mHost + ":" + mPort + + "/pks/lookup?op=get&options=mr&search=" + PgpKeyHelper.convertKeyIdToHex(keyId); + Log.d(Constants.TAG, "hkp keyserver get: " + query); + HttpGet get = new HttpGet(query); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new QueryException("not found"); @@ -305,8 +309,9 @@ public class HkpKeyServer extends KeyServer { public void add(String armoredText) throws AddKeyException { HttpClient client = new DefaultHttpClient(); try { - HttpPost post = new HttpPost("http://" + mHost + ":" + mPort + "/pks/add"); - + String query = "http://" + mHost + ":" + mPort + "/pks/add"; + HttpPost post = new HttpPost(query); + Log.d(Constants.TAG, "hkp keyserver add: " + query); List nameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("keytext", armoredText)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); -- cgit v1.2.3 From 2b774899322ae31f1d22999caae68c3f80985c8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 20 Mar 2014 15:54:49 +0100 Subject: Dont try to parse key/fingerprint result from keyserver query --- .../keychain/pgp/PgpKeyHelper.java | 19 ++--- .../keychain/service/KeychainIntentService.java | 2 +- .../keychain/ui/adapter/ImportKeysAdapter.java | 6 +- .../keychain/ui/adapter/ImportKeysListEntry.java | 43 +++++----- .../keychain/util/HkpKeyServer.java | 98 ++++++++++++---------- .../keychain/util/KeyServer.java | 4 +- 6 files changed, 87 insertions(+), 85 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index d201a1426..09c0b2d8f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -460,12 +460,16 @@ public class PgpKeyHelper { public static String convertFingerprintToHex(byte[] fingerprint, boolean split) { String hexString = Hex.toHexString(fingerprint); if (split) { - hexString = hexString.replaceAll("(.{4})(?!$)", "$1 "); + hexString = splitFingerprintHex(hexString); } return hexString; } + public static String splitFingerprintHex(String hexString) { + return hexString.replaceAll("(.{4})(?!$)", "$1 "); + } + /** * Convert key id from long to 64 bit hex string *

@@ -497,19 +501,6 @@ public class PgpKeyHelper { return hexString; } - /** - * Used in HkpKeyServer to convert hex encoded key ids back to long. - * - * @param hexString - * @return - */ - public static long convertHexToKeyId(String hexString) { - int len = hexString.length(); - String s2 = hexString.substring(len - 8); - String s1 = hexString.substring(0, len - 8); - return ((!s1.isEmpty() ? Long.parseLong(s1, 16) << 32 : 0) | Long.parseLong(s2, 16)); - } - /** * Splits userId string into naming part, email part, and comment part * diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 6ec6dcf8a..5af81d39d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -749,7 +749,7 @@ public class KeychainIntentService extends IntentService HkpKeyServer server = new HkpKeyServer(keyServer); for (ImportKeysListEntry entry : entries) { - byte[] downloadedKey = server.get(entry.getKeyId()).getBytes(); + byte[] downloadedKey = server.get(entry.getKeyIdHex()).getBytes(); /** * TODO: copied from ImportKeysListLoader diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index 0f05af447..37a8dd416 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -134,10 +134,10 @@ public class ImportKeysAdapter extends ArrayAdapter { holder.mMainUserIdRest.setVisibility(View.GONE); } - holder.mKeyId.setText(entry.hexKeyId); + holder.mKeyId.setText(entry.keyIdHex); - if (entry.fingerPrint != null) { - holder.mFingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrint); + if (entry.fingerPrintHex != null) { + holder.mFingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrintHex); holder.mFingerprint.setVisibility(View.VISIBLE); } else { holder.mFingerprint.setVisibility(View.GONE); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index 05521b0c9..d7c38213d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -20,6 +20,7 @@ package org.sufficientlysecure.keychain.ui.adapter; import android.os.Parcel; import android.os.Parcelable; import android.util.SparseArray; + import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPSecretKeyRing; @@ -38,10 +39,11 @@ public class ImportKeysListEntry implements Serializable, Parcelable { public ArrayList userIds; public long keyId; + public String keyIdHex; + public boolean revoked; public Date date; // TODO: not displayed - public String fingerPrint; - public String hexKeyId; + public String fingerPrintHex; public int bitStrength; public String algorithm; public boolean secretKey; @@ -55,8 +57,8 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.keyId = b.keyId; this.revoked = b.revoked; this.date = b.date; - this.fingerPrint = b.fingerPrint; - this.hexKeyId = b.hexKeyId; + this.fingerPrintHex = b.fingerPrintHex; + this.keyIdHex = b.keyIdHex; this.bitStrength = b.bitStrength; this.algorithm = b.algorithm; this.secretKey = b.secretKey; @@ -74,8 +76,8 @@ public class ImportKeysListEntry implements Serializable, Parcelable { dest.writeLong(keyId); dest.writeByte((byte) (revoked ? 1 : 0)); dest.writeSerializable(date); - dest.writeString(fingerPrint); - dest.writeString(hexKeyId); + dest.writeString(fingerPrintHex); + dest.writeString(keyIdHex); dest.writeInt(bitStrength); dest.writeString(algorithm); dest.writeByte((byte) (secretKey ? 1 : 0)); @@ -92,8 +94,8 @@ public class ImportKeysListEntry implements Serializable, Parcelable { vr.keyId = source.readLong(); vr.revoked = source.readByte() == 1; vr.date = (Date) source.readSerializable(); - vr.fingerPrint = source.readString(); - vr.hexKeyId = source.readString(); + vr.fingerPrintHex = source.readString(); + vr.keyIdHex = source.readString(); vr.bitStrength = source.readInt(); vr.algorithm = source.readString(); vr.secretKey = source.readByte() == 1; @@ -109,8 +111,8 @@ public class ImportKeysListEntry implements Serializable, Parcelable { } }; - public long getKeyId() { - return keyId; + public String getKeyIdHex() { + return keyIdHex; } public byte[] getBytes() { @@ -121,6 +123,14 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.mBytes = bytes; } + public boolean isSelected() { + return mSelected; + } + + public void setSelected(boolean selected) { + this.mSelected = selected; + } + /** * Constructor for later querying from keyserver */ @@ -132,14 +142,6 @@ public class ImportKeysListEntry implements Serializable, Parcelable { userIds = new ArrayList(); } - public boolean isSelected() { - return mSelected; - } - - public void setSelected(boolean selected) { - this.mSelected = selected; - } - /** * Constructor based on key object, used for import from NFC, QR Codes, files */ @@ -165,12 +167,13 @@ public class ImportKeysListEntry implements Serializable, Parcelable { for (String userId : new IterableIterator(pgpKeyRing.getPublicKey().getUserIDs())) { userIds.add(userId); } + this.keyId = pgpKeyRing.getPublicKey().getKeyID(); + this.keyIdHex = PgpKeyHelper.convertKeyIdToHex(keyId); this.revoked = pgpKeyRing.getPublicKey().isRevoked(); - this.fingerPrint = PgpKeyHelper.convertFingerprintToHex(pgpKeyRing.getPublicKey() + this.fingerPrintHex = PgpKeyHelper.convertFingerprintToHex(pgpKeyRing.getPublicKey() .getFingerprint(), true); - this.hexKeyId = PgpKeyHelper.convertKeyIdToHex(keyId); this.bitStrength = pgpKeyRing.getPublicKey().getBitStrength(); final int algorithm = pgpKeyRing.getPublicKey().getAlgorithm(); this.algorithm = getAlgorithmFromId(algorithm); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 43b40a4db..3658ef6c6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -18,7 +18,6 @@ package org.sufficientlysecure.keychain.util; -import android.text.Html; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -34,7 +33,6 @@ import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.pgp.PgpHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry; -import org.sufficientlysecure.keychain.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -74,26 +72,26 @@ public class HkpKeyServer extends KeyServer { /** * pub:%keyid%:%algo%:%keylen%:%creationdate%:%expirationdate%:%flags% *

    - *
  • %keyid% = this is either the fingerprint or the key ID of the key. Either the 16-digit or 8-digit - * key IDs are acceptable, but obviously the fingerprint is best.
  • - *
  • %algo% = the algorithm number, (i.e. 1==RSA, 17==DSA, etc). - * See RFC-2440
  • - *
  • %keylen% = the key length (i.e. 1024, 2048, 4096, etc.)
  • - *
  • %creationdate% = creation date of the key in standard - * RFC-2440 form (i.e. number of seconds since - * 1/1/1970 UTC time)
  • - *
  • %expirationdate% = expiration date of the key in standard - * RFC-2440 form (i.e. number of seconds since - * 1/1/1970 UTC time)
  • - *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The - * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so - * the absence of a given flag does not necessarily mean the absence of the detail. - *
      - *
    • r == revoked
    • - *
    • d == disabled
    • - *
    • e == expired
    • - *
    - *
  • + *
  • %keyid% = this is either the fingerprint or the key ID of the key. Either the 16-digit or 8-digit + * key IDs are acceptable, but obviously the fingerprint is best.
  • + *
  • %algo% = the algorithm number, (i.e. 1==RSA, 17==DSA, etc). + * See RFC-2440
  • + *
  • %keylen% = the key length (i.e. 1024, 2048, 4096, etc.)
  • + *
  • %creationdate% = creation date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %expirationdate% = expiration date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The + * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so + * the absence of a given flag does not necessarily mean the absence of the detail. + *
      + *
    • r == revoked
    • + *
    • d == disabled
    • + *
    • e == expired
    • + *
    + *
  • *
* * @see 5.2. Machine Readable Indexes @@ -107,23 +105,23 @@ public class HkpKeyServer extends KeyServer { /** * uid:%escaped uid string%:%creationdate%:%expirationdate%:%flags% *
    - *
  • %escaped uid string% = the user ID string, with HTTP %-escaping for anything that isn't 7-bit - * safe as well as for the ":" character. Any other characters may be escaped, as desired.
  • - *
  • %creationdate% = creation date of the key in standard - * RFC-2440 form (i.e. number of seconds since - * 1/1/1970 UTC time)
  • - *
  • %expirationdate% = expiration date of the key in standard - * RFC-2440 form (i.e. number of seconds since - * 1/1/1970 UTC time)
  • - *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The - * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so - * the absence of a given flag does not necessarily mean the absence of the detail. - *
      - *
    • r == revoked
    • - *
    • d == disabled
    • - *
    • e == expired
    • - *
    - *
  • + *
  • %escaped uid string% = the user ID string, with HTTP %-escaping for anything that isn't 7-bit + * safe as well as for the ":" character. Any other characters may be escaped, as desired.
  • + *
  • %creationdate% = creation date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %expirationdate% = expiration date of the key in standard + * RFC-2440 form (i.e. number of seconds since + * 1/1/1970 UTC time)
  • + *
  • %flags% = letter codes to indicate details of the key, if any. Flags may be in any order. The + * meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so + * the absence of a given flag does not necessarily mean the absence of the detail. + *
      + *
    • r == revoked
    • + *
    • d == disabled
    • + *
    • e == expired
    • + *
    + *
  • *
*/ public static final Pattern UID_LINE = Pattern @@ -246,8 +244,18 @@ public class HkpKeyServer extends KeyServer { final int algorithmId = Integer.decode(matcher.group(2)); info.algorithm = getAlgorithmFromId(algorithmId); - info.hexKeyId = "0x" + matcher.group(1); - info.keyId = PgpKeyHelper.convertHexToKeyId(matcher.group(1)); + // group 1 contains the full fingerprint (v4) or the long key id if available + // see https://bitbucket.org/skskeyserver/sks-keyserver/pull-request/12/fixes-for-machine-readable-indexes/diff + // and https://github.com/openpgp-keychain/openpgp-keychain/issues/259#issuecomment-38168176 + String fingerprintOrKeyId = matcher.group(1); + if (fingerprintOrKeyId.length() > 16) { + info.fingerPrintHex = "0x" + PgpKeyHelper.splitFingerprintHex(fingerprintOrKeyId); + info.keyIdHex = "0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() + - 16, fingerprintOrKeyId.length()); + } else { + // set key id only + info.keyIdHex = "0x" + fingerprintOrKeyId; + } final long creationDate = Long.parseLong(matcher.group(4)); final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); @@ -277,11 +285,11 @@ public class HkpKeyServer extends KeyServer { } @Override - public String get(long keyId) throws QueryException { + public String get(String keyIdHex) throws QueryException { HttpClient client = new DefaultHttpClient(); try { String query = "http://" + mHost + ":" + mPort + - "/pks/lookup?op=get&options=mr&search=" + PgpKeyHelper.convertKeyIdToHex(keyId); + "/pks/lookup?op=get&options=mr&search=" + keyIdHex; Log.d(Constants.TAG, "hkp keyserver get: " + query); HttpGet get = new HttpGet(query); HttpResponse response = client.execute(get); @@ -306,14 +314,14 @@ public class HkpKeyServer extends KeyServer { } @Override - public void add(String armoredText) throws AddKeyException { + public void add(String armoredKey) throws AddKeyException { HttpClient client = new DefaultHttpClient(); try { String query = "http://" + mHost + ":" + mPort + "/pks/add"; HttpPost post = new HttpPost(query); Log.d(Constants.TAG, "hkp keyserver add: " + query); List nameValuePairs = new ArrayList(2); - nameValuePairs.add(new BasicNameValuePair("keytext", armoredText)); + nameValuePairs.add(new BasicNameValuePair("keytext", armoredKey)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java index a31fdc5ae..7f70867a5 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/KeyServer.java @@ -46,7 +46,7 @@ public abstract class KeyServer { abstract List search(String query) throws QueryException, TooManyResponses, InsufficientQuery; - abstract String get(long keyId) throws QueryException; + abstract String get(String keyIdHex) throws QueryException; - abstract void add(String armoredText) throws AddKeyException; + abstract void add(String armoredKey) throws AddKeyException; } -- cgit v1.2.3 From 36815b91851b071ded1cd5707e122f257b932555 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 20 Mar 2014 16:04:05 +0100 Subject: Use getter and setter --- .../keychain/ui/adapter/ImportKeysAdapter.java | 51 ++++++++-------- .../keychain/ui/adapter/ImportKeysListEntry.java | 71 +++++++++++++++++++++- .../keychain/util/HkpKeyServer.java | 29 +++++---- 3 files changed, 111 insertions(+), 40 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index 37a8dd416..d174bd0c8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -43,13 +43,12 @@ public class ImportKeysAdapter extends ArrayAdapter { protected List mData; static class ViewHolder { - private TextView mMainUserId; - private TextView mMainUserIdRest; - private TextView mKeyId; - private TextView mFingerprint; - private TextView mAlgorithm; - private TextView mStatus; - + private TextView mainUserId; + private TextView mainUserIdRest; + private TextView keyId; + private TextView fingerprint; + private TextView algorithm; + private TextView status; } public ImportKeysAdapter(Activity activity) { @@ -100,12 +99,12 @@ public class ImportKeysAdapter extends ArrayAdapter { if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.import_keys_list_entry, null); - holder.mMainUserId = (TextView) convertView.findViewById(R.id.mainUserId); - holder.mMainUserIdRest = (TextView) convertView.findViewById(R.id.mainUserIdRest); - holder.mKeyId = (TextView) convertView.findViewById(R.id.keyId); - holder.mFingerprint = (TextView) convertView.findViewById(R.id.fingerprint); - holder.mAlgorithm = (TextView) convertView.findViewById(R.id.algorithm); - holder.mStatus = (TextView) convertView.findViewById(R.id.status); + holder.mainUserId = (TextView) convertView.findViewById(R.id.mainUserId); + holder.mainUserIdRest = (TextView) convertView.findViewById(R.id.mainUserIdRest); + holder.keyId = (TextView) convertView.findViewById(R.id.keyId); + holder.fingerprint = (TextView) convertView.findViewById(R.id.fingerprint); + holder.algorithm = (TextView) convertView.findViewById(R.id.algorithm); + holder.status = (TextView) convertView.findViewById(R.id.status); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); @@ -119,36 +118,36 @@ public class ImportKeysAdapter extends ArrayAdapter { // show red user id if it is a secret key if (entry.secretKey) { userIdSplit[0] = mActivity.getString(R.string.secret_key) + " " + userIdSplit[0]; - holder.mMainUserId.setTextColor(Color.RED); + holder.mainUserId.setTextColor(Color.RED); } - holder.mMainUserId.setText(userIdSplit[0]); + holder.mainUserId.setText(userIdSplit[0]); } else { - holder.mMainUserId.setText(R.string.user_id_no_name); + holder.mainUserId.setText(R.string.user_id_no_name); } // email if (userIdSplit[1] != null) { - holder.mMainUserIdRest.setText(userIdSplit[1]); - holder.mMainUserIdRest.setVisibility(View.VISIBLE); + holder.mainUserIdRest.setText(userIdSplit[1]); + holder.mainUserIdRest.setVisibility(View.VISIBLE); } else { - holder.mMainUserIdRest.setVisibility(View.GONE); + holder.mainUserIdRest.setVisibility(View.GONE); } - holder.mKeyId.setText(entry.keyIdHex); + holder.keyId.setText(entry.keyIdHex); if (entry.fingerPrintHex != null) { - holder.mFingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrintHex); - holder.mFingerprint.setVisibility(View.VISIBLE); + holder.fingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrintHex); + holder.fingerprint.setVisibility(View.VISIBLE); } else { - holder.mFingerprint.setVisibility(View.GONE); + holder.fingerprint.setVisibility(View.GONE); } - holder.mAlgorithm.setText("" + entry.bitStrength + "/" + entry.algorithm); + holder.algorithm.setText("" + entry.bitStrength + "/" + entry.algorithm); if (entry.revoked) { - holder.mStatus.setText(R.string.revoked); + holder.status.setText(R.string.revoked); } else { - holder.mStatus.setVisibility(View.GONE); + holder.status.setVisibility(View.GONE); } LinearLayout ll = (LinearLayout) convertView.findViewById(R.id.list); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index d7c38213d..2610dfb3e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -36,11 +36,10 @@ import java.util.Date; public class ImportKeysListEntry implements Serializable, Parcelable { private static final long serialVersionUID = -7797972103284992662L; - public ArrayList userIds; + public ArrayList userIds; public long keyId; public String keyIdHex; - public boolean revoked; public Date date; // TODO: not displayed public String fingerPrintHex; @@ -131,6 +130,74 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.mSelected = selected; } + public long getKeyId() { + return keyId; + } + + public void setKeyId(long keyId) { + this.keyId = keyId; + } + + public void setKeyIdHex(String keyIdHex) { + this.keyIdHex = keyIdHex; + } + + public boolean isRevoked() { + return revoked; + } + + public void setRevoked(boolean revoked) { + this.revoked = revoked; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getFingerPrintHex() { + return fingerPrintHex; + } + + public void setFingerPrintHex(String fingerPrintHex) { + this.fingerPrintHex = fingerPrintHex; + } + + public int getBitStrength() { + return bitStrength; + } + + public void setBitStrength(int bitStrength) { + this.bitStrength = bitStrength; + } + + public String getAlgorithm() { + return algorithm; + } + + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } + + public boolean isSecretKey() { + return secretKey; + } + + public void setSecretKey(boolean secretKey) { + this.secretKey = secretKey; + } + + public ArrayList getUserIds() { + return userIds; + } + + public void setUserIds(ArrayList userIds) { + this.userIds = userIds; + } + /** * Constructor for later querying from keyserver */ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index 3658ef6c6..a25e3d748 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -239,32 +239,35 @@ public class HkpKeyServer extends KeyServer { final Matcher matcher = PUB_KEY_LINE.matcher(data); while (matcher.find()) { - final ImportKeysListEntry info = new ImportKeysListEntry(); - info.bitStrength = Integer.parseInt(matcher.group(3)); + final ImportKeysListEntry entry = new ImportKeysListEntry(); + + entry.setBitStrength(Integer.parseInt(matcher.group(3))); + final int algorithmId = Integer.decode(matcher.group(2)); - info.algorithm = getAlgorithmFromId(algorithmId); + entry.setAlgorithm(getAlgorithmFromId(algorithmId)); // group 1 contains the full fingerprint (v4) or the long key id if available // see https://bitbucket.org/skskeyserver/sks-keyserver/pull-request/12/fixes-for-machine-readable-indexes/diff // and https://github.com/openpgp-keychain/openpgp-keychain/issues/259#issuecomment-38168176 String fingerprintOrKeyId = matcher.group(1); if (fingerprintOrKeyId.length() > 16) { - info.fingerPrintHex = "0x" + PgpKeyHelper.splitFingerprintHex(fingerprintOrKeyId); - info.keyIdHex = "0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - - 16, fingerprintOrKeyId.length()); + entry.setFingerPrintHex(PgpKeyHelper.splitFingerprintHex( + fingerprintOrKeyId.toLowerCase(Locale.US))); + entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() + - 16, fingerprintOrKeyId.length())); } else { // set key id only - info.keyIdHex = "0x" + fingerprintOrKeyId; + entry.setKeyIdHex("0x" + fingerprintOrKeyId); } final long creationDate = Long.parseLong(matcher.group(4)); final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); tmpGreg.setTimeInMillis(creationDate * 1000); - info.date = tmpGreg.getTime(); + entry.setDate(tmpGreg.getTime()); - info.revoked = matcher.group(6).contains("r"); - info.userIds = new ArrayList(); + entry.setRevoked(matcher.group(6).contains("r")); + ArrayList userIds = new ArrayList(); final String uidLines = matcher.group(7); final Matcher uidMatcher = UID_LINE.matcher(uidLines); while (uidMatcher.find()) { @@ -277,9 +280,11 @@ public class HkpKeyServer extends KeyServer { // will never happen, because "UTF8" is supported } } - info.userIds.add(tmp); + userIds.add(tmp); } - results.add(info); + entry.setUserIds(userIds); + + results.add(entry); } return results; } -- cgit v1.2.3 From 81e0d04230963cdd6db9c64e51316533c0a1d103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 20 Mar 2014 16:09:05 +0100 Subject: colorize fingerprint in import --- .../org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index d174bd0c8..57aaf0733 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -30,7 +30,9 @@ import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; + import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import java.util.ArrayList; @@ -136,7 +138,7 @@ public class ImportKeysAdapter extends ArrayAdapter { holder.keyId.setText(entry.keyIdHex); if (entry.fingerPrintHex != null) { - holder.fingerprint.setText(mActivity.getString(R.string.fingerprint) + " " + entry.fingerPrintHex); + holder.fingerprint.setText(OtherHelper.colorizeFingerprint(entry.fingerPrintHex)); holder.fingerprint.setVisibility(View.VISIBLE); } else { holder.fingerprint.setVisibility(View.GONE); -- cgit v1.2.3 From 77365202e0771abb0a1e8e3a2599ecb9664b3990 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 20 Mar 2014 16:10:42 +0100 Subject: put colorize method into key helper --- .../keychain/helper/OtherHelper.java | 77 ------------------- .../keychain/pgp/PgpKeyHelper.java | 86 ++++++++++++++++++++++ .../keychain/ui/CertifyKeyActivity.java | 2 +- .../keychain/ui/ViewKeyMainFragment.java | 2 +- .../keychain/ui/adapter/ImportKeysAdapter.java | 2 +- 5 files changed, 89 insertions(+), 80 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java index 736bff02d..d0ba20ea6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java @@ -65,81 +65,4 @@ public class OtherHelper { } } - public static SpannableStringBuilder colorizeFingerprint(String fingerprint) { - SpannableStringBuilder sb = new SpannableStringBuilder(fingerprint); - try { - // for each 4 characters of the fingerprint + 1 space - for (int i = 0; i < fingerprint.length(); i += 5) { - int spanEnd = Math.min(i + 4, fingerprint.length()); - String fourChars = fingerprint.substring(i, spanEnd); - - int raw = Integer.parseInt(fourChars, 16); - byte[] bytes = {(byte) ((raw >> 8) & 0xff - 128), (byte) (raw & 0xff - 128)}; - int[] color = OtherHelper.getRgbForData(bytes); - int r = color[0]; - int g = color[1]; - int b = color[2]; - - // we cannot change black by multiplication, so adjust it to an almost-black grey, - // which will then be brightened to the minimal brightness level - if (r == 0 && g == 0 && b == 0) { - r = 1; - g = 1; - b = 1; - } - - // Convert rgb to brightness - double brightness = 0.2126 * r + 0.7152 * g + 0.0722 * b; - - // If a color is too dark to be seen on black, - // then brighten it up to a minimal brightness. - if (brightness < 80) { - double factor = 80.0 / brightness; - r = Math.min(255, (int) (r * factor)); - g = Math.min(255, (int) (g * factor)); - b = Math.min(255, (int) (b * factor)); - - // If it is too light, then darken it to a respective maximal brightness. - } else if (brightness > 180) { - double factor = 180.0 / brightness; - r = (int) (r * factor); - g = (int) (g * factor); - b = (int) (b * factor); - } - - // Create a foreground color with the 3 digest integers as RGB - // and then converting that int to hex to use as a color - sb.setSpan(new ForegroundColorSpan(Color.rgb(r, g, b)), - i, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE); - } - } catch (Exception e) { - Log.e(Constants.TAG, "Colorization failed", e); - // if anything goes wrong, then just display the fingerprint without colour, - // instead of partially correct colour or wrong colours - return new SpannableStringBuilder(fingerprint); - } - - return sb; - } - - /** - * Converts the given bytes to a unique RGB color using SHA1 algorithm - * - * @param bytes - * @return an integer array containing 3 numeric color representations (Red, Green, Black) - * @throws NoSuchAlgorithmException - * @throws DigestException - */ - public static int[] getRgbForData(byte[] bytes) throws NoSuchAlgorithmException, DigestException { - MessageDigest md = MessageDigest.getInstance("SHA1"); - - md.update(bytes); - byte[] digest = md.digest(); - - int[] result = {((int) digest[0] + 256) % 256, - ((int) digest[1] + 256) % 256, - ((int) digest[2] + 256) % 256}; - return result; - } - } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index 09c0b2d8f..35412d4b8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -18,6 +18,11 @@ package org.sufficientlysecure.keychain.pgp; import android.content.Context; +import android.graphics.Color; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.style.ForegroundColorSpan; + import org.spongycastle.bcpg.sig.KeyFlags; import org.spongycastle.openpgp.*; import org.spongycastle.util.encoders.Hex; @@ -27,6 +32,9 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; +import java.security.DigestException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -501,6 +509,84 @@ public class PgpKeyHelper { return hexString; } + + public static SpannableStringBuilder colorizeFingerprint(String fingerprint) { + SpannableStringBuilder sb = new SpannableStringBuilder(fingerprint); + try { + // for each 4 characters of the fingerprint + 1 space + for (int i = 0; i < fingerprint.length(); i += 5) { + int spanEnd = Math.min(i + 4, fingerprint.length()); + String fourChars = fingerprint.substring(i, spanEnd); + + int raw = Integer.parseInt(fourChars, 16); + byte[] bytes = {(byte) ((raw >> 8) & 0xff - 128), (byte) (raw & 0xff - 128)}; + int[] color = getRgbForData(bytes); + int r = color[0]; + int g = color[1]; + int b = color[2]; + + // we cannot change black by multiplication, so adjust it to an almost-black grey, + // which will then be brightened to the minimal brightness level + if (r == 0 && g == 0 && b == 0) { + r = 1; + g = 1; + b = 1; + } + + // Convert rgb to brightness + double brightness = 0.2126 * r + 0.7152 * g + 0.0722 * b; + + // If a color is too dark to be seen on black, + // then brighten it up to a minimal brightness. + if (brightness < 80) { + double factor = 80.0 / brightness; + r = Math.min(255, (int) (r * factor)); + g = Math.min(255, (int) (g * factor)); + b = Math.min(255, (int) (b * factor)); + + // If it is too light, then darken it to a respective maximal brightness. + } else if (brightness > 180) { + double factor = 180.0 / brightness; + r = (int) (r * factor); + g = (int) (g * factor); + b = (int) (b * factor); + } + + // Create a foreground color with the 3 digest integers as RGB + // and then converting that int to hex to use as a color + sb.setSpan(new ForegroundColorSpan(Color.rgb(r, g, b)), + i, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE); + } + } catch (Exception e) { + Log.e(Constants.TAG, "Colorization failed", e); + // if anything goes wrong, then just display the fingerprint without colour, + // instead of partially correct colour or wrong colours + return new SpannableStringBuilder(fingerprint); + } + + return sb; + } + + /** + * Converts the given bytes to a unique RGB color using SHA1 algorithm + * + * @param bytes + * @return an integer array containing 3 numeric color representations (Red, Green, Black) + * @throws java.security.NoSuchAlgorithmException + * @throws java.security.DigestException + */ + private static int[] getRgbForData(byte[] bytes) throws NoSuchAlgorithmException, DigestException { + MessageDigest md = MessageDigest.getInstance("SHA1"); + + md.update(bytes); + byte[] digest = md.digest(); + + int[] result = {((int) digest[0] + 256) % 256, + ((int) digest[1] + 256) % 256, + ((int) digest[2] + 256) % 256}; + return result; + } + /** * Splits userId string into naming part, email part, and comment part * diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index bd14369b0..0983d54fb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -211,7 +211,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements fingerprintBlob = ProviderHelper.getFingerprint(this, mDataUri); } String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); - ((TextView) findViewById(R.id.fingerprint)).setText(OtherHelper.colorizeFingerprint(fingerprint)); + ((TextView) findViewById(R.id.fingerprint)).setText(PgpKeyHelper.colorizeFingerprint(fingerprint)); } break; case LOADER_ID_USER_IDS: diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index e140cb21e..7beef4b5e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -322,7 +322,7 @@ public class ViewKeyMainFragment extends Fragment implements } String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); - mFingerprint.setText(OtherHelper.colorizeFingerprint(fingerprint)); + mFingerprint.setText(PgpKeyHelper.colorizeFingerprint(fingerprint)); } mKeysAdapter.swapCursor(data); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java index 57aaf0733..7d3166af9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java @@ -138,7 +138,7 @@ public class ImportKeysAdapter extends ArrayAdapter { holder.keyId.setText(entry.keyIdHex); if (entry.fingerPrintHex != null) { - holder.fingerprint.setText(OtherHelper.colorizeFingerprint(entry.fingerPrintHex)); + holder.fingerprint.setText(PgpKeyHelper.colorizeFingerprint(entry.fingerPrintHex)); holder.fingerprint.setVisibility(View.VISIBLE); } else { holder.fingerprint.setVisibility(View.GONE); -- cgit v1.2.3 From a17481b80a2d717afdfc981c5c7e7528d1a7abca Mon Sep 17 00:00:00 2001 From: Thialfihar Date: Thu, 20 Mar 2014 18:33:19 +0100 Subject: Group fingerprint again to make it visually consistent --- .../main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index 35412d4b8..ec0932773 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -511,6 +511,11 @@ public class PgpKeyHelper { public static SpannableStringBuilder colorizeFingerprint(String fingerprint) { + // add line breaks to have a consistent "image" that can be recognized + char[] chars = fingerprint.toCharArray(); + chars[24] = '\n'; + fingerprint = String.valueOf(chars); + SpannableStringBuilder sb = new SpannableStringBuilder(fingerprint); try { // for each 4 characters of the fingerprint + 1 space -- cgit v1.2.3 From 0a8b45ee88b9dcdc7a2c6e067fe65f815641b8ee Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Thu, 20 Mar 2014 23:37:29 +0530 Subject: Fix for #451 --- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 164 ++++++++++++--------- 1 file changed, 96 insertions(+), 68 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 960b4aafb..5b441f17b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -19,22 +19,24 @@ package org.sufficientlysecure.keychain.ui; import android.app.Activity; import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.TextView; import com.beardedhen.androidbootstrap.BootstrapButton; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; -import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.provider.KeychainContract; -public class SelectSecretKeyLayoutFragment extends Fragment { +public class SelectSecretKeyLayoutFragment extends Fragment implements LoaderManager.LoaderCallbacks { private TextView mKeyUserId; private TextView mKeyUserIdRest; @@ -43,12 +45,25 @@ public class SelectSecretKeyLayoutFragment extends Fragment { private BootstrapButton mSelectKeyButton; private Boolean mFilterCertify; + private Uri mReceivedUri = null; + private SelectSecretKeyCallback mCallback; private static final int REQUEST_CODE_SELECT_KEY = 8882; + //Loader ID needs to be different from the usual 0 + private static final int LOADER_ID = 2; + + //The Projection we will retrieve, Master Key ID is for convenience sake, + //to avoid having to pass the Key Around + final String[] PROJECTION = new String[]{KeychainContract.UserIds.USER_ID + , KeychainContract.KeyRings.MASTER_KEY_ID}; + final int INDEX_USER_ID = 0; + final int INDEX_MASTER_KEY_ID = 1; + public interface SelectSecretKeyCallback { void onKeySelected(long secretKeyId); + } public void setCallback(SelectSecretKeyCallback callback) { @@ -59,63 +74,25 @@ public class SelectSecretKeyLayoutFragment extends Fragment { mFilterCertify = filterCertify; } - public void selectKey(long secretKeyId) { - if (secretKeyId == Id.key.none) { - mNoKeySelected.setVisibility(View.VISIBLE); - mKeyUserId.setVisibility(View.GONE); - mKeyUserIdRest.setVisibility(View.GONE); - mKeyMasterKeyIdHex.setVisibility(View.GONE); + public void setNoKeySelected() { + mNoKeySelected.setVisibility(View.VISIBLE); + mKeyUserId.setVisibility(View.GONE); + mKeyUserIdRest.setVisibility(View.GONE); + mKeyMasterKeyIdHex.setVisibility(View.GONE); + } - } else { - PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRingByMasterKeyId( - getActivity(), secretKeyId); - if (keyRing != null) { - PGPSecretKey key = PgpKeyHelper.getMasterKey(keyRing); - String masterkeyIdHex = PgpKeyHelper.convertKeyIdToHexShort(secretKeyId); - - if (key != null) { - String userId = PgpKeyHelper.getMainUserIdSafe(getActivity(), key); - - String[] userIdSplit = PgpKeyHelper.splitUserId(userId); - String userName, userEmail; - - if (userIdSplit[0] != null) { - userName = userIdSplit[0]; - } else { - userName = getActivity().getResources().getString(R.string.user_id_no_name); - } - - if (userIdSplit[1] != null) { - userEmail = userIdSplit[1]; - } else { - userEmail = getActivity().getResources().getString(R.string.error_user_id_no_email); - } - - mKeyMasterKeyIdHex.setText(masterkeyIdHex); - mKeyUserId.setText(userName); - mKeyUserIdRest.setText(userEmail); - mKeyMasterKeyIdHex.setVisibility(View.VISIBLE); - mKeyUserId.setVisibility(View.VISIBLE); - mKeyUserIdRest.setVisibility(View.VISIBLE); - mNoKeySelected.setVisibility(View.GONE); - } else { - mKeyMasterKeyIdHex.setVisibility(View.GONE); - mKeyUserId.setVisibility(View.GONE); - mKeyUserIdRest.setVisibility(View.GONE); - mNoKeySelected.setVisibility(View.VISIBLE); - } - } else { - mKeyMasterKeyIdHex.setText( - getActivity().getResources() - .getString(R.string.no_keys_added_or_updated) - + " for master id: " + secretKeyId); - mKeyMasterKeyIdHex.setVisibility(View.VISIBLE); - mKeyUserId.setVisibility(View.GONE); - mKeyUserIdRest.setVisibility(View.GONE); - mNoKeySelected.setVisibility(View.GONE); - } + public void setSelectedKeyData(String userName, String email, String masterKeyHex) { + + mNoKeySelected.setVisibility(View.GONE); + + mKeyUserId.setText(userName); + mKeyUserIdRest.setText(email); + mKeyMasterKeyIdHex.setText(masterKeyHex); + + mKeyUserId.setVisibility(View.VISIBLE); + mKeyUserIdRest.setVisibility(View.VISIBLE); + mKeyMasterKeyIdHex.setVisibility(View.VISIBLE); - } } public void setError(String error) { @@ -147,29 +124,80 @@ public class SelectSecretKeyLayoutFragment extends Fragment { return view; } + //For AppSettingsFragment + public void selectKey(long masterKeyId){ + Uri buildUri = KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(String.valueOf(masterKeyId)); + mReceivedUri=buildUri; + getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, this); + } + private void startSelectKeyActivity() { Intent intent = new Intent(getActivity(), SelectSecretKeyActivity.class); intent.putExtra(SelectSecretKeyActivity.EXTRA_FILTER_CERTIFY, mFilterCertify); startActivityForResult(intent, REQUEST_CODE_SELECT_KEY); } + @Override + public Loader onCreateLoader(int id, Bundle args) { + //We don't care about the Loader id + return new CursorLoader(getActivity(), mReceivedUri, PROJECTION, null, null, null); + } + + @Override + public void onLoadFinished(Loader loader, Cursor data) { + if (data.moveToFirst()) { + String userName, email, masterKeyHex; + String userID = data.getString(INDEX_USER_ID); + long masterKeyID = data.getLong(INDEX_MASTER_KEY_ID); + + String splitUserID[] = PgpKeyHelper.splitUserId(userID); + + if (splitUserID[0] != null) { + userName = splitUserID[0]; + } else { + userName = getActivity().getResources().getString(R.string.user_id_no_name); + } + + if (splitUserID[1] != null) { + email = splitUserID[1]; + } else { + email = getActivity().getResources().getString(R.string.error_user_id_no_email); + } + + //TODO Can the cursor return invalid values for the Master Key ? + masterKeyHex = PgpKeyHelper.convertKeyIdToHexShort(masterKeyID); + + //Set the data + setSelectedKeyData(userName, email, masterKeyHex); + + //Give value to the callback + mCallback.onKeySelected(masterKeyID); + } else { + //Set The empty View + setNoKeySelected(); + } + + } + + @Override + public void onLoaderReset(Loader loader) { + return; + } + // Select Secret Key Activity delivers the intent which was sent by it using interface to Select - // Secret Key Fragment.Intent contains Master Key Id, User Email, User Name, Master Key Id Hex. + // Secret Key Fragment.Intent contains the passed Uri @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode & 0xFFFF) { case REQUEST_CODE_SELECT_KEY: { - long secretKeyId; if (resultCode == Activity.RESULT_OK) { - Bundle bundle = data.getExtras(); - secretKeyId = bundle.getLong(SelectSecretKeyActivity.RESULT_EXTRA_MASTER_KEY_ID); - selectKey(secretKeyId); + mReceivedUri = data.getData(); + + //Must be restartLoader() or the data will not be updated on selecting a new key + getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, this); - // remove displayed errors mKeyUserId.setError(null); - // give value back to callback - mCallback.onKeySelected(secretKeyId); } break; } -- cgit v1.2.3 From 0510e0e217f5b7bab548dccf7bdd75f2bd5c0463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 20 Mar 2014 19:11:51 +0100 Subject: verify downloaded key by comparing fingerprints --- .../keychain/service/KeychainIntentService.java | 80 ++++++++++++---------- 1 file changed, 45 insertions(+), 35 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 5af81d39d..19358adc9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -25,6 +25,7 @@ import android.os.Bundle; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; + import org.spongycastle.openpgp.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; @@ -692,11 +693,11 @@ public class KeychainIntentService extends IntentService for (long masterKeyId : masterKeyIds) { if ((keyType == Id.type.public_key || keyType == Id.type.public_secret_key) - && allPublicMasterKeyIds.contains(masterKeyId)) { + && allPublicMasterKeyIds.contains(masterKeyId)) { publicMasterKeyIds.add(masterKeyId); } if ((keyType == Id.type.secret_key || keyType == Id.type.public_secret_key) - && allSecretMasterKeyIds.contains(masterKeyId)) { + && allSecretMasterKeyIds.contains(masterKeyId)) { secretMasterKeyIds.add(masterKeyId); } } @@ -745,49 +746,58 @@ public class KeychainIntentService extends IntentService ArrayList entries = data.getParcelableArrayList(DOWNLOAD_KEY_LIST); String keyServer = data.getString(DOWNLOAD_KEY_SERVER); + // TODO: add extra which requires fingerprint suport and force verification! + // only supported by newer sks keyserver versions + // this downloads the keys and places them into the ImportKeysListEntry entries HkpKeyServer server = new HkpKeyServer(keyServer); for (ImportKeysListEntry entry : entries) { - byte[] downloadedKey = server.get(entry.getKeyIdHex()).getBytes(); - - /** - * TODO: copied from ImportKeysListLoader - * - * - * this parses the downloaded key - */ - // need to have access to the bufferedInput, so we can reuse it for the possible - // PGPObject chunks after the first one, e.g. files with several consecutive ASCII - // armor blocks - BufferedInputStream bufferedInput = - new BufferedInputStream(new ByteArrayInputStream(downloadedKey)); - try { - - // read all available blocks... (asc files can contain many blocks with BEGIN END) - while (bufferedInput.available() > 0) { - InputStream in = PGPUtil.getDecoderStream(bufferedInput); - PGPObjectFactory objectFactory = new PGPObjectFactory(in); - - // go through all objects in this block - Object obj; - while ((obj = objectFactory.nextObject()) != null) { - Log.d(Constants.TAG, "Found class: " + obj.getClass()); - - if (obj instanceof PGPKeyRing) { - PGPKeyRing newKeyring = (PGPKeyRing) obj; + // if available use complete fingerprint for get request + byte[] downloadedKeyBytes; + if (entry.getFingerPrintHex() != null) { + downloadedKeyBytes = server.get(entry.getFingerPrintHex()).getBytes(); + } else { + downloadedKeyBytes = server.get(entry.getKeyIdHex()).getBytes(); + } - entry.setBytes(newKeyring.getEncoded()); - } else { - Log.e(Constants.TAG, "Object not recognized as PGPKeyRing!"); - } + // create PGPKeyRing object based on downloaded armored key + PGPKeyRing downloadedKey = null; + BufferedInputStream bufferedInput = + new BufferedInputStream(new ByteArrayInputStream(downloadedKeyBytes)); + if (bufferedInput.available() > 0) { + InputStream in = PGPUtil.getDecoderStream(bufferedInput); + PGPObjectFactory objectFactory = new PGPObjectFactory(in); + + // get first object in block + Object obj; + if ((obj = objectFactory.nextObject()) != null) { + Log.d(Constants.TAG, "Found class: " + obj.getClass()); + + if (obj instanceof PGPKeyRing) { + downloadedKey = (PGPKeyRing) obj; + } else { + throw new PgpGeneralException("Object not recognized as PGPKeyRing!"); } } - } catch (Exception e) { - Log.e(Constants.TAG, "Exception on parsing key file!", e); } + + // verify downloaded key by comparing fingerprints + if (entry.getFingerPrintHex() != null) { + String downloadedKeyFp = PgpKeyHelper.convertFingerprintToHex(downloadedKey.getPublicKey().getFingerprint(), false); + if (downloadedKeyFp.equals(entry.getFingerPrintHex())) { + Log.d(Constants.TAG, "fingerprint of downloaded key is the same as the requested fingerprint!"); + } else { + throw new PgpGeneralException("fingerprint of downloaded key is NOT the same as the requested fingerprint!"); + } + } + + // save key bytes in entry object for doing the + // actual import afterwards + entry.setBytes(downloadedKey.getEncoded()); } + Intent importIntent = new Intent(this, KeychainIntentService.class); importIntent.setAction(ACTION_IMPORT_KEYRING); Bundle importData = new Bundle(); -- cgit v1.2.3 From 016641a422ddff652b697a76d7ed59ab9954239e Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Thu, 20 Mar 2014 23:46:26 +0530 Subject: Cleanup for #451 --- .../org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java | 4 ---- .../sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java | 1 - 2 files changed, 5 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java index 82a3c2e8e..0ff88d97c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyActivity.java @@ -76,10 +76,6 @@ public class SelectSecretKeyActivity extends ActionBarActivity { Intent data = new Intent(); data.setData(selectedUri); - // TODO: deprecate RESULT_EXTRA_MASTER_KEY_ID! - long masterKeyId = Long.valueOf(selectedUri.getLastPathSegment()); - data.putExtra(RESULT_EXTRA_MASTER_KEY_ID, masterKeyId); - setResult(RESULT_OK, data); finish(); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 5b441f17b..41e250bb7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -63,7 +63,6 @@ public class SelectSecretKeyLayoutFragment extends Fragment implements LoaderMan public interface SelectSecretKeyCallback { void onKeySelected(long secretKeyId); - } public void setCallback(SelectSecretKeyCallback callback) { -- cgit v1.2.3 From 59d51fe68eb6502c313c6a74d4a1e04d0e959b22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Thu, 20 Mar 2014 19:48:18 +0100 Subject: Fix fingerprint handling --- .../org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java | 14 +++++--------- .../keychain/service/KeychainIntentService.java | 4 ++-- .../sufficientlysecure/keychain/ui/CertifyKeyActivity.java | 4 +++- .../sufficientlysecure/keychain/ui/ViewKeyActivity.java | 2 +- .../keychain/ui/ViewKeyMainFragment.java | 2 +- .../keychain/ui/adapter/ImportKeysListEntry.java | 2 +- .../keychain/ui/dialog/ShareQrCodeDialogFragment.java | 2 +- .../org/sufficientlysecure/keychain/util/HkpKeyServer.java | 3 +-- 8 files changed, 15 insertions(+), 18 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java index ec0932773..b7db92b9b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyHelper.java @@ -452,7 +452,7 @@ public class PgpKeyHelper { key = secretKey.getPublicKey(); } - return convertFingerprintToHex(key.getFingerprint(), true); + return convertFingerprintToHex(key.getFingerprint()); } /** @@ -465,19 +465,12 @@ public class PgpKeyHelper { * @param split split into 4 character chunks * @return */ - public static String convertFingerprintToHex(byte[] fingerprint, boolean split) { + public static String convertFingerprintToHex(byte[] fingerprint) { String hexString = Hex.toHexString(fingerprint); - if (split) { - hexString = splitFingerprintHex(hexString); - } return hexString; } - public static String splitFingerprintHex(String hexString) { - return hexString.replaceAll("(.{4})(?!$)", "$1 "); - } - /** * Convert key id from long to 64 bit hex string *

@@ -511,6 +504,9 @@ public class PgpKeyHelper { public static SpannableStringBuilder colorizeFingerprint(String fingerprint) { + // split by 4 characters + fingerprint = fingerprint.replaceAll("(.{4})(?!$)", "$1 "); + // add line breaks to have a consistent "image" that can be recognized char[] chars = fingerprint.toCharArray(); chars[24] = '\n'; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 19358adc9..0751fa33c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -756,7 +756,7 @@ public class KeychainIntentService extends IntentService // if available use complete fingerprint for get request byte[] downloadedKeyBytes; if (entry.getFingerPrintHex() != null) { - downloadedKeyBytes = server.get(entry.getFingerPrintHex()).getBytes(); + downloadedKeyBytes = server.get("0x" + entry.getFingerPrintHex()).getBytes(); } else { downloadedKeyBytes = server.get(entry.getKeyIdHex()).getBytes(); } @@ -784,7 +784,7 @@ public class KeychainIntentService extends IntentService // verify downloaded key by comparing fingerprints if (entry.getFingerPrintHex() != null) { - String downloadedKeyFp = PgpKeyHelper.convertFingerprintToHex(downloadedKey.getPublicKey().getFingerprint(), false); + String downloadedKeyFp = PgpKeyHelper.convertFingerprintToHex(downloadedKey.getPublicKey().getFingerprint()); if (downloadedKeyFp.equals(entry.getFingerPrintHex())) { Log.d(Constants.TAG, "fingerprint of downloaded key is the same as the requested fingerprint!"); } else { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index 0983d54fb..dff4e9d72 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -198,6 +198,8 @@ public class CertifyKeyActivity extends ActionBarActivity implements case LOADER_ID_KEYRING: // the first key here is our master key if (data.moveToFirst()) { + // TODO: put findViewById in onCreate! + long keyId = data.getLong(INDEX_MASTER_KEY_ID); String keyIdStr = PgpKeyHelper.convertKeyIdToHexShort(keyId); ((TextView) findViewById(R.id.key_id)).setText(keyIdStr); @@ -210,7 +212,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements // FALLBACK for old database entries fingerprintBlob = ProviderHelper.getFingerprint(this, mDataUri); } - String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); + String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob); ((TextView) findViewById(R.id.fingerprint)).setText(PgpKeyHelper.colorizeFingerprint(fingerprint)); } break; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index c4097403c..41bd95db3 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -182,7 +182,7 @@ public class ViewKeyActivity extends ActionBarActivity { String content; if (fingerprintOnly) { byte[] fingerprintBlob = ProviderHelper.getFingerprint(this, dataUri); - String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, false); + String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob); content = Constants.FINGERPRINT_SCHEME + ":" + fingerprint; } else { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 7beef4b5e..dd4e7fa94 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -320,7 +320,7 @@ public class ViewKeyMainFragment extends Fragment implements // FALLBACK for old database entries fingerprintBlob = ProviderHelper.getFingerprint(getActivity(), mDataUri); } - String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, true); + String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob); mFingerprint.setText(PgpKeyHelper.colorizeFingerprint(fingerprint)); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java index 2610dfb3e..9b20effc2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysListEntry.java @@ -240,7 +240,7 @@ public class ImportKeysListEntry implements Serializable, Parcelable { this.revoked = pgpKeyRing.getPublicKey().isRevoked(); this.fingerPrintHex = PgpKeyHelper.convertFingerprintToHex(pgpKeyRing.getPublicKey() - .getFingerprint(), true); + .getFingerprint()); this.bitStrength = pgpKeyRing.getPublicKey().getBitStrength(); final int algorithm = pgpKeyRing.getPublicKey().getAlgorithm(); this.algorithm = getAlgorithmFromId(algorithm); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java index b501ba230..94586810e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java @@ -90,7 +90,7 @@ public class ShareQrCodeDialogFragment extends DialogFragment { alert.setPositiveButton(R.string.btn_okay, null); byte[] fingerprintBlob = ProviderHelper.getFingerprint(getActivity(), dataUri); - String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob, false); + String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob); mText.setText(getString(R.string.share_qr_code_dialog_fingerprint_text) + " " + fingerprint); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java index a25e3d748..b987e1533 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/util/HkpKeyServer.java @@ -251,8 +251,7 @@ public class HkpKeyServer extends KeyServer { // and https://github.com/openpgp-keychain/openpgp-keychain/issues/259#issuecomment-38168176 String fingerprintOrKeyId = matcher.group(1); if (fingerprintOrKeyId.length() > 16) { - entry.setFingerPrintHex(PgpKeyHelper.splitFingerprintHex( - fingerprintOrKeyId.toLowerCase(Locale.US))); + entry.setFingerPrintHex(fingerprintOrKeyId.toLowerCase(Locale.US)); entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - 16, fingerprintOrKeyId.length())); } else { -- cgit v1.2.3 From d9b909a24f4b32225027451062ed6304b1cf9a2e Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Fri, 21 Mar 2014 00:27:03 +0530 Subject: Update fix for #451 --- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 41e250bb7..2fcfc9650 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -50,9 +50,8 @@ public class SelectSecretKeyLayoutFragment extends Fragment implements LoaderMan private SelectSecretKeyCallback mCallback; private static final int REQUEST_CODE_SELECT_KEY = 8882; - - //Loader ID needs to be different from the usual 0 - private static final int LOADER_ID = 2; + + private static final int LOADER_ID = 0; //The Projection we will retrieve, Master Key ID is for convenience sake, //to avoid having to pass the Key Around -- cgit v1.2.3 From 2816461283c0067f524d94ddf9702e119025c9d3 Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Fri, 21 Mar 2014 01:50:20 +0530 Subject: Fix for #410 --- .../keychain/helper/ExportHelper.java | 4 +- .../keychain/provider/ProviderHelper.java | 23 ++- .../keychain/ui/EditKeyActivity.java | 14 +- .../keychain/ui/KeyListFragment.java | 22 +-- .../keychain/ui/ViewKeyActivity.java | 19 +- .../ui/dialog/DeleteKeyDialogFragment.java | 207 ++++++++++++--------- 6 files changed, 147 insertions(+), 142 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 03cf936ee..2bfa796c7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -53,14 +53,14 @@ public class ExportHelper { this.mActivity = activity; } - public void deleteKey(Uri dataUri, final int keyType, Handler deleteHandler) { + public void deleteKey(Uri dataUri, Handler deleteHandler) { long keyRingRowId = Long.valueOf(dataUri.getLastPathSegment()); // Create a new Messenger for the communication back Messenger messenger = new Messenger(deleteHandler); DeleteKeyDialogFragment deleteKeyDialog = DeleteKeyDialogFragment.newInstance(messenger, - new long[]{keyRingRowId}, keyType); + new long[]{keyRingRowId}); deleteKeyDialog.show(mActivity.getSupportFragmentManager(), "deleteKeyDialog"); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index db2c57207..8b6feeafd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2012-2013 Dominik Schürmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -230,7 +230,7 @@ public class ProviderHelper { // get current _ID of key long currentRowId = -1; Cursor oldQuery = context.getContentResolver() - .query(deleteUri, new String[]{KeyRings._ID}, null, null, null); + .query(deleteUri, new String[]{KeyRings._ID}, null, null, null); if (oldQuery != null && oldQuery.moveToFirst()) { currentRowId = oldQuery.getLong(0); } else { @@ -288,7 +288,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing */ private static ContentProviderOperation buildPublicKeyOperations(Context context, - long keyRingRowId, PGPPublicKey key, int rank) throws IOException { + long keyRingRowId, PGPPublicKey key, int rank) throws IOException { ContentValues values = new ContentValues(); values.put(Keys.KEY_ID, key.getKeyID()); values.put(Keys.IS_MASTER_KEY, key.isMasterKey()); @@ -316,7 +316,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add PublicUserIds to database corresponding to a keyRing */ private static ContentProviderOperation buildPublicUserIdOperations(Context context, - long keyRingRowId, String userId, int rank) { + long keyRingRowId, String userId, int rank) { ContentValues values = new ContentValues(); values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId); values.put(UserIds.USER_ID, userId); @@ -331,7 +331,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add PGPSecretKey to database corresponding to a keyRing */ private static ContentProviderOperation buildSecretKeyOperations(Context context, - long keyRingRowId, PGPSecretKey key, int rank) throws IOException { + long keyRingRowId, PGPSecretKey key, int rank) throws IOException { ContentValues values = new ContentValues(); boolean hasPrivate = true; @@ -368,7 +368,7 @@ public class ProviderHelper { * Build ContentProviderOperation to add SecretUserIds to database corresponding to a keyRing */ private static ContentProviderOperation buildSecretUserIdOperations(Context context, - long keyRingRowId, String userId, int rank) { + long keyRingRowId, String userId, int rank) { ContentValues values = new ContentValues(); values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId); values.put(UserIds.USER_ID, userId); @@ -469,6 +469,15 @@ public class ProviderHelper { cr.delete(KeyRings.buildSecretKeyRingsUri(Long.toString(rowId)), null, null); } + public static void deleteUnifiedKeyRing(Context context,String masterKeyId,boolean isSecretKey){ + ContentResolver cr= context.getContentResolver(); + cr.delete(KeyRings.buildPublicKeyRingsByMasterKeyIdUri(masterKeyId),null,null); + if(isSecretKey){ + cr.delete(KeyRings.buildSecretKeyRingsByMasterKeyIdUri(masterKeyId),null,null); + } + + } + /** * Get master key id of keyring by its row id */ @@ -855,4 +864,4 @@ public class ProviderHelper { return signature; } -} +} \ No newline at end of file diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 31804719f..654942db7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2012-2013 Dominik Schürmann * Copyright (C) 2010 Thialfihar * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -46,6 +46,7 @@ import org.sufficientlysecure.keychain.helper.ExportHelper; import org.sufficientlysecure.keychain.pgp.PgpConversionHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; @@ -58,7 +59,6 @@ import org.sufficientlysecure.keychain.ui.widget.SectionView; import org.sufficientlysecure.keychain.ui.widget.UserIdEditor; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; - import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.Vector; @@ -325,9 +325,13 @@ public class EditKeyActivity extends ActionBarActivity { long masterKeyId = ProviderHelper.getMasterKeyId(this, mDataUri); long[] ids = new long[]{masterKeyId}; mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC, - null); + null); return true; case R.id.menu_key_edit_delete: { + //Convert the uri to one based on rowId + long rowId= ProviderHelper.getRowId(this,mDataUri); + Uri convertUri = KeychainContract.KeyRings.buildSecretKeyRingsUri(Long.toString(rowId)); + // Message is received after key is deleted Handler returnHandler = new Handler() { @Override @@ -339,7 +343,7 @@ public class EditKeyActivity extends ActionBarActivity { } }; - mExportHelper.deleteKey(mDataUri, Id.type.secret_key, returnHandler); + mExportHelper.deleteKey(convertUri, returnHandler); return true; } } @@ -697,4 +701,4 @@ public class EditKeyActivity extends ActionBarActivity { : getString(R.string.btn_set_passphrase)); } -} +} \ No newline at end of file diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index cac8b7046..daf455c03 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -355,25 +355,7 @@ public class KeyListFragment extends Fragment @Override public void handleMessage(Message message) { if (message.what == DeleteKeyDialogFragment.MESSAGE_OKAY) { - Bundle returnData = message.getData(); - if (returnData != null - && returnData.containsKey(DeleteKeyDialogFragment.MESSAGE_NOT_DELETED)) { - ArrayList notDeleted = - returnData.getStringArrayList(DeleteKeyDialogFragment.MESSAGE_NOT_DELETED); - String notDeletedMsg = ""; - for (String userId : notDeleted) { - notDeletedMsg += userId + "\n"; - } - Toast.makeText(getActivity(), - getString(R.string.error_can_not_delete_contacts, notDeletedMsg) - + getResources() - .getQuantityString( - R.plurals.error_can_not_delete_info, - notDeleted.size()), - Toast.LENGTH_LONG).show(); - - mode.finish(); - } + mode.finish(); } } }; @@ -382,7 +364,7 @@ public class KeyListFragment extends Fragment Messenger messenger = new Messenger(returnHandler); DeleteKeyDialogFragment deleteKeyDialog = DeleteKeyDialogFragment.newInstance(messenger, - keyRingRowIds, Id.type.public_key); + keyRingRowIds); deleteKeyDialog.show(getActivity().getSupportFragmentManager(), "deleteKeyDialog"); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index c4097403c..5e7cabcac 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -237,25 +237,12 @@ public class ViewKeyActivity extends ActionBarActivity { Handler returnHandler = new Handler() { @Override public void handleMessage(Message message) { - if (message.what == DeleteKeyDialogFragment.MESSAGE_OKAY) { - Bundle returnData = message.getData(); - if (returnData != null - && returnData.containsKey(DeleteKeyDialogFragment.MESSAGE_NOT_DELETED)) { - // we delete only this key, so MESSAGE_NOT_DELETED will solely contain this key - Toast.makeText(ViewKeyActivity.this, - getString(R.string.error_can_not_delete_contact) - + getResources() - .getQuantityString(R.plurals.error_can_not_delete_info, 1), - Toast.LENGTH_LONG).show(); - } else { - setResult(RESULT_CANCELED); - finish(); - } - } + setResult(RESULT_CANCELED); + finish(); } }; - mExportHelper.deleteKey(dataUri, Id.type.public_key, returnHandler); + mExportHelper.deleteKey(dataUri, returnHandler); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java index 1bcf5b33c..76a69328a 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2013-2014 Dominik Schürmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -14,7 +14,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package org.sufficientlysecure.keychain.ui.dialog; import android.app.AlertDialog; @@ -28,6 +27,11 @@ import android.os.Messenger; import android.os.RemoteException; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.CheckBox; +import android.widget.LinearLayout; +import android.widget.TextView; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -35,148 +39,167 @@ import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.util.Log; - import java.util.ArrayList; public class DeleteKeyDialogFragment extends DialogFragment { private static final String ARG_MESSENGER = "messenger"; private static final String ARG_DELETE_KEY_RING_ROW_IDS = "delete_file"; - private static final String ARG_KEY_TYPE = "key_type"; public static final int MESSAGE_OKAY = 1; + public static final int MESSAGE_ERROR = 0; + + private boolean isSingleSelection = false; - public static final String MESSAGE_NOT_DELETED = "not_deleted"; + private TextView mainMessage; + private CheckBox checkDeleteSecret; + private LinearLayout deleteSecretKeyView; + private View inflateView; private Messenger mMessenger; /** * Creates new instance of this delete file dialog fragment */ - public static DeleteKeyDialogFragment newInstance(Messenger messenger, long[] keyRingRowIds, - int keyType) { + public static DeleteKeyDialogFragment newInstance(Messenger messenger, long[] keyRingRowIds + ) { DeleteKeyDialogFragment frag = new DeleteKeyDialogFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_MESSENGER, messenger); args.putLongArray(ARG_DELETE_KEY_RING_ROW_IDS, keyRingRowIds); - args.putInt(ARG_KEY_TYPE, keyType); + //We don't need the key type frag.setArguments(args); return frag; } - /** - * Creates dialog - */ + @Override public Dialog onCreateDialog(Bundle savedInstanceState) { + final FragmentActivity activity = getActivity(); mMessenger = getArguments().getParcelable(ARG_MESSENGER); final long[] keyRingRowIds = getArguments().getLongArray(ARG_DELETE_KEY_RING_ROW_IDS); - final int keyType = getArguments().getInt(ARG_KEY_TYPE); AlertDialog.Builder builder = new AlertDialog.Builder(activity); + + //Setup custom View to display in AlertDialog + LayoutInflater inflater = activity.getLayoutInflater(); + inflateView = inflater.inflate(R.layout.view_key_delete_fragment, null); + builder.setView(inflateView); + + deleteSecretKeyView = (LinearLayout) inflateView.findViewById(R.id.deleteSecretKeyView); + mainMessage = (TextView) inflateView.findViewById(R.id.mainMessage); + checkDeleteSecret = (CheckBox) inflateView.findViewById(R.id.checkDeleteSecret); + builder.setTitle(R.string.warning); + //If only a single key has been selected if (keyRingRowIds.length == 1) { Uri dataUri; - if (keyType == Id.type.public_key) { - dataUri = KeychainContract.KeyRings.buildPublicKeyRingsUri(String.valueOf(keyRingRowIds[0])); + ArrayList publicKeyRings; //Any one will do + isSingleSelection = true; + + long selectedRow = keyRingRowIds[0]; + long keyType; + publicKeyRings = ProviderHelper.getPublicKeyRingsRowIds(activity); + + if (publicKeyRings.contains(selectedRow)) { + //TODO Should be a better method to do this other than getting all the KeyRings + dataUri = KeychainContract.KeyRings.buildPublicKeyRingsUri(String.valueOf(selectedRow)); + keyType = Id.type.public_key; } else { - dataUri = KeychainContract.KeyRings.buildSecretKeyRingsUri(String.valueOf(keyRingRowIds[0])); + dataUri = KeychainContract.KeyRings.buildSecretKeyRingsUri(String.valueOf(selectedRow)); + keyType = Id.type.secret_key; } + String userId = ProviderHelper.getUserId(activity, dataUri); + //Hide the Checkbox and TextView since this is a single selection,user will be notified thru message + deleteSecretKeyView.setVisibility(View.GONE); + //Set message depending on which key it is. + mainMessage.setText(getString(keyType == Id.type.secret_key ? R.string.secret_key_deletion_confirmation + : R.string.public_key_deletetion_confirmation, userId)); + - builder.setMessage(getString( - keyType == Id.type.public_key ? R.string.key_deletion_confirmation - : R.string.secret_key_deletion_confirmation, userId)); } else { - builder.setMessage(R.string.key_deletion_confirmation_multi); + deleteSecretKeyView.setVisibility(View.VISIBLE); + mainMessage.setText(R.string.key_deletion_confirmation_multi); } + builder.setIcon(R.drawable.ic_dialog_alert_holo_light); builder.setPositiveButton(R.string.btn_delete, new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int id) { - ArrayList notDeleted = new ArrayList(); - - if (keyType == Id.type.public_key) { - Uri queryUri = KeychainContract.KeyRings.buildPublicKeyRingsUri(); - String[] projection = new String[]{ - KeychainContract.KeyRings._ID, // 0 - KeychainContract.KeyRings.MASTER_KEY_ID, // 1 - KeychainContract.UserIds.USER_ID // 2 - }; - - // make selection with all entries where _ID is one of the given row ids - String selection = KeychainDatabase.Tables.KEY_RINGS + "." + - KeychainContract.KeyRings._ID + " IN("; - String selectionIDs = ""; - for (int i = 0; i < keyRingRowIds.length; i++) { - selectionIDs += "'" + String.valueOf(keyRingRowIds[i]) + "'"; - if (i + 1 < keyRingRowIds.length) { - selectionIDs += ","; + @Override + public void onClick(DialogInterface dialog, int which) { + Uri queryUri = KeychainContract.KeyRings.buildUnifiedKeyRingsUri(); + String[] projection = new String[]{ + KeychainContract.KeyRings.MASTER_KEY_ID, // 0 + KeychainContract.KeyRings.TYPE// 1 + }; + + // make selection with all entries where _ID is one of the given row ids + String selection = KeychainDatabase.Tables.KEY_RINGS + "." + + KeychainContract.KeyRings._ID + " IN("; + String selectionIDs = ""; + for (int i = 0; i < keyRingRowIds.length; i++) { + selectionIDs += "'" + String.valueOf(keyRingRowIds[i]) + "'"; + if (i + 1 < keyRingRowIds.length) + selectionIDs += ","; } - } - selection += selectionIDs + ")"; - - Cursor cursor = activity.getContentResolver().query(queryUri, projection, - selection, null, null); - - long rowId; - long masterKeyId; - String userId; - try { - while (cursor != null && cursor.moveToNext()) { - rowId = cursor.getLong(0); - masterKeyId = cursor.getLong(1); - userId = cursor.getString(2); - - Log.d(Constants.TAG, "rowId: " + rowId + ", masterKeyId: " + masterKeyId - + ", userId: " + userId); - - // check if a corresponding secret key exists... - Cursor secretCursor = activity.getContentResolver().query( - KeychainContract.KeyRings - .buildSecretKeyRingsByMasterKeyIdUri( - String.valueOf(masterKeyId)), - null, null, null, null - ); - if (secretCursor != null && secretCursor.getCount() > 0) { - notDeleted.add(userId); - } else { - // it is okay to delete this key, no secret key found! - ProviderHelper.deletePublicKeyRing(activity, rowId); + selection += selectionIDs + ")"; + + Cursor cursor = activity.getContentResolver().query(queryUri, projection, + selection, null, null); + + + long masterKeyId; + long keyType; + boolean isSuccessfullyDeleted; + try { + isSuccessfullyDeleted = false; + while (cursor != null && cursor.moveToNext()) { + masterKeyId = cursor.getLong(0); + keyType = cursor.getLong(1); + + Log.d(Constants.TAG, "masterKeyId: " + masterKeyId + + ", keyType:" + (keyType == KeychainContract.KeyTypes.PUBLIC ? "Public" : "Private")); + + + if (keyType == KeychainContract.KeyTypes.SECRET) { + if (checkDeleteSecret.isChecked() || isSingleSelection) { + ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), true); + } + } else { + ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), false); + } } - if (secretCursor != null) { - secretCursor.close(); + + //Check if the selected rows have actually been deleted + cursor = activity.getContentResolver().query(queryUri, projection, selection, null, null); + if (cursor == null || cursor.getCount() == 0 || !checkDeleteSecret.isChecked()) { + isSuccessfullyDeleted = true; + } + + } finally { + if (cursor != null) { + cursor.close(); } + } - } finally { - if (cursor != null) { - cursor.close(); + + dismiss(); + + if (isSuccessfullyDeleted) { + sendMessageToHandler(MESSAGE_OKAY, null); + } else { + sendMessageToHandler(MESSAGE_ERROR, null); } } - } else { - for (long keyRowId : keyRingRowIds) { - ProviderHelper.deleteSecretKeyRing(activity, keyRowId); - } - } - - dismiss(); - if (notDeleted.size() > 0) { - Bundle data = new Bundle(); - data.putStringArrayList(MESSAGE_NOT_DELETED, notDeleted); - sendMessageToHandler(MESSAGE_OKAY, data); - } else { - sendMessageToHandler(MESSAGE_OKAY, null); } - } - }); + ); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override @@ -198,7 +221,6 @@ public class DeleteKeyDialogFragment extends DialogFragment { if (data != null) { msg.setData(data); } - try { mMessenger.send(msg); } catch (RemoteException e) { @@ -207,4 +229,5 @@ public class DeleteKeyDialogFragment extends DialogFragment { Log.w(Constants.TAG, "Messenger is null!", e); } } -} + +} \ No newline at end of file -- cgit v1.2.3 From 4e6325a14068c173ed4372f60a3fae968b676e51 Mon Sep 17 00:00:00 2001 From: Nikhil Peter Raj Date: Fri, 21 Mar 2014 01:56:33 +0530 Subject: Fix GPL Headers --- .../java/org/sufficientlysecure/keychain/provider/ProviderHelper.java | 2 +- .../main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java | 2 +- .../sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 8b6feeafd..2fa903fe2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2012-2013 Dominik Schürmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 654942db7..9b64def1e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2012-2013 Dominik Schürmann * Copyright (C) 2010 Thialfihar * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java index 76a69328a..a43debd07 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013-2014 Dominik Schürmann + * Copyright (C) 2013-2014 Dominik Schürmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by -- cgit v1.2.3 From 2f0075e043daab6d59e38cdb110960895a06a2b4 Mon Sep 17 00:00:00 2001 From: Daniel Hammann Date: Thu, 20 Mar 2014 22:35:05 +0100 Subject: URI is transported in intents data not extra. --- .../main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index 1231b6209..28c9c7b28 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -1002,8 +1002,8 @@ public class EncryptActivity extends DrawerActivity { case Id.request.secret_keys: { if (resultCode == RESULT_OK) { - Bundle bundle = data.getExtras(); - mSecretKeyId = bundle.getLong(SelectSecretKeyActivity.RESULT_EXTRA_MASTER_KEY_ID); + Uri uri_master_key = data.getData(); + mSecretKeyId = Long.valueOf(uri_master_key.getLastPathSegment()); } else { mSecretKeyId = Id.key.none; } -- cgit v1.2.3 From 620c67f4412fa56d7edfbfad3ace13f3e409ac5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 21 Mar 2014 10:05:59 +0100 Subject: reformat merge --- .../keychain/ui/SelectSecretKeyLayoutFragment.java | 8 +- .../ui/dialog/DeleteKeyDialogFragment.java | 115 +++++++++++---------- 2 files changed, 64 insertions(+), 59 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java index 2fcfc9650..cbc0f4c5c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/SelectSecretKeyLayoutFragment.java @@ -31,7 +31,9 @@ import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.TextView; + import com.beardedhen.androidbootstrap.BootstrapButton; + import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract; @@ -50,7 +52,7 @@ public class SelectSecretKeyLayoutFragment extends Fragment implements LoaderMan private SelectSecretKeyCallback mCallback; private static final int REQUEST_CODE_SELECT_KEY = 8882; - + private static final int LOADER_ID = 0; //The Projection we will retrieve, Master Key ID is for convenience sake, @@ -123,9 +125,9 @@ public class SelectSecretKeyLayoutFragment extends Fragment implements LoaderMan } //For AppSettingsFragment - public void selectKey(long masterKeyId){ + public void selectKey(long masterKeyId) { Uri buildUri = KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(String.valueOf(masterKeyId)); - mReceivedUri=buildUri; + mReceivedUri = buildUri; getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, this); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java index a43debd07..3ff88aa2b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteKeyDialogFragment.java @@ -14,6 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + package org.sufficientlysecure.keychain.ui.dialog; import android.app.AlertDialog; @@ -32,6 +33,7 @@ import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; + import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; @@ -39,11 +41,12 @@ import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.util.Log; + import java.util.ArrayList; public class DeleteKeyDialogFragment extends DialogFragment { private static final String ARG_MESSENGER = "messenger"; - private static final String ARG_DELETE_KEY_RING_ROW_IDS = "delete_file"; + private static final String ARG_DELETE_KEY_RING_ROW_IDS = "delete_key_ring_row_ids"; public static final int MESSAGE_OKAY = 1; public static final int MESSAGE_ERROR = 0; @@ -131,74 +134,74 @@ public class DeleteKeyDialogFragment extends DialogFragment { builder.setIcon(R.drawable.ic_dialog_alert_holo_light); builder.setPositiveButton(R.string.btn_delete, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Uri queryUri = KeychainContract.KeyRings.buildUnifiedKeyRingsUri(); - String[] projection = new String[]{ - KeychainContract.KeyRings.MASTER_KEY_ID, // 0 - KeychainContract.KeyRings.TYPE// 1 - }; - - // make selection with all entries where _ID is one of the given row ids - String selection = KeychainDatabase.Tables.KEY_RINGS + "." + - KeychainContract.KeyRings._ID + " IN("; - String selectionIDs = ""; - for (int i = 0; i < keyRingRowIds.length; i++) { - selectionIDs += "'" + String.valueOf(keyRingRowIds[i]) + "'"; - if (i + 1 < keyRingRowIds.length) - selectionIDs += ","; - } - selection += selectionIDs + ")"; - - Cursor cursor = activity.getContentResolver().query(queryUri, projection, - selection, null, null); - + @Override + public void onClick(DialogInterface dialog, int which) { + Uri queryUri = KeychainContract.KeyRings.buildUnifiedKeyRingsUri(); + String[] projection = new String[]{ + KeychainContract.KeyRings.MASTER_KEY_ID, // 0 + KeychainContract.KeyRings.TYPE// 1 + }; + + // make selection with all entries where _ID is one of the given row ids + String selection = KeychainDatabase.Tables.KEY_RINGS + "." + + KeychainContract.KeyRings._ID + " IN("; + String selectionIDs = ""; + for (int i = 0; i < keyRingRowIds.length; i++) { + selectionIDs += "'" + String.valueOf(keyRingRowIds[i]) + "'"; + if (i + 1 < keyRingRowIds.length) + selectionIDs += ","; + } + selection += selectionIDs + ")"; - long masterKeyId; - long keyType; - boolean isSuccessfullyDeleted; - try { - isSuccessfullyDeleted = false; - while (cursor != null && cursor.moveToNext()) { - masterKeyId = cursor.getLong(0); - keyType = cursor.getLong(1); + Cursor cursor = activity.getContentResolver().query(queryUri, projection, + selection, null, null); - Log.d(Constants.TAG, "masterKeyId: " + masterKeyId - + ", keyType:" + (keyType == KeychainContract.KeyTypes.PUBLIC ? "Public" : "Private")); + long masterKeyId; + long keyType; + boolean isSuccessfullyDeleted; + try { + isSuccessfullyDeleted = false; + while (cursor != null && cursor.moveToNext()) { + masterKeyId = cursor.getLong(0); + keyType = cursor.getLong(1); - if (keyType == KeychainContract.KeyTypes.SECRET) { - if (checkDeleteSecret.isChecked() || isSingleSelection) { - ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), true); - } - } else { - ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), false); - } - } + Log.d(Constants.TAG, "masterKeyId: " + masterKeyId + + ", keyType:" + (keyType == KeychainContract.KeyTypes.PUBLIC ? "Public" : "Private")); - //Check if the selected rows have actually been deleted - cursor = activity.getContentResolver().query(queryUri, projection, selection, null, null); - if (cursor == null || cursor.getCount() == 0 || !checkDeleteSecret.isChecked()) { - isSuccessfullyDeleted = true; - } - } finally { - if (cursor != null) { - cursor.close(); + if (keyType == KeychainContract.KeyTypes.SECRET) { + if (checkDeleteSecret.isChecked() || isSingleSelection) { + ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), true); } - + } else { + ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), false); } + } - dismiss(); + //Check if the selected rows have actually been deleted + cursor = activity.getContentResolver().query(queryUri, projection, selection, null, null); + if (cursor == null || cursor.getCount() == 0 || !checkDeleteSecret.isChecked()) { + isSuccessfullyDeleted = true; + } - if (isSuccessfullyDeleted) { - sendMessageToHandler(MESSAGE_OKAY, null); - } else { - sendMessageToHandler(MESSAGE_ERROR, null); - } + } finally { + if (cursor != null) { + cursor.close(); } } + + dismiss(); + + if (isSuccessfullyDeleted) { + sendMessageToHandler(MESSAGE_OKAY, null); + } else { + sendMessageToHandler(MESSAGE_ERROR, null); + } + } + + } ); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { -- cgit v1.2.3 From 1b57a10bb6a65a1900c79c68efe4c320177485da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 21 Mar 2014 11:26:18 +0100 Subject: Fix nfc help button --- .../java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java index 44b5848d8..110647284 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysNFCFragment.java @@ -57,7 +57,7 @@ public class ImportKeysNFCFragment extends Fragment { public void onClick(View v) { // show nfc help Intent intent = new Intent(getActivity(), HelpActivity.class); - intent.putExtra(HelpActivity.EXTRA_SELECTED_TAB, 1); + intent.putExtra(HelpActivity.EXTRA_SELECTED_TAB, 2); startActivityForResult(intent, 0); } }); -- cgit v1.2.3 From b7bc8faee6e9500287baf86a6bb4fe42be80ef0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 21 Mar 2014 11:43:30 +0100 Subject: raname to mKeychainDatabase --- .../keychain/provider/KeychainProvider.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index b963ceb39..746449f7e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -247,7 +247,7 @@ public class KeychainProvider extends ContentProvider { return matcher; } - private KeychainDatabase mApgDatabase; + private KeychainDatabase mKeychainDatabase; /** * {@inheritDoc} @@ -255,7 +255,7 @@ public class KeychainProvider extends ContentProvider { @Override public boolean onCreate() { mUriMatcher = buildUriMatcher(); - mApgDatabase = new KeychainDatabase(getContext()); + mKeychainDatabase = new KeychainDatabase(getContext()); return true; } @@ -486,7 +486,7 @@ public class KeychainProvider extends ContentProvider { Log.v(Constants.TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); - SQLiteDatabase db = mApgDatabase.getReadableDatabase(); + SQLiteDatabase db = mKeychainDatabase.getReadableDatabase(); int match = mUriMatcher.match(uri); @@ -715,7 +715,7 @@ public class KeychainProvider extends ContentProvider { public Uri insert(Uri uri, ContentValues values) { Log.d(Constants.TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); - final SQLiteDatabase db = mApgDatabase.getWritableDatabase(); + final SQLiteDatabase db = mKeychainDatabase.getWritableDatabase(); Uri rowUri = null; long rowId = -1; @@ -792,7 +792,7 @@ public class KeychainProvider extends ContentProvider { public int delete(Uri uri, String selection, String[] selectionArgs) { Log.v(Constants.TAG, "delete(uri=" + uri + ")"); - final SQLiteDatabase db = mApgDatabase.getWritableDatabase(); + final SQLiteDatabase db = mKeychainDatabase.getWritableDatabase(); int count; final int match = mUriMatcher.match(uri); @@ -853,7 +853,7 @@ public class KeychainProvider extends ContentProvider { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { Log.v(Constants.TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); - final SQLiteDatabase db = mApgDatabase.getWritableDatabase(); + final SQLiteDatabase db = mKeychainDatabase.getWritableDatabase(); String defaultSelection = null; int count = 0; -- cgit v1.2.3 From 8f37569967c44f0693ba63541e4e6ecfe42aa73f Mon Sep 17 00:00:00 2001 From: uberspot Date: Fri, 21 Mar 2014 18:43:11 +0200 Subject: Make foldable settings in EncryptActivity a separate widget --- .../keychain/ui/EncryptActivity.java | 47 ----- .../keychain/ui/widget/FoldableLinearLayout.java | 203 +++++++++++++++++++++ 2 files changed, 203 insertions(+), 47 deletions(-) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FoldableLinearLayout.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index 28c9c7b28..4ccfd393f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -108,11 +108,6 @@ public class EncryptActivity extends DrawerActivity { private String mInputFilename = null; private String mOutputFilename = null; - private Integer mShortAnimationDuration = null; - private boolean mFileAdvancedSettingsVisible = false; - private TextView mFileAdvancedSettings = null; - private LinearLayout mFileAdvancedSettingsContainer = null; - private FontAwesomeText mAdvancedSettingsIcon; private boolean mAsciiArmorDemand = false; private boolean mOverrideAsciiArmor = false; @@ -147,9 +142,6 @@ public class EncryptActivity extends DrawerActivity { updateMode(); updateActionBarButtons(); - - // retrieve and cache the system's short animation time - mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime); } /** @@ -795,49 +787,10 @@ public class EncryptActivity extends DrawerActivity { } }); - mAdvancedSettingsIcon = (FontAwesomeText) findViewById(R.id.advancedSettingsIcon); - mFileAdvancedSettingsContainer = (LinearLayout) findViewById(R.id.fileAdvancedSettingsContainer); - mFileAdvancedSettings = (TextView) findViewById(R.id.advancedSettings); - LinearLayout advancedSettingsControl = (LinearLayout) findViewById(R.id.advancedSettingsControl); - advancedSettingsControl.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - mFileAdvancedSettingsVisible = !mFileAdvancedSettingsVisible; - if (mFileAdvancedSettingsVisible) { - mAdvancedSettingsIcon.setIcon("fa-chevron-down"); - mFileAdvancedSettingsContainer.setVisibility(View.VISIBLE); - AlphaAnimation animation = new AlphaAnimation(0f, 1f); - animation.setDuration(mShortAnimationDuration); - mFileAdvancedSettingsContainer.startAnimation(animation); - mFileAdvancedSettings.setText(R.string.btn_encryption_advanced_settings_hide); - } else { - mAdvancedSettingsIcon.setIcon("fa-chevron-right"); - AlphaAnimation animation = new AlphaAnimation(1f, 0f); - animation.setDuration(mShortAnimationDuration); - animation.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - // do nothing - } - @Override - public void onAnimationEnd(Animation animation) { - // making sure that at the end the container is completely removed from view - mFileAdvancedSettingsContainer.setVisibility(View.GONE); - } - @Override - public void onAnimationRepeat(Animation animation) { - // do nothing - } - }); - mFileAdvancedSettingsContainer.startAnimation(animation); - mFileAdvancedSettings.setText(R.string.btn_encryption_advanced_settings_show); - } - } - }); mFileCompression = (Spinner) findViewById(R.id.fileCompression); Choice[] choices = new Choice[]{ diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FoldableLinearLayout.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FoldableLinearLayout.java new file mode 100644 index 000000000..f9a5b92f3 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/FoldableLinearLayout.java @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.ui.widget; + +import android.content.Context; +import android.content.res.TypedArray; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.view.animation.AlphaAnimation; +import android.view.animation.Animation; +import android.widget.LinearLayout; +import android.widget.TextView; +import com.beardedhen.androidbootstrap.FontAwesomeText; +import org.sufficientlysecure.keychain.R; + +/** + * Class representing a LinearLayout that can fold and hide it's content when pressed + * To use just add the following to your xml layout + + + + + + + + */ +public class FoldableLinearLayout extends LinearLayout { + + private FontAwesomeText mFoldableIcon; + private boolean mFolded; + private boolean mHasMigrated = false; + private Integer mShortAnimationDuration = null; + private TextView mFoldableTextView = null; + private LinearLayout mFoldableContainer = null; + private View mFoldableLayout = null; + + private String mFoldedIconName; + private String mUnFoldedIconName; + private String mFoldedLabel; + private String mUnFoldedLabel; + + public FoldableLinearLayout(Context context) { + super(context); + processAttributes(context, null); + } + + public FoldableLinearLayout(Context context, AttributeSet attrs) { + super(context, attrs); + processAttributes(context, attrs); + } + + public FoldableLinearLayout(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs); + processAttributes(context, attrs); + } + + /** + * Load given attributes to inner variables, + * @param context + * @param attrs + */ + private void processAttributes(Context context, AttributeSet attrs) { + if(attrs != null) { + TypedArray a = context.obtainStyledAttributes(attrs, + R.styleable.FoldableLinearLayout, 0, 0); + mFoldedIconName = a.getString(R.styleable.FoldableLinearLayout_foldedIcon); + mUnFoldedIconName = a.getString(R.styleable.FoldableLinearLayout_unFoldedIcon); + mFoldedLabel = a.getString(R.styleable.FoldableLinearLayout_foldedLabel); + mUnFoldedLabel = a.getString(R.styleable.FoldableLinearLayout_unFoldedLabel); + a.recycle(); + } + // If any attribute isn't found then set a default one + mFoldedIconName = (mFoldedIconName == null) ? "fa-chevron-right" : mFoldedIconName; + mUnFoldedIconName = (mUnFoldedIconName == null) ? "fa-chevron-down" : mUnFoldedIconName; + mFoldedLabel = (mFoldedLabel == null) ? context.getString(R.id.none) : mFoldedLabel; + mUnFoldedLabel = (mUnFoldedLabel == null) ? context.getString(R.id.none) : mUnFoldedLabel; + } + + @Override + protected void onFinishInflate() { + // if the migration has already happened + // there is no need to move any children + if(!mHasMigrated) { + migrateChildrenToContainer(); + mHasMigrated = true; + } + + initialiseInnerViews(); + + super.onFinishInflate(); + } + + /** + * Migrates Child views as declared in xml to the inner foldableContainer + */ + private void migrateChildrenToContainer() { + // Collect children of FoldableLinearLayout as declared in XML + int childNum = getChildCount(); + View[] children = new View[childNum]; + + for(int i = 0; i < childNum; i++) { + children[i] = getChildAt(i); + } + if(children[0].getId() == R.id.foldableControl) { + + } + + // remove all of them from FoldableLinearLayout + detachAllViewsFromParent(); + + // Inflate the inner foldable_linearlayout.xml + LayoutInflater inflator = (LayoutInflater)getContext().getSystemService( + Context.LAYOUT_INFLATER_SERVICE); + + mFoldableLayout = inflator.inflate(R.layout.foldable_linearlayout, this, true); + mFoldableContainer = (LinearLayout) mFoldableLayout.findViewById(R.id.foldableContainer); + + // Push previously collected children into foldableContainer. + for(int i = 0; i < childNum; i++) { + addView(children[i]); + } + } + + private void initialiseInnerViews() { + mFoldableIcon = (FontAwesomeText) mFoldableLayout.findViewById(R.id.foldableIcon); + mFoldableIcon.setIcon(mFoldedIconName); + mFoldableTextView = (TextView) mFoldableLayout.findViewById(R.id.foldableText); + mFoldableTextView.setText(mFoldedLabel); + + // retrieve and cache the system's short animation time + mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime); + + LinearLayout foldableControl = (LinearLayout) mFoldableLayout.findViewById(R.id.foldableControl); + foldableControl.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + mFolded = !mFolded; + if (mFolded) { + mFoldableIcon.setIcon(mUnFoldedIconName); + mFoldableContainer.setVisibility(View.VISIBLE); + AlphaAnimation animation = new AlphaAnimation(0f, 1f); + animation.setDuration(mShortAnimationDuration); + mFoldableContainer.startAnimation(animation); + mFoldableTextView.setText(mUnFoldedLabel); + + } else { + mFoldableIcon.setIcon(mFoldedIconName); + AlphaAnimation animation = new AlphaAnimation(1f, 0f); + animation.setDuration(mShortAnimationDuration); + animation.setAnimationListener(new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) { + // making sure that at the end the container is completely removed from view + mFoldableContainer.setVisibility(View.GONE); + } + + @Override + public void onAnimationRepeat(Animation animation) { } + }); + mFoldableContainer.startAnimation(animation); + mFoldableTextView.setText(mFoldedLabel); + } + } + }); + + } + + /** + * Adds provided child view to foldableContainer View + * @param child + */ + @Override + public void addView(View child) { + if(mFoldableContainer != null) { + mFoldableContainer.addView(child); + } + } +} -- cgit v1.2.3 From 0f6dc253a40ecada0c0c2a467c56ee45b7b9cc72 Mon Sep 17 00:00:00 2001 From: Daniel Hammann Date: Fri, 21 Mar 2014 23:01:24 +0100 Subject: Because of an unknown reason toast messages were commented out. --- .../sufficientlysecure/keychain/ui/EditKeyActivity.java | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 9b64def1e..092a502e1 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -495,11 +495,10 @@ public class EditKeyActivity extends ActionBarActivity { private void saveClicked() { long masterKeyId = getMasterKeyId(); - try { - if (!isPassphraseSet()) { - throw new PgpGeneralException(this.getString(R.string.set_a_passphrase)); - } - + if (!isPassphraseSet()) { + Log.e(Constants.TAG, "No passphrase has been set"); + Toast.makeText(this, R.string.set_a_passphrase, Toast.LENGTH_LONG).show(); + } else { String passphrase = null; if (mIsPassPhraseSet) { passphrase = PassphraseCacheService.getCachedPassphrase(this, masterKeyId); @@ -512,9 +511,6 @@ public class EditKeyActivity extends ActionBarActivity { mCurrentPassphrase = passphrase; finallySaveClicked(); } - } catch (PgpGeneralException e) { - //Toast.makeText(this, getString(R.string.error_message, e.getMessage()), - // Toast.LENGTH_SHORT).show(); } } @@ -576,8 +572,9 @@ public class EditKeyActivity extends ActionBarActivity { // start service with intent startService(intent); } catch (PgpGeneralException e) { - //Toast.makeText(this, getString(R.string.error_message, e.getMessage()), - // Toast.LENGTH_SHORT).show(); + Log.e(Constants.TAG, getString(R.string.error_message, e.getMessage())); + Toast.makeText(this, getString(R.string.error_message, e.getMessage()), + Toast.LENGTH_SHORT).show(); } } -- cgit v1.2.3 From 9c180629510d6b07aa296088f61593234b52a14a Mon Sep 17 00:00:00 2001 From: Daniel Hammann Date: Sat, 22 Mar 2014 15:31:18 +0100 Subject: The current implementation of saving new generated key doesn't save the key due to the public key of master key id can not be resolved by ProviderHelper.getPGPPublicKeyByKeyId (via URI/Cursor). Workaround uses local keys-arraylist for resoving the pubkey of master key id. --- .../keychain/service/KeychainIntentService.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 0751fa33c..e26ee3c76 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -543,7 +543,15 @@ public class KeychainIntentService extends IntentService ProviderHelper.getPGPSecretKeyRingByKeyId(this, masterKeyId), oldPassPhrase, newPassPhrase); } else { - PGPPublicKey pubkey = ProviderHelper.getPGPPublicKeyByKeyId(this, masterKeyId); + //TODO: Workaround due to ProviderHelper.getPGPPublicKeyByKeyId can not resolve public key of master-key id with uri/cursor + PGPPublicKey pubkey = null; + for(PGPSecretKey key : keys) { + PGPPublicKey tempKey = key.getPublicKey(); + if (tempKey.getKeyID() == masterKeyId) { + pubkey = tempKey; + } + } + //PGPPublicKey pubkey = ProviderHelper.getPGPPublicKeyByKeyId(this, masterKeyId); keyOperations.buildSecretKey(userIds, keys, keysUsages, keysExpiryDates, pubkey, oldPassPhrase, newPassPhrase); } -- cgit v1.2.3 From 153b99a186f514ff08f4b2a659202049f237c9fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Sun, 23 Mar 2014 00:03:49 +0100 Subject: Use new FoldableLinearLayout in API settings --- .../service/remote/AppSettingsFragment.java | 46 +++------------------- 1 file changed, 5 insertions(+), 41 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java index 837295018..52b06a2ae 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java @@ -25,13 +25,13 @@ import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; -import android.view.animation.AlphaAnimation; -import android.view.animation.Animation; -import android.widget.*; +import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; -import com.beardedhen.androidbootstrap.BootstrapButton; +import android.widget.ImageView; +import android.widget.Spinner; +import android.widget.TextView; + import org.spongycastle.util.encoders.Hex; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; @@ -50,8 +50,6 @@ public class AppSettingsFragment extends Fragment implements private AppSettings mAppSettings; // view - private LinearLayout mAdvancedSettingsContainer; - private BootstrapButton mAdvancedSettingsButton; private TextView mAppNameView; private ImageView mAppIconView; private Spinner mEncryptionAlgorithm; @@ -117,11 +115,6 @@ public class AppSettingsFragment extends Fragment implements R.id.api_app_settings_select_key_fragment); mSelectKeyFragment.setCallback(this); - mAdvancedSettingsButton = (BootstrapButton) view - .findViewById(R.id.api_app_settings_advanced_button); - mAdvancedSettingsContainer = (LinearLayout) view - .findViewById(R.id.api_app_settings_advanced); - mAppNameView = (TextView) view.findViewById(R.id.api_app_settings_app_name); mAppIconView = (ImageView) view.findViewById(R.id.api_app_settings_app_icon); mEncryptionAlgorithm = (Spinner) view @@ -176,35 +169,6 @@ public class AppSettingsFragment extends Fragment implements public void onNothingSelected(AdapterView parent) { } }); - - final Animation visibleAnimation = new AlphaAnimation(0.0f, 1.0f); - visibleAnimation.setDuration(250); - final Animation invisibleAnimation = new AlphaAnimation(1.0f, 0.0f); - invisibleAnimation.setDuration(250); - - // TODO: Better: collapse/expand animation - // final Animation animation2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, - // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, - // Animation.RELATIVE_TO_SELF, 0.0f);u - // animation2.setDuration(150); - - mAdvancedSettingsButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - if (mAdvancedSettingsContainer.getVisibility() == View.VISIBLE) { - mAdvancedSettingsContainer.startAnimation(invisibleAnimation); - mAdvancedSettingsContainer.setVisibility(View.GONE); - mAdvancedSettingsButton.setText(getString(R.string.api_settings_show_advanced)); - mAdvancedSettingsButton.setLeftIcon("fa-caret-up"); - } else { - mAdvancedSettingsContainer.startAnimation(visibleAnimation); - mAdvancedSettingsContainer.setVisibility(View.VISIBLE); - mAdvancedSettingsButton.setText(getString(R.string.api_settings_hide_advanced)); - mAdvancedSettingsButton.setLeftIcon("fa-caret-down"); - } - } - }); } private void setPackage(String packageName) { -- cgit v1.2.3 From 12402d9a513e83755aa657acd29dd7382f355d5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Sun, 23 Mar 2014 01:16:56 +0100 Subject: New db table for api accounts --- .../keychain/provider/KeychainContract.java | 4 ++++ .../keychain/provider/KeychainDatabase.java | 27 +++++++++++++++++----- 2 files changed, 25 insertions(+), 6 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index 5f2354c24..de51cebbb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -56,10 +56,14 @@ public class KeychainContract { interface ApiAppsColumns { String PACKAGE_NAME = "package_name"; String PACKAGE_SIGNATURE = "package_signature"; + } + + interface ApiAppsAccountsColumns { String KEY_ID = "key_id"; // not a database id String ENCRYPTION_ALGORITHM = "encryption_algorithm"; String HASH_ALORITHM = "hash_algorithm"; String COMPRESSION = "compression"; + String PACKAGE_NAME = "package_name"; // foreign key to api_apps.package_name } public static final class KeyTypes { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java index 031a7d5ae..f7c9fe79d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java @@ -23,6 +23,7 @@ import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsColumns; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsAccountsColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingsColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.KeysColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIdsColumns; @@ -30,13 +31,14 @@ import org.sufficientlysecure.keychain.util.Log; public class KeychainDatabase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "apg.db"; - private static final int DATABASE_VERSION = 7; + private static final int DATABASE_VERSION = 8; public interface Tables { String KEY_RINGS = "key_rings"; String KEYS = "keys"; String USER_IDS = "user_ids"; String API_APPS = "api_apps"; + String API_APPS_ACCOUNTS = "api_apps_accounts"; } private static final String CREATE_KEY_RINGS = "CREATE TABLE IF NOT EXISTS " + Tables.KEY_RINGS @@ -76,11 +78,17 @@ public class KeychainDatabase extends SQLiteOpenHelper { private static final String CREATE_API_APPS = "CREATE TABLE IF NOT EXISTS " + Tables.API_APPS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ApiAppsColumns.PACKAGE_NAME + " TEXT UNIQUE, " - + ApiAppsColumns.PACKAGE_SIGNATURE + " BLOB, " - + ApiAppsColumns.KEY_ID + " INT64, " - + ApiAppsColumns.ENCRYPTION_ALGORITHM + " INTEGER, " - + ApiAppsColumns.HASH_ALORITHM + " INTEGER, " - + ApiAppsColumns.COMPRESSION + " INTEGER)"; + + ApiAppsColumns.PACKAGE_SIGNATURE + " BLOB)"; + + private static final String CREATE_API_APPS_ACCOUNTS = "CREATE TABLE IF NOT EXISTS " + Tables.API_APPS_ACCOUNTS + + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + ApiAppsAccountsColumns.KEY_ID + " INT64, " + + ApiAppsAccountsColumns.ENCRYPTION_ALGORITHM + " INTEGER, " + + ApiAppsAccountsColumns.HASH_ALORITHM + " INTEGER, " + + ApiAppsAccountsColumns.COMPRESSION + " INTEGER" + + ApiAppsAccountsColumns.PACKAGE_NAME + " TEXT NOT NULL, FOREIGN KEY(" + + ApiAppsAccountsColumns.PACKAGE_NAME + ") REFERENCES " + Tables.API_APPS + "(" + + ApiAppsColumns.PACKAGE_NAME + ") ON DELETE CASCADE)"; KeychainDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); @@ -94,6 +102,7 @@ public class KeychainDatabase extends SQLiteOpenHelper { db.execSQL(CREATE_KEYS); db.execSQL(CREATE_USER_IDS); db.execSQL(CREATE_API_APPS); + db.execSQL(CREATE_API_APPS_ACCOUNTS); } @Override @@ -133,6 +142,12 @@ public class KeychainDatabase extends SQLiteOpenHelper { db.execSQL("ALTER TABLE " + Tables.KEYS + " ADD COLUMN " + KeysColumns.FINGERPRINT + " BLOB;"); break; + case 7: + // new db layout for api apps + db.execSQL("DROP TABLE IF EXISTS " + Tables.API_APPS); + db.execSQL(CREATE_API_APPS); + db.execSQL(CREATE_API_APPS_ACCOUNTS); + break; default: break; -- cgit v1.2.3 From 9555ae3bc1287daa27151456a1f266bdc1640e51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Sun, 23 Mar 2014 01:26:49 +0100 Subject: Move classes for OpenPGP API into remote package --- .../keychain/provider/ProviderHelper.java | 10 +- .../keychain/remote/AppSettings.java | 94 +++++ .../keychain/remote/OpenPgpService.java | 463 +++++++++++++++++++++ .../keychain/remote/RemoteService.java | 233 +++++++++++ .../remote/WrongPackageSignatureException.java | 27 ++ .../keychain/remote/ui/AppSettingsActivity.java | 109 +++++ .../keychain/remote/ui/AppSettingsFragment.java | 202 +++++++++ .../keychain/remote/ui/RegisteredAppsAdapter.java | 75 ++++ .../remote/ui/RegisteredAppsListActivity.java | 35 ++ .../remote/ui/RegisteredAppsListFragment.java | 101 +++++ .../keychain/remote/ui/RemoteServiceActivity.java | 279 +++++++++++++ .../keychain/service/remote/AppSettings.java | 94 ----- .../service/remote/AppSettingsActivity.java | 108 ----- .../service/remote/AppSettingsFragment.java | 201 --------- .../keychain/service/remote/OpenPgpService.java | 462 -------------------- .../service/remote/RegisteredAppsAdapter.java | 75 ---- .../service/remote/RegisteredAppsListActivity.java | 35 -- .../service/remote/RegisteredAppsListFragment.java | 101 ----- .../keychain/service/remote/RemoteService.java | 232 ----------- .../service/remote/RemoteServiceActivity.java | 278 ------------- .../remote/WrongPackageSignatureException.java | 27 -- 21 files changed, 1623 insertions(+), 1618 deletions(-) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/WrongPackageSignatureException.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 2fa903fe2..e0d007de7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -33,7 +33,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; -import org.sufficientlysecure.keychain.service.remote.AppSettings; +import org.sufficientlysecure.keychain.remote.AppSettings; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; @@ -801,10 +801,10 @@ public class ProviderHelper { ContentValues values = new ContentValues(); values.put(ApiApps.PACKAGE_NAME, appSettings.getPackageName()); values.put(ApiApps.PACKAGE_SIGNATURE, appSettings.getPackageSignature()); - values.put(ApiApps.KEY_ID, appSettings.getKeyId()); - values.put(ApiApps.COMPRESSION, appSettings.getCompression()); - values.put(ApiApps.ENCRYPTION_ALGORITHM, appSettings.getEncryptionAlgorithm()); - values.put(ApiApps.HASH_ALORITHM, appSettings.getHashAlgorithm()); +// values.put(ApiApps.KEY_ID, appSettings.getKeyId()); +// values.put(ApiApps.COMPRESSION, appSettings.getCompression()); +// values.put(ApiApps.ENCRYPTION_ALGORITHM, appSettings.getEncryptionAlgorithm()); +// values.put(ApiApps.HASH_ALORITHM, appSettings.getHashAlgorithm()); return values; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java new file mode 100644 index 000000000..ad48a402b --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote; + +import org.spongycastle.bcpg.HashAlgorithmTags; +import org.spongycastle.openpgp.PGPEncryptedData; +import org.sufficientlysecure.keychain.Id; + +public class AppSettings { + private String mPackageName; + private byte[] mPackageSignature; + private long mKeyId = Id.key.none; + private int mEncryptionAlgorithm; + private int mHashAlgorithm; + private int mCompression; + + public AppSettings() { + + } + + public AppSettings(String packageName, byte[] packageSignature) { + super(); + this.mPackageName = packageName; + this.mPackageSignature = packageSignature; + // defaults: + this.mEncryptionAlgorithm = PGPEncryptedData.AES_256; + this.mHashAlgorithm = HashAlgorithmTags.SHA512; + this.mCompression = Id.choice.compression.zlib; + } + + public String getPackageName() { + return mPackageName; + } + + public void setPackageName(String packageName) { + this.mPackageName = packageName; + } + + public byte[] getPackageSignature() { + return mPackageSignature; + } + + public void setPackageSignature(byte[] packageSignature) { + this.mPackageSignature = packageSignature; + } + + public long getKeyId() { + return mKeyId; + } + + public void setKeyId(long scretKeyId) { + this.mKeyId = scretKeyId; + } + + public int getEncryptionAlgorithm() { + return mEncryptionAlgorithm; + } + + public void setEncryptionAlgorithm(int encryptionAlgorithm) { + this.mEncryptionAlgorithm = encryptionAlgorithm; + } + + public int getHashAlgorithm() { + return mHashAlgorithm; + } + + public void setHashAlgorithm(int hashAlgorithm) { + this.mHashAlgorithm = hashAlgorithm; + } + + public int getCompression() { + return mCompression; + } + + public void setCompression(int compression) { + this.mCompression = compression; + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java new file mode 100644 index 000000000..9b56a491a --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java @@ -0,0 +1,463 @@ +/* + * Copyright (C) 2013-2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote; + +import android.app.PendingIntent; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.os.IBinder; +import android.os.ParcelFileDescriptor; +import org.openintents.openpgp.IOpenPgpService; +import org.openintents.openpgp.OpenPgpError; +import org.openintents.openpgp.OpenPgpSignatureResult; +import org.openintents.openpgp.util.OpenPgpApi; +import org.spongycastle.util.Arrays; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.pgp.PgpDecryptVerify; +import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyResult; +import org.sufficientlysecure.keychain.pgp.PgpSignEncrypt; +import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.remote.ui.RemoteServiceActivity; +import org.sufficientlysecure.keychain.service.PassphraseCacheService; +import org.sufficientlysecure.keychain.util.InputData; +import org.sufficientlysecure.keychain.util.Log; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; + +public class OpenPgpService extends RemoteService { + + private static final int PRIVATE_REQUEST_CODE_PASSPHRASE = 551; + private static final int PRIVATE_REQUEST_CODE_USER_IDS = 552; + private static final int PRIVATE_REQUEST_CODE_GET_KEYS = 553; + + /** + * Search database for key ids based on emails. + * + * @param encryptionUserIds + * @return + */ + private Intent getKeyIdsFromEmails(Intent data, String[] encryptionUserIds) { + // find key ids to given emails in database + ArrayList keyIds = new ArrayList(); + + boolean missingUserIdsCheck = false; + boolean dublicateUserIdsCheck = false; + ArrayList missingUserIds = new ArrayList(); + ArrayList dublicateUserIds = new ArrayList(); + + for (String email : encryptionUserIds) { + Uri uri = KeychainContract.KeyRings.buildPublicKeyRingsByEmailsUri(email); + Cursor cur = getContentResolver().query(uri, null, null, null, null); + if (cur.moveToFirst()) { + long id = cur.getLong(cur.getColumnIndex(KeychainContract.KeyRings.MASTER_KEY_ID)); + keyIds.add(id); + } else { + missingUserIdsCheck = true; + missingUserIds.add(email); + Log.d(Constants.TAG, "user id missing"); + } + if (cur.moveToNext()) { + dublicateUserIdsCheck = true; + dublicateUserIds.add(email); + Log.d(Constants.TAG, "more than one user id with the same email"); + } + } + + // convert to long[] + long[] keyIdsArray = new long[keyIds.size()]; + for (int i = 0; i < keyIdsArray.length; i++) { + keyIdsArray[i] = keyIds.get(i); + } + + // allow the user to verify pub key selection + if (missingUserIdsCheck || dublicateUserIdsCheck) { + // build PendingIntent + Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); + intent.setAction(RemoteServiceActivity.ACTION_SELECT_PUB_KEYS); + intent.putExtra(RemoteServiceActivity.EXTRA_SELECTED_MASTER_KEY_IDS, keyIdsArray); + intent.putExtra(RemoteServiceActivity.EXTRA_MISSING_USER_IDS, missingUserIds); + intent.putExtra(RemoteServiceActivity.EXTRA_DUBLICATE_USER_IDS, dublicateUserIds); + intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); + + PendingIntent pi = PendingIntent.getActivity + (getBaseContext(), PRIVATE_REQUEST_CODE_USER_IDS, intent, 0); + + // return PendingIntent to be executed by client + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); + return result; + } + + if (keyIdsArray.length == 0) { + return null; + } + + Intent result = new Intent(); + result.putExtra(OpenPgpApi.EXTRA_KEY_IDS, keyIdsArray); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); + return result; + } + + private Intent getPassphraseBundleIntent(Intent data, long keyId) { + // build PendingIntent for passphrase input + Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); + intent.setAction(RemoteServiceActivity.ACTION_CACHE_PASSPHRASE); + intent.putExtra(RemoteServiceActivity.EXTRA_SECRET_KEY_ID, keyId); + // pass params through to activity that it can be returned again later to repeat pgp operation + intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); + PendingIntent pi = PendingIntent.getActivity + (getBaseContext(), PRIVATE_REQUEST_CODE_PASSPHRASE, intent, 0); + + // return PendingIntent to be executed by client + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); + return result; + } + + private Intent signImpl(Intent data, ParcelFileDescriptor input, + ParcelFileDescriptor output, AppSettings appSettings) { + try { + boolean asciiArmor = data.getBooleanExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); + + // get passphrase from cache, if key has "no" passphrase, this returns an empty String + String passphrase; + if (data.hasExtra(OpenPgpApi.EXTRA_PASSPHRASE)) { + passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); + } else { + passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), appSettings.getKeyId()); + } + if (passphrase == null) { + // get PendingIntent for passphrase input, add it to given params and return to client + Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); + return passphraseBundle; + } + + // Get Input- and OutputStream from ParcelFileDescriptor + InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input); + OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output); + try { + long inputLength = is.available(); + InputData inputData = new InputData(is, inputLength); + + // sign-only + PgpSignEncrypt.Builder builder = new PgpSignEncrypt.Builder(getContext(), inputData, os); + builder.enableAsciiArmorOutput(asciiArmor) + .signatureHashAlgorithm(appSettings.getHashAlgorithm()) + .signatureForceV3(false) + .signatureKeyId(appSettings.getKeyId()) + .signaturePassphrase(passphrase); + builder.build().execute(); + } finally { + is.close(); + os.close(); + } + + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); + return result; + } catch (Exception e) { + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_ERROR, + new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + return result; + } + } + + private Intent encryptAndSignImpl(Intent data, ParcelFileDescriptor input, + ParcelFileDescriptor output, AppSettings appSettings, boolean sign) { + try { + boolean asciiArmor = data.getBooleanExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); + + long[] keyIds; + if (data.hasExtra(OpenPgpApi.EXTRA_KEY_IDS)) { + keyIds = data.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS); + } else if (data.hasExtra(OpenPgpApi.EXTRA_USER_IDS)) { + // get key ids based on given user ids + String[] userIds = data.getStringArrayExtra(OpenPgpApi.EXTRA_USER_IDS); + // give params through to activity... + Intent result = getKeyIdsFromEmails(data, userIds); + + if (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0) == OpenPgpApi.RESULT_CODE_SUCCESS) { + keyIds = result.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS); + } else { + // if not success -> result contains a PendingIntent for user interaction + return result; + } + } else { + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_ERROR, + new OpenPgpError(OpenPgpError.GENERIC_ERROR, + "Missing parameter user_ids or key_ids!")); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + return result; + } + + // add own key for encryption + keyIds = Arrays.copyOf(keyIds, keyIds.length + 1); + keyIds[keyIds.length - 1] = appSettings.getKeyId(); + + // build InputData and write into OutputStream + // Get Input- and OutputStream from ParcelFileDescriptor + InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input); + OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output); + try { + long inputLength = is.available(); + InputData inputData = new InputData(is, inputLength); + + PgpSignEncrypt.Builder builder = new PgpSignEncrypt.Builder(getContext(), inputData, os); + builder.enableAsciiArmorOutput(asciiArmor) + .compressionId(appSettings.getCompression()) + .symmetricEncryptionAlgorithm(appSettings.getEncryptionAlgorithm()) + .encryptionKeyIds(keyIds); + + if (sign) { + String passphrase; + if (data.hasExtra(OpenPgpApi.EXTRA_PASSPHRASE)) { + passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); + } else { + passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), + appSettings.getKeyId()); + } + if (passphrase == null) { + // get PendingIntent for passphrase input, add it to given params and return to client + Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); + return passphraseBundle; + } + + // sign and encrypt + builder.signatureHashAlgorithm(appSettings.getHashAlgorithm()) + .signatureForceV3(false) + .signatureKeyId(appSettings.getKeyId()) + .signaturePassphrase(passphrase); + } else { + // encrypt only + builder.signatureKeyId(Id.key.none); + } + // execute PGP operation! + builder.build().execute(); + } finally { + is.close(); + os.close(); + } + + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); + return result; + } catch (Exception e) { + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_ERROR, + new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + return result; + } + } + + private Intent decryptAndVerifyImpl(Intent data, ParcelFileDescriptor input, + ParcelFileDescriptor output, AppSettings appSettings) { + try { + // Get Input- and OutputStream from ParcelFileDescriptor + InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input); + OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output); + + Intent result = new Intent(); + try { + + String passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); + long inputLength = is.available(); + InputData inputData = new InputData(is, inputLength); + + PgpDecryptVerify.Builder builder = new PgpDecryptVerify.Builder(this, inputData, os); + builder.assumeSymmetric(false) // no support for symmetric encryption + // allow only the private key for this app for decryption + .enforcedKeyId(appSettings.getKeyId()) + .passphrase(passphrase); + + // TODO: currently does not support binary signed-only content + PgpDecryptVerifyResult decryptVerifyResult = builder.build().execute(); + + if (decryptVerifyResult.isKeyPassphraseNeeded()) { + // get PendingIntent for passphrase input, add it to given params and return to client + Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); + return passphraseBundle; + } else if (decryptVerifyResult.isSymmetricPassphraseNeeded()) { + throw new PgpGeneralException("Decryption of symmetric content not supported by API!"); + } + + OpenPgpSignatureResult signatureResult = decryptVerifyResult.getSignatureResult(); + if (signatureResult != null) { + if (signatureResult.getStatus() == OpenPgpSignatureResult.SIGNATURE_UNKNOWN_PUB_KEY) { + // If signature is unknown we return an _additional_ PendingIntent + // to retrieve the missing key + // TODO!!! + Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); + intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); + intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, "todo"); + intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); + + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), + PRIVATE_REQUEST_CODE_GET_KEYS, intent, 0); + + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); + } + + result.putExtra(OpenPgpApi.RESULT_SIGNATURE, signatureResult); + } + + } finally { + is.close(); + os.close(); + } + + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); + return result; + } catch (Exception e) { + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_ERROR, + new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + return result; + } + } + + private Intent getKeyImpl(Intent data) { + try { + long keyId = data.getLongExtra(OpenPgpApi.EXTRA_KEY_ID, 0); + + if (ProviderHelper.getPGPPublicKeyByKeyId(this, keyId) == null) { + Intent result = new Intent(); + + // If keys are not in db we return an additional PendingIntent + // to retrieve the missing key + // TODO!!! + Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); + intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); + intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, "todo"); + intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); + + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), + PRIVATE_REQUEST_CODE_GET_KEYS, intent, 0); + + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); + return result; + } else { + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); + return result; + } + } catch (Exception e) { + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_ERROR, + new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + return result; + } + } + + private Intent getKeyIdsImpl(Intent data) { + // get key ids based on given user ids + String[] userIds = data.getStringArrayExtra(OpenPgpApi.EXTRA_USER_IDS); + Intent result = getKeyIdsFromEmails(data, userIds); + return result; + } + + /** + * Check requirements: + * - params != null + * - has supported API version + * - is allowed to call the service (access has been granted) + * + * @param data + * @return null if everything is okay, or a Bundle with an error/PendingIntent + */ + private Intent checkRequirements(Intent data) { + // params Bundle is required! + if (data == null) { + Intent result = new Intent(); + OpenPgpError error = new OpenPgpError(OpenPgpError.GENERIC_ERROR, "params Bundle required!"); + result.putExtra(OpenPgpApi.RESULT_ERROR, error); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + return result; + } + + // version code is required and needs to correspond to version code of service! + if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != OpenPgpApi.API_VERSION) { + Intent result = new Intent(); + OpenPgpError error = new OpenPgpError + (OpenPgpError.INCOMPATIBLE_API_VERSIONS, "Incompatible API versions!"); + result.putExtra(OpenPgpApi.RESULT_ERROR, error); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + return result; + } + + // check if caller is allowed to access openpgp keychain + Intent result = isAllowed(data); + if (result != null) { + return result; + } + + return null; + } + + // TODO: multi-threading + private final IOpenPgpService.Stub mBinder = new IOpenPgpService.Stub() { + + @Override + public Intent execute(Intent data, ParcelFileDescriptor input, ParcelFileDescriptor output) { + Intent errorResult = checkRequirements(data); + if (errorResult != null) { + return errorResult; + } + + final AppSettings appSettings = getAppSettings(); + + String action = data.getAction(); + if (OpenPgpApi.ACTION_SIGN.equals(action)) { + return signImpl(data, input, output, appSettings); + } else if (OpenPgpApi.ACTION_ENCRYPT.equals(action)) { + return encryptAndSignImpl(data, input, output, appSettings, false); + } else if (OpenPgpApi.ACTION_SIGN_AND_ENCRYPT.equals(action)) { + return encryptAndSignImpl(data, input, output, appSettings, true); + } else if (OpenPgpApi.ACTION_DECRYPT_VERIFY.equals(action)) { + return decryptAndVerifyImpl(data, input, output, appSettings); + } else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) { + return getKeyImpl(data); + } else if (OpenPgpApi.ACTION_GET_KEY_IDS.equals(action)) { + return getKeyIdsImpl(data); + } else { + return null; + } + } + + }; + + @Override + public IBinder onBind(Intent intent) { + return mBinder; + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java new file mode 100644 index 000000000..434fe84c1 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java @@ -0,0 +1,233 @@ +/* + * Copyright (C) 2013-2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote; + +import android.app.PendingIntent; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.pm.Signature; +import android.net.Uri; +import android.os.Binder; +import org.openintents.openpgp.OpenPgpError; +import org.openintents.openpgp.util.OpenPgpApi; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.remote.ui.RemoteServiceActivity; +import org.sufficientlysecure.keychain.util.Log; + +import java.util.ArrayList; +import java.util.Arrays; + +/** + * Abstract service class for remote APIs that handle app registration and user input. + */ +public abstract class RemoteService extends Service { + Context mContext; + + private static final int PRIVATE_REQUEST_CODE_REGISTER = 651; + private static final int PRIVATE_REQUEST_CODE_ERROR = 652; + + + public Context getContext() { + return mContext; + } + + protected Intent isAllowed(Intent data) { + try { + if (isCallerAllowed(false)) { + + return null; + } else { + String[] callingPackages = getPackageManager().getPackagesForUid( + Binder.getCallingUid()); + // TODO: currently simply uses first entry + String packageName = callingPackages[0]; + + byte[] packageSignature; + try { + packageSignature = getPackageSignature(packageName); + } catch (NameNotFoundException e) { + Log.e(Constants.TAG, "Should not happen, returning!", e); + // return error + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); + result.putExtra(OpenPgpApi.RESULT_ERROR, + new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); + return result; + } + Log.e(Constants.TAG, "Not allowed to use service! return PendingIntent for registration!"); + + Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); + intent.setAction(RemoteServiceActivity.ACTION_REGISTER); + intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_NAME, packageName); + intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_SIGNATURE, packageSignature); + intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); + + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), + PRIVATE_REQUEST_CODE_REGISTER, intent, 0); + + // return PendingIntent to be executed by client + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); + + return result; + } + } catch (WrongPackageSignatureException e) { + Log.e(Constants.TAG, "wrong signature!", e); + + Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); + intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); + intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, + getString(R.string.api_error_wrong_signature)); + intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); + + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), + PRIVATE_REQUEST_CODE_ERROR, intent, 0); + + // return PendingIntent to be executed by client + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); + + return result; + } + } + + private byte[] getPackageSignature(String packageName) throws NameNotFoundException { + PackageInfo pkgInfo = getPackageManager().getPackageInfo(packageName, + PackageManager.GET_SIGNATURES); + Signature[] signatures = pkgInfo.signatures; + // TODO: Only first signature?! + byte[] packageSignature = signatures[0].toByteArray(); + + return packageSignature; + } + + /** + * Retrieves AppSettings from database for the application calling this remote service + * + * @return + */ + protected AppSettings getAppSettings() { + String[] callingPackages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); + + // get app settings for this package + for (int i = 0; i < callingPackages.length; i++) { + String currentPkg = callingPackages[i]; + + Uri uri = KeychainContract.ApiApps.buildByPackageNameUri(currentPkg); + + AppSettings settings = ProviderHelper.getApiAppSettings(this, uri); + + if (settings != null) { + return settings; + } + } + + return null; + } + + /** + * Checks if process that binds to this service (i.e. the package name corresponding to the + * process) is in the list of allowed package names. + * + * @param allowOnlySelf allow only Keychain app itself + * @return true if process is allowed to use this service + * @throws WrongPackageSignatureException + */ + private boolean isCallerAllowed(boolean allowOnlySelf) throws WrongPackageSignatureException { + return isUidAllowed(Binder.getCallingUid(), allowOnlySelf); + } + + private boolean isUidAllowed(int uid, boolean allowOnlySelf) + throws WrongPackageSignatureException { + if (android.os.Process.myUid() == uid) { + return true; + } + if (allowOnlySelf) { // barrier + return false; + } + + String[] callingPackages = getPackageManager().getPackagesForUid(uid); + + // is calling package allowed to use this service? + for (int i = 0; i < callingPackages.length; i++) { + String currentPkg = callingPackages[i]; + + if (isPackageAllowed(currentPkg)) { + return true; + } + } + + Log.d(Constants.TAG, "Caller is NOT allowed!"); + return false; + } + + /** + * Checks if packageName is a registered app for the API. Does not return true for own package! + * + * @param packageName + * @return + * @throws WrongPackageSignatureException + */ + private boolean isPackageAllowed(String packageName) throws WrongPackageSignatureException { + Log.d(Constants.TAG, "packageName: " + packageName); + + ArrayList allowedPkgs = ProviderHelper.getRegisteredApiApps(this); + Log.d(Constants.TAG, "allowed: " + allowedPkgs); + + // check if package is allowed to use our service + if (allowedPkgs.contains(packageName)) { + Log.d(Constants.TAG, "Package is allowed! packageName: " + packageName); + + // check package signature + byte[] currentSig; + try { + currentSig = getPackageSignature(packageName); + } catch (NameNotFoundException e) { + throw new WrongPackageSignatureException(e.getMessage()); + } + + byte[] storedSig = ProviderHelper.getApiAppSignature(this, packageName); + if (Arrays.equals(currentSig, storedSig)) { + Log.d(Constants.TAG, + "Package signature is correct! (equals signature from database)"); + return true; + } else { + throw new WrongPackageSignatureException( + "PACKAGE NOT ALLOWED! Signature wrong! (Signature not equals signature from database)"); + } + } + + return false; + } + + @Override + public void onCreate() { + super.onCreate(); + mContext = this; + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/WrongPackageSignatureException.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/WrongPackageSignatureException.java new file mode 100644 index 000000000..6f44a65e9 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/WrongPackageSignatureException.java @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote; + +public class WrongPackageSignatureException extends Exception { + + private static final long serialVersionUID = -8294642703122196028L; + + public WrongPackageSignatureException(String message) { + super(message); + } +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java new file mode 100644 index 000000000..d544455ec --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.support.v7.app.ActionBarActivity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ActionBarHelper; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.remote.AppSettings; +import org.sufficientlysecure.keychain.util.Log; + +public class AppSettingsActivity extends ActionBarActivity { + private Uri mAppUri; + + private AppSettingsFragment mSettingsFragment; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Inflate a "Done" custom action bar + ActionBarHelper.setOneButtonView(getSupportActionBar(), + R.string.api_settings_save, R.drawable.ic_action_done, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // "Done" + save(); + } + }); + + setContentView(R.layout.api_app_settings_activity); + + mSettingsFragment = (AppSettingsFragment) getSupportFragmentManager().findFragmentById( + R.id.api_app_settings_fragment); + + Intent intent = getIntent(); + mAppUri = intent.getData(); + if (mAppUri == null) { + Log.e(Constants.TAG, "Intent data missing. Should be Uri of app!"); + finish(); + return; + } else { + Log.d(Constants.TAG, "uri: " + mAppUri); + loadData(mAppUri); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + getMenuInflater().inflate(R.menu.api_app_settings, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_api_settings_revoke: + revokeAccess(); + return true; + case R.id.menu_api_settings_cancel: + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + private void loadData(Uri appUri) { + AppSettings settings = ProviderHelper.getApiAppSettings(this, appUri); + mSettingsFragment.setAppSettings(settings); + } + + private void revokeAccess() { + if (getContentResolver().delete(mAppUri, null, null) <= 0) { + throw new RuntimeException(); + } + finish(); + } + + private void save() { + ProviderHelper.updateApiApp(this, mSettingsFragment.getAppSettings(), mAppUri); + + finish(); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java new file mode 100644 index 000000000..8e8f3827b --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2013-2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemSelectedListener; +import android.widget.ImageView; +import android.widget.Spinner; +import android.widget.TextView; + +import org.spongycastle.util.encoders.Hex; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.remote.AppSettings; +import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; +import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; +import org.sufficientlysecure.keychain.util.AlgorithmNames; +import org.sufficientlysecure.keychain.util.Log; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class AppSettingsFragment extends Fragment implements + SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { + + // model + private AppSettings mAppSettings; + + // view + private TextView mAppNameView; + private ImageView mAppIconView; + private Spinner mEncryptionAlgorithm; + private Spinner mHashAlgorithm; + private Spinner mCompression; + private TextView mPackageName; + private TextView mPackageSignature; + + private SelectSecretKeyLayoutFragment mSelectKeyFragment; + + KeyValueSpinnerAdapter mEncryptionAdapter; + KeyValueSpinnerAdapter mHashAdapter; + KeyValueSpinnerAdapter mCompressionAdapter; + + public AppSettings getAppSettings() { + return mAppSettings; + } + + public void setAppSettings(AppSettings appSettings) { + this.mAppSettings = appSettings; + setPackage(appSettings.getPackageName()); + mPackageName.setText(appSettings.getPackageName()); + + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(appSettings.getPackageSignature()); + byte[] digest = md.digest(); + String signature = new String(Hex.encode(digest)); + + mPackageSignature.setText(signature); + } catch (NoSuchAlgorithmException e) { + Log.e(Constants.TAG, "Should not happen!", e); + } + + mSelectKeyFragment.selectKey(appSettings.getKeyId()); + mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(appSettings + .getEncryptionAlgorithm())); + mHashAlgorithm.setSelection(mHashAdapter.getPosition(appSettings.getHashAlgorithm())); + mCompression.setSelection(mCompressionAdapter.getPosition(appSettings.getCompression())); + } + + /** + * Inflate the layout for this fragment + */ + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.api_app_settings_fragment, container, false); + initView(view); + return view; + } + + /** + * Set error String on key selection + * + * @param error + */ + public void setErrorOnSelectKeyFragment(String error) { + mSelectKeyFragment.setError(error); + } + + private void initView(View view) { + mSelectKeyFragment = (SelectSecretKeyLayoutFragment) getFragmentManager().findFragmentById( + R.id.api_app_settings_select_key_fragment); + mSelectKeyFragment.setCallback(this); + + mAppNameView = (TextView) view.findViewById(R.id.api_app_settings_app_name); + mAppIconView = (ImageView) view.findViewById(R.id.api_app_settings_app_icon); + mEncryptionAlgorithm = (Spinner) view + .findViewById(R.id.api_app_settings_encryption_algorithm); + mHashAlgorithm = (Spinner) view.findViewById(R.id.api_app_settings_hash_algorithm); + mCompression = (Spinner) view.findViewById(R.id.api_app_settings_compression); + mPackageName = (TextView) view.findViewById(R.id.api_app_settings_package_name); + mPackageSignature = (TextView) view.findViewById(R.id.api_app_settings_package_signature); + + AlgorithmNames algorithmNames = new AlgorithmNames(getActivity()); + + mEncryptionAdapter = new KeyValueSpinnerAdapter(getActivity(), + algorithmNames.getEncryptionNames()); + mEncryptionAlgorithm.setAdapter(mEncryptionAdapter); + mEncryptionAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + mAppSettings.setEncryptionAlgorithm((int) id); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + mHashAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getHashNames()); + mHashAlgorithm.setAdapter(mHashAdapter); + mHashAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + mAppSettings.setHashAlgorithm((int) id); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + mCompressionAdapter = new KeyValueSpinnerAdapter(getActivity(), + algorithmNames.getCompressionNames()); + mCompression.setAdapter(mCompressionAdapter); + mCompression.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + mAppSettings.setCompression((int) id); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + } + + private void setPackage(String packageName) { + PackageManager pm = getActivity().getApplicationContext().getPackageManager(); + + // get application name and icon from package manager + String appName = null; + Drawable appIcon = null; + try { + ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); + + appName = (String) pm.getApplicationLabel(ai); + appIcon = pm.getApplicationIcon(ai); + } catch (final NameNotFoundException e) { + // fallback + appName = packageName; + } + mAppNameView.setText(appName); + mAppIconView.setImageDrawable(appIcon); + } + + /** + * callback from select secret key fragment + */ + @Override + public void onKeySelected(long secretKeyId) { + mAppSettings.setKeyId(secretKeyId); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java new file mode 100644 index 000000000..c846343ab --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.database.Cursor; +import android.support.v4.widget.CursorAdapter; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; + +public class RegisteredAppsAdapter extends CursorAdapter { + + private LayoutInflater mInflater; + private PackageManager mPM; + + public RegisteredAppsAdapter(Context context, Cursor c, int flags) { + super(context, c, flags); + + mInflater = LayoutInflater.from(context); + mPM = context.getApplicationContext().getPackageManager(); + } + + @Override + public void bindView(View view, Context context, Cursor cursor) { + TextView text = (TextView) view.findViewById(R.id.api_apps_adapter_item_name); + ImageView icon = (ImageView) view.findViewById(R.id.api_apps_adapter_item_icon); + + String packageName = cursor.getString(cursor.getColumnIndex(ApiApps.PACKAGE_NAME)); + if (packageName != null) { + // get application name + try { + ApplicationInfo ai = mPM.getApplicationInfo(packageName, 0); + + text.setText(mPM.getApplicationLabel(ai)); + icon.setImageDrawable(mPM.getApplicationIcon(ai)); + } catch (final NameNotFoundException e) { + // fallback + text.setText(packageName); + } + } else { + // fallback + text.setText(packageName); + } + + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return mInflater.inflate(R.layout.api_apps_adapter_list_item, null); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java new file mode 100644 index 000000000..79b3c8abc --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.os.Bundle; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.DrawerActivity; + +public class RegisteredAppsListActivity extends DrawerActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.api_apps_list_activity); + + setupDrawerNavigation(savedInstanceState); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java new file mode 100644 index 000000000..99e73e510 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.ContentUris; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.support.v4.app.ListFragment; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; +import android.view.View; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; + +public class RegisteredAppsListFragment extends ListFragment implements + LoaderManager.LoaderCallbacks { + + // This is the Adapter being used to display the list's data. + RegisteredAppsAdapter mAdapter; + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + getListView().setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int position, long id) { + // edit app settings + Intent intent = new Intent(getActivity(), AppSettingsActivity.class); + intent.setData(ContentUris.withAppendedId(KeychainContract.ApiApps.CONTENT_URI, id)); + startActivity(intent); + } + }); + + // Give some text to display if there is no data. In a real + // application this would come from a resource. + setEmptyText(getString(R.string.api_no_apps)); + + // We have a menu item to show in action bar. + setHasOptionsMenu(true); + + // Create an empty adapter we will use to display the loaded data. + mAdapter = new RegisteredAppsAdapter(getActivity(), null, 0); + setListAdapter(mAdapter); + + // Prepare the loader. Either re-connect with an existing one, + // or start a new one. + getLoaderManager().initLoader(0, null, this); + } + + // These are the Contacts rows that we will retrieve. + static final String[] PROJECTION = new String[]{ApiApps._ID, ApiApps.PACKAGE_NAME}; + + public Loader onCreateLoader(int id, Bundle args) { + // This is called when a new Loader needs to be created. This + // sample only has one Loader, so we don't care about the ID. + // First, pick the base URI to use depending on whether we are + // currently filtering. + Uri baseUri = ApiApps.CONTENT_URI; + + // Now create and return a CursorLoader that will take care of + // creating a Cursor for the data being displayed. + return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, + ApiApps.PACKAGE_NAME + " COLLATE LOCALIZED ASC"); + } + + public void onLoadFinished(Loader loader, Cursor data) { + // Swap the new cursor in. (The framework will take care of closing the + // old cursor once we return.) + mAdapter.swapCursor(data); + } + + public void onLoaderReset(Loader loader) { + // This is called when the last Cursor provided to onLoadFinished() + // above is about to be closed. We need to make sure we are no + // longer using it. + mAdapter.swapCursor(null); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java new file mode 100644 index 000000000..3e19a8ef6 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java @@ -0,0 +1,279 @@ +/* + * Copyright (C) 2013-2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.Messenger; +import android.support.v7.app.ActionBarActivity; +import android.view.View; +import org.openintents.openpgp.util.OpenPgpApi; +import org.sufficientlysecure.htmltextview.HtmlTextView; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ActionBarHelper; +import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.remote.AppSettings; +import org.sufficientlysecure.keychain.ui.SelectPublicKeyFragment; +import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; +import org.sufficientlysecure.keychain.util.Log; + +import java.util.ArrayList; + +public class RemoteServiceActivity extends ActionBarActivity { + + public static final String ACTION_REGISTER = Constants.INTENT_PREFIX + "API_ACTIVITY_REGISTER"; + public static final String ACTION_CACHE_PASSPHRASE = Constants.INTENT_PREFIX + + "API_ACTIVITY_CACHE_PASSPHRASE"; + public static final String ACTION_SELECT_PUB_KEYS = Constants.INTENT_PREFIX + + "API_ACTIVITY_SELECT_PUB_KEYS"; + public static final String ACTION_ERROR_MESSAGE = Constants.INTENT_PREFIX + + "API_ACTIVITY_ERROR_MESSAGE"; + + public static final String EXTRA_MESSENGER = "messenger"; + + public static final String EXTRA_DATA = "data"; + + // passphrase action + public static final String EXTRA_SECRET_KEY_ID = "secret_key_id"; + // register action + public static final String EXTRA_PACKAGE_NAME = "package_name"; + public static final String EXTRA_PACKAGE_SIGNATURE = "package_signature"; + // select pub keys action + public static final String EXTRA_SELECTED_MASTER_KEY_IDS = "master_key_ids"; + public static final String EXTRA_MISSING_USER_IDS = "missing_user_ids"; + public static final String EXTRA_DUBLICATE_USER_IDS = "dublicate_user_ids"; + // error message + public static final String EXTRA_ERROR_MESSAGE = "error_message"; + + // register view + private AppSettingsFragment mSettingsFragment; + // select pub keys view + private SelectPublicKeyFragment mSelectFragment; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + handleActions(getIntent(), savedInstanceState); + } + + protected void handleActions(Intent intent, Bundle savedInstanceState) { + + String action = intent.getAction(); + final Bundle extras = intent.getExtras(); + + + if (ACTION_REGISTER.equals(action)) { + final String packageName = extras.getString(EXTRA_PACKAGE_NAME); + final byte[] packageSignature = extras.getByteArray(EXTRA_PACKAGE_SIGNATURE); + + // Inflate a "Done"/"Cancel" custom action bar view + ActionBarHelper.setTwoButtonView(getSupportActionBar(), + R.string.api_register_allow, R.drawable.ic_action_done, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // Allow + + // user needs to select a key! + if (mSettingsFragment.getAppSettings().getKeyId() == Id.key.none) { + mSettingsFragment.setErrorOnSelectKeyFragment( + getString(R.string.api_register_error_select_key)); + } else { + ProviderHelper.insertApiApp(RemoteServiceActivity.this, + mSettingsFragment.getAppSettings()); + + // give data through for new service call + Intent resultData = extras.getParcelable(EXTRA_DATA); + RemoteServiceActivity.this.setResult(RESULT_OK, resultData); + RemoteServiceActivity.this.finish(); + } + } + }, R.string.api_register_disallow, R.drawable.ic_action_cancel, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // Disallow + RemoteServiceActivity.this.setResult(RESULT_CANCELED); + RemoteServiceActivity.this.finish(); + } + } + ); + + setContentView(R.layout.api_app_register_activity); + + mSettingsFragment = (AppSettingsFragment) getSupportFragmentManager().findFragmentById( + R.id.api_app_settings_fragment); + + AppSettings settings = new AppSettings(packageName, packageSignature); + mSettingsFragment.setAppSettings(settings); + } else if (ACTION_CACHE_PASSPHRASE.equals(action)) { + long secretKeyId = extras.getLong(EXTRA_SECRET_KEY_ID); + Intent resultData = extras.getParcelable(EXTRA_DATA); + + showPassphraseDialog(resultData, secretKeyId); + } else if (ACTION_SELECT_PUB_KEYS.equals(action)) { + long[] selectedMasterKeyIds = intent.getLongArrayExtra(EXTRA_SELECTED_MASTER_KEY_IDS); + ArrayList missingUserIds = intent + .getStringArrayListExtra(EXTRA_MISSING_USER_IDS); + ArrayList dublicateUserIds = intent + .getStringArrayListExtra(EXTRA_DUBLICATE_USER_IDS); + + // TODO: do this with spannable instead of HTML to prevent parsing failures with weird user ids + String text = "" + getString(R.string.api_select_pub_keys_text) + ""; + text += "

"; + if (missingUserIds != null && missingUserIds.size() > 0) { + text += getString(R.string.api_select_pub_keys_missing_text); + text += "
"; + text += "

    "; + for (String userId : missingUserIds) { + text += "
  • " + userId + "
  • "; + } + text += "
"; + text += "
"; + } + if (dublicateUserIds != null && dublicateUserIds.size() > 0) { + text += getString(R.string.api_select_pub_keys_dublicates_text); + text += "
"; + text += "
    "; + for (String userId : dublicateUserIds) { + text += "
  • " + userId + "
  • "; + } + text += "
"; + } + + // Inflate a "Done"/"Cancel" custom action bar view + ActionBarHelper.setTwoButtonView(getSupportActionBar(), + R.string.btn_okay, R.drawable.ic_action_done, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // add key ids to params Bundle for new request + Intent resultData = extras.getParcelable(EXTRA_DATA); + resultData.putExtra(OpenPgpApi.EXTRA_KEY_IDS, + mSelectFragment.getSelectedMasterKeyIds()); + + RemoteServiceActivity.this.setResult(RESULT_OK, resultData); + RemoteServiceActivity.this.finish(); + } + }, R.string.btn_do_not_save, R.drawable.ic_action_cancel, new View.OnClickListener() { + @Override + public void onClick(View v) { + // cancel + RemoteServiceActivity.this.setResult(RESULT_CANCELED); + RemoteServiceActivity.this.finish(); + } + } + ); + + setContentView(R.layout.api_app_select_pub_keys_activity); + + // set text on view + HtmlTextView textView = (HtmlTextView) findViewById(R.id.api_select_pub_keys_text); + textView.setHtmlFromString(text); + + /* Load select pub keys fragment */ + // Check that the activity is using the layout version with + // the fragment_container FrameLayout + if (findViewById(R.id.api_select_pub_keys_fragment_container) != null) { + + // However, if we're being restored from a previous state, + // then we don't need to do anything and should return or else + // we could end up with overlapping fragments. + if (savedInstanceState != null) { + return; + } + + // Create an instance of the fragment + mSelectFragment = SelectPublicKeyFragment.newInstance(selectedMasterKeyIds); + + // Add the fragment to the 'fragment_container' FrameLayout + getSupportFragmentManager().beginTransaction() + .add(R.id.api_select_pub_keys_fragment_container, mSelectFragment).commit(); + } + } else if (ACTION_ERROR_MESSAGE.equals(action)) { + String errorMessage = intent.getStringExtra(EXTRA_ERROR_MESSAGE); + + String text = "" + errorMessage + ""; + + // Inflate a "Done" custom action bar view + ActionBarHelper.setOneButtonView(getSupportActionBar(), + R.string.btn_okay, R.drawable.ic_action_done, + new View.OnClickListener() { + + @Override + public void onClick(View v) { + RemoteServiceActivity.this.setResult(RESULT_CANCELED); + RemoteServiceActivity.this.finish(); + } + }); + + setContentView(R.layout.api_app_error_message); + + // set text on view + HtmlTextView textView = (HtmlTextView) findViewById(R.id.api_app_error_message_text); + textView.setHtmlFromString(text); + } else { + Log.e(Constants.TAG, "Action does not exist!"); + setResult(RESULT_CANCELED); + finish(); + } + } + + /** + * Shows passphrase dialog to cache a new passphrase the user enters for using it later for + * encryption. Based on mSecretKeyId it asks for a passphrase to open a private key or it asks + * for a symmetric passphrase + */ + private void showPassphraseDialog(final Intent data, long secretKeyId) { + // Message is received after passphrase is cached + Handler returnHandler = new Handler() { + @Override + public void handleMessage(Message message) { + if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) { + // return given params again, for calling the service method again + RemoteServiceActivity.this.setResult(RESULT_OK, data); + } else { + RemoteServiceActivity.this.setResult(RESULT_CANCELED); + } + + RemoteServiceActivity.this.finish(); + } + }; + + // Create a new Messenger for the communication back + Messenger messenger = new Messenger(returnHandler); + + try { + PassphraseDialogFragment passphraseDialog = PassphraseDialogFragment.newInstance(this, + messenger, secretKeyId); + + passphraseDialog.show(getSupportFragmentManager(), "passphraseDialog"); + } catch (PgpGeneralException e) { + Log.d(Constants.TAG, "No passphrase for this secret key, do pgp operation directly!"); + // return given params again, for calling the service method again + setResult(RESULT_OK, data); + finish(); + } + } +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java deleted file mode 100644 index 6f2d67efb..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettings.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import org.spongycastle.bcpg.HashAlgorithmTags; -import org.spongycastle.openpgp.PGPEncryptedData; -import org.sufficientlysecure.keychain.Id; - -public class AppSettings { - private String mPackageName; - private byte[] mPackageSignature; - private long mKeyId = Id.key.none; - private int mEncryptionAlgorithm; - private int mHashAlgorithm; - private int mCompression; - - public AppSettings() { - - } - - public AppSettings(String packageName, byte[] packageSignature) { - super(); - this.mPackageName = packageName; - this.mPackageSignature = packageSignature; - // defaults: - this.mEncryptionAlgorithm = PGPEncryptedData.AES_256; - this.mHashAlgorithm = HashAlgorithmTags.SHA512; - this.mCompression = Id.choice.compression.zlib; - } - - public String getPackageName() { - return mPackageName; - } - - public void setPackageName(String packageName) { - this.mPackageName = packageName; - } - - public byte[] getPackageSignature() { - return mPackageSignature; - } - - public void setPackageSignature(byte[] packageSignature) { - this.mPackageSignature = packageSignature; - } - - public long getKeyId() { - return mKeyId; - } - - public void setKeyId(long scretKeyId) { - this.mKeyId = scretKeyId; - } - - public int getEncryptionAlgorithm() { - return mEncryptionAlgorithm; - } - - public void setEncryptionAlgorithm(int encryptionAlgorithm) { - this.mEncryptionAlgorithm = encryptionAlgorithm; - } - - public int getHashAlgorithm() { - return mHashAlgorithm; - } - - public void setHashAlgorithm(int hashAlgorithm) { - this.mHashAlgorithm = hashAlgorithm; - } - - public int getCompression() { - return mCompression; - } - - public void setCompression(int compression) { - this.mCompression = compression; - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java deleted file mode 100644 index 2ef170dec..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsActivity.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.support.v7.app.ActionBarActivity; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.util.Log; - -public class AppSettingsActivity extends ActionBarActivity { - private Uri mAppUri; - - private AppSettingsFragment mSettingsFragment; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // Inflate a "Done" custom action bar - ActionBarHelper.setOneButtonView(getSupportActionBar(), - R.string.api_settings_save, R.drawable.ic_action_done, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // "Done" - save(); - } - }); - - setContentView(R.layout.api_app_settings_activity); - - mSettingsFragment = (AppSettingsFragment) getSupportFragmentManager().findFragmentById( - R.id.api_app_settings_fragment); - - Intent intent = getIntent(); - mAppUri = intent.getData(); - if (mAppUri == null) { - Log.e(Constants.TAG, "Intent data missing. Should be Uri of app!"); - finish(); - return; - } else { - Log.d(Constants.TAG, "uri: " + mAppUri); - loadData(mAppUri); - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - getMenuInflater().inflate(R.menu.api_app_settings, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_api_settings_revoke: - revokeAccess(); - return true; - case R.id.menu_api_settings_cancel: - finish(); - return true; - } - return super.onOptionsItemSelected(item); - } - - private void loadData(Uri appUri) { - AppSettings settings = ProviderHelper.getApiAppSettings(this, appUri); - mSettingsFragment.setAppSettings(settings); - } - - private void revokeAccess() { - if (getContentResolver().delete(mAppUri, null, null) <= 0) { - throw new RuntimeException(); - } - finish(); - } - - private void save() { - ProviderHelper.updateApiApp(this, mSettingsFragment.getAppSettings(), mAppUri); - - finish(); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java deleted file mode 100644 index 52b06a2ae..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/AppSettingsFragment.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (C) 2013-2014 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.ImageView; -import android.widget.Spinner; -import android.widget.TextView; - -import org.spongycastle.util.encoders.Hex; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; -import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; -import org.sufficientlysecure.keychain.util.AlgorithmNames; -import org.sufficientlysecure.keychain.util.Log; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -public class AppSettingsFragment extends Fragment implements - SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { - - // model - private AppSettings mAppSettings; - - // view - private TextView mAppNameView; - private ImageView mAppIconView; - private Spinner mEncryptionAlgorithm; - private Spinner mHashAlgorithm; - private Spinner mCompression; - private TextView mPackageName; - private TextView mPackageSignature; - - private SelectSecretKeyLayoutFragment mSelectKeyFragment; - - KeyValueSpinnerAdapter mEncryptionAdapter; - KeyValueSpinnerAdapter mHashAdapter; - KeyValueSpinnerAdapter mCompressionAdapter; - - public AppSettings getAppSettings() { - return mAppSettings; - } - - public void setAppSettings(AppSettings appSettings) { - this.mAppSettings = appSettings; - setPackage(appSettings.getPackageName()); - mPackageName.setText(appSettings.getPackageName()); - - try { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(appSettings.getPackageSignature()); - byte[] digest = md.digest(); - String signature = new String(Hex.encode(digest)); - - mPackageSignature.setText(signature); - } catch (NoSuchAlgorithmException e) { - Log.e(Constants.TAG, "Should not happen!", e); - } - - mSelectKeyFragment.selectKey(appSettings.getKeyId()); - mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(appSettings - .getEncryptionAlgorithm())); - mHashAlgorithm.setSelection(mHashAdapter.getPosition(appSettings.getHashAlgorithm())); - mCompression.setSelection(mCompressionAdapter.getPosition(appSettings.getCompression())); - } - - /** - * Inflate the layout for this fragment - */ - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.api_app_settings_fragment, container, false); - initView(view); - return view; - } - - /** - * Set error String on key selection - * - * @param error - */ - public void setErrorOnSelectKeyFragment(String error) { - mSelectKeyFragment.setError(error); - } - - private void initView(View view) { - mSelectKeyFragment = (SelectSecretKeyLayoutFragment) getFragmentManager().findFragmentById( - R.id.api_app_settings_select_key_fragment); - mSelectKeyFragment.setCallback(this); - - mAppNameView = (TextView) view.findViewById(R.id.api_app_settings_app_name); - mAppIconView = (ImageView) view.findViewById(R.id.api_app_settings_app_icon); - mEncryptionAlgorithm = (Spinner) view - .findViewById(R.id.api_app_settings_encryption_algorithm); - mHashAlgorithm = (Spinner) view.findViewById(R.id.api_app_settings_hash_algorithm); - mCompression = (Spinner) view.findViewById(R.id.api_app_settings_compression); - mPackageName = (TextView) view.findViewById(R.id.api_app_settings_package_name); - mPackageSignature = (TextView) view.findViewById(R.id.api_app_settings_package_signature); - - AlgorithmNames algorithmNames = new AlgorithmNames(getActivity()); - - mEncryptionAdapter = new KeyValueSpinnerAdapter(getActivity(), - algorithmNames.getEncryptionNames()); - mEncryptionAlgorithm.setAdapter(mEncryptionAdapter); - mEncryptionAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - mAppSettings.setEncryptionAlgorithm((int) id); - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - - mHashAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getHashNames()); - mHashAlgorithm.setAdapter(mHashAdapter); - mHashAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - mAppSettings.setHashAlgorithm((int) id); - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - - mCompressionAdapter = new KeyValueSpinnerAdapter(getActivity(), - algorithmNames.getCompressionNames()); - mCompression.setAdapter(mCompressionAdapter); - mCompression.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - mAppSettings.setCompression((int) id); - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - } - - private void setPackage(String packageName) { - PackageManager pm = getActivity().getApplicationContext().getPackageManager(); - - // get application name and icon from package manager - String appName = null; - Drawable appIcon = null; - try { - ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); - - appName = (String) pm.getApplicationLabel(ai); - appIcon = pm.getApplicationIcon(ai); - } catch (final NameNotFoundException e) { - // fallback - appName = packageName; - } - mAppNameView.setText(appName); - mAppIconView.setImageDrawable(appIcon); - } - - /** - * callback from select secret key fragment - */ - @Override - public void onKeySelected(long secretKeyId) { - mAppSettings.setKeyId(secretKeyId); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java deleted file mode 100644 index 95dc897f0..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/OpenPgpService.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Copyright (C) 2013-2014 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.app.PendingIntent; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.os.IBinder; -import android.os.ParcelFileDescriptor; -import org.openintents.openpgp.IOpenPgpService; -import org.openintents.openpgp.OpenPgpError; -import org.openintents.openpgp.OpenPgpSignatureResult; -import org.openintents.openpgp.util.OpenPgpApi; -import org.spongycastle.util.Arrays; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.pgp.PgpDecryptVerify; -import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyResult; -import org.sufficientlysecure.keychain.pgp.PgpSignEncrypt; -import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.service.PassphraseCacheService; -import org.sufficientlysecure.keychain.util.InputData; -import org.sufficientlysecure.keychain.util.Log; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; - -public class OpenPgpService extends RemoteService { - - private static final int PRIVATE_REQUEST_CODE_PASSPHRASE = 551; - private static final int PRIVATE_REQUEST_CODE_USER_IDS = 552; - private static final int PRIVATE_REQUEST_CODE_GET_KEYS = 553; - - /** - * Search database for key ids based on emails. - * - * @param encryptionUserIds - * @return - */ - private Intent getKeyIdsFromEmails(Intent data, String[] encryptionUserIds) { - // find key ids to given emails in database - ArrayList keyIds = new ArrayList(); - - boolean missingUserIdsCheck = false; - boolean dublicateUserIdsCheck = false; - ArrayList missingUserIds = new ArrayList(); - ArrayList dublicateUserIds = new ArrayList(); - - for (String email : encryptionUserIds) { - Uri uri = KeychainContract.KeyRings.buildPublicKeyRingsByEmailsUri(email); - Cursor cur = getContentResolver().query(uri, null, null, null, null); - if (cur.moveToFirst()) { - long id = cur.getLong(cur.getColumnIndex(KeychainContract.KeyRings.MASTER_KEY_ID)); - keyIds.add(id); - } else { - missingUserIdsCheck = true; - missingUserIds.add(email); - Log.d(Constants.TAG, "user id missing"); - } - if (cur.moveToNext()) { - dublicateUserIdsCheck = true; - dublicateUserIds.add(email); - Log.d(Constants.TAG, "more than one user id with the same email"); - } - } - - // convert to long[] - long[] keyIdsArray = new long[keyIds.size()]; - for (int i = 0; i < keyIdsArray.length; i++) { - keyIdsArray[i] = keyIds.get(i); - } - - // allow the user to verify pub key selection - if (missingUserIdsCheck || dublicateUserIdsCheck) { - // build PendingIntent - Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); - intent.setAction(RemoteServiceActivity.ACTION_SELECT_PUB_KEYS); - intent.putExtra(RemoteServiceActivity.EXTRA_SELECTED_MASTER_KEY_IDS, keyIdsArray); - intent.putExtra(RemoteServiceActivity.EXTRA_MISSING_USER_IDS, missingUserIds); - intent.putExtra(RemoteServiceActivity.EXTRA_DUBLICATE_USER_IDS, dublicateUserIds); - intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - - PendingIntent pi = PendingIntent.getActivity - (getBaseContext(), PRIVATE_REQUEST_CODE_USER_IDS, intent, 0); - - // return PendingIntent to be executed by client - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_INTENT, pi); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); - return result; - } - - if (keyIdsArray.length == 0) { - return null; - } - - Intent result = new Intent(); - result.putExtra(OpenPgpApi.EXTRA_KEY_IDS, keyIdsArray); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); - return result; - } - - private Intent getPassphraseBundleIntent(Intent data, long keyId) { - // build PendingIntent for passphrase input - Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); - intent.setAction(RemoteServiceActivity.ACTION_CACHE_PASSPHRASE); - intent.putExtra(RemoteServiceActivity.EXTRA_SECRET_KEY_ID, keyId); - // pass params through to activity that it can be returned again later to repeat pgp operation - intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity - (getBaseContext(), PRIVATE_REQUEST_CODE_PASSPHRASE, intent, 0); - - // return PendingIntent to be executed by client - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_INTENT, pi); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); - return result; - } - - private Intent signImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AppSettings appSettings) { - try { - boolean asciiArmor = data.getBooleanExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); - - // get passphrase from cache, if key has "no" passphrase, this returns an empty String - String passphrase; - if (data.hasExtra(OpenPgpApi.EXTRA_PASSPHRASE)) { - passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); - } else { - passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), appSettings.getKeyId()); - } - if (passphrase == null) { - // get PendingIntent for passphrase input, add it to given params and return to client - Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); - return passphraseBundle; - } - - // Get Input- and OutputStream from ParcelFileDescriptor - InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input); - OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output); - try { - long inputLength = is.available(); - InputData inputData = new InputData(is, inputLength); - - // sign-only - PgpSignEncrypt.Builder builder = new PgpSignEncrypt.Builder(getContext(), inputData, os); - builder.enableAsciiArmorOutput(asciiArmor) - .signatureHashAlgorithm(appSettings.getHashAlgorithm()) - .signatureForceV3(false) - .signatureKeyId(appSettings.getKeyId()) - .signaturePassphrase(passphrase); - builder.build().execute(); - } finally { - is.close(); - os.close(); - } - - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); - return result; - } catch (Exception e) { - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_ERROR, - new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - return result; - } - } - - private Intent encryptAndSignImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AppSettings appSettings, boolean sign) { - try { - boolean asciiArmor = data.getBooleanExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); - - long[] keyIds; - if (data.hasExtra(OpenPgpApi.EXTRA_KEY_IDS)) { - keyIds = data.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS); - } else if (data.hasExtra(OpenPgpApi.EXTRA_USER_IDS)) { - // get key ids based on given user ids - String[] userIds = data.getStringArrayExtra(OpenPgpApi.EXTRA_USER_IDS); - // give params through to activity... - Intent result = getKeyIdsFromEmails(data, userIds); - - if (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0) == OpenPgpApi.RESULT_CODE_SUCCESS) { - keyIds = result.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS); - } else { - // if not success -> result contains a PendingIntent for user interaction - return result; - } - } else { - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_ERROR, - new OpenPgpError(OpenPgpError.GENERIC_ERROR, - "Missing parameter user_ids or key_ids!")); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - return result; - } - - // add own key for encryption - keyIds = Arrays.copyOf(keyIds, keyIds.length + 1); - keyIds[keyIds.length - 1] = appSettings.getKeyId(); - - // build InputData and write into OutputStream - // Get Input- and OutputStream from ParcelFileDescriptor - InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input); - OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output); - try { - long inputLength = is.available(); - InputData inputData = new InputData(is, inputLength); - - PgpSignEncrypt.Builder builder = new PgpSignEncrypt.Builder(getContext(), inputData, os); - builder.enableAsciiArmorOutput(asciiArmor) - .compressionId(appSettings.getCompression()) - .symmetricEncryptionAlgorithm(appSettings.getEncryptionAlgorithm()) - .encryptionKeyIds(keyIds); - - if (sign) { - String passphrase; - if (data.hasExtra(OpenPgpApi.EXTRA_PASSPHRASE)) { - passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); - } else { - passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), - appSettings.getKeyId()); - } - if (passphrase == null) { - // get PendingIntent for passphrase input, add it to given params and return to client - Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); - return passphraseBundle; - } - - // sign and encrypt - builder.signatureHashAlgorithm(appSettings.getHashAlgorithm()) - .signatureForceV3(false) - .signatureKeyId(appSettings.getKeyId()) - .signaturePassphrase(passphrase); - } else { - // encrypt only - builder.signatureKeyId(Id.key.none); - } - // execute PGP operation! - builder.build().execute(); - } finally { - is.close(); - os.close(); - } - - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); - return result; - } catch (Exception e) { - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_ERROR, - new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - return result; - } - } - - private Intent decryptAndVerifyImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AppSettings appSettings) { - try { - // Get Input- and OutputStream from ParcelFileDescriptor - InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input); - OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output); - - Intent result = new Intent(); - try { - - String passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); - long inputLength = is.available(); - InputData inputData = new InputData(is, inputLength); - - PgpDecryptVerify.Builder builder = new PgpDecryptVerify.Builder(this, inputData, os); - builder.assumeSymmetric(false) // no support for symmetric encryption - // allow only the private key for this app for decryption - .enforcedKeyId(appSettings.getKeyId()) - .passphrase(passphrase); - - // TODO: currently does not support binary signed-only content - PgpDecryptVerifyResult decryptVerifyResult = builder.build().execute(); - - if (decryptVerifyResult.isKeyPassphraseNeeded()) { - // get PendingIntent for passphrase input, add it to given params and return to client - Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); - return passphraseBundle; - } else if (decryptVerifyResult.isSymmetricPassphraseNeeded()) { - throw new PgpGeneralException("Decryption of symmetric content not supported by API!"); - } - - OpenPgpSignatureResult signatureResult = decryptVerifyResult.getSignatureResult(); - if (signatureResult != null) { - if (signatureResult.getStatus() == OpenPgpSignatureResult.SIGNATURE_UNKNOWN_PUB_KEY) { - // If signature is unknown we return an _additional_ PendingIntent - // to retrieve the missing key - // TODO!!! - Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); - intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); - intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, "todo"); - intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_GET_KEYS, intent, 0); - - result.putExtra(OpenPgpApi.RESULT_INTENT, pi); - } - - result.putExtra(OpenPgpApi.RESULT_SIGNATURE, signatureResult); - } - - } finally { - is.close(); - os.close(); - } - - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); - return result; - } catch (Exception e) { - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_ERROR, - new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - return result; - } - } - - private Intent getKeyImpl(Intent data) { - try { - long keyId = data.getLongExtra(OpenPgpApi.EXTRA_KEY_ID, 0); - - if (ProviderHelper.getPGPPublicKeyByKeyId(this, keyId) == null) { - Intent result = new Intent(); - - // If keys are not in db we return an additional PendingIntent - // to retrieve the missing key - // TODO!!! - Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); - intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); - intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, "todo"); - intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_GET_KEYS, intent, 0); - - result.putExtra(OpenPgpApi.RESULT_INTENT, pi); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); - return result; - } else { - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); - return result; - } - } catch (Exception e) { - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_ERROR, - new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - return result; - } - } - - private Intent getKeyIdsImpl(Intent data) { - // get key ids based on given user ids - String[] userIds = data.getStringArrayExtra(OpenPgpApi.EXTRA_USER_IDS); - Intent result = getKeyIdsFromEmails(data, userIds); - return result; - } - - /** - * Check requirements: - * - params != null - * - has supported API version - * - is allowed to call the service (access has been granted) - * - * @param data - * @return null if everything is okay, or a Bundle with an error/PendingIntent - */ - private Intent checkRequirements(Intent data) { - // params Bundle is required! - if (data == null) { - Intent result = new Intent(); - OpenPgpError error = new OpenPgpError(OpenPgpError.GENERIC_ERROR, "params Bundle required!"); - result.putExtra(OpenPgpApi.RESULT_ERROR, error); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - return result; - } - - // version code is required and needs to correspond to version code of service! - if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != OpenPgpApi.API_VERSION) { - Intent result = new Intent(); - OpenPgpError error = new OpenPgpError - (OpenPgpError.INCOMPATIBLE_API_VERSIONS, "Incompatible API versions!"); - result.putExtra(OpenPgpApi.RESULT_ERROR, error); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - return result; - } - - // check if caller is allowed to access openpgp keychain - Intent result = isAllowed(data); - if (result != null) { - return result; - } - - return null; - } - - // TODO: multi-threading - private final IOpenPgpService.Stub mBinder = new IOpenPgpService.Stub() { - - @Override - public Intent execute(Intent data, ParcelFileDescriptor input, ParcelFileDescriptor output) { - Intent errorResult = checkRequirements(data); - if (errorResult != null) { - return errorResult; - } - - final AppSettings appSettings = getAppSettings(); - - String action = data.getAction(); - if (OpenPgpApi.ACTION_SIGN.equals(action)) { - return signImpl(data, input, output, appSettings); - } else if (OpenPgpApi.ACTION_ENCRYPT.equals(action)) { - return encryptAndSignImpl(data, input, output, appSettings, false); - } else if (OpenPgpApi.ACTION_SIGN_AND_ENCRYPT.equals(action)) { - return encryptAndSignImpl(data, input, output, appSettings, true); - } else if (OpenPgpApi.ACTION_DECRYPT_VERIFY.equals(action)) { - return decryptAndVerifyImpl(data, input, output, appSettings); - } else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) { - return getKeyImpl(data); - } else if (OpenPgpApi.ACTION_GET_KEY_IDS.equals(action)) { - return getKeyIdsImpl(data); - } else { - return null; - } - } - - }; - - @Override - public IBinder onBind(Intent intent) { - return mBinder; - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java deleted file mode 100644 index e0dc4162f..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsAdapter.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.database.Cursor; -import android.support.v4.widget.CursorAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; - -public class RegisteredAppsAdapter extends CursorAdapter { - - private LayoutInflater mInflater; - private PackageManager mPM; - - public RegisteredAppsAdapter(Context context, Cursor c, int flags) { - super(context, c, flags); - - mInflater = LayoutInflater.from(context); - mPM = context.getApplicationContext().getPackageManager(); - } - - @Override - public void bindView(View view, Context context, Cursor cursor) { - TextView text = (TextView) view.findViewById(R.id.api_apps_adapter_item_name); - ImageView icon = (ImageView) view.findViewById(R.id.api_apps_adapter_item_icon); - - String packageName = cursor.getString(cursor.getColumnIndex(ApiApps.PACKAGE_NAME)); - if (packageName != null) { - // get application name - try { - ApplicationInfo ai = mPM.getApplicationInfo(packageName, 0); - - text.setText(mPM.getApplicationLabel(ai)); - icon.setImageDrawable(mPM.getApplicationIcon(ai)); - } catch (final NameNotFoundException e) { - // fallback - text.setText(packageName); - } - } else { - // fallback - text.setText(packageName); - } - - } - - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return mInflater.inflate(R.layout.api_apps_adapter_list_item, null); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java deleted file mode 100644 index f6f216efd..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListActivity.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.os.Bundle; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.ui.DrawerActivity; - -public class RegisteredAppsListActivity extends DrawerActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.api_apps_list_activity); - - setupDrawerNavigation(savedInstanceState); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java deleted file mode 100644 index 25d0c7593..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RegisteredAppsListFragment.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.content.ContentUris; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.os.Bundle; -import android.support.v4.app.ListFragment; -import android.support.v4.app.LoaderManager; -import android.support.v4.content.CursorLoader; -import android.support.v4.content.Loader; -import android.view.View; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; - -public class RegisteredAppsListFragment extends ListFragment implements - LoaderManager.LoaderCallbacks { - - // This is the Adapter being used to display the list's data. - RegisteredAppsAdapter mAdapter; - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - getListView().setOnItemClickListener(new OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int position, long id) { - // edit app settings - Intent intent = new Intent(getActivity(), AppSettingsActivity.class); - intent.setData(ContentUris.withAppendedId(KeychainContract.ApiApps.CONTENT_URI, id)); - startActivity(intent); - } - }); - - // Give some text to display if there is no data. In a real - // application this would come from a resource. - setEmptyText(getString(R.string.api_no_apps)); - - // We have a menu item to show in action bar. - setHasOptionsMenu(true); - - // Create an empty adapter we will use to display the loaded data. - mAdapter = new RegisteredAppsAdapter(getActivity(), null, 0); - setListAdapter(mAdapter); - - // Prepare the loader. Either re-connect with an existing one, - // or start a new one. - getLoaderManager().initLoader(0, null, this); - } - - // These are the Contacts rows that we will retrieve. - static final String[] PROJECTION = new String[]{ApiApps._ID, ApiApps.PACKAGE_NAME}; - - public Loader onCreateLoader(int id, Bundle args) { - // This is called when a new Loader needs to be created. This - // sample only has one Loader, so we don't care about the ID. - // First, pick the base URI to use depending on whether we are - // currently filtering. - Uri baseUri = ApiApps.CONTENT_URI; - - // Now create and return a CursorLoader that will take care of - // creating a Cursor for the data being displayed. - return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, - ApiApps.PACKAGE_NAME + " COLLATE LOCALIZED ASC"); - } - - public void onLoadFinished(Loader loader, Cursor data) { - // Swap the new cursor in. (The framework will take care of closing the - // old cursor once we return.) - mAdapter.swapCursor(data); - } - - public void onLoaderReset(Loader loader) { - // This is called when the last Cursor provided to onLoadFinished() - // above is about to be closed. We need to make sure we are no - // longer using it. - mAdapter.swapCursor(null); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java deleted file mode 100644 index 6a883316a..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteService.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (C) 2013-2014 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.app.PendingIntent; -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.content.pm.Signature; -import android.net.Uri; -import android.os.Binder; -import org.openintents.openpgp.OpenPgpError; -import org.openintents.openpgp.util.OpenPgpApi; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.util.Log; - -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Abstract service class for remote APIs that handle app registration and user input. - */ -public abstract class RemoteService extends Service { - Context mContext; - - private static final int PRIVATE_REQUEST_CODE_REGISTER = 651; - private static final int PRIVATE_REQUEST_CODE_ERROR = 652; - - - public Context getContext() { - return mContext; - } - - protected Intent isAllowed(Intent data) { - try { - if (isCallerAllowed(false)) { - - return null; - } else { - String[] callingPackages = getPackageManager().getPackagesForUid( - Binder.getCallingUid()); - // TODO: currently simply uses first entry - String packageName = callingPackages[0]; - - byte[] packageSignature; - try { - packageSignature = getPackageSignature(packageName); - } catch (NameNotFoundException e) { - Log.e(Constants.TAG, "Should not happen, returning!", e); - // return error - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); - result.putExtra(OpenPgpApi.RESULT_ERROR, - new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); - return result; - } - Log.e(Constants.TAG, "Not allowed to use service! return PendingIntent for registration!"); - - Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); - intent.setAction(RemoteServiceActivity.ACTION_REGISTER); - intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_NAME, packageName); - intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_SIGNATURE, packageSignature); - intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_REGISTER, intent, 0); - - // return PendingIntent to be executed by client - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); - result.putExtra(OpenPgpApi.RESULT_INTENT, pi); - - return result; - } - } catch (WrongPackageSignatureException e) { - Log.e(Constants.TAG, "wrong signature!", e); - - Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); - intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); - intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, - getString(R.string.api_error_wrong_signature)); - intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_ERROR, intent, 0); - - // return PendingIntent to be executed by client - Intent result = new Intent(); - result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); - result.putExtra(OpenPgpApi.RESULT_INTENT, pi); - - return result; - } - } - - private byte[] getPackageSignature(String packageName) throws NameNotFoundException { - PackageInfo pkgInfo = getPackageManager().getPackageInfo(packageName, - PackageManager.GET_SIGNATURES); - Signature[] signatures = pkgInfo.signatures; - // TODO: Only first signature?! - byte[] packageSignature = signatures[0].toByteArray(); - - return packageSignature; - } - - /** - * Retrieves AppSettings from database for the application calling this remote service - * - * @return - */ - protected AppSettings getAppSettings() { - String[] callingPackages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); - - // get app settings for this package - for (int i = 0; i < callingPackages.length; i++) { - String currentPkg = callingPackages[i]; - - Uri uri = KeychainContract.ApiApps.buildByPackageNameUri(currentPkg); - - AppSettings settings = ProviderHelper.getApiAppSettings(this, uri); - - if (settings != null) { - return settings; - } - } - - return null; - } - - /** - * Checks if process that binds to this service (i.e. the package name corresponding to the - * process) is in the list of allowed package names. - * - * @param allowOnlySelf allow only Keychain app itself - * @return true if process is allowed to use this service - * @throws WrongPackageSignatureException - */ - private boolean isCallerAllowed(boolean allowOnlySelf) throws WrongPackageSignatureException { - return isUidAllowed(Binder.getCallingUid(), allowOnlySelf); - } - - private boolean isUidAllowed(int uid, boolean allowOnlySelf) - throws WrongPackageSignatureException { - if (android.os.Process.myUid() == uid) { - return true; - } - if (allowOnlySelf) { // barrier - return false; - } - - String[] callingPackages = getPackageManager().getPackagesForUid(uid); - - // is calling package allowed to use this service? - for (int i = 0; i < callingPackages.length; i++) { - String currentPkg = callingPackages[i]; - - if (isPackageAllowed(currentPkg)) { - return true; - } - } - - Log.d(Constants.TAG, "Caller is NOT allowed!"); - return false; - } - - /** - * Checks if packageName is a registered app for the API. Does not return true for own package! - * - * @param packageName - * @return - * @throws WrongPackageSignatureException - */ - private boolean isPackageAllowed(String packageName) throws WrongPackageSignatureException { - Log.d(Constants.TAG, "packageName: " + packageName); - - ArrayList allowedPkgs = ProviderHelper.getRegisteredApiApps(this); - Log.d(Constants.TAG, "allowed: " + allowedPkgs); - - // check if package is allowed to use our service - if (allowedPkgs.contains(packageName)) { - Log.d(Constants.TAG, "Package is allowed! packageName: " + packageName); - - // check package signature - byte[] currentSig; - try { - currentSig = getPackageSignature(packageName); - } catch (NameNotFoundException e) { - throw new WrongPackageSignatureException(e.getMessage()); - } - - byte[] storedSig = ProviderHelper.getApiAppSignature(this, packageName); - if (Arrays.equals(currentSig, storedSig)) { - Log.d(Constants.TAG, - "Package signature is correct! (equals signature from database)"); - return true; - } else { - throw new WrongPackageSignatureException( - "PACKAGE NOT ALLOWED! Signature wrong! (Signature not equals signature from database)"); - } - } - - return false; - } - - @Override - public void onCreate() { - super.onCreate(); - mContext = this; - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java deleted file mode 100644 index e20114853..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/RemoteServiceActivity.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2013-2014 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -import android.content.Intent; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.support.v7.app.ActionBarActivity; -import android.view.View; -import org.openintents.openpgp.util.OpenPgpApi; -import org.sufficientlysecure.htmltextview.HtmlTextView; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Id; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; -import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.ui.SelectPublicKeyFragment; -import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; -import org.sufficientlysecure.keychain.util.Log; - -import java.util.ArrayList; - -public class RemoteServiceActivity extends ActionBarActivity { - - public static final String ACTION_REGISTER = Constants.INTENT_PREFIX + "API_ACTIVITY_REGISTER"; - public static final String ACTION_CACHE_PASSPHRASE = Constants.INTENT_PREFIX - + "API_ACTIVITY_CACHE_PASSPHRASE"; - public static final String ACTION_SELECT_PUB_KEYS = Constants.INTENT_PREFIX - + "API_ACTIVITY_SELECT_PUB_KEYS"; - public static final String ACTION_ERROR_MESSAGE = Constants.INTENT_PREFIX - + "API_ACTIVITY_ERROR_MESSAGE"; - - public static final String EXTRA_MESSENGER = "messenger"; - - public static final String EXTRA_DATA = "data"; - - // passphrase action - public static final String EXTRA_SECRET_KEY_ID = "secret_key_id"; - // register action - public static final String EXTRA_PACKAGE_NAME = "package_name"; - public static final String EXTRA_PACKAGE_SIGNATURE = "package_signature"; - // select pub keys action - public static final String EXTRA_SELECTED_MASTER_KEY_IDS = "master_key_ids"; - public static final String EXTRA_MISSING_USER_IDS = "missing_user_ids"; - public static final String EXTRA_DUBLICATE_USER_IDS = "dublicate_user_ids"; - // error message - public static final String EXTRA_ERROR_MESSAGE = "error_message"; - - // register view - private AppSettingsFragment mSettingsFragment; - // select pub keys view - private SelectPublicKeyFragment mSelectFragment; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - handleActions(getIntent(), savedInstanceState); - } - - protected void handleActions(Intent intent, Bundle savedInstanceState) { - - String action = intent.getAction(); - final Bundle extras = intent.getExtras(); - - - if (ACTION_REGISTER.equals(action)) { - final String packageName = extras.getString(EXTRA_PACKAGE_NAME); - final byte[] packageSignature = extras.getByteArray(EXTRA_PACKAGE_SIGNATURE); - - // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setTwoButtonView(getSupportActionBar(), - R.string.api_register_allow, R.drawable.ic_action_done, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // Allow - - // user needs to select a key! - if (mSettingsFragment.getAppSettings().getKeyId() == Id.key.none) { - mSettingsFragment.setErrorOnSelectKeyFragment( - getString(R.string.api_register_error_select_key)); - } else { - ProviderHelper.insertApiApp(RemoteServiceActivity.this, - mSettingsFragment.getAppSettings()); - - // give data through for new service call - Intent resultData = extras.getParcelable(EXTRA_DATA); - RemoteServiceActivity.this.setResult(RESULT_OK, resultData); - RemoteServiceActivity.this.finish(); - } - } - }, R.string.api_register_disallow, R.drawable.ic_action_cancel, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // Disallow - RemoteServiceActivity.this.setResult(RESULT_CANCELED); - RemoteServiceActivity.this.finish(); - } - } - ); - - setContentView(R.layout.api_app_register_activity); - - mSettingsFragment = (AppSettingsFragment) getSupportFragmentManager().findFragmentById( - R.id.api_app_settings_fragment); - - AppSettings settings = new AppSettings(packageName, packageSignature); - mSettingsFragment.setAppSettings(settings); - } else if (ACTION_CACHE_PASSPHRASE.equals(action)) { - long secretKeyId = extras.getLong(EXTRA_SECRET_KEY_ID); - Intent resultData = extras.getParcelable(EXTRA_DATA); - - showPassphraseDialog(resultData, secretKeyId); - } else if (ACTION_SELECT_PUB_KEYS.equals(action)) { - long[] selectedMasterKeyIds = intent.getLongArrayExtra(EXTRA_SELECTED_MASTER_KEY_IDS); - ArrayList missingUserIds = intent - .getStringArrayListExtra(EXTRA_MISSING_USER_IDS); - ArrayList dublicateUserIds = intent - .getStringArrayListExtra(EXTRA_DUBLICATE_USER_IDS); - - // TODO: do this with spannable instead of HTML to prevent parsing failures with weird user ids - String text = "" + getString(R.string.api_select_pub_keys_text) + ""; - text += "

"; - if (missingUserIds != null && missingUserIds.size() > 0) { - text += getString(R.string.api_select_pub_keys_missing_text); - text += "
"; - text += "
    "; - for (String userId : missingUserIds) { - text += "
  • " + userId + "
  • "; - } - text += "
"; - text += "
"; - } - if (dublicateUserIds != null && dublicateUserIds.size() > 0) { - text += getString(R.string.api_select_pub_keys_dublicates_text); - text += "
"; - text += "
    "; - for (String userId : dublicateUserIds) { - text += "
  • " + userId + "
  • "; - } - text += "
"; - } - - // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setTwoButtonView(getSupportActionBar(), - R.string.btn_okay, R.drawable.ic_action_done, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // add key ids to params Bundle for new request - Intent resultData = extras.getParcelable(EXTRA_DATA); - resultData.putExtra(OpenPgpApi.EXTRA_KEY_IDS, - mSelectFragment.getSelectedMasterKeyIds()); - - RemoteServiceActivity.this.setResult(RESULT_OK, resultData); - RemoteServiceActivity.this.finish(); - } - }, R.string.btn_do_not_save, R.drawable.ic_action_cancel, new View.OnClickListener() { - @Override - public void onClick(View v) { - // cancel - RemoteServiceActivity.this.setResult(RESULT_CANCELED); - RemoteServiceActivity.this.finish(); - } - } - ); - - setContentView(R.layout.api_app_select_pub_keys_activity); - - // set text on view - HtmlTextView textView = (HtmlTextView) findViewById(R.id.api_select_pub_keys_text); - textView.setHtmlFromString(text); - - /* Load select pub keys fragment */ - // Check that the activity is using the layout version with - // the fragment_container FrameLayout - if (findViewById(R.id.api_select_pub_keys_fragment_container) != null) { - - // However, if we're being restored from a previous state, - // then we don't need to do anything and should return or else - // we could end up with overlapping fragments. - if (savedInstanceState != null) { - return; - } - - // Create an instance of the fragment - mSelectFragment = SelectPublicKeyFragment.newInstance(selectedMasterKeyIds); - - // Add the fragment to the 'fragment_container' FrameLayout - getSupportFragmentManager().beginTransaction() - .add(R.id.api_select_pub_keys_fragment_container, mSelectFragment).commit(); - } - } else if (ACTION_ERROR_MESSAGE.equals(action)) { - String errorMessage = intent.getStringExtra(EXTRA_ERROR_MESSAGE); - - String text = "" + errorMessage + ""; - - // Inflate a "Done" custom action bar view - ActionBarHelper.setOneButtonView(getSupportActionBar(), - R.string.btn_okay, R.drawable.ic_action_done, - new View.OnClickListener() { - - @Override - public void onClick(View v) { - RemoteServiceActivity.this.setResult(RESULT_CANCELED); - RemoteServiceActivity.this.finish(); - } - }); - - setContentView(R.layout.api_app_error_message); - - // set text on view - HtmlTextView textView = (HtmlTextView) findViewById(R.id.api_app_error_message_text); - textView.setHtmlFromString(text); - } else { - Log.e(Constants.TAG, "Action does not exist!"); - setResult(RESULT_CANCELED); - finish(); - } - } - - /** - * Shows passphrase dialog to cache a new passphrase the user enters for using it later for - * encryption. Based on mSecretKeyId it asks for a passphrase to open a private key or it asks - * for a symmetric passphrase - */ - private void showPassphraseDialog(final Intent data, long secretKeyId) { - // Message is received after passphrase is cached - Handler returnHandler = new Handler() { - @Override - public void handleMessage(Message message) { - if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) { - // return given params again, for calling the service method again - RemoteServiceActivity.this.setResult(RESULT_OK, data); - } else { - RemoteServiceActivity.this.setResult(RESULT_CANCELED); - } - - RemoteServiceActivity.this.finish(); - } - }; - - // Create a new Messenger for the communication back - Messenger messenger = new Messenger(returnHandler); - - try { - PassphraseDialogFragment passphraseDialog = PassphraseDialogFragment.newInstance(this, - messenger, secretKeyId); - - passphraseDialog.show(getSupportFragmentManager(), "passphraseDialog"); - } catch (PgpGeneralException e) { - Log.d(Constants.TAG, "No passphrase for this secret key, do pgp operation directly!"); - // return given params again, for calling the service method again - setResult(RESULT_OK, data); - finish(); - } - } -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java deleted file mode 100644 index 0b642086a..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/remote/WrongPackageSignatureException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.service.remote; - -public class WrongPackageSignatureException extends Exception { - - private static final long serialVersionUID = -8294642703122196028L; - - public WrongPackageSignatureException(String message) { - super(message); - } -} -- cgit v1.2.3 From f082b53118e7a174b8c9a79964abaeef4a34fa29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Sun, 23 Mar 2014 02:17:39 +0100 Subject: Extend provider for new api tables --- .../keychain/provider/KeychainContract.java | 64 ++++++++- .../keychain/provider/KeychainDatabase.java | 8 +- .../keychain/provider/KeychainProvider.java | 149 ++++++++++++++++++--- .../keychain/provider/ProviderHelper.java | 42 ++++-- 4 files changed, 222 insertions(+), 41 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index de51cebbb..aa4c1f131 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -63,7 +63,7 @@ public class KeychainContract { String ENCRYPTION_ALGORITHM = "encryption_algorithm"; String HASH_ALORITHM = "hash_algorithm"; String COMPRESSION = "compression"; - String PACKAGE_NAME = "package_name"; // foreign key to api_apps.package_name + String PACKAGE_NAME_FK = "package_name"; // foreign key to api_apps.package_name } public static final class KeyTypes { @@ -90,7 +90,10 @@ public class KeychainContract { public static final String PATH_USER_IDS = "user_ids"; public static final String PATH_KEYS = "keys"; - public static final String BASE_API_APPS = "api_apps"; + public static final String BASE_API = "api"; + public static final String PATH_APPS = "apps"; + public static final String PATH_ACCOUNTS = "accounts"; + public static final String PATH_BY_PACKAGE_NAME = "package_name"; public static class KeyRings implements KeyRingsColumns, BaseColumns { @@ -254,19 +257,70 @@ public class KeychainContract { } } + /** + * Join over ApiApps with ApiAppsAccounts + */ + public static class Api implements ApiAppsColumns, ApiAppsAccountsColumns, BaseColumns { + public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() + .appendPath(BASE_API).build(); + + /** + * Use if multiple items get returned + */ + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.apis"; + + /** + * Use if a single item is returned + */ + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api"; + + public static Uri buildIdUri(String rowId) { + return CONTENT_URI.buildUpon().appendPath(rowId).build(); + } + + public static Uri buildByPackageNameUri(String packageName) { + return CONTENT_URI.buildUpon().appendPath(PATH_BY_PACKAGE_NAME).appendPath(packageName) + .build(); + } + } + public static class ApiApps implements ApiAppsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() - .appendPath(BASE_API_APPS).build(); + .appendPath(BASE_API).appendPath(PATH_APPS).build(); + + /** + * Use if multiple items get returned + */ + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api.app"; + + /** + * Use if a single item is returned + */ + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api.apps"; + + public static Uri buildIdUri(String rowId) { + return CONTENT_URI.buildUpon().appendPath(rowId).build(); + } + + public static Uri buildByPackageNameUri(String packageName) { + return CONTENT_URI.buildUpon().appendPath(PATH_BY_PACKAGE_NAME).appendPath(packageName) + .build(); + } + } + + public static class ApiAccounts implements ApiAppsAccountsColumns, BaseColumns { + public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() + .appendPath(BASE_API).appendPath(PATH_ACCOUNTS).build(); /** * Use if multiple items get returned */ - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api_apps"; + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api.acoounts"; /** * Use if a single item is returned */ - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api_apps"; + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api.account"; public static Uri buildIdUri(String rowId) { return CONTENT_URI.buildUpon().appendPath(rowId).build(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java index f7c9fe79d..e56fa2f8f 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java @@ -38,7 +38,7 @@ public class KeychainDatabase extends SQLiteOpenHelper { String KEYS = "keys"; String USER_IDS = "user_ids"; String API_APPS = "api_apps"; - String API_APPS_ACCOUNTS = "api_apps_accounts"; + String API_ACCOUNTS = "api_accounts"; } private static final String CREATE_KEY_RINGS = "CREATE TABLE IF NOT EXISTS " + Tables.KEY_RINGS @@ -80,14 +80,14 @@ public class KeychainDatabase extends SQLiteOpenHelper { + ApiAppsColumns.PACKAGE_NAME + " TEXT UNIQUE, " + ApiAppsColumns.PACKAGE_SIGNATURE + " BLOB)"; - private static final String CREATE_API_APPS_ACCOUNTS = "CREATE TABLE IF NOT EXISTS " + Tables.API_APPS_ACCOUNTS + private static final String CREATE_API_APPS_ACCOUNTS = "CREATE TABLE IF NOT EXISTS " + Tables.API_ACCOUNTS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ApiAppsAccountsColumns.KEY_ID + " INT64, " + ApiAppsAccountsColumns.ENCRYPTION_ALGORITHM + " INTEGER, " + ApiAppsAccountsColumns.HASH_ALORITHM + " INTEGER, " + ApiAppsAccountsColumns.COMPRESSION + " INTEGER" - + ApiAppsAccountsColumns.PACKAGE_NAME + " TEXT NOT NULL, FOREIGN KEY(" - + ApiAppsAccountsColumns.PACKAGE_NAME + ") REFERENCES " + Tables.API_APPS + "(" + + ApiAppsAccountsColumns.PACKAGE_NAME_FK + " TEXT NOT NULL, FOREIGN KEY(" + + ApiAppsAccountsColumns.PACKAGE_NAME_FK + ") REFERENCES " + Tables.API_APPS + "(" + ApiAppsColumns.PACKAGE_NAME + ") ON DELETE CASCADE)"; KeychainDatabase(Context context) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 746449f7e..a094b13de 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2013 Dominik Schürmann + * Copyright (C) 2012-2014 Dominik Schürmann * Copyright (C) 2010 Thialfihar * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -28,8 +28,19 @@ import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; + import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.provider.KeychainContract.*; +import org.sufficientlysecure.keychain.provider.KeychainContract.Api; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAccounts; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsAccountsColumns; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingsColumns; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; +import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeysColumns; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; +import org.sufficientlysecure.keychain.provider.KeychainContract.UserIdsColumns; import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; import org.sufficientlysecure.keychain.util.Log; @@ -70,9 +81,15 @@ public class KeychainProvider extends ContentProvider { private static final int SECRET_KEY_RING_USER_ID = 221; private static final int SECRET_KEY_RING_USER_ID_BY_ROW_ID = 222; - private static final int API_APPS = 301; - private static final int API_APPS_BY_ROW_ID = 302; - private static final int API_APPS_BY_PACKAGE_NAME = 303; + private static final int API = 301; + private static final int API_BY_ROW_ID = 302; + private static final int API_BY_PACKAGE_NAME = 303; + private static final int API_APPS = 304; + private static final int API_APPS_BY_ROW_ID = 305; + private static final int API_APPS_BY_PACKAGE_NAME = 306; + private static final int API_ACCOUNTS = 307; + private static final int API_ACCOUNTS_BY_ROW_ID = 308; + private static final int API_ACCOUNTS_BY_PACKAGE_NAME = 309; private static final int UNIFIED_KEY_RING = 401; @@ -230,11 +247,27 @@ public class KeychainProvider extends ContentProvider { /** * API apps */ - matcher.addURI(authority, KeychainContract.BASE_API_APPS, API_APPS); - matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/#", API_APPS_BY_ROW_ID); - matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + matcher.addURI(authority, KeychainContract.BASE_API, API); + matcher.addURI(authority, KeychainContract.BASE_API + "/#", API_BY_ROW_ID); + matcher.addURI(authority, KeychainContract.BASE_API + "/" + + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_BY_PACKAGE_NAME); + + matcher.addURI(authority, KeychainContract.BASE_API + "/" + + KeychainContract.PATH_APPS, API_APPS); + matcher.addURI(authority, KeychainContract.BASE_API + "/" + + KeychainContract.PATH_APPS + "/#", API_APPS_BY_ROW_ID); + matcher.addURI(authority, KeychainContract.BASE_API + "/" + + KeychainContract.PATH_APPS + "/" + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_APPS_BY_PACKAGE_NAME); + matcher.addURI(authority, KeychainContract.BASE_API + "/" + + KeychainContract.PATH_ACCOUNTS, API_ACCOUNTS); + matcher.addURI(authority, KeychainContract.BASE_API + "/" + + KeychainContract.PATH_ACCOUNTS + "/#", API_ACCOUNTS_BY_ROW_ID); + matcher.addURI(authority, KeychainContract.BASE_API + "/" + + KeychainContract.PATH_ACCOUNTS + "/" + + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_ACCOUNTS_BY_PACKAGE_NAME); + /** * data stream * @@ -299,6 +332,13 @@ public class KeychainProvider extends ContentProvider { case SECRET_KEY_RING_USER_ID_BY_ROW_ID: return UserIds.CONTENT_ITEM_TYPE; + case API: + return Api.CONTENT_TYPE; + + case API_BY_ROW_ID: + case API_BY_PACKAGE_NAME: + return Api.CONTENT_ITEM_TYPE; + case API_APPS: return ApiApps.CONTENT_TYPE; @@ -306,6 +346,13 @@ public class KeychainProvider extends ContentProvider { case API_APPS_BY_PACKAGE_NAME: return ApiApps.CONTENT_ITEM_TYPE; + case API_ACCOUNTS: + return ApiAccounts.CONTENT_TYPE; + + case API_ACCOUNTS_BY_ROW_ID: + case API_ACCOUNTS_BY_PACKAGE_NAME: + return ApiAccounts.CONTENT_ITEM_TYPE; + default: throw new UnsupportedOperationException("Unknown uri: " + uri); } @@ -506,7 +553,6 @@ public class KeychainProvider extends ContentProvider { } break; - case PUBLIC_KEY_RING: case SECRET_KEY_RING: qb = buildKeyRingQuery(qb, match); @@ -516,7 +562,6 @@ public class KeychainProvider extends ContentProvider { } break; - case PUBLIC_KEY_RING_BY_ROW_ID: case SECRET_KEY_RING_BY_ROW_ID: qb = buildKeyRingQuery(qb, match); @@ -529,7 +574,6 @@ public class KeychainProvider extends ContentProvider { } break; - case PUBLIC_KEY_RING_BY_MASTER_KEY_ID: case SECRET_KEY_RING_BY_MASTER_KEY_ID: qb = buildKeyRingQuery(qb, match); @@ -542,7 +586,6 @@ public class KeychainProvider extends ContentProvider { } break; - case SECRET_KEY_RING_BY_KEY_ID: case PUBLIC_KEY_RING_BY_KEY_ID: qb = buildKeyRingQueryWithSpecificKey(qb, match); @@ -555,7 +598,6 @@ public class KeychainProvider extends ContentProvider { } break; - case SECRET_KEY_RING_BY_EMAILS: case PUBLIC_KEY_RING_BY_EMAILS: qb = buildKeyRingQuery(qb, match); @@ -585,7 +627,6 @@ public class KeychainProvider extends ContentProvider { } break; - case SECRET_KEY_RING_BY_LIKE_EMAIL: case PUBLIC_KEY_RING_BY_LIKE_EMAIL: qb = buildKeyRingQuery(qb, match); @@ -601,7 +642,6 @@ public class KeychainProvider extends ContentProvider { + "))"); break; - case PUBLIC_KEY_RING_KEY: case SECRET_KEY_RING_KEY: qb.setTables(Tables.KEYS); @@ -614,7 +654,6 @@ public class KeychainProvider extends ContentProvider { qb.setProjectionMap(getProjectionMapForKeys()); break; - case PUBLIC_KEY_RING_KEY_BY_ROW_ID: case SECRET_KEY_RING_KEY_BY_ROW_ID: qb.setTables(Tables.KEYS); @@ -630,7 +669,6 @@ public class KeychainProvider extends ContentProvider { qb.setProjectionMap(getProjectionMapForKeys()); break; - case PUBLIC_KEY_RING_BY_MASTER_KEY_ID_USER_ID: qb.setTables(Tables.USER_IDS + " INNER JOIN " + Tables.KEY_RINGS + " ON " + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.USER_IDS + "." @@ -641,7 +679,6 @@ public class KeychainProvider extends ContentProvider { qb.setProjectionMap(getProjectionMapForUserIds()); break; - case PUBLIC_KEY_RING_USER_ID: case SECRET_KEY_RING_USER_ID: qb.setTables(Tables.USER_IDS); @@ -649,7 +686,6 @@ public class KeychainProvider extends ContentProvider { qb.appendWhereEscapeString(uri.getPathSegments().get(2)); break; - case PUBLIC_KEY_RING_USER_ID_BY_ROW_ID: case SECRET_KEY_RING_USER_ID_BY_ROW_ID: qb.setTables(Tables.USER_IDS); @@ -660,7 +696,28 @@ public class KeychainProvider extends ContentProvider { qb.appendWhereEscapeString(uri.getLastPathSegment()); break; + case API: + qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" + + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." + + ApiAccounts.PACKAGE_NAME_FK + " )"); + + break; + case API_BY_ROW_ID: + qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" + + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." + + ApiAccounts.PACKAGE_NAME_FK + " )"); + qb.appendWhere(Tables.API_APPS + "." + BaseColumns._ID + " = "); + qb.appendWhereEscapeString(uri.getLastPathSegment()); + + break; + case API_BY_PACKAGE_NAME: + qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" + + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." + + ApiAccounts.PACKAGE_NAME_FK + " )"); + qb.appendWhere(Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = "); + qb.appendWhereEscapeString(uri.getLastPathSegment()); + break; case API_APPS: qb.setTables(Tables.API_APPS); @@ -675,10 +732,26 @@ public class KeychainProvider extends ContentProvider { case API_APPS_BY_PACKAGE_NAME: qb.setTables(Tables.API_APPS); qb.appendWhere(ApiApps.PACKAGE_NAME + " = "); - qb.appendWhereEscapeString(uri.getPathSegments().get(2)); + qb.appendWhereEscapeString(uri.getLastPathSegment()); + + break; + case API_ACCOUNTS: + qb.setTables(Tables.API_ACCOUNTS); break; + case API_ACCOUNTS_BY_ROW_ID: + qb.setTables(Tables.API_ACCOUNTS); + qb.appendWhere(BaseColumns._ID + " = "); + qb.appendWhereEscapeString(uri.getLastPathSegment()); + + break; + case API_ACCOUNTS_BY_PACKAGE_NAME: + qb.setTables(Tables.API_ACCOUNTS); + qb.appendWhere(ApiAppsAccountsColumns.PACKAGE_NAME_FK + " = "); + qb.appendWhereEscapeString(uri.getLastPathSegment()); + + break; default: throw new IllegalArgumentException("Unknown URI " + uri); @@ -770,6 +843,11 @@ public class KeychainProvider extends ContentProvider { rowId = db.insertOrThrow(Tables.API_APPS, null, values); rowUri = ApiApps.buildIdUri(Long.toString(rowId)); + break; + case API_ACCOUNTS: + rowId = db.insertOrThrow(Tables.API_ACCOUNTS, null, values); + rowUri = ApiAccounts.buildIdUri(Long.toString(rowId)); + break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); @@ -836,6 +914,14 @@ public class KeychainProvider extends ContentProvider { count = db.delete(Tables.API_APPS, buildDefaultApiAppsSelection(uri, true, selection), selectionArgs); break; + case API_ACCOUNTS_BY_ROW_ID: + count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, false, selection), + selectionArgs); + break; + case API_ACCOUNTS_BY_PACKAGE_NAME: + count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, true, selection), + selectionArgs); + break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } @@ -906,6 +992,14 @@ public class KeychainProvider extends ContentProvider { count = db.update(Tables.API_APPS, values, buildDefaultApiAppsSelection(uri, true, selection), selectionArgs); break; + case API_ACCOUNTS_BY_ROW_ID: + count = db.update(Tables.API_ACCOUNTS, values, + buildDefaultApiAccountsSelection(uri, false, selection), selectionArgs); + break; + case API_ACCOUNTS_BY_PACKAGE_NAME: + count = db.update(Tables.API_ACCOUNTS, values, + buildDefaultApiAccountsSelection(uri, true, selection), selectionArgs); + break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } @@ -1018,6 +1112,21 @@ public class KeychainProvider extends ContentProvider { } } + private String buildDefaultApiAccountsSelection(Uri uri, boolean packageSelection, String selection) { + String lastPathSegment = uri.getLastPathSegment(); + + String andSelection = ""; + if (!TextUtils.isEmpty(selection)) { + andSelection = " AND (" + selection + ")"; + } + + if (packageSelection) { + return ApiAccounts.PACKAGE_NAME_FK + "=" + lastPathSegment + andSelection; + } else { + return BaseColumns._ID + "=" + lastPathSegment + andSelection; + } + } + // @Override // public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { // int match = mUriMatcher.match(uri); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index e0d007de7..7e8bfbc7b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -809,44 +809,62 @@ public class ProviderHelper { return values; } - public static void insertApiApp(Context context, AppSettings appSettings) { - context.getContentResolver().insert(ApiApps.CONTENT_URI, + private static ContentValues contentValueForApiAccounts(AppSettings appSettings) { + ContentValues values = new ContentValues(); + values.put(KeychainContract.ApiAccounts.PACKAGE_NAME_FK, appSettings.getPackageName()); + values.put(KeychainContract.ApiAccounts.KEY_ID, appSettings.getKeyId()); + values.put(KeychainContract.ApiAccounts.COMPRESSION, appSettings.getCompression()); + values.put(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM, appSettings.getEncryptionAlgorithm()); + values.put(KeychainContract.ApiAccounts.HASH_ALORITHM, appSettings.getHashAlgorithm()); + + return values; + } + + public static void insertApi(Context context, AppSettings appSettings) { + context.getContentResolver().insert(KeychainContract.ApiApps.CONTENT_URI, + contentValueForApiApps(appSettings)); + context.getContentResolver().insert(KeychainContract.ApiAccounts.CONTENT_URI, contentValueForApiApps(appSettings)); } + // TODO: uri not working because it is used for both tables public static void updateApiApp(Context context, AppSettings appSettings, Uri uri) { if (context.getContentResolver().update(uri, contentValueForApiApps(appSettings), null, null) <= 0) { throw new RuntimeException(); } + if (context.getContentResolver().update(uri, contentValueForApiAccounts(appSettings), null, + null) <= 0) { + throw new RuntimeException(); + } } - public static AppSettings getApiAppSettings(Context context, Uri uri) { + public static AppSettings getApiSettings(Context context, Uri uri) { AppSettings settings = null; Cursor cur = context.getContentResolver().query(uri, null, null, null, null); if (cur != null && cur.moveToFirst()) { settings = new AppSettings(); settings.setPackageName(cur.getString(cur - .getColumnIndex(KeychainContract.ApiApps.PACKAGE_NAME))); + .getColumnIndex(KeychainContract.Api.PACKAGE_NAME))); settings.setPackageSignature(cur.getBlob(cur - .getColumnIndex(KeychainContract.ApiApps.PACKAGE_SIGNATURE))); - settings.setKeyId(cur.getLong(cur.getColumnIndex(KeychainContract.ApiApps.KEY_ID))); + .getColumnIndex(KeychainContract.Api.PACKAGE_SIGNATURE))); + settings.setKeyId(cur.getLong(cur.getColumnIndex(KeychainContract.Api.KEY_ID))); settings.setCompression(cur.getInt(cur - .getColumnIndexOrThrow(KeychainContract.ApiApps.COMPRESSION))); + .getColumnIndexOrThrow(KeychainContract.Api.COMPRESSION))); settings.setHashAlgorithm(cur.getInt(cur - .getColumnIndexOrThrow(KeychainContract.ApiApps.HASH_ALORITHM))); + .getColumnIndexOrThrow(KeychainContract.Api.HASH_ALORITHM))); settings.setEncryptionAlgorithm(cur.getInt(cur - .getColumnIndexOrThrow(KeychainContract.ApiApps.ENCRYPTION_ALGORITHM))); + .getColumnIndexOrThrow(KeychainContract.Api.ENCRYPTION_ALGORITHM))); } return settings; } - public static byte[] getApiAppSignature(Context context, String packageName) { - Uri queryUri = KeychainContract.ApiApps.buildByPackageNameUri(packageName); + public static byte[] getApiSignature(Context context, String packageName) { + Uri queryUri = KeychainContract.Api.buildByPackageNameUri(packageName); - String[] projection = new String[]{ApiApps.PACKAGE_SIGNATURE}; + String[] projection = new String[]{KeychainContract.Api.PACKAGE_SIGNATURE}; ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(queryUri, projection, null, null, null); -- cgit v1.2.3 From 57f9b55677fd0829280a082f739e7d49fbf61db2 Mon Sep 17 00:00:00 2001 From: Sreeram Boyapati Date: Sun, 23 Mar 2014 14:35:48 +0530 Subject: Added can_encrypt check --- .../sufficientlysecure/keychain/ui/ViewKeyMainFragment.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index e140cb21e..e4f707f3c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -324,7 +324,17 @@ public class ViewKeyMainFragment extends Fragment implements mFingerprint.setText(OtherHelper.colorizeFingerprint(fingerprint)); } - + int valid_keys = 0; + data.moveToFirst(); + do{ + if(data.getInt(KEYS_INDEX_CAN_ENCRYPT) == 1){ + valid_keys++; + } + }while(data.moveToNext()); + if(valid_keys == 0){ + mActionEncrypt.setVisibility(View.GONE); + } + Log.i("Valid Encryption keys", Integer.toString(valid_keys)); mKeysAdapter.swapCursor(data); break; -- cgit v1.2.3 From a2048773ee194168594c52c4ea6472b211ef0d5e Mon Sep 17 00:00:00 2001 From: Thialfihar Date: Sun, 23 Mar 2014 19:37:41 +0100 Subject: Fix file decryption interface Actually use mAssumeSymmetricEncryption and set it to false as default. Don't close the file input stream, so we can actually look for PGP encrypted data in the next step. --- .../org/sufficientlysecure/keychain/ui/DecryptActivity.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index 3e389c034..ed9735d8c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -443,8 +443,7 @@ public class DecryptActivity extends DrawerActivity { getDecryptionKeyFromInputStream(); // if we need a symmetric passphrase or a passphrase to use a secret key ask for it - if (mSecretKeyId == Id.key.symmetric - || PassphraseCacheService.getCachedPassphrase(this, mSecretKeyId) == null) { + if (mAssumeSymmetricEncryption || PassphraseCacheService.getCachedPassphrase(this, mSecretKeyId) == null) { showPassphraseDialog(); } else { if (mDecryptTarget == Id.target.file) { @@ -494,6 +493,7 @@ public class DecryptActivity extends DrawerActivity { * TODO: Rework function, remove global variables */ private void getDecryptionKeyFromInputStream() { + mAssumeSymmetricEncryption = false; InputStream inStream = null; if (mContentUri != null) { try { @@ -517,13 +517,6 @@ public class DecryptActivity extends DrawerActivity { Log.e(Constants.TAG, "File not found!", e); AppMsg.makeText(this, getString(R.string.error_file_not_found, e.getMessage()), AppMsg.STYLE_ALERT).show(); - } finally { - try { - if (inStream != null) { - inStream.close(); - } - } catch (Exception e) { - } } } else { inStream = new ByteArrayInputStream(mMessage.getText().toString().getBytes()); @@ -540,7 +533,6 @@ public class DecryptActivity extends DrawerActivity { if (mSecretKeyId == Id.key.none) { throw new PgpGeneralException(getString(R.string.error_no_secret_key_found)); } - mAssumeSymmetricEncryption = false; } catch (NoAsymmetricEncryptionException e) { if (inStream.markSupported()) { inStream.reset(); @@ -553,6 +545,7 @@ public class DecryptActivity extends DrawerActivity { mAssumeSymmetricEncryption = true; } } catch (Exception e) { + Log.e(Constants.TAG, "error while reading decryption key from input stream", e); AppMsg.makeText(this, getString(R.string.error_message, e.getMessage()), AppMsg.STYLE_ALERT).show(); } -- cgit v1.2.3 From c9053b97a880ffcc7e7f8a58b9150fa546f87db0 Mon Sep 17 00:00:00 2001 From: Thialfihar Date: Sun, 23 Mar 2014 21:56:18 +0100 Subject: Rename old mentionings of APG-named things Mostly in comments, most importantly: STORE_PATH now ends in /KeychainBlobs instead of /ApgBlobs --- .../java/org/sufficientlysecure/keychain/helper/ExportHelper.java | 4 ++-- .../keychain/provider/KeychainServiceBlobProvider.java | 2 +- .../keychain/service/KeychainIntentService.java | 2 +- .../org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java | 8 ++++---- .../java/org/sufficientlysecure/keychain/ui/DecryptActivity.java | 4 ++-- .../java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java | 8 ++++---- .../java/org/sufficientlysecure/keychain/ui/EncryptActivity.java | 4 ++-- .../org/sufficientlysecure/keychain/ui/ImportKeysActivity.java | 2 +- .../org/sufficientlysecure/keychain/ui/UploadKeyActivity.java | 4 ++-- .../keychain/ui/dialog/DeleteFileDialogFragment.java | 4 ++-- .../org/sufficientlysecure/keychain/ui/widget/SectionView.java | 4 ++-- 11 files changed, 23 insertions(+), 23 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java index 2bfa796c7..cc240a67b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java @@ -139,7 +139,7 @@ public class ExportHelper { intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after exporting is done in ApgService + // Message is received after exporting is done in KeychainIntentService KeychainIntentServiceHandler exportHandler = new KeychainIntentServiceHandler(mActivity, mActivity.getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL, @@ -151,7 +151,7 @@ public class ExportHelper { } }) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java index 6ac61e157..aa30e845d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainServiceBlobProvider.java @@ -38,7 +38,7 @@ import java.util.List; import java.util.UUID; public class KeychainServiceBlobProvider extends ContentProvider { - private static final String STORE_PATH = Constants.Path.APP_DIR + "/ApgBlobs"; + private static final String STORE_PATH = Constants.Path.APP_DIR + "/KeychainBlobs"; private KeychainServiceBlobDatabase mBlobDatabase = null; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index e26ee3c76..bd3a0421b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -855,7 +855,7 @@ public class KeychainIntentService extends IntentService if (this.mIsCanceled) { return; } - Log.e(Constants.TAG, "ApgService Exception: ", e); + Log.e(Constants.TAG, "KeychainIntentService Exception: ", e); e.printStackTrace(); Bundle data = new Bundle(); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java index dff4e9d72..5dc06c16d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/CertifyKeyActivity.java @@ -327,11 +327,11 @@ public class CertifyKeyActivity extends ActionBarActivity implements intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after signing is done in ApgService + // Message is received after signing is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, getString(R.string.progress_signing), ProgressDialog.STYLE_SPINNER) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { @@ -380,11 +380,11 @@ public class CertifyKeyActivity extends ActionBarActivity implements intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after uploading is done in ApgService + // Message is received after uploading is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java index ed9735d8c..9b3b00c19 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java @@ -631,11 +631,11 @@ public class DecryptActivity extends DrawerActivity { intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after encrypting is done in ApgService + // Message is received after encrypting is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, getString(R.string.progress_decrypting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index 092a502e1..6eb5b9d2d 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -180,7 +180,7 @@ public class EditKeyActivity extends ActionBarActivity { serviceIntent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after generating is done in ApgService + // Message is received after generating is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler( this, getResources().getQuantityString(R.plurals.progress_generating, 1), ProgressDialog.STYLE_HORIZONTAL, true, @@ -197,7 +197,7 @@ public class EditKeyActivity extends ActionBarActivity { @Override public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { @@ -540,11 +540,11 @@ public class EditKeyActivity extends ActionBarActivity { intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after saving is done in ApgService + // Message is received after saving is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, getString(R.string.progress_saving), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java index 4ccfd393f..4f18f69d7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java @@ -597,11 +597,11 @@ public class EncryptActivity extends DrawerActivity { intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after encrypting is done in ApgService + // Message is received after encrypting is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, getString(R.string.progress_encrypting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index 05bfc613e..834509f53 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -363,7 +363,7 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa * Import keys with mImportData */ public void importKeys() { - // Message is received after importing is done in ApgService + // Message is received after importing is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler( this, getString(R.string.progress_importing), diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java index 2c8f66488..0e231e6a8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/UploadKeyActivity.java @@ -98,11 +98,11 @@ public class UploadKeyActivity extends ActionBarActivity { intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - // Message is received after uploading is done in ApgService + // Message is received after uploading is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, getString(R.string.progress_exporting), ProgressDialog.STYLE_HORIZONTAL) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java index b067010df..b4c38184c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java @@ -87,11 +87,11 @@ public class DeleteFileDialogFragment extends DialogFragment { false, null); - // Message is received after deleting is done in ApgService + // Message is received after deleting is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(activity, deletingDialog) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java index e5b6003b1..1ef178f15 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/SectionView.java @@ -256,11 +256,11 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor } }); - // Message is received after generating is done in ApgService + // Message is received after generating is done in KeychainIntentService KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(mActivity, mGeneratingDialog) { public void handleMessage(Message message) { - // handle messages by standard ApgHandler first + // handle messages by standard KeychainIntentServiceHandler first super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { -- cgit v1.2.3 From 4e481512c31c60177d3c1b404c97fa8d7a004124 Mon Sep 17 00:00:00 2001 From: Alexander Sulfrian Date: Tue, 25 Mar 2014 05:26:35 +0100 Subject: Display expiry of subkeys in single key view. --- .../keychain/ui/adapter/ViewKeyKeysAdapter.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index 068d6e6e9..d925480e9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -22,6 +22,7 @@ import android.content.res.ColorStateList; import android.database.Cursor; import android.graphics.Color; import android.support.v4.widget.CursorAdapter; +import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -31,6 +32,8 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; +import java.util.Date; + public class ViewKeyKeysAdapter extends CursorAdapter { private LayoutInflater mInflater; @@ -42,6 +45,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { private int mIndexCanEncrypt; private int mIndexCanSign; private int mIndexRevokedKey; + private int mIndexExpiry; private ColorStateList mDefaultTextColor; @@ -76,6 +80,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { mIndexCanEncrypt = cursor.getColumnIndexOrThrow(Keys.CAN_ENCRYPT); mIndexCanSign = cursor.getColumnIndexOrThrow(Keys.CAN_SIGN); mIndexRevokedKey = cursor.getColumnIndexOrThrow(Keys.IS_REVOKED); + mIndexExpiry = cursor.getColumnIndexOrThrow(Keys.EXPIRY); } } @@ -83,6 +88,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter { public void bindView(View view, Context context, Cursor cursor) { TextView keyId = (TextView) view.findViewById(R.id.keyId); TextView keyDetails = (TextView) view.findViewById(R.id.keyDetails); + TextView keyExpiry = (TextView) view.findViewById(R.id.keyExpiry); ImageView masterKeyIcon = (ImageView) view.findViewById(R.id.ic_masterKey); ImageView certifyIcon = (ImageView) view.findViewById(R.id.ic_certifyKey); ImageView encryptIcon = (ImageView) view.findViewById(R.id.ic_encryptKey); @@ -129,6 +135,22 @@ public class ViewKeyKeysAdapter extends CursorAdapter { keyDetails.setTextColor(mDefaultTextColor); revokedKeyIcon.setVisibility(View.GONE); } + + boolean valid = true; + if (!cursor.isNull(mIndexExpiry)) { + Date expiryDate = new Date(cursor.getLong(mIndexExpiry) * 1000); + valid = expiryDate.after(new Date()); + keyExpiry.setText("(" + + context.getString(R.string.label_expiry) + ": " + + DateFormat.getDateFormat(context).format(expiryDate) + ")"); + keyExpiry.setVisibility(View.VISIBLE); + } + else { + keyExpiry.setVisibility(View.GONE); + } + keyId.setEnabled(valid); + keyDetails.setEnabled(valid); + keyExpiry.setEnabled(valid); } @Override -- cgit v1.2.3 From aa35b1f4b5a5198482c9c5a659d357b3ac9a101b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 25 Mar 2014 19:11:20 +0100 Subject: More experimental work on API accounts --- .../org/sufficientlysecure/keychain/Constants.java | 4 +- .../keychain/provider/KeychainContract.java | 61 +++---- .../keychain/provider/KeychainDatabase.java | 3 +- .../keychain/provider/KeychainProvider.java | 108 ++++------- .../keychain/provider/ProviderHelper.java | 99 ++++++---- .../keychain/remote/AccountSettings.java | 85 +++++++++ .../keychain/remote/AppSettings.java | 40 ---- .../keychain/remote/OpenPgpService.java | 48 ++--- .../keychain/remote/RemoteService.java | 8 +- .../remote/ui/AccountSettingsFragment.java | 203 +++++++++++++++++++++ .../keychain/remote/ui/AccountsListFragment.java | 174 ++++++++++++++++++ .../keychain/remote/ui/AppSettingsFragment.java | 87 +-------- .../keychain/remote/ui/AppsListActivity.java | 35 ++++ .../keychain/remote/ui/AppsListFragment.java | 152 +++++++++++++++ .../keychain/remote/ui/RegisteredAppsAdapter.java | 75 -------- .../remote/ui/RegisteredAppsListActivity.java | 35 ---- .../remote/ui/RegisteredAppsListFragment.java | 101 ---------- .../keychain/remote/ui/RemoteServiceActivity.java | 84 +++++++-- 18 files changed, 877 insertions(+), 525 deletions(-) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListActivity.java create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java delete mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java index ff4abe56a..f9a7962ec 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/Constants.java @@ -19,7 +19,7 @@ package org.sufficientlysecure.keychain; import android.os.Environment; import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.sufficientlysecure.keychain.service.remote.RegisteredAppsListActivity; +import org.sufficientlysecure.keychain.remote.ui.AppsListActivity; import org.sufficientlysecure.keychain.ui.DecryptActivity; import org.sufficientlysecure.keychain.ui.EncryptActivity; import org.sufficientlysecure.keychain.ui.ImportKeysActivity; @@ -73,7 +73,7 @@ public final class Constants { public static final Class ENCRYPT = EncryptActivity.class; public static final Class DECRYPT = DecryptActivity.class; public static final Class IMPORT_KEYS = ImportKeysActivity.class; - public static final Class REGISTERED_APPS_LIST = RegisteredAppsListActivity.class; + public static final Class REGISTERED_APPS_LIST = AppsListActivity.class; public static final Class[] ARRAY = new Class[]{KEY_LIST, ENCRYPT, DECRYPT, IMPORT_KEYS, REGISTERED_APPS_LIST}; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index aa4c1f131..6e7b76fbe 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -19,6 +19,7 @@ package org.sufficientlysecure.keychain.provider; import android.net.Uri; import android.provider.BaseColumns; + import org.sufficientlysecure.keychain.Constants; public class KeychainContract { @@ -59,6 +60,7 @@ public class KeychainContract { } interface ApiAppsAccountsColumns { + String ACCOUNT_NAME = "account_name"; String KEY_ID = "key_id"; // not a database id String ENCRYPTION_ALGORITHM = "encryption_algorithm"; String HASH_ALORITHM = "hash_algorithm"; @@ -90,8 +92,7 @@ public class KeychainContract { public static final String PATH_USER_IDS = "user_ids"; public static final String PATH_KEYS = "keys"; - public static final String BASE_API = "api"; - public static final String PATH_APPS = "apps"; + public static final String BASE_API_APPS = "api_apps"; public static final String PATH_ACCOUNTS = "accounts"; public static final String PATH_BY_PACKAGE_NAME = "package_name"; @@ -257,36 +258,9 @@ public class KeychainContract { } } - /** - * Join over ApiApps with ApiAppsAccounts - */ - public static class Api implements ApiAppsColumns, ApiAppsAccountsColumns, BaseColumns { - public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() - .appendPath(BASE_API).build(); - - /** - * Use if multiple items get returned - */ - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.apis"; - - /** - * Use if a single item is returned - */ - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api"; - - public static Uri buildIdUri(String rowId) { - return CONTENT_URI.buildUpon().appendPath(rowId).build(); - } - - public static Uri buildByPackageNameUri(String packageName) { - return CONTENT_URI.buildUpon().appendPath(PATH_BY_PACKAGE_NAME).appendPath(packageName) - .build(); - } - } - public static class ApiApps implements ApiAppsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() - .appendPath(BASE_API).appendPath(PATH_APPS).build(); + .appendPath(BASE_API_APPS).build(); /** * Use if multiple items get returned @@ -303,14 +277,14 @@ public class KeychainContract { } public static Uri buildByPackageNameUri(String packageName) { - return CONTENT_URI.buildUpon().appendPath(PATH_BY_PACKAGE_NAME).appendPath(packageName) - .build(); + return CONTENT_URI.buildUpon().appendPath(PATH_BY_PACKAGE_NAME) + .appendEncodedPath(packageName).build(); } } public static class ApiAccounts implements ApiAppsAccountsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() - .appendPath(BASE_API).appendPath(PATH_ACCOUNTS).build(); + .appendPath(BASE_API_APPS).build(); /** * Use if multiple items get returned @@ -322,13 +296,24 @@ public class KeychainContract { */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api.account"; - public static Uri buildIdUri(String rowId) { - return CONTENT_URI.buildUpon().appendPath(rowId).build(); +// public static Uri buildUri(String rowIdApp) { +// return CONTENT_URI.buildUpon().appendPath(rowIdApp).appendPath(PATH_ACCOUNTS) +// .build(); +// } +// +// public static Uri buildIdUri(String rowIdApp, String rowId) { +// return CONTENT_URI.buildUpon().appendPath(rowIdApp).appendPath(PATH_ACCOUNTS) +// .appendPath(rowId).build(); +// } + + public static Uri buildBaseUri(String packageName) { + return CONTENT_URI.buildUpon().appendEncodedPath(packageName).appendPath(PATH_ACCOUNTS) + .build(); } - public static Uri buildByPackageNameUri(String packageName) { - return CONTENT_URI.buildUpon().appendPath(PATH_BY_PACKAGE_NAME).appendPath(packageName) - .build(); + public static Uri buildByPackageAndAccountUri(String packageName, String accountName) { + return CONTENT_URI.buildUpon().appendEncodedPath(packageName).appendPath(PATH_ACCOUNTS) + .appendEncodedPath(accountName).build(); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java index e56fa2f8f..ca1a47f0c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java @@ -82,10 +82,11 @@ public class KeychainDatabase extends SQLiteOpenHelper { private static final String CREATE_API_APPS_ACCOUNTS = "CREATE TABLE IF NOT EXISTS " + Tables.API_ACCOUNTS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + ApiAppsAccountsColumns.ACCOUNT_NAME + " TEXT UNIQUE, " + ApiAppsAccountsColumns.KEY_ID + " INT64, " + ApiAppsAccountsColumns.ENCRYPTION_ALGORITHM + " INTEGER, " + ApiAppsAccountsColumns.HASH_ALORITHM + " INTEGER, " - + ApiAppsAccountsColumns.COMPRESSION + " INTEGER" + + ApiAppsAccountsColumns.COMPRESSION + " INTEGER, " + ApiAppsAccountsColumns.PACKAGE_NAME_FK + " TEXT NOT NULL, FOREIGN KEY(" + ApiAppsAccountsColumns.PACKAGE_NAME_FK + ") REFERENCES " + Tables.API_APPS + "(" + ApiAppsColumns.PACKAGE_NAME + ") ON DELETE CASCADE)"; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index a094b13de..cae76003c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -30,10 +30,8 @@ import android.provider.BaseColumns; import android.text.TextUtils; import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.provider.KeychainContract.Api; import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAccounts; import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsAccountsColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingsColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyTypes; @@ -81,15 +79,12 @@ public class KeychainProvider extends ContentProvider { private static final int SECRET_KEY_RING_USER_ID = 221; private static final int SECRET_KEY_RING_USER_ID_BY_ROW_ID = 222; - private static final int API = 301; - private static final int API_BY_ROW_ID = 302; - private static final int API_BY_PACKAGE_NAME = 303; - private static final int API_APPS = 304; - private static final int API_APPS_BY_ROW_ID = 305; - private static final int API_APPS_BY_PACKAGE_NAME = 306; - private static final int API_ACCOUNTS = 307; - private static final int API_ACCOUNTS_BY_ROW_ID = 308; - private static final int API_ACCOUNTS_BY_PACKAGE_NAME = 309; + private static final int API_APPS = 301; + private static final int API_APPS_BY_ROW_ID = 302; + private static final int API_APPS_BY_PACKAGE_NAME = 303; + private static final int API_ACCOUNTS = 304; + private static final int API_ACCOUNTS_BY_ROW_ID = 305; + private static final int API_ACCOUNTS_BY_ACCOUNT_NAME = 306; private static final int UNIFIED_KEY_RING = 401; @@ -247,26 +242,18 @@ public class KeychainProvider extends ContentProvider { /** * API apps */ - matcher.addURI(authority, KeychainContract.BASE_API, API); - matcher.addURI(authority, KeychainContract.BASE_API + "/#", API_BY_ROW_ID); - matcher.addURI(authority, KeychainContract.BASE_API + "/" - + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_BY_PACKAGE_NAME); - - matcher.addURI(authority, KeychainContract.BASE_API + "/" - + KeychainContract.PATH_APPS, API_APPS); - matcher.addURI(authority, KeychainContract.BASE_API + "/" - + KeychainContract.PATH_APPS + "/#", API_APPS_BY_ROW_ID); - matcher.addURI(authority, KeychainContract.BASE_API + "/" - + KeychainContract.PATH_APPS + "/" + matcher.addURI(authority, KeychainContract.BASE_API_APPS, API_APPS); + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/#", API_APPS_BY_ROW_ID); + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_APPS_BY_PACKAGE_NAME); - matcher.addURI(authority, KeychainContract.BASE_API + "/" + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + KeychainContract.PATH_ACCOUNTS, API_ACCOUNTS); - matcher.addURI(authority, KeychainContract.BASE_API + "/" + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + KeychainContract.PATH_ACCOUNTS + "/#", API_ACCOUNTS_BY_ROW_ID); - matcher.addURI(authority, KeychainContract.BASE_API + "/" + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + KeychainContract.PATH_ACCOUNTS + "/" - + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_ACCOUNTS_BY_PACKAGE_NAME); + + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_ACCOUNTS_BY_ACCOUNT_NAME); /** * data stream @@ -332,13 +319,6 @@ public class KeychainProvider extends ContentProvider { case SECRET_KEY_RING_USER_ID_BY_ROW_ID: return UserIds.CONTENT_ITEM_TYPE; - case API: - return Api.CONTENT_TYPE; - - case API_BY_ROW_ID: - case API_BY_PACKAGE_NAME: - return Api.CONTENT_ITEM_TYPE; - case API_APPS: return ApiApps.CONTENT_TYPE; @@ -350,7 +330,7 @@ public class KeychainProvider extends ContentProvider { return ApiAccounts.CONTENT_TYPE; case API_ACCOUNTS_BY_ROW_ID: - case API_ACCOUNTS_BY_PACKAGE_NAME: + case API_ACCOUNTS_BY_ACCOUNT_NAME: return ApiAccounts.CONTENT_ITEM_TYPE; default: @@ -695,28 +675,6 @@ public class KeychainProvider extends ContentProvider { qb.appendWhere(" AND " + BaseColumns._ID + " = "); qb.appendWhereEscapeString(uri.getLastPathSegment()); - break; - case API: - qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" - + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." - + ApiAccounts.PACKAGE_NAME_FK + " )"); - - break; - case API_BY_ROW_ID: - qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" - + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." - + ApiAccounts.PACKAGE_NAME_FK + " )"); - qb.appendWhere(Tables.API_APPS + "." + BaseColumns._ID + " = "); - qb.appendWhereEscapeString(uri.getLastPathSegment()); - - break; - case API_BY_PACKAGE_NAME: - qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" - + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." - + ApiAccounts.PACKAGE_NAME_FK + " )"); - qb.appendWhere(Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = "); - qb.appendWhereEscapeString(uri.getLastPathSegment()); - break; case API_APPS: qb.setTables(Tables.API_APPS); @@ -740,15 +698,24 @@ public class KeychainProvider extends ContentProvider { break; case API_ACCOUNTS_BY_ROW_ID: - qb.setTables(Tables.API_ACCOUNTS); + qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" + + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." + + ApiAccounts.PACKAGE_NAME_FK + " )"); + qb.appendWhere(Tables.API_APPS + "." + BaseColumns._ID + " = "); + qb.appendWhereEscapeString(uri.getPathSegments().get(2)); - qb.appendWhere(BaseColumns._ID + " = "); + qb.appendWhere(" AND " + Tables.API_ACCOUNTS + "." + BaseColumns._ID + " = "); qb.appendWhereEscapeString(uri.getLastPathSegment()); break; - case API_ACCOUNTS_BY_PACKAGE_NAME: - qb.setTables(Tables.API_ACCOUNTS); - qb.appendWhere(ApiAppsAccountsColumns.PACKAGE_NAME_FK + " = "); + case API_ACCOUNTS_BY_ACCOUNT_NAME: + qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" + + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." + + ApiAccounts.PACKAGE_NAME_FK + " )"); + qb.appendWhere(Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = "); + qb.appendWhereEscapeString(uri.getPathSegments().get(2)); + + qb.appendWhere(" AND " + Tables.API_ACCOUNTS + "." + ApiAccounts.ACCOUNT_NAME + " = "); qb.appendWhereEscapeString(uri.getLastPathSegment()); break; @@ -808,13 +775,15 @@ public class KeychainProvider extends ContentProvider { values.put(Keys.TYPE, KeyTypes.PUBLIC); rowId = db.insertOrThrow(Tables.KEYS, null, values); - rowUri = Keys.buildPublicKeysUri(Long.toString(rowId)); + // TODO: this is wrong: +// rowUri = Keys.buildPublicKeysUri(Long.toString(rowId)); sendBroadcastDatabaseChange(getKeyType(match), getType(uri)); break; case PUBLIC_KEY_RING_USER_ID: rowId = db.insertOrThrow(Tables.USER_IDS, null, values); - rowUri = UserIds.buildPublicUserIdsUri(Long.toString(rowId)); + // TODO: this is wrong: +// rowUri = UserIds.buildPublicUserIdsUri(Long.toString(rowId)); sendBroadcastDatabaseChange(getKeyType(match), getType(uri)); break; @@ -830,13 +799,15 @@ public class KeychainProvider extends ContentProvider { values.put(Keys.TYPE, KeyTypes.SECRET); rowId = db.insertOrThrow(Tables.KEYS, null, values); - rowUri = Keys.buildSecretKeysUri(Long.toString(rowId)); + // TODO: this is wrong: +// rowUri = Keys.buildSecretKeysUri(Long.toString(rowId)); sendBroadcastDatabaseChange(getKeyType(match), getType(uri)); break; case SECRET_KEY_RING_USER_ID: rowId = db.insertOrThrow(Tables.USER_IDS, null, values); - rowUri = UserIds.buildSecretUserIdsUri(Long.toString(rowId)); + // TODO: this is wrong: +// rowUri = UserIds.buildSecretUserIdsUri(Long.toString(rowId)); break; case API_APPS: @@ -846,7 +817,8 @@ public class KeychainProvider extends ContentProvider { break; case API_ACCOUNTS: rowId = db.insertOrThrow(Tables.API_ACCOUNTS, null, values); - rowUri = ApiAccounts.buildIdUri(Long.toString(rowId)); + // TODO: this is wrong: +// rowUri = ApiAccounts.buildIdUri(Long.toString(rowId)); break; default: @@ -918,7 +890,7 @@ public class KeychainProvider extends ContentProvider { count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, false, selection), selectionArgs); break; - case API_ACCOUNTS_BY_PACKAGE_NAME: + case API_ACCOUNTS_BY_ACCOUNT_NAME: count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, true, selection), selectionArgs); break; @@ -996,7 +968,7 @@ public class KeychainProvider extends ContentProvider { count = db.update(Tables.API_ACCOUNTS, values, buildDefaultApiAccountsSelection(uri, false, selection), selectionArgs); break; - case API_ACCOUNTS_BY_PACKAGE_NAME: + case API_ACCOUNTS_BY_ACCOUNT_NAME: count = db.update(Tables.API_ACCOUNTS, values, buildDefaultApiAccountsSelection(uri, true, selection), selectionArgs); break; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 7e8bfbc7b..e3727b2f8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -22,6 +22,7 @@ import android.database.Cursor; import android.database.DatabaseUtils; import android.net.Uri; import android.os.RemoteException; + import org.spongycastle.bcpg.ArmoredOutputStream; import org.spongycastle.openpgp.*; import org.sufficientlysecure.keychain.Constants; @@ -33,6 +34,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; +import org.sufficientlysecure.keychain.remote.AccountSettings; import org.sufficientlysecure.keychain.remote.AppSettings; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; @@ -469,11 +471,11 @@ public class ProviderHelper { cr.delete(KeyRings.buildSecretKeyRingsUri(Long.toString(rowId)), null, null); } - public static void deleteUnifiedKeyRing(Context context,String masterKeyId,boolean isSecretKey){ - ContentResolver cr= context.getContentResolver(); - cr.delete(KeyRings.buildPublicKeyRingsByMasterKeyIdUri(masterKeyId),null,null); - if(isSecretKey){ - cr.delete(KeyRings.buildSecretKeyRingsByMasterKeyIdUri(masterKeyId),null,null); + public static void deleteUnifiedKeyRing(Context context, String masterKeyId, boolean isSecretKey) { + ContentResolver cr = context.getContentResolver(); + cr.delete(KeyRings.buildPublicKeyRingsByMasterKeyIdUri(masterKeyId), null, null); + if (isSecretKey) { + cr.delete(KeyRings.buildSecretKeyRingsByMasterKeyIdUri(masterKeyId), null, null); } } @@ -504,7 +506,7 @@ public class ProviderHelper { + " AS sign_keys WHERE sign_keys." + Keys.KEY_RING_ROW_ID + " = " + KeychainDatabase.Tables.KEY_RINGS + "." + KeyRings._ID + " AND sign_keys." + Keys.CAN_SIGN + " = '1' AND " + Keys.IS_MASTER_KEY - + " = 1) AS sign", }; + + " = 1) AS sign",}; ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(queryUri, projection, null, null, null); @@ -801,70 +803,93 @@ public class ProviderHelper { ContentValues values = new ContentValues(); values.put(ApiApps.PACKAGE_NAME, appSettings.getPackageName()); values.put(ApiApps.PACKAGE_SIGNATURE, appSettings.getPackageSignature()); -// values.put(ApiApps.KEY_ID, appSettings.getKeyId()); -// values.put(ApiApps.COMPRESSION, appSettings.getCompression()); -// values.put(ApiApps.ENCRYPTION_ALGORITHM, appSettings.getEncryptionAlgorithm()); -// values.put(ApiApps.HASH_ALORITHM, appSettings.getHashAlgorithm()); - return values; } - private static ContentValues contentValueForApiAccounts(AppSettings appSettings) { + private static ContentValues contentValueForApiAccounts(AccountSettings accSettings) { ContentValues values = new ContentValues(); - values.put(KeychainContract.ApiAccounts.PACKAGE_NAME_FK, appSettings.getPackageName()); - values.put(KeychainContract.ApiAccounts.KEY_ID, appSettings.getKeyId()); - values.put(KeychainContract.ApiAccounts.COMPRESSION, appSettings.getCompression()); - values.put(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM, appSettings.getEncryptionAlgorithm()); - values.put(KeychainContract.ApiAccounts.HASH_ALORITHM, appSettings.getHashAlgorithm()); - + values.put(KeychainContract.ApiAccounts.ACCOUNT_NAME, accSettings.getAccountName()); + values.put(KeychainContract.ApiAccounts.KEY_ID, accSettings.getKeyId()); + values.put(KeychainContract.ApiAccounts.COMPRESSION, accSettings.getCompression()); + values.put(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM, accSettings.getEncryptionAlgorithm()); + values.put(KeychainContract.ApiAccounts.HASH_ALORITHM, accSettings.getHashAlgorithm()); +// values.put(KeychainContract.ApiAccounts.PACKAGE_NAME_FK, accSettings.getPackageName()); return values; } - public static void insertApi(Context context, AppSettings appSettings) { + public static void insertApiApp(Context context, AppSettings appSettings) { context.getContentResolver().insert(KeychainContract.ApiApps.CONTENT_URI, contentValueForApiApps(appSettings)); - context.getContentResolver().insert(KeychainContract.ApiAccounts.CONTENT_URI, - contentValueForApiApps(appSettings)); } - // TODO: uri not working because it is used for both tables + public static void insertApiAccount(Context context, Uri uri, AccountSettings accSettings) { + context.getContentResolver().insert(uri, + contentValueForApiAccounts(accSettings)); + } + public static void updateApiApp(Context context, AppSettings appSettings, Uri uri) { if (context.getContentResolver().update(uri, contentValueForApiApps(appSettings), null, null) <= 0) { throw new RuntimeException(); } - if (context.getContentResolver().update(uri, contentValueForApiAccounts(appSettings), null, + } + + public static void updateApiAccount(Context context, AccountSettings accSettings, Uri uri) { + if (context.getContentResolver().update(uri, contentValueForApiAccounts(accSettings), null, null) <= 0) { throw new RuntimeException(); } } - public static AppSettings getApiSettings(Context context, Uri uri) { + + /** + * Must be an uri pointing to an account + * + * @param context + * @param uri + * @return + */ + public static AppSettings getApiAppSettings(Context context, Uri uri) { AppSettings settings = null; Cursor cur = context.getContentResolver().query(uri, null, null, null, null); if (cur != null && cur.moveToFirst()) { settings = new AppSettings(); - settings.setPackageName(cur.getString(cur - .getColumnIndex(KeychainContract.Api.PACKAGE_NAME))); - settings.setPackageSignature(cur.getBlob(cur - .getColumnIndex(KeychainContract.Api.PACKAGE_SIGNATURE))); - settings.setKeyId(cur.getLong(cur.getColumnIndex(KeychainContract.Api.KEY_ID))); - settings.setCompression(cur.getInt(cur - .getColumnIndexOrThrow(KeychainContract.Api.COMPRESSION))); - settings.setHashAlgorithm(cur.getInt(cur - .getColumnIndexOrThrow(KeychainContract.Api.HASH_ALORITHM))); - settings.setEncryptionAlgorithm(cur.getInt(cur - .getColumnIndexOrThrow(KeychainContract.Api.ENCRYPTION_ALGORITHM))); + settings.setPackageName(cur.getString( + cur.getColumnIndex(KeychainContract.ApiApps.PACKAGE_NAME))); + settings.setPackageSignature(cur.getBlob( + cur.getColumnIndex(KeychainContract.ApiApps.PACKAGE_SIGNATURE))); + } + + return settings; + } + + public static AccountSettings getApiAccountSettings(Context context, Uri uri) { + AccountSettings settings = null; + + Cursor cur = context.getContentResolver().query(uri, null, null, null, null); + if (cur != null && cur.moveToFirst()) { + settings = new AccountSettings(); + + settings.setAccountName(cur.getString( + cur.getColumnIndex(KeychainContract.ApiAccounts.ACCOUNT_NAME))); + settings.setKeyId(cur.getLong( + cur.getColumnIndex(KeychainContract.ApiAccounts.KEY_ID))); + settings.setCompression(cur.getInt( + cur.getColumnIndexOrThrow(KeychainContract.ApiAccounts.COMPRESSION))); + settings.setHashAlgorithm(cur.getInt( + cur.getColumnIndexOrThrow(KeychainContract.ApiAccounts.HASH_ALORITHM))); + settings.setEncryptionAlgorithm(cur.getInt( + cur.getColumnIndexOrThrow(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM))); } return settings; } public static byte[] getApiSignature(Context context, String packageName) { - Uri queryUri = KeychainContract.Api.buildByPackageNameUri(packageName); + Uri queryUri = ApiApps.buildByPackageNameUri(packageName); - String[] projection = new String[]{KeychainContract.Api.PACKAGE_SIGNATURE}; + String[] projection = new String[]{ApiApps.PACKAGE_SIGNATURE}; ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(queryUri, projection, null, null, null); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java new file mode 100644 index 000000000..832cbc752 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote; + +import org.spongycastle.bcpg.HashAlgorithmTags; +import org.spongycastle.openpgp.PGPEncryptedData; +import org.sufficientlysecure.keychain.Id; + +public class AccountSettings { + private String mAccountName; + private long mKeyId = Id.key.none; + private int mEncryptionAlgorithm; + private int mHashAlgorithm; + private int mCompression; + + public AccountSettings() { + + } + + public AccountSettings(String accountName) { + super(); + this.mAccountName = accountName; + + // defaults: + this.mEncryptionAlgorithm = PGPEncryptedData.AES_256; + this.mHashAlgorithm = HashAlgorithmTags.SHA512; + this.mCompression = Id.choice.compression.zlib; + } + + public String getAccountName() { + return mAccountName; + } + + public void setAccountName(String mAccountName) { + this.mAccountName = mAccountName; + } + + public long getKeyId() { + return mKeyId; + } + + public void setKeyId(long scretKeyId) { + this.mKeyId = scretKeyId; + } + + public int getEncryptionAlgorithm() { + return mEncryptionAlgorithm; + } + + public void setEncryptionAlgorithm(int encryptionAlgorithm) { + this.mEncryptionAlgorithm = encryptionAlgorithm; + } + + public int getHashAlgorithm() { + return mHashAlgorithm; + } + + public void setHashAlgorithm(int hashAlgorithm) { + this.mHashAlgorithm = hashAlgorithm; + } + + public int getCompression() { + return mCompression; + } + + public void setCompression(int compression) { + this.mCompression = compression; + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java index ad48a402b..6c7e51bf0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/AppSettings.java @@ -24,10 +24,6 @@ import org.sufficientlysecure.keychain.Id; public class AppSettings { private String mPackageName; private byte[] mPackageSignature; - private long mKeyId = Id.key.none; - private int mEncryptionAlgorithm; - private int mHashAlgorithm; - private int mCompression; public AppSettings() { @@ -37,10 +33,6 @@ public class AppSettings { super(); this.mPackageName = packageName; this.mPackageSignature = packageSignature; - // defaults: - this.mEncryptionAlgorithm = PGPEncryptedData.AES_256; - this.mHashAlgorithm = HashAlgorithmTags.SHA512; - this.mCompression = Id.choice.compression.zlib; } public String getPackageName() { @@ -59,36 +51,4 @@ public class AppSettings { this.mPackageSignature = packageSignature; } - public long getKeyId() { - return mKeyId; - } - - public void setKeyId(long scretKeyId) { - this.mKeyId = scretKeyId; - } - - public int getEncryptionAlgorithm() { - return mEncryptionAlgorithm; - } - - public void setEncryptionAlgorithm(int encryptionAlgorithm) { - this.mEncryptionAlgorithm = encryptionAlgorithm; - } - - public int getHashAlgorithm() { - return mHashAlgorithm; - } - - public void setHashAlgorithm(int hashAlgorithm) { - this.mHashAlgorithm = hashAlgorithm; - } - - public int getCompression() { - return mCompression; - } - - public void setCompression(int compression) { - this.mCompression = compression; - } - } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java index 9b56a491a..b04e76cbd 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java @@ -138,7 +138,7 @@ public class OpenPgpService extends RemoteService { } private Intent signImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AppSettings appSettings) { + ParcelFileDescriptor output, AccountSettings accSettings) { try { boolean asciiArmor = data.getBooleanExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); @@ -147,11 +147,11 @@ public class OpenPgpService extends RemoteService { if (data.hasExtra(OpenPgpApi.EXTRA_PASSPHRASE)) { passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); } else { - passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), appSettings.getKeyId()); + passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), accSettings.getKeyId()); } if (passphrase == null) { // get PendingIntent for passphrase input, add it to given params and return to client - Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); + Intent passphraseBundle = getPassphraseBundleIntent(data, accSettings.getKeyId()); return passphraseBundle; } @@ -165,9 +165,9 @@ public class OpenPgpService extends RemoteService { // sign-only PgpSignEncrypt.Builder builder = new PgpSignEncrypt.Builder(getContext(), inputData, os); builder.enableAsciiArmorOutput(asciiArmor) - .signatureHashAlgorithm(appSettings.getHashAlgorithm()) + .signatureHashAlgorithm(accSettings.getHashAlgorithm()) .signatureForceV3(false) - .signatureKeyId(appSettings.getKeyId()) + .signatureKeyId(accSettings.getKeyId()) .signaturePassphrase(passphrase); builder.build().execute(); } finally { @@ -188,7 +188,7 @@ public class OpenPgpService extends RemoteService { } private Intent encryptAndSignImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AppSettings appSettings, boolean sign) { + ParcelFileDescriptor output, AccountSettings accSettings, boolean sign) { try { boolean asciiArmor = data.getBooleanExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); @@ -218,7 +218,7 @@ public class OpenPgpService extends RemoteService { // add own key for encryption keyIds = Arrays.copyOf(keyIds, keyIds.length + 1); - keyIds[keyIds.length - 1] = appSettings.getKeyId(); + keyIds[keyIds.length - 1] = accSettings.getKeyId(); // build InputData and write into OutputStream // Get Input- and OutputStream from ParcelFileDescriptor @@ -230,8 +230,8 @@ public class OpenPgpService extends RemoteService { PgpSignEncrypt.Builder builder = new PgpSignEncrypt.Builder(getContext(), inputData, os); builder.enableAsciiArmorOutput(asciiArmor) - .compressionId(appSettings.getCompression()) - .symmetricEncryptionAlgorithm(appSettings.getEncryptionAlgorithm()) + .compressionId(accSettings.getCompression()) + .symmetricEncryptionAlgorithm(accSettings.getEncryptionAlgorithm()) .encryptionKeyIds(keyIds); if (sign) { @@ -240,18 +240,18 @@ public class OpenPgpService extends RemoteService { passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); } else { passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), - appSettings.getKeyId()); + accSettings.getKeyId()); } if (passphrase == null) { // get PendingIntent for passphrase input, add it to given params and return to client - Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); + Intent passphraseBundle = getPassphraseBundleIntent(data, accSettings.getKeyId()); return passphraseBundle; } // sign and encrypt - builder.signatureHashAlgorithm(appSettings.getHashAlgorithm()) + builder.signatureHashAlgorithm(accSettings.getHashAlgorithm()) .signatureForceV3(false) - .signatureKeyId(appSettings.getKeyId()) + .signatureKeyId(accSettings.getKeyId()) .signaturePassphrase(passphrase); } else { // encrypt only @@ -277,7 +277,7 @@ public class OpenPgpService extends RemoteService { } private Intent decryptAndVerifyImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AppSettings appSettings) { + ParcelFileDescriptor output, AccountSettings accSettings) { try { // Get Input- and OutputStream from ParcelFileDescriptor InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input); @@ -293,7 +293,7 @@ public class OpenPgpService extends RemoteService { PgpDecryptVerify.Builder builder = new PgpDecryptVerify.Builder(this, inputData, os); builder.assumeSymmetric(false) // no support for symmetric encryption // allow only the private key for this app for decryption - .enforcedKeyId(appSettings.getKeyId()) + .enforcedKeyId(accSettings.getKeyId()) .passphrase(passphrase); // TODO: currently does not support binary signed-only content @@ -301,7 +301,7 @@ public class OpenPgpService extends RemoteService { if (decryptVerifyResult.isKeyPassphraseNeeded()) { // get PendingIntent for passphrase input, add it to given params and return to client - Intent passphraseBundle = getPassphraseBundleIntent(data, appSettings.getKeyId()); + Intent passphraseBundle = getPassphraseBundleIntent(data, accSettings.getKeyId()); return passphraseBundle; } else if (decryptVerifyResult.isSymmetricPassphraseNeeded()) { throw new PgpGeneralException("Decryption of symmetric content not supported by API!"); @@ -433,17 +433,23 @@ public class OpenPgpService extends RemoteService { return errorResult; } - final AppSettings appSettings = getAppSettings(); + String accName; + if (data.getStringExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME) != null) { + accName = data.getStringExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME); + } else { + accName = "default"; + } + final AccountSettings accSettings = getAccSettings(accName); String action = data.getAction(); if (OpenPgpApi.ACTION_SIGN.equals(action)) { - return signImpl(data, input, output, appSettings); + return signImpl(data, input, output, accSettings); } else if (OpenPgpApi.ACTION_ENCRYPT.equals(action)) { - return encryptAndSignImpl(data, input, output, appSettings, false); + return encryptAndSignImpl(data, input, output, accSettings, false); } else if (OpenPgpApi.ACTION_SIGN_AND_ENCRYPT.equals(action)) { - return encryptAndSignImpl(data, input, output, appSettings, true); + return encryptAndSignImpl(data, input, output, accSettings, true); } else if (OpenPgpApi.ACTION_DECRYPT_VERIFY.equals(action)) { - return decryptAndVerifyImpl(data, input, output, appSettings); + return decryptAndVerifyImpl(data, input, output, accSettings); } else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) { return getKeyImpl(data); } else if (OpenPgpApi.ACTION_GET_KEY_IDS.equals(action)) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java index 434fe84c1..7b66a0b5c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java @@ -130,16 +130,16 @@ public abstract class RemoteService extends Service { * * @return */ - protected AppSettings getAppSettings() { + protected AccountSettings getAccSettings(String accountName) { String[] callingPackages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); // get app settings for this package for (int i = 0; i < callingPackages.length; i++) { String currentPkg = callingPackages[i]; - Uri uri = KeychainContract.ApiApps.buildByPackageNameUri(currentPkg); + Uri uri = KeychainContract.ApiAccounts.buildByPackageAndAccountUri(currentPkg, accountName); - AppSettings settings = ProviderHelper.getApiAppSettings(this, uri); + AccountSettings settings = ProviderHelper.getApiAccountSettings(this, uri); if (settings != null) { return settings; @@ -210,7 +210,7 @@ public abstract class RemoteService extends Service { throw new WrongPackageSignatureException(e.getMessage()); } - byte[] storedSig = ProviderHelper.getApiAppSignature(this, packageName); + byte[] storedSig = ProviderHelper.getApiSignature(this, packageName); if (Arrays.equals(currentSig, storedSig)) { Log.d(Constants.TAG, "Package signature is correct! (equals signature from database)"); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java new file mode 100644 index 000000000..3d88d216e --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2013-2014 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemSelectedListener; +import android.widget.ImageView; +import android.widget.Spinner; +import android.widget.TextView; + +import org.spongycastle.util.encoders.Hex; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.remote.AccountSettings; +import org.sufficientlysecure.keychain.remote.AppSettings; +import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; +import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; +import org.sufficientlysecure.keychain.util.AlgorithmNames; +import org.sufficientlysecure.keychain.util.Log; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class AccountSettingsFragment extends Fragment implements + SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { + + // model + private AccountSettings mAccSettings; + + // view + private TextView mAppNameView; + private ImageView mAppIconView; + private Spinner mEncryptionAlgorithm; + private Spinner mHashAlgorithm; + private Spinner mCompression; + private TextView mPackageName; + private TextView mPackageSignature; + + private SelectSecretKeyLayoutFragment mSelectKeyFragment; + + KeyValueSpinnerAdapter mEncryptionAdapter; + KeyValueSpinnerAdapter mHashAdapter; + KeyValueSpinnerAdapter mCompressionAdapter; + + public AccountSettings getAccSettings() { + return mAccSettings; + } + + public void setAccSettings(AccountSettings appSettings) { + this.mAccSettings = appSettings; +// setPackage(appSettings.getPackageName()); +// mPackageName.setText(appSettings.getPackageName()); + +// try { +// MessageDigest md = MessageDigest.getInstance("SHA-256"); +// md.update(appSettings.getPackageSignature()); +// byte[] digest = md.digest(); +// String signature = new String(Hex.encode(digest)); +// +// mPackageSignature.setText(signature); +// } catch (NoSuchAlgorithmException e) { +// Log.e(Constants.TAG, "Should not happen!", e); +// } + + mSelectKeyFragment.selectKey(appSettings.getKeyId()); + mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(appSettings + .getEncryptionAlgorithm())); + mHashAlgorithm.setSelection(mHashAdapter.getPosition(appSettings.getHashAlgorithm())); + mCompression.setSelection(mCompressionAdapter.getPosition(appSettings.getCompression())); + } + + /** + * Inflate the layout for this fragment + */ + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.api_account_settings_fragment, container, false); + initView(view); + return view; + } + + /** + * Set error String on key selection + * + * @param error + */ + public void setErrorOnSelectKeyFragment(String error) { + mSelectKeyFragment.setError(error); + } + + private void initView(View view) { + mSelectKeyFragment = (SelectSecretKeyLayoutFragment) getFragmentManager().findFragmentById( + R.id.api_account_settings_select_key_fragment); + mSelectKeyFragment.setCallback(this); + + mAppNameView = (TextView) view.findViewById(R.id.api_account_settings_app_name); + mAppIconView = (ImageView) view.findViewById(R.id.api_account_settings_app_icon); + mEncryptionAlgorithm = (Spinner) view + .findViewById(R.id.api_account_settings_encryption_algorithm); + mHashAlgorithm = (Spinner) view.findViewById(R.id.api_account_settings_hash_algorithm); + mCompression = (Spinner) view.findViewById(R.id.api_account_settings_compression); + mPackageName = (TextView) view.findViewById(R.id.api_account_settings_package_name); + mPackageSignature = (TextView) view.findViewById(R.id.api_account_settings_package_signature); + + AlgorithmNames algorithmNames = new AlgorithmNames(getActivity()); + + mEncryptionAdapter = new KeyValueSpinnerAdapter(getActivity(), + algorithmNames.getEncryptionNames()); + mEncryptionAlgorithm.setAdapter(mEncryptionAdapter); + mEncryptionAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + mAccSettings.setEncryptionAlgorithm((int) id); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + mHashAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getHashNames()); + mHashAlgorithm.setAdapter(mHashAdapter); + mHashAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + mAccSettings.setHashAlgorithm((int) id); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + mCompressionAdapter = new KeyValueSpinnerAdapter(getActivity(), + algorithmNames.getCompressionNames()); + mCompression.setAdapter(mCompressionAdapter); + mCompression.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + mAccSettings.setCompression((int) id); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + } +// +// private void setPackage(String packageName) { +// PackageManager pm = getActivity().getApplicationContext().getPackageManager(); +// +// // get application name and icon from package manager +// String appName = null; +// Drawable appIcon = null; +// try { +// ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); +// +// appName = (String) pm.getApplicationLabel(ai); +// appIcon = pm.getApplicationIcon(ai); +// } catch (final NameNotFoundException e) { +// // fallback +// appName = packageName; +// } +// mAppNameView.setText(appName); +// mAppIconView.setImageDrawable(appIcon); +// } + + /** + * callback from select secret key fragment + */ + @Override + public void onKeySelected(long secretKeyId) { + mAccSettings.setKeyId(secretKeyId); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java new file mode 100644 index 000000000..0cec319a5 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.annotation.TargetApi; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.support.v4.app.ListFragment; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; +import android.support.v4.widget.CursorAdapter; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.ImageView; +import android.widget.SimpleCursorAdapter; +import android.widget.TextView; + +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; + +// TODO: make compat with < 11 +@TargetApi(Build.VERSION_CODES.HONEYCOMB) +public class AccountsListFragment extends ListFragment implements + LoaderManager.LoaderCallbacks { + + // This is the Adapter being used to display the list's data. + SimpleCursorAdapter mAdapter; + + private String mPackageName; + + public String getPackageName() { + return mPackageName; + } + + public void setPackageName(String packageName) { + this.mPackageName = packageName; + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + getListView().setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int position, long id) { + // edit app settings + Intent intent = new Intent(getActivity(), AppSettingsActivity.class); + intent.setData(ContentUris.withAppendedId(ApiApps.CONTENT_URI, id)); + startActivity(intent); + } + }); + + // Give some text to display if there is no data. In a real + // application this would come from a resource. + setEmptyText(getString(R.string.api_no_apps)); + + // We have a menu item to show in action bar. + setHasOptionsMenu(true); + + // Create an empty adapter we will use to display the loaded data. + mAdapter = new SimpleCursorAdapter(getActivity(), + android.R.layout.simple_list_item_1, + null, + new String[]{KeychainContract.ApiAccounts.ACCOUNT_NAME}, + new int[]{android.R.id.text1}, + 0); + setListAdapter(mAdapter); + + // Prepare the loader. Either re-connect with an existing one, + // or start a new one. + getLoaderManager().initLoader(0, null, this); + } + + // These are the Contacts rows that we will retrieve. + static final String[] PROJECTION = new String[]{ + KeychainContract.ApiAccounts._ID, + KeychainContract.ApiAccounts.ACCOUNT_NAME}; + + public Loader onCreateLoader(int id, Bundle args) { + // This is called when a new Loader needs to be created. This + // sample only has one Loader, so we don't care about the ID. + // First, pick the base URI to use depending on whether we are + // currently filtering. + Uri baseUri = KeychainContract.ApiAccounts.buildBaseUri(mPackageName); + + // Now create and return a CursorLoader that will take care of + // creating a Cursor for the data being displayed. + return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, + KeychainContract.ApiAccounts.ACCOUNT_NAME + " COLLATE LOCALIZED ASC"); + } + + public void onLoadFinished(Loader loader, Cursor data) { + // Swap the new cursor in. (The framework will take care of closing the + // old cursor once we return.) + mAdapter.swapCursor(data); + } + + public void onLoaderReset(Loader loader) { + // This is called when the last Cursor provided to onLoadFinished() + // above is about to be closed. We need to make sure we are no + // longer using it. + mAdapter.swapCursor(null); + } + +// private class RegisteredAppsAdapter extends CursorAdapter { +// +// private LayoutInflater mInflater; +// private PackageManager mPM; +// +// public RegisteredAppsAdapter(Context context, Cursor c, int flags) { +// super(context, c, flags); +// +// mInflater = LayoutInflater.from(context); +// mPM = context.getApplicationContext().getPackageManager(); +// } +// +// @Override +// public void bindView(View view, Context context, Cursor cursor) { +// TextView text = (TextView) view.findViewById(R.id.api_apps_adapter_item_name); +// ImageView icon = (ImageView) view.findViewById(R.id.api_apps_adapter_item_icon); +// +// String packageName = cursor.getString(cursor.getColumnIndex(ApiApps.PACKAGE_NAME)); +// if (packageName != null) { +// // get application name +// try { +// ApplicationInfo ai = mPM.getApplicationInfo(packageName, 0); +// +// text.setText(mPM.getApplicationLabel(ai)); +// icon.setImageDrawable(mPM.getApplicationIcon(ai)); +// } catch (final PackageManager.NameNotFoundException e) { +// // fallback +// text.setText(packageName); +// } +// } else { +// // fallback +// text.setText(packageName); +// } +// +// } +// +// @Override +// public View newView(Context context, Cursor cursor, ViewGroup parent) { +// return mInflater.inflate(R.layout.api_apps_adapter_list_item, null); +// } +// } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java index 8e8f3827b..8bcd83fc7 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java @@ -44,8 +44,7 @@ import org.sufficientlysecure.keychain.util.Log; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -public class AppSettingsFragment extends Fragment implements - SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { +public class AppSettingsFragment extends Fragment { // model private AppSettings mAppSettings; @@ -53,18 +52,9 @@ public class AppSettingsFragment extends Fragment implements // view private TextView mAppNameView; private ImageView mAppIconView; - private Spinner mEncryptionAlgorithm; - private Spinner mHashAlgorithm; - private Spinner mCompression; private TextView mPackageName; private TextView mPackageSignature; - private SelectSecretKeyLayoutFragment mSelectKeyFragment; - - KeyValueSpinnerAdapter mEncryptionAdapter; - KeyValueSpinnerAdapter mHashAdapter; - KeyValueSpinnerAdapter mCompressionAdapter; - public AppSettings getAppSettings() { return mAppSettings; } @@ -85,11 +75,6 @@ public class AppSettingsFragment extends Fragment implements Log.e(Constants.TAG, "Should not happen!", e); } - mSelectKeyFragment.selectKey(appSettings.getKeyId()); - mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(appSettings - .getEncryptionAlgorithm())); - mHashAlgorithm.setSelection(mHashAdapter.getPosition(appSettings.getHashAlgorithm())); - mCompression.setSelection(mCompressionAdapter.getPosition(appSettings.getCompression())); } /** @@ -102,74 +87,13 @@ public class AppSettingsFragment extends Fragment implements return view; } - /** - * Set error String on key selection - * - * @param error - */ - public void setErrorOnSelectKeyFragment(String error) { - mSelectKeyFragment.setError(error); - } private void initView(View view) { - mSelectKeyFragment = (SelectSecretKeyLayoutFragment) getFragmentManager().findFragmentById( - R.id.api_app_settings_select_key_fragment); - mSelectKeyFragment.setCallback(this); - mAppNameView = (TextView) view.findViewById(R.id.api_app_settings_app_name); mAppIconView = (ImageView) view.findViewById(R.id.api_app_settings_app_icon); - mEncryptionAlgorithm = (Spinner) view - .findViewById(R.id.api_app_settings_encryption_algorithm); - mHashAlgorithm = (Spinner) view.findViewById(R.id.api_app_settings_hash_algorithm); - mCompression = (Spinner) view.findViewById(R.id.api_app_settings_compression); + mPackageName = (TextView) view.findViewById(R.id.api_app_settings_package_name); mPackageSignature = (TextView) view.findViewById(R.id.api_app_settings_package_signature); - - AlgorithmNames algorithmNames = new AlgorithmNames(getActivity()); - - mEncryptionAdapter = new KeyValueSpinnerAdapter(getActivity(), - algorithmNames.getEncryptionNames()); - mEncryptionAlgorithm.setAdapter(mEncryptionAdapter); - mEncryptionAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - mAppSettings.setEncryptionAlgorithm((int) id); - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - - mHashAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getHashNames()); - mHashAlgorithm.setAdapter(mHashAdapter); - mHashAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - mAppSettings.setHashAlgorithm((int) id); - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - - mCompressionAdapter = new KeyValueSpinnerAdapter(getActivity(), - algorithmNames.getCompressionNames()); - mCompression.setAdapter(mCompressionAdapter); - mCompression.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - mAppSettings.setCompression((int) id); - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); } private void setPackage(String packageName) { @@ -191,12 +115,5 @@ public class AppSettingsFragment extends Fragment implements mAppIconView.setImageDrawable(appIcon); } - /** - * callback from select secret key fragment - */ - @Override - public void onKeySelected(long secretKeyId) { - mAppSettings.setKeyId(secretKeyId); - } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListActivity.java new file mode 100644 index 000000000..f86d279f0 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListActivity.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.os.Bundle; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.DrawerActivity; + +public class AppsListActivity extends DrawerActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.api_apps_list_activity); + + setupDrawerNavigation(savedInstanceState); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java new file mode 100644 index 000000000..7054a2195 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.support.v4.app.ListFragment; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; +import android.support.v4.widget.CursorAdapter; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.ImageView; +import android.widget.TextView; + +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; + +public class AppsListFragment extends ListFragment implements + LoaderManager.LoaderCallbacks { + + // This is the Adapter being used to display the list's data. + RegisteredAppsAdapter mAdapter; + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + getListView().setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int position, long id) { + // edit app settings + Intent intent = new Intent(getActivity(), AppSettingsActivity.class); + intent.setData(ContentUris.withAppendedId(KeychainContract.ApiApps.CONTENT_URI, id)); + startActivity(intent); + } + }); + + // Give some text to display if there is no data. In a real + // application this would come from a resource. + setEmptyText(getString(R.string.api_no_apps)); + + // We have a menu item to show in action bar. + setHasOptionsMenu(true); + + // Create an empty adapter we will use to display the loaded data. + mAdapter = new RegisteredAppsAdapter(getActivity(), null, 0); + setListAdapter(mAdapter); + + // Prepare the loader. Either re-connect with an existing one, + // or start a new one. + getLoaderManager().initLoader(0, null, this); + } + + // These are the Contacts rows that we will retrieve. + static final String[] PROJECTION = new String[]{ApiApps._ID, ApiApps.PACKAGE_NAME}; + + public Loader onCreateLoader(int id, Bundle args) { + // This is called when a new Loader needs to be created. This + // sample only has one Loader, so we don't care about the ID. + // First, pick the base URI to use depending on whether we are + // currently filtering. + Uri baseUri = ApiApps.CONTENT_URI; + + // Now create and return a CursorLoader that will take care of + // creating a Cursor for the data being displayed. + return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, + ApiApps.PACKAGE_NAME + " COLLATE LOCALIZED ASC"); + } + + public void onLoadFinished(Loader loader, Cursor data) { + // Swap the new cursor in. (The framework will take care of closing the + // old cursor once we return.) + mAdapter.swapCursor(data); + } + + public void onLoaderReset(Loader loader) { + // This is called when the last Cursor provided to onLoadFinished() + // above is about to be closed. We need to make sure we are no + // longer using it. + mAdapter.swapCursor(null); + } + + private class RegisteredAppsAdapter extends CursorAdapter { + + private LayoutInflater mInflater; + private PackageManager mPM; + + public RegisteredAppsAdapter(Context context, Cursor c, int flags) { + super(context, c, flags); + + mInflater = LayoutInflater.from(context); + mPM = context.getApplicationContext().getPackageManager(); + } + + @Override + public void bindView(View view, Context context, Cursor cursor) { + TextView text = (TextView) view.findViewById(R.id.api_apps_adapter_item_name); + ImageView icon = (ImageView) view.findViewById(R.id.api_apps_adapter_item_icon); + + String packageName = cursor.getString(cursor.getColumnIndex(ApiApps.PACKAGE_NAME)); + if (packageName != null) { + // get application name + try { + ApplicationInfo ai = mPM.getApplicationInfo(packageName, 0); + + text.setText(mPM.getApplicationLabel(ai)); + icon.setImageDrawable(mPM.getApplicationIcon(ai)); + } catch (final PackageManager.NameNotFoundException e) { + // fallback + text.setText(packageName); + } + } else { + // fallback + text.setText(packageName); + } + + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return mInflater.inflate(R.layout.api_apps_adapter_list_item, null); + } + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java deleted file mode 100644 index c846343ab..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsAdapter.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.remote.ui; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.database.Cursor; -import android.support.v4.widget.CursorAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; - -public class RegisteredAppsAdapter extends CursorAdapter { - - private LayoutInflater mInflater; - private PackageManager mPM; - - public RegisteredAppsAdapter(Context context, Cursor c, int flags) { - super(context, c, flags); - - mInflater = LayoutInflater.from(context); - mPM = context.getApplicationContext().getPackageManager(); - } - - @Override - public void bindView(View view, Context context, Cursor cursor) { - TextView text = (TextView) view.findViewById(R.id.api_apps_adapter_item_name); - ImageView icon = (ImageView) view.findViewById(R.id.api_apps_adapter_item_icon); - - String packageName = cursor.getString(cursor.getColumnIndex(ApiApps.PACKAGE_NAME)); - if (packageName != null) { - // get application name - try { - ApplicationInfo ai = mPM.getApplicationInfo(packageName, 0); - - text.setText(mPM.getApplicationLabel(ai)); - icon.setImageDrawable(mPM.getApplicationIcon(ai)); - } catch (final NameNotFoundException e) { - // fallback - text.setText(packageName); - } - } else { - // fallback - text.setText(packageName); - } - - } - - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) { - return mInflater.inflate(R.layout.api_apps_adapter_list_item, null); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java deleted file mode 100644 index 79b3c8abc..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListActivity.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.remote.ui; - -import android.os.Bundle; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.ui.DrawerActivity; - -public class RegisteredAppsListActivity extends DrawerActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.api_apps_list_activity); - - setupDrawerNavigation(savedInstanceState); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java deleted file mode 100644 index 99e73e510..000000000 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RegisteredAppsListFragment.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2013 Dominik Schürmann - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.remote.ui; - -import android.content.ContentUris; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.os.Bundle; -import android.support.v4.app.ListFragment; -import android.support.v4.app.LoaderManager; -import android.support.v4.content.CursorLoader; -import android.support.v4.content.Loader; -import android.view.View; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; - -public class RegisteredAppsListFragment extends ListFragment implements - LoaderManager.LoaderCallbacks { - - // This is the Adapter being used to display the list's data. - RegisteredAppsAdapter mAdapter; - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - getListView().setOnItemClickListener(new OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int position, long id) { - // edit app settings - Intent intent = new Intent(getActivity(), AppSettingsActivity.class); - intent.setData(ContentUris.withAppendedId(KeychainContract.ApiApps.CONTENT_URI, id)); - startActivity(intent); - } - }); - - // Give some text to display if there is no data. In a real - // application this would come from a resource. - setEmptyText(getString(R.string.api_no_apps)); - - // We have a menu item to show in action bar. - setHasOptionsMenu(true); - - // Create an empty adapter we will use to display the loaded data. - mAdapter = new RegisteredAppsAdapter(getActivity(), null, 0); - setListAdapter(mAdapter); - - // Prepare the loader. Either re-connect with an existing one, - // or start a new one. - getLoaderManager().initLoader(0, null, this); - } - - // These are the Contacts rows that we will retrieve. - static final String[] PROJECTION = new String[]{ApiApps._ID, ApiApps.PACKAGE_NAME}; - - public Loader onCreateLoader(int id, Bundle args) { - // This is called when a new Loader needs to be created. This - // sample only has one Loader, so we don't care about the ID. - // First, pick the base URI to use depending on whether we are - // currently filtering. - Uri baseUri = ApiApps.CONTENT_URI; - - // Now create and return a CursorLoader that will take care of - // creating a Cursor for the data being displayed. - return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, - ApiApps.PACKAGE_NAME + " COLLATE LOCALIZED ASC"); - } - - public void onLoadFinished(Loader loader, Cursor data) { - // Swap the new cursor in. (The framework will take care of closing the - // old cursor once we return.) - mAdapter.swapCursor(data); - } - - public void onLoaderReset(Loader loader) { - // This is called when the last Cursor provided to onLoadFinished() - // above is about to be closed. We need to make sure we are no - // longer using it. - mAdapter.swapCursor(null); - } - -} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java index 3e19a8ef6..a088ad4b0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java @@ -24,6 +24,7 @@ import android.os.Message; import android.os.Messenger; import android.support.v7.app.ActionBarActivity; import android.view.View; + import org.openintents.openpgp.util.OpenPgpApi; import org.sufficientlysecure.htmltextview.HtmlTextView; import org.sufficientlysecure.keychain.Constants; @@ -31,7 +32,9 @@ import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.ActionBarHelper; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.remote.AccountSettings; import org.sufficientlysecure.keychain.remote.AppSettings; import org.sufficientlysecure.keychain.ui.SelectPublicKeyFragment; import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; @@ -42,6 +45,8 @@ import java.util.ArrayList; public class RemoteServiceActivity extends ActionBarActivity { public static final String ACTION_REGISTER = Constants.INTENT_PREFIX + "API_ACTIVITY_REGISTER"; + public static final String ACTION_REGISTER_ACCOUNT = Constants.INTENT_PREFIX + + "API_ACTIVITY_REGISTER_ACCOUNT"; public static final String ACTION_CACHE_PASSPHRASE = Constants.INTENT_PREFIX + "API_ACTIVITY_CACHE_PASSPHRASE"; public static final String ACTION_SELECT_PUB_KEYS = Constants.INTENT_PREFIX @@ -58,6 +63,8 @@ public class RemoteServiceActivity extends ActionBarActivity { // register action public static final String EXTRA_PACKAGE_NAME = "package_name"; public static final String EXTRA_PACKAGE_SIGNATURE = "package_signature"; + // create acc action + public static final String EXTRA_ACC_NAME = "acc_name"; // select pub keys action public static final String EXTRA_SELECTED_MASTER_KEY_IDS = "master_key_ids"; public static final String EXTRA_MISSING_USER_IDS = "missing_user_ids"; @@ -66,7 +73,9 @@ public class RemoteServiceActivity extends ActionBarActivity { public static final String EXTRA_ERROR_MESSAGE = "error_message"; // register view - private AppSettingsFragment mSettingsFragment; + private AppSettingsFragment mAppSettingsFragment; + // create acc view + private AccountSettingsFragment mAccSettingsFragment; // select pub keys view private SelectPublicKeyFragment mSelectFragment; @@ -95,13 +104,52 @@ public class RemoteServiceActivity extends ActionBarActivity { public void onClick(View v) { // Allow + ProviderHelper.insertApiApp(RemoteServiceActivity.this, + mAppSettingsFragment.getAppSettings()); + + // give data through for new service call + Intent resultData = extras.getParcelable(EXTRA_DATA); + RemoteServiceActivity.this.setResult(RESULT_OK, resultData); + RemoteServiceActivity.this.finish(); + } + }, R.string.api_register_disallow, R.drawable.ic_action_cancel, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // Disallow + RemoteServiceActivity.this.setResult(RESULT_CANCELED); + RemoteServiceActivity.this.finish(); + } + } + ); + + setContentView(R.layout.api_app_register_activity); + + mAppSettingsFragment = (AppSettingsFragment) getSupportFragmentManager().findFragmentById( + R.id.api_app_settings_fragment); + + AppSettings settings = new AppSettings(packageName, packageSignature); + mAppSettingsFragment.setAppSettings(settings); + } else if (ACTION_REGISTER_ACCOUNT.equals(action)) { + final String packageName = extras.getString(EXTRA_PACKAGE_NAME); + final String accName = extras.getString(EXTRA_ACC_NAME); + + // Inflate a "Done"/"Cancel" custom action bar view + ActionBarHelper.setTwoButtonView(getSupportActionBar(), + R.string.api_settings_save, R.drawable.ic_action_done, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // Save + // user needs to select a key! - if (mSettingsFragment.getAppSettings().getKeyId() == Id.key.none) { - mSettingsFragment.setErrorOnSelectKeyFragment( + if (mAccSettingsFragment.getAccSettings().getKeyId() == Id.key.none) { + mAccSettingsFragment.setErrorOnSelectKeyFragment( getString(R.string.api_register_error_select_key)); } else { - ProviderHelper.insertApiApp(RemoteServiceActivity.this, - mSettingsFragment.getAppSettings()); + ProviderHelper.insertApiAccount(RemoteServiceActivity.this, + KeychainContract.ApiAccounts.buildBaseUri(packageName), + mAccSettingsFragment.getAccSettings()); // give data through for new service call Intent resultData = extras.getParcelable(EXTRA_DATA); @@ -109,24 +157,24 @@ public class RemoteServiceActivity extends ActionBarActivity { RemoteServiceActivity.this.finish(); } } - }, R.string.api_register_disallow, R.drawable.ic_action_cancel, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // Disallow - RemoteServiceActivity.this.setResult(RESULT_CANCELED); - RemoteServiceActivity.this.finish(); - } + }, R.string.api_settings_cancel, R.drawable.ic_action_cancel, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // Cancel + RemoteServiceActivity.this.setResult(RESULT_CANCELED); + RemoteServiceActivity.this.finish(); + } } ); - setContentView(R.layout.api_app_register_activity); + setContentView(R.layout.api_account_create_activity); - mSettingsFragment = (AppSettingsFragment) getSupportFragmentManager().findFragmentById( - R.id.api_app_settings_fragment); + mAccSettingsFragment = (AccountSettingsFragment) getSupportFragmentManager().findFragmentById( + R.id.api_account_settings_fragment); - AppSettings settings = new AppSettings(packageName, packageSignature); - mSettingsFragment.setAppSettings(settings); + AccountSettings settings = new AccountSettings(accName); + mAccSettingsFragment.setAccSettings(settings); } else if (ACTION_CACHE_PASSPHRASE.equals(action)) { long secretKeyId = extras.getLong(EXTRA_SECRET_KEY_ID); Intent resultData = extras.getParcelable(EXTRA_DATA); -- cgit v1.2.3 From cff35ca84283202d1a0b824b6eb9eaf4231c061a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 25 Mar 2014 21:23:59 +0100 Subject: More experimental work on api accounts --- .../keychain/provider/KeychainContract.java | 11 ++-- .../keychain/provider/KeychainProvider.java | 61 +++++----------------- .../keychain/remote/ui/AccountsListFragment.java | 44 ++++++++-------- .../keychain/remote/ui/AppSettingsActivity.java | 32 +++++++++++- .../keychain/remote/ui/AppsListFragment.java | 30 +++++++++-- 5 files changed, 97 insertions(+), 81 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index 6e7b76fbe..98ce98495 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -95,8 +95,6 @@ public class KeychainContract { public static final String BASE_API_APPS = "api_apps"; public static final String PATH_ACCOUNTS = "accounts"; - public static final String PATH_BY_PACKAGE_NAME = "package_name"; - public static class KeyRings implements KeyRingsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon() .appendPath(BASE_KEY_RINGS).build(); @@ -272,13 +270,12 @@ public class KeychainContract { */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api.apps"; - public static Uri buildIdUri(String rowId) { - return CONTENT_URI.buildUpon().appendPath(rowId).build(); - } +// public static Uri buildIdUri(String rowId) { +// return CONTENT_URI.buildUpon().appendPath(rowId).build(); +// } public static Uri buildByPackageNameUri(String packageName) { - return CONTENT_URI.buildUpon().appendPath(PATH_BY_PACKAGE_NAME) - .appendEncodedPath(packageName).build(); + return CONTENT_URI.buildUpon().appendEncodedPath(packageName).build(); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index cae76003c..005be2fd6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -80,10 +80,8 @@ public class KeychainProvider extends ContentProvider { private static final int SECRET_KEY_RING_USER_ID_BY_ROW_ID = 222; private static final int API_APPS = 301; - private static final int API_APPS_BY_ROW_ID = 302; private static final int API_APPS_BY_PACKAGE_NAME = 303; private static final int API_ACCOUNTS = 304; - private static final int API_ACCOUNTS_BY_ROW_ID = 305; private static final int API_ACCOUNTS_BY_ACCOUNT_NAME = 306; private static final int UNIFIED_KEY_RING = 401; @@ -241,19 +239,22 @@ public class KeychainProvider extends ContentProvider { /** * API apps + * + *
+         * api_apps
+         * api_apps/_
+         *
+         * api_apps/_/accounts
+         * api_apps/_/accounts/_
+         * 
*/ matcher.addURI(authority, KeychainContract.BASE_API_APPS, API_APPS); - matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/#", API_APPS_BY_ROW_ID); - matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" - + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_APPS_BY_PACKAGE_NAME); + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/*", API_APPS_BY_PACKAGE_NAME); - matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/*/" + KeychainContract.PATH_ACCOUNTS, API_ACCOUNTS); - matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" - + KeychainContract.PATH_ACCOUNTS + "/#", API_ACCOUNTS_BY_ROW_ID); - matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/" - + KeychainContract.PATH_ACCOUNTS + "/" - + KeychainContract.PATH_BY_PACKAGE_NAME + "/*", API_ACCOUNTS_BY_ACCOUNT_NAME); + matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/*/" + + KeychainContract.PATH_ACCOUNTS + "/*", API_ACCOUNTS_BY_ACCOUNT_NAME); /** * data stream @@ -322,14 +323,12 @@ public class KeychainProvider extends ContentProvider { case API_APPS: return ApiApps.CONTENT_TYPE; - case API_APPS_BY_ROW_ID: case API_APPS_BY_PACKAGE_NAME: return ApiApps.CONTENT_ITEM_TYPE; case API_ACCOUNTS: return ApiAccounts.CONTENT_TYPE; - case API_ACCOUNTS_BY_ROW_ID: case API_ACCOUNTS_BY_ACCOUNT_NAME: return ApiAccounts.CONTENT_ITEM_TYPE; @@ -679,13 +678,6 @@ public class KeychainProvider extends ContentProvider { case API_APPS: qb.setTables(Tables.API_APPS); - break; - case API_APPS_BY_ROW_ID: - qb.setTables(Tables.API_APPS); - - qb.appendWhere(BaseColumns._ID + " = "); - qb.appendWhereEscapeString(uri.getLastPathSegment()); - break; case API_APPS_BY_PACKAGE_NAME: qb.setTables(Tables.API_APPS); @@ -696,17 +688,6 @@ public class KeychainProvider extends ContentProvider { case API_ACCOUNTS: qb.setTables(Tables.API_ACCOUNTS); - break; - case API_ACCOUNTS_BY_ROW_ID: - qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" - + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." - + ApiAccounts.PACKAGE_NAME_FK + " )"); - qb.appendWhere(Tables.API_APPS + "." + BaseColumns._ID + " = "); - qb.appendWhereEscapeString(uri.getPathSegments().get(2)); - - qb.appendWhere(" AND " + Tables.API_ACCOUNTS + "." + BaseColumns._ID + " = "); - qb.appendWhereEscapeString(uri.getLastPathSegment()); - break; case API_ACCOUNTS_BY_ACCOUNT_NAME: qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" @@ -812,7 +793,7 @@ public class KeychainProvider extends ContentProvider { break; case API_APPS: rowId = db.insertOrThrow(Tables.API_APPS, null, values); - rowUri = ApiApps.buildIdUri(Long.toString(rowId)); +// rowUri = ApiApps.buildIdUri(Long.toString(rowId)); break; case API_ACCOUNTS: @@ -878,18 +859,10 @@ public class KeychainProvider extends ContentProvider { count = db.delete(Tables.KEYS, buildDefaultUserIdsSelection(uri, selection), selectionArgs); break; - case API_APPS_BY_ROW_ID: - count = db.delete(Tables.API_APPS, buildDefaultApiAppsSelection(uri, false, selection), - selectionArgs); - break; case API_APPS_BY_PACKAGE_NAME: count = db.delete(Tables.API_APPS, buildDefaultApiAppsSelection(uri, true, selection), selectionArgs); break; - case API_ACCOUNTS_BY_ROW_ID: - count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, false, selection), - selectionArgs); - break; case API_ACCOUNTS_BY_ACCOUNT_NAME: count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, true, selection), selectionArgs); @@ -956,18 +929,10 @@ public class KeychainProvider extends ContentProvider { count = db.update(Tables.USER_IDS, values, buildDefaultUserIdsSelection(uri, selection), selectionArgs); break; - case API_APPS_BY_ROW_ID: - count = db.update(Tables.API_APPS, values, - buildDefaultApiAppsSelection(uri, false, selection), selectionArgs); - break; case API_APPS_BY_PACKAGE_NAME: count = db.update(Tables.API_APPS, values, buildDefaultApiAppsSelection(uri, true, selection), selectionArgs); break; - case API_ACCOUNTS_BY_ROW_ID: - count = db.update(Tables.API_ACCOUNTS, values, - buildDefaultApiAccountsSelection(uri, false, selection), selectionArgs); - break; case API_ACCOUNTS_BY_ACCOUNT_NAME: count = db.update(Tables.API_ACCOUNTS, values, buildDefaultApiAccountsSelection(uri, true, selection), selectionArgs); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java index 0cec319a5..853dc2d3c 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java @@ -19,10 +19,7 @@ package org.sufficientlysecure.keychain.remote.ui; import android.annotation.TargetApi; import android.content.ContentUris; -import android.content.Context; import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; @@ -31,15 +28,10 @@ import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; -import android.support.v4.widget.CursorAdapter; -import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; -import android.widget.ImageView; import android.widget.SimpleCursorAdapter; -import android.widget.TextView; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.provider.KeychainContract; @@ -50,36 +42,46 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; public class AccountsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks { + private static final String ARG_DATA_URI = "uri"; + // This is the Adapter being used to display the list's data. SimpleCursorAdapter mAdapter; - private String mPackageName; + private Uri mDataUri; - public String getPackageName() { - return mPackageName; - } + /** + * Creates new instance of this fragment + */ + public static AccountsListFragment newInstance(Uri dataUri) { + AccountsListFragment frag = new AccountsListFragment(); + + Bundle args = new Bundle(); + args.putParcelable(ARG_DATA_URI, dataUri); - public void setPackageName(String packageName) { - this.mPackageName = packageName; + frag.setArguments(args); + + return frag; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); + mDataUri = getArguments().getParcelable(ARG_DATA_URI); + getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int position, long id) { - // edit app settings - Intent intent = new Intent(getActivity(), AppSettingsActivity.class); - intent.setData(ContentUris.withAppendedId(ApiApps.CONTENT_URI, id)); - startActivity(intent); +// // edit app settings +// Intent intent = new Intent(getActivity(), AppSettingsActivity.class); +// intent.setData(ContentUris.withAppendedId(ApiApps.CONTENT_URI, id)); +// startActivity(intent); } }); // Give some text to display if there is no data. In a real // application this would come from a resource. - setEmptyText(getString(R.string.api_no_apps)); + setEmptyText(getString(R.string.api_settings_accounts_empty)); // We have a menu item to show in action bar. setHasOptionsMenu(true); @@ -108,11 +110,11 @@ public class AccountsListFragment extends ListFragment implements // sample only has one Loader, so we don't care about the ID. // First, pick the base URI to use depending on whether we are // currently filtering. - Uri baseUri = KeychainContract.ApiAccounts.buildBaseUri(mPackageName); +// Uri baseUri = KeychainContract.ApiAccounts.buildBaseUri(mPackageName); // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. - return new CursorLoader(getActivity(), baseUri, PROJECTION, null, null, + return new CursorLoader(getActivity(), mDataUri, PROJECTION, null, null, KeychainContract.ApiAccounts.ACCOUNT_NAME + " COLLATE LOCALIZED ASC"); } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java index d544455ec..33cde49ba 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java @@ -24,9 +24,11 @@ import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; + import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.ActionBarHelper; +import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.remote.AppSettings; import org.sufficientlysecure.keychain.util.Log; @@ -35,6 +37,7 @@ public class AppSettingsActivity extends ActionBarActivity { private Uri mAppUri; private AppSettingsFragment mSettingsFragment; + private AccountsListFragment mAccountsListFragment; @Override protected void onCreate(Bundle savedInstanceState) { @@ -64,7 +67,7 @@ public class AppSettingsActivity extends ActionBarActivity { return; } else { Log.d(Constants.TAG, "uri: " + mAppUri); - loadData(mAppUri); + loadData(savedInstanceState, mAppUri); } } @@ -88,9 +91,34 @@ public class AppSettingsActivity extends ActionBarActivity { return super.onOptionsItemSelected(item); } - private void loadData(Uri appUri) { + private void loadData(Bundle savedInstanceState, Uri appUri) { + // TODO: load this also like other fragment with newInstance arguments? AppSettings settings = ProviderHelper.getApiAppSettings(this, appUri); mSettingsFragment.setAppSettings(settings); + + Uri accountsUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ACCOUNTS).build(); + Log.d(Constants.TAG, "accountsUri: " + accountsUri); + startListFragment(savedInstanceState, accountsUri); + } + + private void startListFragment(Bundle savedInstanceState, Uri dataUri) { + // However, if we're being restored from a previous state, + // then we don't need to do anything and should return or else + // we could end up with overlapping fragments. + if (savedInstanceState != null) { + return; + } + + // Create an instance of the fragment + mAccountsListFragment = AccountsListFragment.newInstance(dataUri); + + // Add the fragment to the 'fragment_container' FrameLayout + // NOTE: We use commitAllowingStateLoss() to prevent weird crashes! + getSupportFragmentManager().beginTransaction() + .replace(R.id.api_accounts_list_fragment, mAccountsListFragment) + .commitAllowingStateLoss(); + // do it immediately! + getSupportFragmentManager().executePendingTransactions(); } private void revokeAccess() { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java index 7054a2195..f3fa6e7c6 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppsListFragment.java @@ -17,7 +17,6 @@ package org.sufficientlysecure.keychain.remote.ui; -import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; @@ -38,9 +37,11 @@ import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.TextView; +import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; +import org.sufficientlysecure.keychain.util.Log; public class AppsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks { @@ -55,9 +56,10 @@ public class AppsListFragment extends ListFragment implements getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int position, long id) { + String selectedPackageName = mAdapter.getItemPackageName(position); // edit app settings Intent intent = new Intent(getActivity(), AppSettingsActivity.class); - intent.setData(ContentUris.withAppendedId(KeychainContract.ApiApps.CONTENT_URI, id)); + intent.setData(KeychainContract.ApiApps.buildByPackageNameUri(selectedPackageName)); startActivity(intent); } }); @@ -79,7 +81,10 @@ public class AppsListFragment extends ListFragment implements } // These are the Contacts rows that we will retrieve. - static final String[] PROJECTION = new String[]{ApiApps._ID, ApiApps.PACKAGE_NAME}; + static final String[] PROJECTION = new String[]{ + ApiApps._ID, // 0 + ApiApps.PACKAGE_NAME // 1 + }; public Loader onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This @@ -119,6 +124,25 @@ public class AppsListFragment extends ListFragment implements mPM = context.getApplicationContext().getPackageManager(); } + /** + * Similar to CursorAdapter.getItemId(). + * Required to build Uris for api app view, which is not based on row ids + * + * @param position + * @return + */ + public String getItemPackageName(int position) { + if (mDataValid && mCursor != null) { + if (mCursor.moveToPosition(position)) { + return mCursor.getString(1); + } else { + return null; + } + } else { + return null; + } + } + @Override public void bindView(View view, Context context, Cursor cursor) { TextView text = (TextView) view.findViewById(R.id.api_apps_adapter_item_name); -- cgit v1.2.3 From 8c496d3393188559c4ce86d5ac4e3a9b1b2bdff9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 25 Mar 2014 21:52:06 +0100 Subject: Fix update and insert for new api content provider --- .../keychain/provider/KeychainProvider.java | 32 ++++++++++------------ 1 file changed, 14 insertions(+), 18 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 005be2fd6..1f725266e 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -27,6 +27,7 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; +import android.support.v4.database.DatabaseUtilsCompat; import android.text.TextUtils; import org.sufficientlysecure.keychain.Constants; @@ -860,11 +861,11 @@ public class KeychainProvider extends ContentProvider { selectionArgs); break; case API_APPS_BY_PACKAGE_NAME: - count = db.delete(Tables.API_APPS, buildDefaultApiAppsSelection(uri, true, selection), + count = db.delete(Tables.API_APPS, buildDefaultApiAppsSelection(uri, selection), selectionArgs); break; case API_ACCOUNTS_BY_ACCOUNT_NAME: - count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, true, selection), + count = db.delete(Tables.API_ACCOUNTS, buildDefaultApiAccountsSelection(uri, selection), selectionArgs); break; default: @@ -931,11 +932,11 @@ public class KeychainProvider extends ContentProvider { break; case API_APPS_BY_PACKAGE_NAME: count = db.update(Tables.API_APPS, values, - buildDefaultApiAppsSelection(uri, true, selection), selectionArgs); + buildDefaultApiAppsSelection(uri, selection), selectionArgs); break; case API_ACCOUNTS_BY_ACCOUNT_NAME: count = db.update(Tables.API_ACCOUNTS, values, - buildDefaultApiAccountsSelection(uri, true, selection), selectionArgs); + buildDefaultApiAccountsSelection(uri, selection), selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); @@ -1034,34 +1035,29 @@ public class KeychainProvider extends ContentProvider { * @param selection * @return */ - private String buildDefaultApiAppsSelection(Uri uri, boolean packageSelection, String selection) { - String lastPathSegment = uri.getLastPathSegment(); + private String buildDefaultApiAppsSelection(Uri uri, String selection) { + String packageName = DatabaseUtils.sqlEscapeString(uri.getLastPathSegment()); String andSelection = ""; if (!TextUtils.isEmpty(selection)) { andSelection = " AND (" + selection + ")"; } - if (packageSelection) { - return ApiApps.PACKAGE_NAME + "=" + lastPathSegment + andSelection; - } else { - return BaseColumns._ID + "=" + lastPathSegment + andSelection; - } + return ApiApps.PACKAGE_NAME + "=" + packageName + andSelection; } - private String buildDefaultApiAccountsSelection(Uri uri, boolean packageSelection, String selection) { - String lastPathSegment = uri.getLastPathSegment(); + private String buildDefaultApiAccountsSelection(Uri uri, String selection) { + String packageName = DatabaseUtils.sqlEscapeString(uri.getPathSegments().get(2)); + String accountName = DatabaseUtils.sqlEscapeString(uri.getLastPathSegment()); String andSelection = ""; if (!TextUtils.isEmpty(selection)) { andSelection = " AND (" + selection + ")"; } - if (packageSelection) { - return ApiAccounts.PACKAGE_NAME_FK + "=" + lastPathSegment + andSelection; - } else { - return BaseColumns._ID + "=" + lastPathSegment + andSelection; - } + return ApiAccounts.PACKAGE_NAME_FK + "=" + packageName + " AND " + + ApiAccounts.ACCOUNT_NAME + "=" + accountName + + andSelection; } // @Override -- cgit v1.2.3 From dc9fd1221387a4f31ec2ceba615b376b0796ff10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 25 Mar 2014 23:09:57 +0100 Subject: Return account creation intent if account does not exists in db --- .../keychain/provider/KeychainContract.java | 23 ++------ .../keychain/provider/KeychainProvider.java | 5 +- .../keychain/remote/OpenPgpService.java | 3 + .../keychain/remote/RemoteService.java | 69 +++++++++++++++------- .../keychain/remote/ui/RemoteServiceActivity.java | 6 +- 5 files changed, 60 insertions(+), 46 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index 98ce98495..6e4899fc2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -160,6 +160,7 @@ public class KeychainContract { } public static Uri buildSecretKeyRingsByEmailsUri(String emails) { + // TODO: encoded? return CONTENT_URI.buildUpon().appendPath(PATH_SECRET).appendPath(PATH_BY_EMAILS) .appendPath(emails).build(); } @@ -263,16 +264,12 @@ public class KeychainContract { /** * Use if multiple items get returned */ - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api.app"; + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api_apps"; /** * Use if a single item is returned */ - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api.apps"; - -// public static Uri buildIdUri(String rowId) { -// return CONTENT_URI.buildUpon().appendPath(rowId).build(); -// } + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api_app"; public static Uri buildByPackageNameUri(String packageName) { return CONTENT_URI.buildUpon().appendEncodedPath(packageName).build(); @@ -286,22 +283,12 @@ public class KeychainContract { /** * Use if multiple items get returned */ - public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api.acoounts"; + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api_app.accounts"; /** * Use if a single item is returned */ - public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api.account"; - -// public static Uri buildUri(String rowIdApp) { -// return CONTENT_URI.buildUpon().appendPath(rowIdApp).appendPath(PATH_ACCOUNTS) -// .build(); -// } -// -// public static Uri buildIdUri(String rowIdApp, String rowId) { -// return CONTENT_URI.buildUpon().appendPath(rowIdApp).appendPath(PATH_ACCOUNTS) -// .appendPath(rowId).build(); -// } + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api_app.account"; public static Uri buildBaseUri(String packageName) { return CONTENT_URI.buildUpon().appendEncodedPath(packageName).appendPath(PATH_ACCOUNTS) diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 1f725266e..6e5515cab 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -27,7 +27,6 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; -import android.support.v4.database.DatabaseUtilsCompat; import android.text.TextUtils; import org.sufficientlysecure.keychain.Constants; @@ -243,10 +242,10 @@ public class KeychainProvider extends ContentProvider { * *
          * api_apps
-         * api_apps/_
+         * api_apps/_ (package name)
          *
          * api_apps/_/accounts
-         * api_apps/_/accounts/_
+         * api_apps/_/accounts/_ (account name)
          * 
*/ matcher.addURI(authority, KeychainContract.BASE_API_APPS, API_APPS); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java index b04e76cbd..fa6ccf63b 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java @@ -440,6 +440,9 @@ public class OpenPgpService extends RemoteService { accName = "default"; } final AccountSettings accSettings = getAccSettings(accName); + if (accSettings == null) { + return getCreateAccountIntent(data, accName); + } String action = data.getAction(); if (OpenPgpApi.ACTION_SIGN.equals(action)) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java index 7b66a0b5c..0fd9ee7df 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java @@ -27,6 +27,7 @@ import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.net.Uri; import android.os.Binder; + import org.openintents.openpgp.OpenPgpError; import org.openintents.openpgp.util.OpenPgpApi; import org.sufficientlysecure.keychain.Constants; @@ -48,7 +49,6 @@ public abstract class RemoteService extends Service { private static final int PRIVATE_REQUEST_CODE_REGISTER = 651; private static final int PRIVATE_REQUEST_CODE_ERROR = 652; - public Context getContext() { return mContext; } @@ -56,13 +56,9 @@ public abstract class RemoteService extends Service { protected Intent isAllowed(Intent data) { try { if (isCallerAllowed(false)) { - return null; } else { - String[] callingPackages = getPackageManager().getPackagesForUid( - Binder.getCallingUid()); - // TODO: currently simply uses first entry - String packageName = callingPackages[0]; + String packageName = getCurrentCallingPackage(); byte[] packageSignature; try { @@ -85,7 +81,7 @@ public abstract class RemoteService extends Service { intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_REGISTER, intent, 0); + PRIVATE_REQUEST_CODE_REGISTER, intent, 0); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -100,11 +96,11 @@ public abstract class RemoteService extends Service { Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, - getString(R.string.api_error_wrong_signature)); + getString(R.string.api_error_wrong_signature)); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_ERROR, intent, 0); + PRIVATE_REQUEST_CODE_ERROR, intent, 0); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -126,27 +122,56 @@ public abstract class RemoteService extends Service { } /** - * Retrieves AppSettings from database for the application calling this remote service + * Returns package name associated with the UID, which is assigned to the process that sent you the + * current transaction that is being processed :) + * + * @return package name + */ + private String getCurrentCallingPackage() { + // TODO: + // callingPackages contains more than one entry when sharedUserId has been used... + String[] callingPackages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); + String currentPkg = callingPackages[0]; + Log.d(Constants.TAG, "currentPkg: " + currentPkg); + + return currentPkg; + } + + /** + * Retrieves AccountSettings from database for the application calling this remote service * * @return */ protected AccountSettings getAccSettings(String accountName) { - String[] callingPackages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); + String currentPkg = getCurrentCallingPackage(); + Log.d(Constants.TAG, "accountName: " + accountName); - // get app settings for this package - for (int i = 0; i < callingPackages.length; i++) { - String currentPkg = callingPackages[i]; + Uri uri = KeychainContract.ApiAccounts.buildByPackageAndAccountUri(currentPkg, accountName); - Uri uri = KeychainContract.ApiAccounts.buildByPackageAndAccountUri(currentPkg, accountName); + AccountSettings settings = ProviderHelper.getApiAccountSettings(this, uri); - AccountSettings settings = ProviderHelper.getApiAccountSettings(this, uri); + return settings; // can be null! + } - if (settings != null) { - return settings; - } - } + protected Intent getCreateAccountIntent(Intent data, String accountName) { + String packageName = getCurrentCallingPackage(); + Log.d(Constants.TAG, "accountName: " + accountName); + + Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); + intent.setAction(RemoteServiceActivity.ACTION_CREATE_ACCOUNT); + intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_NAME, packageName); + intent.putExtra(RemoteServiceActivity.EXTRA_ACC_NAME, accountName); + intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); + + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), + PRIVATE_REQUEST_CODE_REGISTER, intent, 0); + + // return PendingIntent to be executed by client + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); - return null; + return result; } /** @@ -217,7 +242,7 @@ public abstract class RemoteService extends Service { return true; } else { throw new WrongPackageSignatureException( - "PACKAGE NOT ALLOWED! Signature wrong! (Signature not equals signature from database)"); + "PACKAGE NOT ALLOWED! Signature wrong! (Signature not equals signature from database)"); } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java index a088ad4b0..d3ac5cade 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java @@ -45,8 +45,8 @@ import java.util.ArrayList; public class RemoteServiceActivity extends ActionBarActivity { public static final String ACTION_REGISTER = Constants.INTENT_PREFIX + "API_ACTIVITY_REGISTER"; - public static final String ACTION_REGISTER_ACCOUNT = Constants.INTENT_PREFIX - + "API_ACTIVITY_REGISTER_ACCOUNT"; + public static final String ACTION_CREATE_ACCOUNT = Constants.INTENT_PREFIX + + "API_ACTIVITY_CREATE_ACCOUNT"; public static final String ACTION_CACHE_PASSPHRASE = Constants.INTENT_PREFIX + "API_ACTIVITY_CACHE_PASSPHRASE"; public static final String ACTION_SELECT_PUB_KEYS = Constants.INTENT_PREFIX @@ -130,7 +130,7 @@ public class RemoteServiceActivity extends ActionBarActivity { AppSettings settings = new AppSettings(packageName, packageSignature); mAppSettingsFragment.setAppSettings(settings); - } else if (ACTION_REGISTER_ACCOUNT.equals(action)) { + } else if (ACTION_CREATE_ACCOUNT.equals(action)) { final String packageName = extras.getString(EXTRA_PACKAGE_NAME); final String accName = extras.getString(EXTRA_ACC_NAME); -- cgit v1.2.3 From 0edfd7ed48943607ebaaa1dd2c9b1018ace0b024 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Tue, 25 Mar 2014 23:25:03 +0100 Subject: Temporary fix for inserting by content provider --- .../sufficientlysecure/keychain/provider/KeychainProvider.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 6e5515cab..a5ee723f0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -757,14 +757,14 @@ public class KeychainProvider extends ContentProvider { rowId = db.insertOrThrow(Tables.KEYS, null, values); // TODO: this is wrong: -// rowUri = Keys.buildPublicKeysUri(Long.toString(rowId)); + rowUri = Keys.buildPublicKeysUri(Long.toString(rowId)); sendBroadcastDatabaseChange(getKeyType(match), getType(uri)); break; case PUBLIC_KEY_RING_USER_ID: rowId = db.insertOrThrow(Tables.USER_IDS, null, values); // TODO: this is wrong: -// rowUri = UserIds.buildPublicUserIdsUri(Long.toString(rowId)); + rowUri = UserIds.buildPublicUserIdsUri(Long.toString(rowId)); sendBroadcastDatabaseChange(getKeyType(match), getType(uri)); break; @@ -781,14 +781,14 @@ public class KeychainProvider extends ContentProvider { rowId = db.insertOrThrow(Tables.KEYS, null, values); // TODO: this is wrong: -// rowUri = Keys.buildSecretKeysUri(Long.toString(rowId)); + rowUri = Keys.buildSecretKeysUri(Long.toString(rowId)); sendBroadcastDatabaseChange(getKeyType(match), getType(uri)); break; case SECRET_KEY_RING_USER_ID: rowId = db.insertOrThrow(Tables.USER_IDS, null, values); // TODO: this is wrong: -// rowUri = UserIds.buildSecretUserIdsUri(Long.toString(rowId)); + rowUri = UserIds.buildSecretUserIdsUri(Long.toString(rowId)); break; case API_APPS: -- cgit v1.2.3 From 028af0c1195b2d6a747874af8cae07dde542dc64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 00:11:49 +0100 Subject: Fix constraints and insert --- .../keychain/provider/KeychainDatabase.java | 25 ++++++++++++---------- .../keychain/provider/KeychainProvider.java | 11 ++++++++-- .../keychain/provider/ProviderHelper.java | 7 ++---- .../keychain/remote/RemoteService.java | 2 +- 4 files changed, 26 insertions(+), 19 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java index ca1a47f0c..4abcec435 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java @@ -21,6 +21,7 @@ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; + import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsColumns; import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsAccountsColumns; @@ -63,33 +64,35 @@ public class KeychainDatabase extends SQLiteOpenHelper { + KeysColumns.KEY_DATA + " BLOB," + KeysColumns.RANK + " INTEGER, " + KeysColumns.FINGERPRINT + " BLOB, " - + KeysColumns.KEY_RING_ROW_ID + " INTEGER NOT NULL, FOREIGN KEY(" - + KeysColumns.KEY_RING_ROW_ID + ") REFERENCES " + Tables.KEY_RINGS + "(" - + BaseColumns._ID + ") ON DELETE CASCADE)"; + + KeysColumns.KEY_RING_ROW_ID + " INTEGER NOT NULL, " + + "FOREIGN KEY(" + KeysColumns.KEY_RING_ROW_ID + ") REFERENCES " + + Tables.KEY_RINGS + "(" + BaseColumns._ID + ") ON DELETE CASCADE)"; private static final String CREATE_USER_IDS = "CREATE TABLE IF NOT EXISTS " + Tables.USER_IDS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + UserIdsColumns.USER_ID + " TEXT, " + UserIdsColumns.RANK + " INTEGER, " - + UserIdsColumns.KEY_RING_ROW_ID + " INTEGER NOT NULL, FOREIGN KEY(" - + UserIdsColumns.KEY_RING_ROW_ID + ") REFERENCES " + Tables.KEY_RINGS + "(" - + BaseColumns._ID + ") ON DELETE CASCADE)"; + + UserIdsColumns.KEY_RING_ROW_ID + " INTEGER NOT NULL, " + + "FOREIGN KEY(" + UserIdsColumns.KEY_RING_ROW_ID + ") REFERENCES " + + Tables.KEY_RINGS + "(" + BaseColumns._ID + ") ON DELETE CASCADE)"; private static final String CREATE_API_APPS = "CREATE TABLE IF NOT EXISTS " + Tables.API_APPS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + ApiAppsColumns.PACKAGE_NAME + " TEXT UNIQUE, " + + ApiAppsColumns.PACKAGE_NAME + " TEXT NOT NULL UNIQUE, " + ApiAppsColumns.PACKAGE_SIGNATURE + " BLOB)"; private static final String CREATE_API_APPS_ACCOUNTS = "CREATE TABLE IF NOT EXISTS " + Tables.API_ACCOUNTS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + ApiAppsAccountsColumns.ACCOUNT_NAME + " TEXT UNIQUE, " + + ApiAppsAccountsColumns.ACCOUNT_NAME + " TEXT NOT NULL, " + ApiAppsAccountsColumns.KEY_ID + " INT64, " + ApiAppsAccountsColumns.ENCRYPTION_ALGORITHM + " INTEGER, " + ApiAppsAccountsColumns.HASH_ALORITHM + " INTEGER, " + ApiAppsAccountsColumns.COMPRESSION + " INTEGER, " - + ApiAppsAccountsColumns.PACKAGE_NAME_FK + " TEXT NOT NULL, FOREIGN KEY(" - + ApiAppsAccountsColumns.PACKAGE_NAME_FK + ") REFERENCES " + Tables.API_APPS + "(" - + ApiAppsColumns.PACKAGE_NAME + ") ON DELETE CASCADE)"; + + ApiAppsAccountsColumns.PACKAGE_NAME_FK + " TEXT NOT NULL, " + + "UNIQUE(" + ApiAppsAccountsColumns.ACCOUNT_NAME + ", " + + ApiAppsAccountsColumns.PACKAGE_NAME_FK + "), " + + "FOREIGN KEY(" + ApiAppsAccountsColumns.PACKAGE_NAME_FK + ") REFERENCES " + + Tables.API_APPS + "(" + ApiAppsColumns.PACKAGE_NAME + ") ON DELETE CASCADE)"; KeychainDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index a5ee723f0..6469da978 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -694,7 +694,7 @@ public class KeychainProvider extends ContentProvider { + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." + ApiAccounts.PACKAGE_NAME_FK + " )"); qb.appendWhere(Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = "); - qb.appendWhereEscapeString(uri.getPathSegments().get(2)); + qb.appendWhereEscapeString(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + Tables.API_ACCOUNTS + "." + ApiAccounts.ACCOUNT_NAME + " = "); qb.appendWhereEscapeString(uri.getLastPathSegment()); @@ -797,6 +797,13 @@ public class KeychainProvider extends ContentProvider { break; case API_ACCOUNTS: + // set foreign key automatically based on given uri + // e.g., api_apps/com.example.app/accounts/ + String packageName = uri.getPathSegments().get(1); + values.put(ApiAccounts.PACKAGE_NAME_FK, packageName); + + Log.d(Constants.TAG, "provider packageName: " + packageName); + rowId = db.insertOrThrow(Tables.API_ACCOUNTS, null, values); // TODO: this is wrong: // rowUri = ApiAccounts.buildIdUri(Long.toString(rowId)); @@ -1046,7 +1053,7 @@ public class KeychainProvider extends ContentProvider { } private String buildDefaultApiAccountsSelection(Uri uri, String selection) { - String packageName = DatabaseUtils.sqlEscapeString(uri.getPathSegments().get(2)); + String packageName = DatabaseUtils.sqlEscapeString(uri.getPathSegments().get(1)); String accountName = DatabaseUtils.sqlEscapeString(uri.getLastPathSegment()); String andSelection = ""; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index e3727b2f8..71f74b8d8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -813,7 +813,6 @@ public class ProviderHelper { values.put(KeychainContract.ApiAccounts.COMPRESSION, accSettings.getCompression()); values.put(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM, accSettings.getEncryptionAlgorithm()); values.put(KeychainContract.ApiAccounts.HASH_ALORITHM, accSettings.getHashAlgorithm()); -// values.put(KeychainContract.ApiAccounts.PACKAGE_NAME_FK, accSettings.getPackageName()); return values; } @@ -823,8 +822,7 @@ public class ProviderHelper { } public static void insertApiAccount(Context context, Uri uri, AccountSettings accSettings) { - context.getContentResolver().insert(uri, - contentValueForApiAccounts(accSettings)); + context.getContentResolver().insert(uri, contentValueForApiAccounts(accSettings)); } public static void updateApiApp(Context context, AppSettings appSettings, Uri uri) { @@ -841,7 +839,6 @@ public class ProviderHelper { } } - /** * Must be an uri pointing to an account * @@ -886,7 +883,7 @@ public class ProviderHelper { return settings; } - public static byte[] getApiSignature(Context context, String packageName) { + public static byte[] getApiAppSignature(Context context, String packageName) { Uri queryUri = ApiApps.buildByPackageNameUri(packageName); String[] projection = new String[]{ApiApps.PACKAGE_SIGNATURE}; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java index 0fd9ee7df..7e935d317 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java @@ -235,7 +235,7 @@ public abstract class RemoteService extends Service { throw new WrongPackageSignatureException(e.getMessage()); } - byte[] storedSig = ProviderHelper.getApiSignature(this, packageName); + byte[] storedSig = ProviderHelper.getApiAppSignature(this, packageName); if (Arrays.equals(currentSig, storedSig)) { Log.d(Constants.TAG, "Package signature is correct! (equals signature from database)"); -- cgit v1.2.3 From 930d722013c36104300bfe4773798ae3d5089b6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 00:40:13 +0100 Subject: Simplify can encrypt check --- .../keychain/ui/ViewKeyMainFragment.java | 43 ++++++++++++---------- 1 file changed, 24 insertions(+), 19 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index 8a4f2758a..691be5fa9 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -32,7 +32,9 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; + import com.beardedhen.androidbootstrap.BootstrapButton; + import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.OtherHelper; @@ -143,7 +145,7 @@ public class ViewKeyMainFragment extends Fragment implements editIntent.setData( KeychainContract .KeyRings.buildSecretKeyRingsByMasterKeyIdUri( - Long.toString(masterKeyId))); + Long.toString(masterKeyId))); editIntent.setAction(EditKeyActivity.ACTION_EDIT_KEY); startActivityForResult(editIntent, 0); } @@ -192,27 +194,27 @@ public class ViewKeyMainFragment extends Fragment implements static final String[] KEYRING_PROJECTION = new String[]{KeychainContract.KeyRings._ID, KeychainContract.KeyRings.MASTER_KEY_ID, - KeychainContract.UserIds.USER_ID}; + KeychainContract.UserIds.USER_ID}; static final int KEYRING_INDEX_ID = 0; static final int KEYRING_INDEX_MASTER_KEY_ID = 1; static final int KEYRING_INDEX_USER_ID = 2; static final String[] USER_IDS_PROJECTION = new String[]{ - KeychainContract.UserIds._ID, - KeychainContract.UserIds.USER_ID, - KeychainContract.UserIds.RANK, + KeychainContract.UserIds._ID, + KeychainContract.UserIds.USER_ID, + KeychainContract.UserIds.RANK, }; static final String USER_IDS_SORT_ORDER = KeychainContract.UserIds.RANK + " COLLATE LOCALIZED ASC"; static final String[] KEYS_PROJECTION = new String[]{KeychainContract.Keys._ID, KeychainContract.Keys.KEY_ID, - KeychainContract.Keys.IS_MASTER_KEY, KeychainContract.Keys.ALGORITHM, - KeychainContract.Keys.KEY_SIZE, KeychainContract.Keys.CAN_CERTIFY, - KeychainContract.Keys.CAN_SIGN, KeychainContract.Keys.CAN_ENCRYPT, - KeychainContract.Keys.IS_REVOKED, KeychainContract.Keys.CREATION, - KeychainContract.Keys.EXPIRY, KeychainContract.Keys.FINGERPRINT}; + KeychainContract.Keys.IS_MASTER_KEY, KeychainContract.Keys.ALGORITHM, + KeychainContract.Keys.KEY_SIZE, KeychainContract.Keys.CAN_CERTIFY, + KeychainContract.Keys.CAN_SIGN, KeychainContract.Keys.CAN_ENCRYPT, + KeychainContract.Keys.IS_REVOKED, KeychainContract.Keys.CREATION, + KeychainContract.Keys.EXPIRY, KeychainContract.Keys.FINGERPRINT}; static final String KEYS_SORT_ORDER = KeychainContract.Keys.RANK + " ASC"; static final int KEYS_INDEX_ID = 0; static final int KEYS_INDEX_KEY_ID = 1; @@ -297,7 +299,7 @@ public class ViewKeyMainFragment extends Fragment implements mCreation.setText( DateFormat.getDateFormat(getActivity().getApplicationContext()).format( - creationDate)); + creationDate)); } // get expiry date from EXPIRY @@ -308,7 +310,7 @@ public class ViewKeyMainFragment extends Fragment implements mExpiry.setText( DateFormat.getDateFormat(getActivity().getApplicationContext()).format( - expiryDate)); + expiryDate)); } String algorithmStr = PgpKeyHelper.getAlgorithmInfo( @@ -324,17 +326,20 @@ public class ViewKeyMainFragment extends Fragment implements mFingerprint.setText(PgpKeyHelper.colorizeFingerprint(fingerprint)); } - int valid_keys = 0; + + // hide encrypt button if no encryption key is available + boolean canEncrypt = false; data.moveToFirst(); - do{ - if(data.getInt(KEYS_INDEX_CAN_ENCRYPT) == 1){ - valid_keys++; + do { + if (data.getInt(KEYS_INDEX_CAN_ENCRYPT) == 1) { + canEncrypt = true; + break; } - }while(data.moveToNext()); - if(valid_keys == 0){ + } while (data.moveToNext()); + if (!canEncrypt) { mActionEncrypt.setVisibility(View.GONE); } - Log.i("Valid Encryption keys", Integer.toString(valid_keys)); + mKeysAdapter.swapCursor(data); break; -- cgit v1.2.3 From 9542dc0e12a61535c2866a70cdd9266aff6cd9d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 13:07:32 +0100 Subject: Accounts API, user interface --- .../remote/ui/AccountSettingsActivity.java | 110 ++++++++++++++++++ .../keychain/remote/ui/AccountsListFragment.java | 127 ++++++++++----------- .../keychain/remote/ui/AppSettingsActivity.java | 38 +++--- .../keychain/remote/ui/AppSettingsFragment.java | 10 +- 4 files changed, 194 insertions(+), 91 deletions(-) create mode 100644 OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java new file mode 100644 index 000000000..1092c7dc8 --- /dev/null +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2013 Dominik Schürmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.support.v7.app.ActionBarActivity; +import android.view.MenuItem; +import android.view.View; + +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ActionBarHelper; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.remote.AccountSettings; +import org.sufficientlysecure.keychain.util.Log; + +public class AccountSettingsActivity extends ActionBarActivity { + private Uri mAccountUri; + + private AccountSettingsFragment mAccountSettingsFragment; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Inflate a "Done" custom action bar + ActionBarHelper.setOneButtonView(getSupportActionBar(), + R.string.api_settings_save, R.drawable.ic_action_done, + new View.OnClickListener() { + @Override + public void onClick(View v) { + // "Done" + save(); + } + }); + + setContentView(R.layout.api_account_settings_activity); + + mAccountSettingsFragment = (AccountSettingsFragment) getSupportFragmentManager().findFragmentById( + R.id.api_account_settings_fragment); + + Intent intent = getIntent(); + mAccountUri = intent.getData(); + if (mAccountUri == null) { + Log.e(Constants.TAG, "Intent data missing. Should be Uri of app!"); + finish(); + return; + } else { + Log.d(Constants.TAG, "uri: " + mAccountUri); + loadData(savedInstanceState, mAccountUri); + } + } + +// @Override +// public boolean onCreateOptionsMenu(Menu menu) { +// super.onCreateOptionsMenu(menu); +// getMenuInflater().inflate(R.menu.api_app_settings, menu); +// return true; +// } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_api_settings_revoke: + deleteAccount(); + return true; + case R.id.menu_api_settings_cancel: + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + private void loadData(Bundle savedInstanceState, Uri accountUri) { + // TODO: load this also like other fragment with newInstance arguments? + AccountSettings settings = ProviderHelper.getApiAccountSettings(this, accountUri); + mAccountSettingsFragment.setAccSettings(settings); + } + + private void deleteAccount() { + if (getContentResolver().delete(mAccountUri, null, null) <= 0) { + throw new RuntimeException(); + } + finish(); + } + + private void save() { + ProviderHelper.updateApiAccount(this, mAccountSettingsFragment.getAccSettings(), mAccountUri); + + finish(); + } + +} diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java index 853dc2d3c..22ee7db76 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Dominik Schürmann + * Copyright (C) 2014 Dominik Schürmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,35 +17,35 @@ package org.sufficientlysecure.keychain.remote.ui; -import android.annotation.TargetApi; -import android.content.ContentUris; +import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; -import android.os.Build; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; +import android.support.v4.widget.CursorAdapter; +import android.view.LayoutInflater; import android.view.View; +import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; -import android.widget.SimpleCursorAdapter; +import android.widget.TextView; +import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.provider.KeychainContract; -import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps; +import org.sufficientlysecure.keychain.util.Log; -// TODO: make compat with < 11 -@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class AccountsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks { private static final String ARG_DATA_URI = "uri"; // This is the Adapter being used to display the list's data. - SimpleCursorAdapter mAdapter; + AccountsAdapter mAdapter; private Uri mDataUri; @@ -72,10 +72,14 @@ public class AccountsListFragment extends ListFragment implements getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int position, long id) { -// // edit app settings -// Intent intent = new Intent(getActivity(), AppSettingsActivity.class); -// intent.setData(ContentUris.withAppendedId(ApiApps.CONTENT_URI, id)); -// startActivity(intent); + String selectedAccountName = mAdapter.getItemAccountName(position); + Uri accountUri = mDataUri.buildUpon().appendEncodedPath(selectedAccountName).build(); + Log.d(Constants.TAG, "accountUri: " + accountUri); + + // edit account settings + Intent intent = new Intent(getActivity(), AccountSettingsActivity.class); + intent.setData(accountUri); + startActivity(intent); } }); @@ -87,12 +91,7 @@ public class AccountsListFragment extends ListFragment implements setHasOptionsMenu(true); // Create an empty adapter we will use to display the loaded data. - mAdapter = new SimpleCursorAdapter(getActivity(), - android.R.layout.simple_list_item_1, - null, - new String[]{KeychainContract.ApiAccounts.ACCOUNT_NAME}, - new int[]{android.R.id.text1}, - 0); + mAdapter = new AccountsAdapter(getActivity(), null, 0); setListAdapter(mAdapter); // Prepare the loader. Either re-connect with an existing one, @@ -102,15 +101,13 @@ public class AccountsListFragment extends ListFragment implements // These are the Contacts rows that we will retrieve. static final String[] PROJECTION = new String[]{ - KeychainContract.ApiAccounts._ID, - KeychainContract.ApiAccounts.ACCOUNT_NAME}; + KeychainContract.ApiAccounts._ID, // 0 + KeychainContract.ApiAccounts.ACCOUNT_NAME // 1 + }; public Loader onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader, so we don't care about the ID. - // First, pick the base URI to use depending on whether we are - // currently filtering. -// Uri baseUri = KeychainContract.ApiAccounts.buildBaseUri(mPackageName); // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. @@ -131,46 +128,46 @@ public class AccountsListFragment extends ListFragment implements mAdapter.swapCursor(null); } -// private class RegisteredAppsAdapter extends CursorAdapter { -// -// private LayoutInflater mInflater; -// private PackageManager mPM; -// -// public RegisteredAppsAdapter(Context context, Cursor c, int flags) { -// super(context, c, flags); -// -// mInflater = LayoutInflater.from(context); -// mPM = context.getApplicationContext().getPackageManager(); -// } -// -// @Override -// public void bindView(View view, Context context, Cursor cursor) { -// TextView text = (TextView) view.findViewById(R.id.api_apps_adapter_item_name); -// ImageView icon = (ImageView) view.findViewById(R.id.api_apps_adapter_item_icon); -// -// String packageName = cursor.getString(cursor.getColumnIndex(ApiApps.PACKAGE_NAME)); -// if (packageName != null) { -// // get application name -// try { -// ApplicationInfo ai = mPM.getApplicationInfo(packageName, 0); -// -// text.setText(mPM.getApplicationLabel(ai)); -// icon.setImageDrawable(mPM.getApplicationIcon(ai)); -// } catch (final PackageManager.NameNotFoundException e) { -// // fallback -// text.setText(packageName); -// } -// } else { -// // fallback -// text.setText(packageName); -// } -// -// } -// -// @Override -// public View newView(Context context, Cursor cursor, ViewGroup parent) { -// return mInflater.inflate(R.layout.api_apps_adapter_list_item, null); -// } -// } + private class AccountsAdapter extends CursorAdapter { + private LayoutInflater mInflater; + + public AccountsAdapter(Context context, Cursor c, int flags) { + super(context, c, flags); + + mInflater = LayoutInflater.from(context); + } + + /** + * Similar to CursorAdapter.getItemId(). + * Required to build Uris for api app view, which is not based on row ids + * + * @param position + * @return + */ + public String getItemAccountName(int position) { + if (mDataValid && mCursor != null) { + if (mCursor.moveToPosition(position)) { + return mCursor.getString(1); + } else { + return null; + } + } else { + return null; + } + } + + @Override + public void bindView(View view, Context context, Cursor cursor) { + TextView text = (TextView) view.findViewById(R.id.api_accounts_adapter_item_name); + + String accountName = cursor.getString(1); + text.setText(accountName); + } + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return mInflater.inflate(R.layout.api_accounts_adapter_list_item, null); + } + } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java index 33cde49ba..e4b943734 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java @@ -18,16 +18,17 @@ package org.sufficientlysecure.keychain.remote.ui; import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; +import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; -import android.view.View; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.remote.AppSettings; @@ -43,16 +44,11 @@ public class AppSettingsActivity extends ActionBarActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - // Inflate a "Done" custom action bar - ActionBarHelper.setOneButtonView(getSupportActionBar(), - R.string.api_settings_save, R.drawable.ic_action_done, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // "Done" - save(); - } - }); + // let the actionbar look like Android's contact app + ActionBar actionBar = getSupportActionBar(); + actionBar.setDisplayHomeAsUpEnabled(true); + actionBar.setIcon(android.R.color.transparent); + actionBar.setHomeButtonEnabled(true); setContentView(R.layout.api_app_settings_activity); @@ -96,6 +92,18 @@ public class AppSettingsActivity extends ActionBarActivity { AppSettings settings = ProviderHelper.getApiAppSettings(this, appUri); mSettingsFragment.setAppSettings(settings); + String appName; + PackageManager pm = getPackageManager(); + try { + ApplicationInfo ai = pm.getApplicationInfo(settings.getPackageName(), 0); + appName = (String) pm.getApplicationLabel(ai); + } catch (PackageManager.NameNotFoundException e) { + // fallback + appName = settings.getPackageName(); + } + setTitle(appName); + + Uri accountsUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ACCOUNTS).build(); Log.d(Constants.TAG, "accountsUri: " + accountsUri); startListFragment(savedInstanceState, accountsUri); @@ -128,10 +136,4 @@ public class AppSettingsActivity extends ActionBarActivity { finish(); } - private void save() { - ProviderHelper.updateApiApp(this, mSettingsFragment.getAppSettings(), mAppUri); - - finish(); - } - } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java index 8bcd83fc7..5a6151d88 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java @@ -26,19 +26,13 @@ import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageView; -import android.widget.Spinner; import android.widget.TextView; import org.spongycastle.util.encoders.Hex; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.remote.AppSettings; -import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; -import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; -import org.sufficientlysecure.keychain.util.AlgorithmNames; import org.sufficientlysecure.keychain.util.Log; import java.security.MessageDigest; @@ -100,14 +94,14 @@ public class AppSettingsFragment extends Fragment { PackageManager pm = getActivity().getApplicationContext().getPackageManager(); // get application name and icon from package manager - String appName = null; + String appName; Drawable appIcon = null; try { ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); appName = (String) pm.getApplicationLabel(ai); appIcon = pm.getApplicationIcon(ai); - } catch (final NameNotFoundException e) { + } catch (NameNotFoundException e) { // fallback appName = packageName; } -- cgit v1.2.3 From 8d23ba968a033cd29ac63216ad4f2179222b0cbf Mon Sep 17 00:00:00 2001 From: uberspot Date: Wed, 26 Mar 2014 14:06:40 +0200 Subject: add strike through text for revoked or expired keys and disable views for revoked keys as well --- .../keychain/helper/OtherHelper.java | 14 +++++++------ .../keychain/ui/adapter/ViewKeyKeysAdapter.java | 23 ++++++++++++++++++---- 2 files changed, 27 insertions(+), 10 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java index d0ba20ea6..b31a889f0 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/helper/OtherHelper.java @@ -17,18 +17,14 @@ package org.sufficientlysecure.keychain.helper; -import android.graphics.Color; import android.os.Bundle; -import android.text.Spannable; import android.text.SpannableStringBuilder; -import android.text.style.ForegroundColorSpan; +import android.text.Spanned; +import android.text.style.StrikethroughSpan; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.util.Log; -import java.security.DigestException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Set; @@ -65,4 +61,10 @@ public class OtherHelper { } } + public static SpannableStringBuilder strikeOutText(CharSequence text) { + SpannableStringBuilder sb = new SpannableStringBuilder(text); + sb.setSpan(new StrikethroughSpan(), 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); + return sb; + } + } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index d925480e9..ed4113fb8 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -29,6 +29,7 @@ import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract.Keys; @@ -126,28 +127,42 @@ public class ViewKeyKeysAdapter extends CursorAdapter { signIcon.setVisibility(View.VISIBLE); } + boolean valid = true; if (cursor.getInt(mIndexRevokedKey) > 0) { revokedKeyIcon.setVisibility(View.VISIBLE); + keyId.setTextColor(Color.RED); keyDetails.setTextColor(Color.RED); + keyExpiry.setTextColor(Color.RED); + + valid = false; } else { keyId.setTextColor(mDefaultTextColor); keyDetails.setTextColor(mDefaultTextColor); + keyExpiry.setTextColor(mDefaultTextColor); + revokedKeyIcon.setVisibility(View.GONE); } - boolean valid = true; if (!cursor.isNull(mIndexExpiry)) { Date expiryDate = new Date(cursor.getLong(mIndexExpiry) * 1000); - valid = expiryDate.after(new Date()); + + valid = valid && expiryDate.after(new Date()); keyExpiry.setText("(" + - context.getString(R.string.label_expiry) + ": " + - DateFormat.getDateFormat(context).format(expiryDate) + ")"); + context.getString(R.string.label_expiry) + ": " + + DateFormat.getDateFormat(context).format(expiryDate) + ")"); + keyExpiry.setVisibility(View.VISIBLE); } else { keyExpiry.setVisibility(View.GONE); } + // if key is expired or revoked, strike through text + if (!valid) { + keyId.setText(OtherHelper.strikeOutText(keyId.getText())); + keyDetails.setText(OtherHelper.strikeOutText(keyDetails.getText())); + keyExpiry.setText(OtherHelper.strikeOutText(keyExpiry.getText())); + } keyId.setEnabled(valid); keyDetails.setEnabled(valid); keyExpiry.setEnabled(valid); -- cgit v1.2.3 From 92a4d0e914d7cd132b7e755caf914710969e512d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 13:21:29 +0100 Subject: Part 2 of basic user interface for api accounts --- .../remote/ui/AccountSettingsActivity.java | 17 ++--- .../remote/ui/AccountSettingsFragment.java | 79 +++++++++------------- 2 files changed, 41 insertions(+), 55 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java index 1092c7dc8..671a3e0aa 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java @@ -21,6 +21,7 @@ import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; +import android.view.Menu; import android.view.MenuItem; import android.view.View; @@ -68,20 +69,20 @@ public class AccountSettingsActivity extends ActionBarActivity { } } -// @Override -// public boolean onCreateOptionsMenu(Menu menu) { -// super.onCreateOptionsMenu(menu); -// getMenuInflater().inflate(R.menu.api_app_settings, menu); -// return true; -// } + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + getMenuInflater().inflate(R.menu.api_account_settings, menu); + return true; + } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.menu_api_settings_revoke: + case R.id.menu_account_settings_delete: deleteAccount(); return true; - case R.id.menu_api_settings_cancel: + case R.id.menu_account_settings_cancel: finish(); return true; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java index 3d88d216e..91e74f2bf 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java @@ -17,6 +17,7 @@ package org.sufficientlysecure.keychain.remote.ui; +import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; @@ -32,11 +33,14 @@ import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; +import com.beardedhen.androidbootstrap.BootstrapButton; + import org.spongycastle.util.encoders.Hex; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.remote.AccountSettings; import org.sufficientlysecure.keychain.remote.AppSettings; +import org.sufficientlysecure.keychain.ui.EditKeyActivity; import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; import org.sufficientlysecure.keychain.util.AlgorithmNames; @@ -52,15 +56,13 @@ public class AccountSettingsFragment extends Fragment implements private AccountSettings mAccSettings; // view - private TextView mAppNameView; - private ImageView mAppIconView; + private TextView mAccNameView; private Spinner mEncryptionAlgorithm; private Spinner mHashAlgorithm; private Spinner mCompression; - private TextView mPackageName; - private TextView mPackageSignature; private SelectSecretKeyLayoutFragment mSelectKeyFragment; + private BootstrapButton mCreateKeyButton; KeyValueSpinnerAdapter mEncryptionAdapter; KeyValueSpinnerAdapter mHashAdapter; @@ -70,27 +72,15 @@ public class AccountSettingsFragment extends Fragment implements return mAccSettings; } - public void setAccSettings(AccountSettings appSettings) { - this.mAccSettings = appSettings; -// setPackage(appSettings.getPackageName()); -// mPackageName.setText(appSettings.getPackageName()); - -// try { -// MessageDigest md = MessageDigest.getInstance("SHA-256"); -// md.update(appSettings.getPackageSignature()); -// byte[] digest = md.digest(); -// String signature = new String(Hex.encode(digest)); -// -// mPackageSignature.setText(signature); -// } catch (NoSuchAlgorithmException e) { -// Log.e(Constants.TAG, "Should not happen!", e); -// } - - mSelectKeyFragment.selectKey(appSettings.getKeyId()); - mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(appSettings + public void setAccSettings(AccountSettings accountSettings) { + this.mAccSettings = accountSettings; + + mAccNameView.setText(accountSettings.getAccountName()); + mSelectKeyFragment.selectKey(accountSettings.getKeyId()); + mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(accountSettings .getEncryptionAlgorithm())); - mHashAlgorithm.setSelection(mHashAdapter.getPosition(appSettings.getHashAlgorithm())); - mCompression.setSelection(mCompressionAdapter.getPosition(appSettings.getCompression())); + mHashAlgorithm.setSelection(mHashAdapter.getPosition(accountSettings.getHashAlgorithm())); + mCompression.setSelection(mCompressionAdapter.getPosition(accountSettings.getCompression())); } /** @@ -117,14 +107,19 @@ public class AccountSettingsFragment extends Fragment implements R.id.api_account_settings_select_key_fragment); mSelectKeyFragment.setCallback(this); - mAppNameView = (TextView) view.findViewById(R.id.api_account_settings_app_name); - mAppIconView = (ImageView) view.findViewById(R.id.api_account_settings_app_icon); + mAccNameView = (TextView) view.findViewById(R.id.api_account_settings_acc_name); mEncryptionAlgorithm = (Spinner) view .findViewById(R.id.api_account_settings_encryption_algorithm); mHashAlgorithm = (Spinner) view.findViewById(R.id.api_account_settings_hash_algorithm); mCompression = (Spinner) view.findViewById(R.id.api_account_settings_compression); - mPackageName = (TextView) view.findViewById(R.id.api_account_settings_package_name); - mPackageSignature = (TextView) view.findViewById(R.id.api_account_settings_package_signature); + mCreateKeyButton = (BootstrapButton) view.findViewById(R.id.api_account_settings_create_key); + + mCreateKeyButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + createKey(); + } + }); AlgorithmNames algorithmNames = new AlgorithmNames(getActivity()); @@ -172,25 +167,15 @@ public class AccountSettingsFragment extends Fragment implements } }); } -// -// private void setPackage(String packageName) { -// PackageManager pm = getActivity().getApplicationContext().getPackageManager(); -// -// // get application name and icon from package manager -// String appName = null; -// Drawable appIcon = null; -// try { -// ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); -// -// appName = (String) pm.getApplicationLabel(ai); -// appIcon = pm.getApplicationIcon(ai); -// } catch (final NameNotFoundException e) { -// // fallback -// appName = packageName; -// } -// mAppNameView.setText(appName); -// mAppIconView.setImageDrawable(appIcon); -// } + + private void createKey() { + Intent intent = new Intent(getActivity(), EditKeyActivity.class); + intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); + intent.putExtra(EditKeyActivity.EXTRA_GENERATE_DEFAULT_KEYS, true); + // set default user id to account name TODO: not working currently in EditKey + intent.putExtra(EditKeyActivity.EXTRA_USER_IDS, mAccSettings.getAccountName()); + startActivityForResult(intent, 0); + } /** * callback from select secret key fragment -- cgit v1.2.3 From f10235220d08628892432142ad632512e3f2c68e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 13:32:36 +0100 Subject: Forgot resource --- .../keychain/remote/ui/AccountSettingsFragment.java | 12 ------------ 1 file changed, 12 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java index 91e74f2bf..0931e6e31 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java @@ -18,10 +18,6 @@ package org.sufficientlysecure.keychain.remote.ui; import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; @@ -29,25 +25,17 @@ import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import com.beardedhen.androidbootstrap.BootstrapButton; -import org.spongycastle.util.encoders.Hex; -import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.remote.AccountSettings; -import org.sufficientlysecure.keychain.remote.AppSettings; import org.sufficientlysecure.keychain.ui.EditKeyActivity; import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; import org.sufficientlysecure.keychain.util.AlgorithmNames; -import org.sufficientlysecure.keychain.util.Log; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; public class AccountSettingsFragment extends Fragment implements SelectSecretKeyLayoutFragment.SelectSecretKeyCallback { -- cgit v1.2.3 From c8b77171051a4b7403c3a62e526798a40e250898 Mon Sep 17 00:00:00 2001 From: uberspot Date: Wed, 26 Mar 2014 14:45:56 +0200 Subject: fix capability icons and remove red text for revoked keys --- .../sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java | 4 ---- 1 file changed, 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java index ed4113fb8..9d60c1530 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ViewKeyKeysAdapter.java @@ -131,10 +131,6 @@ public class ViewKeyKeysAdapter extends CursorAdapter { if (cursor.getInt(mIndexRevokedKey) > 0) { revokedKeyIcon.setVisibility(View.VISIBLE); - keyId.setTextColor(Color.RED); - keyDetails.setTextColor(Color.RED); - keyExpiry.setTextColor(Color.RED); - valid = false; } else { keyId.setTextColor(mDefaultTextColor); -- cgit v1.2.3 From ec3459733180a5d83805b6fe9ddf5571f7b0380f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 14:11:28 +0100 Subject: Make PendingIntents with FLAG_CANCEL_CURRENT and FLAG_ONE_SHOT --- .../keychain/remote/OpenPgpService.java | 29 ++++++------- .../keychain/remote/RemoteService.java | 24 ++++++----- .../keychain/remote/ui/AppSettingsFragment.java | 47 ++++++++++------------ .../keychain/remote/ui/RemoteServiceActivity.java | 1 + 4 files changed, 50 insertions(+), 51 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java index fa6ccf63b..ad0c658ad 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java @@ -23,6 +23,7 @@ import android.database.Cursor; import android.net.Uri; import android.os.IBinder; import android.os.ParcelFileDescriptor; + import org.openintents.openpgp.IOpenPgpService; import org.openintents.openpgp.OpenPgpError; import org.openintents.openpgp.OpenPgpSignatureResult; @@ -47,10 +48,6 @@ import java.util.ArrayList; public class OpenPgpService extends RemoteService { - private static final int PRIVATE_REQUEST_CODE_PASSPHRASE = 551; - private static final int PRIVATE_REQUEST_CODE_USER_IDS = 552; - private static final int PRIVATE_REQUEST_CODE_GET_KEYS = 553; - /** * Search database for key ids based on emails. * @@ -100,8 +97,9 @@ public class OpenPgpService extends RemoteService { intent.putExtra(RemoteServiceActivity.EXTRA_DUBLICATE_USER_IDS, dublicateUserIds); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity - (getBaseContext(), PRIVATE_REQUEST_CODE_USER_IDS, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -127,8 +125,9 @@ public class OpenPgpService extends RemoteService { intent.putExtra(RemoteServiceActivity.EXTRA_SECRET_KEY_ID, keyId); // pass params through to activity that it can be returned again later to repeat pgp operation intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity - (getBaseContext(), PRIVATE_REQUEST_CODE_PASSPHRASE, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -211,7 +210,7 @@ public class OpenPgpService extends RemoteService { Intent result = new Intent(); result.putExtra(OpenPgpApi.RESULT_ERROR, new OpenPgpError(OpenPgpError.GENERIC_ERROR, - "Missing parameter user_ids or key_ids!")); + "Missing parameter user_ids or key_ids!")); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); return result; } @@ -318,8 +317,9 @@ public class OpenPgpService extends RemoteService { intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, "todo"); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_GET_KEYS, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); result.putExtra(OpenPgpApi.RESULT_INTENT, pi); } @@ -358,8 +358,9 @@ public class OpenPgpService extends RemoteService { intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, "todo"); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_GET_KEYS, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); result.putExtra(OpenPgpApi.RESULT_INTENT, pi); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); @@ -408,7 +409,7 @@ public class OpenPgpService extends RemoteService { if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != OpenPgpApi.API_VERSION) { Intent result = new Intent(); OpenPgpError error = new OpenPgpError - (OpenPgpError.INCOMPATIBLE_API_VERSIONS, "Incompatible API versions!"); + (OpenPgpError.INCOMPATIBLE_API_VERSIONS, "Incompatible API versions!"); result.putExtra(OpenPgpApi.RESULT_ERROR, error); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); return result; diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java index 7e935d317..8cea3cd21 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java @@ -46,9 +46,6 @@ import java.util.Arrays; public abstract class RemoteService extends Service { Context mContext; - private static final int PRIVATE_REQUEST_CODE_REGISTER = 651; - private static final int PRIVATE_REQUEST_CODE_ERROR = 652; - public Context getContext() { return mContext; } @@ -59,6 +56,7 @@ public abstract class RemoteService extends Service { return null; } else { String packageName = getCurrentCallingPackage(); + Log.d(Constants.TAG, "isAllowed packageName: " + packageName); byte[] packageSignature; try { @@ -80,8 +78,9 @@ public abstract class RemoteService extends Service { intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_SIGNATURE, packageSignature); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_REGISTER, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -99,8 +98,9 @@ public abstract class RemoteService extends Service { getString(R.string.api_error_wrong_signature)); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_ERROR, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -163,8 +163,9 @@ public abstract class RemoteService extends Service { intent.putExtra(RemoteServiceActivity.EXTRA_ACC_NAME, accountName); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); - PendingIntent pi = PendingIntent.getActivity(getBaseContext(), - PRIVATE_REQUEST_CODE_REGISTER, intent, 0); + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); // return PendingIntent to be executed by client Intent result = new Intent(); @@ -206,7 +207,7 @@ public abstract class RemoteService extends Service { } } - Log.d(Constants.TAG, "Caller is NOT allowed!"); + Log.d(Constants.TAG, "Uid is NOT allowed!"); return false; } @@ -218,7 +219,7 @@ public abstract class RemoteService extends Service { * @throws WrongPackageSignatureException */ private boolean isPackageAllowed(String packageName) throws WrongPackageSignatureException { - Log.d(Constants.TAG, "packageName: " + packageName); + Log.d(Constants.TAG, "isPackageAllowed packageName: " + packageName); ArrayList allowedPkgs = ProviderHelper.getRegisteredApiApps(this); Log.d(Constants.TAG, "allowed: " + allowedPkgs); @@ -246,6 +247,7 @@ public abstract class RemoteService extends Service { } } + Log.d(Constants.TAG, "Package is NOT allowed! packageName: " + packageName); return false; } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java index 5a6151d88..a6db02708 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsFragment.java @@ -55,20 +55,7 @@ public class AppSettingsFragment extends Fragment { public void setAppSettings(AppSettings appSettings) { this.mAppSettings = appSettings; - setPackage(appSettings.getPackageName()); - mPackageName.setText(appSettings.getPackageName()); - - try { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(appSettings.getPackageSignature()); - byte[] digest = md.digest(); - String signature = new String(Hex.encode(digest)); - - mPackageSignature.setText(signature); - } catch (NoSuchAlgorithmException e) { - Log.e(Constants.TAG, "Should not happen!", e); - } - + updateView(appSettings); } /** @@ -77,36 +64,44 @@ public class AppSettingsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.api_app_settings_fragment, container, false); - initView(view); - return view; - } - - - private void initView(View view) { mAppNameView = (TextView) view.findViewById(R.id.api_app_settings_app_name); mAppIconView = (ImageView) view.findViewById(R.id.api_app_settings_app_icon); - mPackageName = (TextView) view.findViewById(R.id.api_app_settings_package_name); mPackageSignature = (TextView) view.findViewById(R.id.api_app_settings_package_signature); + return view; } - private void setPackage(String packageName) { - PackageManager pm = getActivity().getApplicationContext().getPackageManager(); - + private void updateView(AppSettings appSettings) { // get application name and icon from package manager String appName; Drawable appIcon = null; + PackageManager pm = getActivity().getApplicationContext().getPackageManager(); try { - ApplicationInfo ai = pm.getApplicationInfo(packageName, 0); + ApplicationInfo ai = pm.getApplicationInfo(appSettings.getPackageName(), 0); appName = (String) pm.getApplicationLabel(ai); appIcon = pm.getApplicationIcon(ai); } catch (NameNotFoundException e) { // fallback - appName = packageName; + appName = appSettings.getPackageName(); } mAppNameView.setText(appName); mAppIconView.setImageDrawable(appIcon); + + // advanced info: package name + mPackageName.setText(appSettings.getPackageName()); + + // advanced info: package signature SHA-256 + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(appSettings.getPackageSignature()); + byte[] digest = md.digest(); + String signature = new String(Hex.encode(digest)); + + mPackageSignature.setText(signature); + } catch (NoSuchAlgorithmException e) { + Log.e(Constants.TAG, "Should not happen!", e); + } } diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java index d3ac5cade..ba0d4d088 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java @@ -95,6 +95,7 @@ public class RemoteServiceActivity extends ActionBarActivity { if (ACTION_REGISTER.equals(action)) { final String packageName = extras.getString(EXTRA_PACKAGE_NAME); final byte[] packageSignature = extras.getByteArray(EXTRA_PACKAGE_SIGNATURE); + Log.d(Constants.TAG, "ACTION_REGISTER packageName: "+packageName); // Inflate a "Done"/"Cancel" custom action bar view ActionBarHelper.setTwoButtonView(getSupportActionBar(), -- cgit v1.2.3 From 65857d2b5fea5cbb5d156b1b4ddfd68ded311624 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 17:43:26 +0100 Subject: Accounts list prettified --- .../keychain/remote/ui/AccountsListFragment.java | 27 ++++++++++++++++++++++ .../keychain/remote/ui/AppSettingsActivity.java | 1 - 2 files changed, 27 insertions(+), 1 deletion(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java index 22ee7db76..8e65a2f04 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountsListFragment.java @@ -32,11 +32,15 @@ import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; +import android.widget.LinearLayout; +import android.widget.ListView; import android.widget.TextView; import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.ui.widget.FixedListView; import org.sufficientlysecure.keychain.util.Log; public class AccountsListFragment extends ListFragment implements @@ -63,6 +67,29 @@ public class AccountsListFragment extends ListFragment implements return frag; } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View layout = super.onCreateView(inflater, container, + savedInstanceState); + ListView lv = (ListView) layout.findViewById(android.R.id.list); + ViewGroup parent = (ViewGroup) lv.getParent(); + + /* + * http://stackoverflow.com/a/15880684 + * Remove ListView and add FixedListView in its place. + * This is done here programatically to be still able to use the progressBar of ListFragment. + * + * We want FixedListView to be able to put this ListFragment inside a ScrollView + */ + int lvIndex = parent.indexOfChild(lv); + parent.removeViewAt(lvIndex); + FixedListView newLv = new FixedListView(getActivity()); + newLv.setId(android.R.id.list); + parent.addView(newLv, lvIndex, lv.getLayoutParams()); + return layout; + } + @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java index e4b943734..9e0ba49eb 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AppSettingsActivity.java @@ -103,7 +103,6 @@ public class AppSettingsActivity extends ActionBarActivity { } setTitle(appName); - Uri accountsUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ACCOUNTS).build(); Log.d(Constants.TAG, "accountsUri: " + accountsUri); startListFragment(savedInstanceState, accountsUri); -- cgit v1.2.3 From 2e063a42ed9a0d2976b52b8bc40a12672f3ae166 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 17:55:48 +0100 Subject: Fix provider for API_ACCOUNTS --- .../keychain/provider/KeychainContract.java | 2 +- .../keychain/provider/KeychainDatabase.java | 6 +++--- .../keychain/provider/KeychainProvider.java | 12 ++++++------ 3 files changed, 10 insertions(+), 10 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java index 6e4899fc2..e7b31bf65 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainContract.java @@ -65,7 +65,7 @@ public class KeychainContract { String ENCRYPTION_ALGORITHM = "encryption_algorithm"; String HASH_ALORITHM = "hash_algorithm"; String COMPRESSION = "compression"; - String PACKAGE_NAME_FK = "package_name"; // foreign key to api_apps.package_name + String PACKAGE_NAME = "package_name"; // foreign key to api_apps.package_name } public static final class KeyTypes { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java index 4abcec435..8c33844b2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java @@ -88,10 +88,10 @@ public class KeychainDatabase extends SQLiteOpenHelper { + ApiAppsAccountsColumns.ENCRYPTION_ALGORITHM + " INTEGER, " + ApiAppsAccountsColumns.HASH_ALORITHM + " INTEGER, " + ApiAppsAccountsColumns.COMPRESSION + " INTEGER, " - + ApiAppsAccountsColumns.PACKAGE_NAME_FK + " TEXT NOT NULL, " + + ApiAppsAccountsColumns.PACKAGE_NAME + " TEXT NOT NULL, " + "UNIQUE(" + ApiAppsAccountsColumns.ACCOUNT_NAME + ", " - + ApiAppsAccountsColumns.PACKAGE_NAME_FK + "), " - + "FOREIGN KEY(" + ApiAppsAccountsColumns.PACKAGE_NAME_FK + ") REFERENCES " + + ApiAppsAccountsColumns.PACKAGE_NAME + "), " + + "FOREIGN KEY(" + ApiAppsAccountsColumns.PACKAGE_NAME + ") REFERENCES " + Tables.API_APPS + "(" + ApiAppsColumns.PACKAGE_NAME + ") ON DELETE CASCADE)"; KeychainDatabase(Context context) { diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java index 6469da978..1c5e3ab36 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainProvider.java @@ -687,13 +687,13 @@ public class KeychainProvider extends ContentProvider { break; case API_ACCOUNTS: qb.setTables(Tables.API_ACCOUNTS); + qb.appendWhere(Tables.API_ACCOUNTS + "." + ApiAccounts.PACKAGE_NAME + " = "); + qb.appendWhereEscapeString(uri.getPathSegments().get(1)); break; case API_ACCOUNTS_BY_ACCOUNT_NAME: - qb.setTables(Tables.API_ACCOUNTS + " INNER JOIN " + Tables.API_APPS + " ON " + "(" - + Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = " + Tables.API_ACCOUNTS + "." - + ApiAccounts.PACKAGE_NAME_FK + " )"); - qb.appendWhere(Tables.API_APPS + "." + ApiApps.PACKAGE_NAME + " = "); + qb.setTables(Tables.API_ACCOUNTS); + qb.appendWhere(Tables.API_ACCOUNTS + "." + ApiAccounts.PACKAGE_NAME + " = "); qb.appendWhereEscapeString(uri.getPathSegments().get(1)); qb.appendWhere(" AND " + Tables.API_ACCOUNTS + "." + ApiAccounts.ACCOUNT_NAME + " = "); @@ -800,7 +800,7 @@ public class KeychainProvider extends ContentProvider { // set foreign key automatically based on given uri // e.g., api_apps/com.example.app/accounts/ String packageName = uri.getPathSegments().get(1); - values.put(ApiAccounts.PACKAGE_NAME_FK, packageName); + values.put(ApiAccounts.PACKAGE_NAME, packageName); Log.d(Constants.TAG, "provider packageName: " + packageName); @@ -1061,7 +1061,7 @@ public class KeychainProvider extends ContentProvider { andSelection = " AND (" + selection + ")"; } - return ApiAccounts.PACKAGE_NAME_FK + "=" + packageName + " AND " + return ApiAccounts.PACKAGE_NAME + "=" + packageName + " AND " + ApiAccounts.ACCOUNT_NAME + "=" + accountName + andSelection; } -- cgit v1.2.3 From 399106015e6d4a8d08385f9d5d360fe634e5cc56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 18:18:00 +0100 Subject: Rename layouts for remote activity --- .../keychain/remote/ui/RemoteServiceActivity.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java index ba0d4d088..a894da448 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/RemoteServiceActivity.java @@ -124,7 +124,7 @@ public class RemoteServiceActivity extends ActionBarActivity { } ); - setContentView(R.layout.api_app_register_activity); + setContentView(R.layout.api_remote_register_app); mAppSettingsFragment = (AppSettingsFragment) getSupportFragmentManager().findFragmentById( R.id.api_app_settings_fragment); @@ -169,7 +169,7 @@ public class RemoteServiceActivity extends ActionBarActivity { } ); - setContentView(R.layout.api_account_create_activity); + setContentView(R.layout.api_remote_create_account); mAccSettingsFragment = (AccountSettingsFragment) getSupportFragmentManager().findFragmentById( R.id.api_account_settings_fragment); @@ -235,7 +235,7 @@ public class RemoteServiceActivity extends ActionBarActivity { } ); - setContentView(R.layout.api_app_select_pub_keys_activity); + setContentView(R.layout.api_remote_select_pub_keys); // set text on view HtmlTextView textView = (HtmlTextView) findViewById(R.id.api_select_pub_keys_text); @@ -277,7 +277,7 @@ public class RemoteServiceActivity extends ActionBarActivity { } }); - setContentView(R.layout.api_app_error_message); + setContentView(R.layout.api_remote_error_message); // set text on view HtmlTextView textView = (HtmlTextView) findViewById(R.id.api_app_error_message_text); -- cgit v1.2.3 From cc8fd35137d1c8e78727a76a5cceb5f92b234a0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Wed, 26 Mar 2014 18:34:48 +0100 Subject: Show divider only when used --- .../java/org/sufficientlysecure/keychain/ui/KeyListFragment.java | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'OpenPGP-Keychain/src/main/java') diff --git a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index daf455c03..957c822d2 100644 --- a/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenPGP-Keychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -498,11 +498,15 @@ public class KeyListFragment extends Fragment } { // set edit button and revoked info, specific by key type + View statusDivider = (View) view.findViewById(R.id.status_divider); + FrameLayout statusLayout = (FrameLayout) view.findViewById(R.id.status_layout); Button button = (Button) view.findViewById(R.id.edit); TextView revoked = (TextView) view.findViewById(R.id.revoked); if (cursor.getInt(KeyListFragment.INDEX_TYPE) == KeyTypes.SECRET) { // this is a secret key - show the edit button + statusDivider.setVisibility(View.VISIBLE); + statusLayout.setVisibility(View.VISIBLE); revoked.setVisibility(View.GONE); button.setVisibility(View.VISIBLE); @@ -519,9 +523,11 @@ public class KeyListFragment extends Fragment }); } else { // this is a public key - hide the edit button, show if it's revoked + statusDivider.setVisibility(View.GONE); button.setVisibility(View.GONE); boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0; + statusLayout.setVisibility(isRevoked ? View.VISIBLE : View.GONE); revoked.setVisibility(isRevoked ? View.VISIBLE : View.GONE); } } -- cgit v1.2.3