aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/explorer/ui/dialogs/AssociationsDialog.java
blob: 08dec3b16bb2055c414405b08bfba958eb75f20b (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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*
 * Copyright (C) 2008 The Android Open Source Project
 * Copyright (C) 2012 The CyanogenMod Project
 *
 * 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 com.cyanogenmod.explorer.ui.dialogs;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.PatternMatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.cyanogenmod.explorer.ExplorerApplication;
import com.cyanogenmod.explorer.R;
import com.cyanogenmod.explorer.adapters.AssociationsAdapter;
import com.cyanogenmod.explorer.util.DialogHelper;
import com.cyanogenmod.explorer.util.ExceptionUtil;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * A class that wraps a dialog for showing the list of available intents that can handle an
 * action. This dialog allows predetermined
 */
public class AssociationsDialog implements OnItemClickListener {

    private static final String TAG = "AssociationsDialog"; //$NON-NLS-1$

    private final Context mContext;
    private final List<ResolveInfo> mIntents;
    private final ResolveInfo mPreferred;
    private final boolean mAllowPreferred;
    /**
     * @hide
     */
    final Intent mRequestIntent;

    private AlertDialog mDialog;
    /**
     * @hide
     */
    GridView mGrid;
    /**
     * @hide
     */
    CheckBox mRemember;

    private boolean mLoaded;

    /**
     * Constructor of <code>AssociationsDialog</code>.
     *
     * @param context The current context
     * @param icon The icon of the dialog
     * @param title The title dialog
     * @param action The title of the action button
     * @param requestIntent The original request
     * @param intents The list of available intents that can handle an action
     * @param preferred The preferred intent. null if no preferred exists
     * @param allowPreferred If allow the user to mark the selected app as preferred
     */
    public AssociationsDialog(
            Context context, int icon, String title, String action,
            Intent requestIntent, List<ResolveInfo> intents, ResolveInfo preferred,
            boolean allowPreferred) {
        super();

        //Save the data
        this.mContext = context;
        this.mRequestIntent = requestIntent;
        this.mIntents = intents;
        this.mPreferred = preferred;
        this.mAllowPreferred = allowPreferred;
        this.mLoaded = false;

        //Initialize dialog
        init(icon, title, action);
    }

    /**
     * Method that initializes the dialog.
     *
     * @param context The current context
     * @param icon The icon of the dialog
     * @param title The title of the dialog
     * @param action The title of the action button
     */
    private void init(int icon, String title, String action) {
        boolean isPlatformSigned =
                ExplorerApplication.isAppPlatformSignature(this.mContext);

        //Create the layout, and retrieve the views
        LayoutInflater li =
                (LayoutInflater)this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = li.inflate(R.layout.associations_dialog, null, false);
        this.mRemember = (CheckBox)v.findViewById(R.id.associations_remember);
        this.mRemember.setVisibility(
                isPlatformSigned && this.mAllowPreferred ? View.VISIBLE : View.GONE);
        this.mGrid = (GridView)v.findViewById(R.id.associations_gridview);
        this.mGrid.setAdapter(new AssociationsAdapter(this.mContext, this.mIntents, this));

        // Ensure a default title dialog
        String dialogTitle = title;
        if (dialogTitle == null) {
            dialogTitle = this.mContext.getString(R.string.associations_dialog_title);
        }

        //Create the dialog
        this.mDialog = DialogHelper.createDialog(
                                        this.mContext,
                                        icon,
                                        dialogTitle,
                                        v);
        this.mDialog.setButton(
                DialogInterface.BUTTON_POSITIVE,
                action,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ResolveInfo ri = getSelected();
                        Intent intent = new Intent(AssociationsDialog.this.mRequestIntent);
                        intent.setFlags(
                                intent.getFlags() &~
                                Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        intent.addFlags(
                                Intent.FLAG_ACTIVITY_FORWARD_RESULT |
                                Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
                        intent.setComponent(
                                new ComponentName(
                                        ri.activityInfo.applicationInfo.packageName,
                                        ri.activityInfo.name));

                        // Open the intent (and remember the action is the check is marked)
                        onIntentSelected(
                                ri,
                                intent,
                                AssociationsDialog.this.mRemember.isChecked());
                    }
                });
        this.mDialog.setButton(
                DialogInterface.BUTTON_NEGATIVE,
                this.mContext.getString(android.R.string.cancel),
                (DialogInterface.OnClickListener)null);
    }

    /**
     * Method that shows the dialog.
     */
    public void show() {
        this.mDialog.show();

        // Set user preferences
        this.mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
        this.mGrid.post(new Runnable() {
            @Override
            public void run() {
                if (!checkUserPreferences()) {
                    // Recall for check user preferences
                    AssociationsDialog.this.mGrid.postDelayed(this, 50L);
                }
            }
        });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        deselectAll();
        ((ViewGroup)view).setSelected(true);

        // Enable action button
        this.mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
    }

    /**
     * Method that check the user preferences
     *
     * @return boolean Indicates if the user preferences was set
     * @hide
     */
    boolean checkUserPreferences() {
        boolean ret = false;
        if (!this.mLoaded) {
            // Check that the view is loaded
            if ((ViewGroup)this.mGrid.getChildAt(0) == null) return false;

            if (this.mPreferred != null) {
                boolean found = false;
                int cc = this.mIntents.size();
                for (int i = 0; i < cc; i++) {
                    ResolveInfo info = this.mIntents.get(i);
                    if (info.activityInfo.name.equals(this.mPreferred.activityInfo.name)) {
                        // Select the item
                        ViewGroup item = (ViewGroup)this.mGrid.getChildAt(i);
                        if (item != null) {
                            if (!item.isSelected()) {
                                onItemClick(null, item, i, item.getId());

                                // Not allow to revert remember status
                                this.mRemember.setChecked(true);
                                this.mRemember.setEnabled(false);
                                ret = false;
                            } else {
                                this.mLoaded = true;
                                ret = true;
                            }
                        }
                        found = true;
                        break;
                    }
                }

                // Is there is no user preferences?
                if (!found) {
                    this.mLoaded = true;
                    ret = true;
                }
            } else {
                // There is no user preferences
                this.mLoaded = true;
                ret = true;
            }
        }
        return ret;
    }

    /**
     * Method that returns if the preferred intent is still selected
     *
     * @return  if the preferred intent is selected
     */
    private boolean isPreferredSelected() {
        if (this.mPreferred != null) {
            int cc = this.mIntents.size();
            for (int i = 0; i < cc; i++) {
                ResolveInfo info = this.mIntents.get(i);
                if (info.activityInfo.name.equals(this.mPreferred.activityInfo.name)) {
                    ViewGroup item = (ViewGroup)this.mGrid.getChildAt(i);
                    if (item != null) {
                        if (item.isSelected()) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * Method that deselect all the items of the grid view
     */
    private void deselectAll() {
        ListAdapter adapter = this.mGrid.getAdapter();
        int cc = adapter.getCount();
        for (int i = 0; i < cc; i++) {
            ViewGroup item = (ViewGroup)this.mGrid.getChildAt(i);
            item.setSelected(false);
        }
    }

    /**
     * Method that deselect all the items of the grid view
     *
     * @return ResolveInfo The selected item
     * @hide
     */
    ResolveInfo getSelected() {
        AssociationsAdapter adapter = (AssociationsAdapter)this.mGrid.getAdapter();
        int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            ViewGroup item = (ViewGroup)this.mGrid.getChildAt(i);
            if (item.isSelected()) {
                return adapter.getItem(i);
            }
        }
        return null;
    }

    /**
     * Method that opens the associated intent.
     *
     * @param ri The resolve information
     * @param intent The user selection
     * @param remember If the user selection, must be remembered
     * @see ResolverActivity (copied from)
     * @hide
     */
    @SuppressWarnings({"boxing"})
    void onIntentSelected(ResolveInfo ri, Intent intent, boolean remember) {
        if (remember) {
            // Build a reasonable intent filter, based on what matched.
            IntentFilter filter = new IntentFilter();

            if (intent.getAction() != null) {
                filter.addAction(intent.getAction());
            }
            Set<String> categories = intent.getCategories();
            if (categories != null) {
                for (String cat : categories) {
                    filter.addCategory(cat);
                }
            }
            filter.addCategory(Intent.CATEGORY_DEFAULT);

            int cat = ri.match & IntentFilter.MATCH_CATEGORY_MASK;
            Uri data = intent.getData();
            if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
                String mimeType = intent.resolveType(this.mContext);
                if (mimeType != null) {
                    try {
                        filter.addDataType(mimeType);
                    } catch (IntentFilter.MalformedMimeTypeException e) {
                        Log.w(TAG, e);
                        filter = null;
                    }
                }
            }
            if (data != null && data.getScheme() != null && filter != null) {
                // We need the data specification if there was no type,
                // OR if the scheme is not one of our magical "file:"
                // or "content:" schemes (see IntentFilter for the reason).
                if (cat != IntentFilter.MATCH_CATEGORY_TYPE
                        || (!"file".equals(data.getScheme()) //$NON-NLS-1$
                                && !"content".equals(data.getScheme()))) { //$NON-NLS-1$
                    filter.addDataScheme(data.getScheme());

                    // Look through the resolved filter to determine which part
                    // of it matched the original Intent.
                    Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
                    if (aIt != null) {
                        while (aIt.hasNext()) {
                            IntentFilter.AuthorityEntry a = aIt.next();
                            if (a.match(data) >= 0) {
                                int port = a.getPort();
                                filter.addDataAuthority(a.getHost(),
                                        port >= 0 ? Integer.toString(port) : null);
                                break;
                            }
                        }
                    }
                    Iterator<PatternMatcher> pIt = ri.filter.pathsIterator();
                    if (pIt != null) {
                        String path = data.getPath();
                        while (path != null && pIt.hasNext()) {
                            PatternMatcher p = pIt.next();
                            if (p.match(path)) {
                                filter.addDataPath(p.getPath(), p.getType());
                                break;
                            }
                        }
                    }
                }
            }

            // Register preferred association is only allowed by platform signature
            // CMExplorer will be signed with this signature, but when is launch from
            // inside ADT, the app is signed with testkey.
            // Ignore it if the preferred can be saved. Only notify the user and open the
            // intent
            boolean isPlatformSigned =
                    ExplorerApplication.isAppPlatformSignature(this.mContext);
            if (isPlatformSigned && this.mAllowPreferred) {
                if (filter != null && !isPreferredSelected()) {
                    try {
                        AssociationsAdapter adapter = (AssociationsAdapter)this.mGrid.getAdapter();
                        final int cc = adapter.getCount();
                        ComponentName[] set = new ComponentName[cc];
                        int bestMatch = 0;
                        for (int i = 0; i < cc; i++) {
                            ResolveInfo r = adapter.getItem(i);
                            set[i] = new ComponentName(
                                    r.activityInfo.packageName, r.activityInfo.name);
                            if (r.match > bestMatch) bestMatch = r.match;
                        }

                        // Use reflection to access the hidden replacePreferredActivity method
                        // FIXME This need to be tested on a CM compilation. Now
                        // replacePreferredActivity is not working. Check also
                        // the use of addPreferredActivity.
                        PackageManager pm = this.mContext.getPackageManager();
                        Method m = pm.getClass().getMethod(
                                            "replacePreferredActivity", //$NON-NLS-1$
                                            IntentFilter.class, int.class,
                                            ComponentName[].class, ComponentName.class);
                        m.invoke(pm, filter, bestMatch, set, intent.getComponent());

                    } catch (Exception e) {
                        // Capture the exception
                        ExceptionUtil.translateException(this.mContext, e, true, false);
                        DialogHelper.showToast(
                                this.mContext,
                                R.string.msgs_action_association_failed,
                                Toast.LENGTH_SHORT);
                    }
                }
            }
        }

        if (intent != null) {
            this.mContext.startActivity(intent);
        }
    }
}