aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyAdvSubkeysFragment.java
blob: b93eccb92bddc9b97af5b01b24b896a32d42fd24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
 *
 * 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 <http://www.gnu.org/licenses/>.
 */

package org.sufficientlysecure.keychain.ui;


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.FragmentActivity;
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.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ViewAnimator;

import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.SecretKeyType;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel.SubkeyChange;
import org.sufficientlysecure.keychain.ui.adapter.SubkeysAdapter;
import org.sufficientlysecure.keychain.ui.adapter.SubkeysAddedAdapter;
import org.sufficientlysecure.keychain.ui.dialog.AddSubkeyDialogFragment;
import org.sufficientlysecure.keychain.ui.dialog.EditSubkeyDialogFragment;
import org.sufficientlysecure.keychain.ui.dialog.EditSubkeyExpiryDialogFragment;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.util.Log;

public class ViewKeyAdvSubkeysFragment extends LoaderFragment implements
        LoaderManager.LoaderCallbacks<Cursor> {

    public static final String ARG_DATA_URI = "data_uri";
    public static final String ARG_HAS_SECRET = "has_secret";

    public static final int LOADER_ID_SUBKEYS = 0;

    private ListView mSubkeysList;
    private ListView mSubkeysAddedList;
    private View mSubkeysAddedLayout;
    private ViewAnimator mSubkeyAddFabLayout;

    private SubkeysAdapter mSubkeysAdapter;
    private SubkeysAddedAdapter mSubkeysAddedAdapter;

    private Uri mDataUriSubkeys;

    private boolean mHasSecret;
    private SaveKeyringParcel mEditModeSaveKeyringParcel;

    /**
     * Creates new instance of this fragment
     */
    public static ViewKeyAdvSubkeysFragment newInstance(Uri dataUri, boolean hasSecret) {
        ViewKeyAdvSubkeysFragment frag = new ViewKeyAdvSubkeysFragment();

        Bundle args = new Bundle();
        args.putParcelable(ARG_DATA_URI, dataUri);
        args.putBoolean(ARG_HAS_SECRET, hasSecret);

        frag.setArguments(args);
        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup superContainer, Bundle savedInstanceState) {
        View root = super.onCreateView(inflater, superContainer, savedInstanceState);
        View view = inflater.inflate(R.layout.view_key_adv_subkeys_fragment, getContainer());

        mSubkeysList = (ListView) view.findViewById(R.id.view_key_subkeys);
        mSubkeysAddedList = (ListView) view.findViewById(R.id.view_key_subkeys_added);
        mSubkeysAddedLayout = view.findViewById(R.id.view_key_subkeys_add_layout);

        mSubkeysList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editSubkey(position);
            }
        });

        View footer = new View(getActivity());
        int spacing = (int) android.util.TypedValue.applyDimension(
                android.util.TypedValue.COMPLEX_UNIT_DIP, 72, getResources().getDisplayMetrics()
        );
        android.widget.AbsListView.LayoutParams params = new android.widget.AbsListView.LayoutParams(
                android.widget.AbsListView.LayoutParams.MATCH_PARENT,
                spacing
        );
        footer.setLayoutParams(params);
        mSubkeysAddedList.addFooterView(footer, null, false);

        mSubkeyAddFabLayout = (ViewAnimator) view.findViewById(R.id.view_key_subkey_fab_layout);
        view.findViewById(R.id.view_key_subkey_fab).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addSubkey();
            }
        });

        setHasOptionsMenu(true);

        return root;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Uri dataUri = getArguments().getParcelable(ARG_DATA_URI);
        if (dataUri == null) {
            Log.e(Constants.TAG, "Data missing. Should be Uri of key!");
            getActivity().finish();
            return;
        }
        mHasSecret = getArguments().getBoolean(ARG_HAS_SECRET);

        loadData(dataUri);
    }

    private void loadData(Uri dataUri) {
        mDataUriSubkeys = KeychainContract.Keys.buildKeysUri(dataUri);

        // Create an empty adapter we will use to display the loaded data.
        mSubkeysAdapter = new SubkeysAdapter(getActivity(), null, 0);
        mSubkeysList.setAdapter(mSubkeysAdapter);

        // Prepare the loaders. Either re-connect with an existing ones,
        // or start new ones.
        getLoaderManager().initLoader(LOADER_ID_SUBKEYS, null, this);
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        setContentShown(false);

        return new CursorLoader(getActivity(), mDataUriSubkeys,
                SubkeysAdapter.SUBKEYS_PROJECTION, null, null, null);
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Avoid NullPointerExceptions, if we get an empty result set.
        if (data.getCount() == 0) {
            return;
        }

        // Swap the new cursor in. (The framework will take care of closing the
        // old cursor once we return.)
        mSubkeysAdapter.swapCursor(data);

        // TODO: maybe show not before both are loaded!
        setContentShown(true);
    }

    /**
     * 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.
     */
    public void onLoaderReset(Loader<Cursor> loader) {
        mSubkeysAdapter.swapCursor(null);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_action_mode_edit:
                enterEditMode();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void enterEditMode() {
        FragmentActivity activity = getActivity();
        if (activity == null) {
            return;
        }
        activity.startActionMode(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {

                mEditModeSaveKeyringParcel = new SaveKeyringParcel(0L, new byte[0]);

                mSubkeysAddedAdapter =
                        new SubkeysAddedAdapter(getActivity(), mEditModeSaveKeyringParcel.mAddSubKeys, false);
                mSubkeysAddedList.setAdapter(mSubkeysAddedAdapter);
                mSubkeysAddedLayout.setVisibility(View.VISIBLE);
                mSubkeyAddFabLayout.setDisplayedChild(1);

                mSubkeysAdapter.setEditMode(mEditModeSaveKeyringParcel);
                getLoaderManager().restartLoader(LOADER_ID_SUBKEYS, null, ViewKeyAdvSubkeysFragment.this);

                mode.setTitle(R.string.title_edit_subkeys);
                mode.getMenuInflater().inflate(R.menu.action_edit_uids, menu);

                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                mode.finish();
                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                mEditModeSaveKeyringParcel = null;
                mSubkeysAdapter.setEditMode(null);
                mSubkeysAddedLayout.setVisibility(View.GONE);
                mSubkeyAddFabLayout.setDisplayedChild(0);
                getLoaderManager().restartLoader(0, null, ViewKeyAdvSubkeysFragment.this);
            }
        });
    }

    private void addSubkey() {
        boolean willBeMasterKey;
        if (mSubkeysAdapter != null) {
            willBeMasterKey = mSubkeysAdapter.getCount() == 0 && mSubkeysAddedAdapter.getCount() == 0;
        } else {
            willBeMasterKey = mSubkeysAddedAdapter.getCount() == 0;
        }

        AddSubkeyDialogFragment addSubkeyDialogFragment =
                AddSubkeyDialogFragment.newInstance(willBeMasterKey);
        addSubkeyDialogFragment
                .setOnAlgorithmSelectedListener(
                        new AddSubkeyDialogFragment.OnAlgorithmSelectedListener() {
                            @Override
                            public void onAlgorithmSelected(SaveKeyringParcel.SubkeyAdd newSubkey) {
                                mSubkeysAddedAdapter.add(newSubkey);
                            }
                        }
                );
        addSubkeyDialogFragment.show(getActivity().getSupportFragmentManager(), "addSubkeyDialog");
    }

    private void editSubkey(final int position) {
        final long keyId = mSubkeysAdapter.getKeyId(position);

        Handler returnHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                switch (message.what) {
                    case EditSubkeyDialogFragment.MESSAGE_CHANGE_EXPIRY:
                        editSubkeyExpiry(position);
                        break;
                    case EditSubkeyDialogFragment.MESSAGE_REVOKE:
                        // toggle
                        if (mEditModeSaveKeyringParcel.mRevokeSubKeys.contains(keyId)) {
                            mEditModeSaveKeyringParcel.mRevokeSubKeys.remove(keyId);
                        } else {
                            mEditModeSaveKeyringParcel.mRevokeSubKeys.add(keyId);
                        }
                        break;
                    case EditSubkeyDialogFragment.MESSAGE_STRIP: {
                        SecretKeyType secretKeyType = mSubkeysAdapter.getSecretKeyType(position);
                        if (secretKeyType == SecretKeyType.GNU_DUMMY) {
                            // Key is already stripped; this is a no-op.
                            break;
                        }

                        SubkeyChange change = mEditModeSaveKeyringParcel.getSubkeyChange(keyId);
                        if (change == null) {
                            mEditModeSaveKeyringParcel.mChangeSubKeys.add(new SubkeyChange(keyId, true, false));
                            break;
                        }
                        // toggle
                        change.mDummyStrip = !change.mDummyStrip;
                        if (change.mDummyStrip && change.mMoveKeyToCard) {
                            // User had chosen to divert key, but now wants to strip it instead.
                            change.mMoveKeyToCard = false;
                        }
                        break;
                    }
                    case EditSubkeyDialogFragment.MESSAGE_MOVE_KEY_TO_CARD: {
                        // TODO: enable later when Admin PIN handling is resolved
                        Notify.create(getActivity(),
                                "This feature will be available in an upcoming OpenKeychain version.",
                                Notify.Style.WARN).show();
                        break;

//                        Activity activity = EditKeyFragment.this.getActivity();
//                        SecretKeyType secretKeyType = mSubkeysAdapter.getSecretKeyType(position);
//                        if (secretKeyType == SecretKeyType.DIVERT_TO_CARD ||
//                            secretKeyType == SecretKeyType.GNU_DUMMY) {
//                            Notify.create(activity, R.string.edit_key_error_bad_nfc_stripped, Notify.Style.ERROR)
//                                    .show((ViewGroup) activity.findViewById(R.id.import_snackbar));
//                            break;
//                        }
//                        int algorithm = mSubkeysAdapter.getAlgorithm(position);
//                        // these are the PGP constants for RSA_GENERAL, RSA_ENCRYPT and RSA_SIGN
//                        if (algorithm != 1 && algorithm != 2 && algorithm != 3) {
//                            Notify.create(activity, R.string.edit_key_error_bad_nfc_algo, Notify.Style.ERROR)
//                                    .show((ViewGroup) activity.findViewById(R.id.import_snackbar));
//                            break;
//                        }
//                        if (mSubkeysAdapter.getKeySize(position) != 2048) {
//                            Notify.create(activity, R.string.edit_key_error_bad_nfc_size, Notify.Style.ERROR)
//                                    .show((ViewGroup) activity.findViewById(R.id.import_snackbar));
//                            break;
//                        }
//
//
//                        SubkeyChange change;
//                        change = mSaveKeyringParcel.getSubkeyChange(keyId);
//                        if (change == null) {
//                            mSaveKeyringParcel.mChangeSubKeys.add(
//                                    new SubkeyChange(keyId, false, true)
//                            );
//                            break;
//                        }
//                        // toggle
//                        change.mMoveKeyToCard = !change.mMoveKeyToCard;
//                        if (change.mMoveKeyToCard && change.mDummyStrip) {
//                            // User had chosen to strip key, but now wants to divert it.
//                            change.mDummyStrip = false;
//                        }
//                        break;
                    }
                }
                getLoaderManager().getLoader(LOADER_ID_SUBKEYS).forceLoad();
            }
        };

        // Create a new Messenger for the communication back
        final Messenger messenger = new Messenger(returnHandler);

        DialogFragmentWorkaround.INTERFACE.runnableRunDelayed(new Runnable() {
            public void run() {
                EditSubkeyDialogFragment dialogFragment =
                        EditSubkeyDialogFragment.newInstance(messenger);

                dialogFragment.show(getActivity().getSupportFragmentManager(), "editSubkeyDialog");
            }
        });
    }

    private void editSubkeyExpiry(final int position) {
        final long keyId = mSubkeysAdapter.getKeyId(position);
        final Long creationDate = mSubkeysAdapter.getCreationDate(position);
        final Long expiryDate = mSubkeysAdapter.getExpiryDate(position);

        Handler returnHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                switch (message.what) {
                    case EditSubkeyExpiryDialogFragment.MESSAGE_NEW_EXPIRY:
                        mEditModeSaveKeyringParcel.getOrCreateSubkeyChange(keyId).mExpiry =
                                (Long) message.getData().getSerializable(
                                        EditSubkeyExpiryDialogFragment.MESSAGE_DATA_EXPIRY);
                        break;
                }
                getLoaderManager().getLoader(LOADER_ID_SUBKEYS).forceLoad();
            }
        };

        // Create a new Messenger for the communication back
        final Messenger messenger = new Messenger(returnHandler);

        DialogFragmentWorkaround.INTERFACE.runnableRunDelayed(new Runnable() {
            public void run() {
                EditSubkeyExpiryDialogFragment dialogFragment =
                        EditSubkeyExpiryDialogFragment.newInstance(messenger, creationDate, expiryDate);

                dialogFragment.show(getActivity().getSupportFragmentManager(), "editSubkeyExpiryDialog");
            }
        });
    }

}