File: ActivityHandlerHelper.java

package info (click to toggle)
wine-gecko-2.24 2.24%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 740,092 kB
  • ctags: 688,789
  • sloc: cpp: 3,160,639; ansic: 1,619,153; python: 164,084; java: 128,022; asm: 114,527; xml: 69,863; sh: 55,281; makefile: 49,648; perl: 20,454; objc: 2,344; yacc: 2,066; pascal: 995; lex: 982; exp: 449; php: 244; lisp: 228; awk: 211; sed: 61; csh: 21; ada: 16; ruby: 3
file content (359 lines) | stat: -rw-r--r-- 15,083 bytes parent folder | download | duplicates (4)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko;

import org.mozilla.gecko.util.ActivityResultHandler;
import org.mozilla.gecko.util.ActivityResultHandlerMap;
import org.mozilla.gecko.util.ThreadUtils;
import org.mozilla.gecko.util.GeckoEventListener;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

public class ActivityHandlerHelper implements GeckoEventListener {
    private static final String LOGTAG = "GeckoActivityHandlerHelper";

    private final ConcurrentLinkedQueue<String> mFilePickerResult;

    private final ActivityResultHandlerMap mActivityResultHandlerMap;
    private final FilePickerResultHandlerSync mFilePickerResultHandlerSync;
    private final AwesomebarResultHandler mAwesomebarResultHandler;
    private final CameraImageResultHandler mCameraImageResultHandler;
    private final CameraVideoResultHandler mCameraVideoResultHandler;

    public interface FileResultHandler {
        public void gotFile(String filename);
    }

    @SuppressWarnings("serial")
    public ActivityHandlerHelper() {
        mFilePickerResult = new ConcurrentLinkedQueue<String>() {
            @Override public boolean offer(String e) {
                if (super.offer(e)) {
                    // poke the Gecko thread in case it's waiting for new events
                    GeckoAppShell.sendEventToGecko(GeckoEvent.createNoOpEvent());
                    return true;
                }
                return false;
            }
        };
        mActivityResultHandlerMap = new ActivityResultHandlerMap();
        mFilePickerResultHandlerSync = new FilePickerResultHandlerSync(mFilePickerResult);
        mAwesomebarResultHandler = new AwesomebarResultHandler();
        mCameraImageResultHandler = new CameraImageResultHandler(mFilePickerResult);
        mCameraVideoResultHandler = new CameraVideoResultHandler(mFilePickerResult);
        GeckoAppShell.getEventDispatcher().registerEventListener("FilePicker:Show", this);
    }

    @Override
    public void handleMessage(String event, final JSONObject message) {
        if (event.equals("FilePicker:Show")) {
            String mimeType = "*/*";
            String mode = message.optString("mode");

            if ("mimeType".equals(mode))
                mimeType = message.optString("mimeType");
            else if ("extension".equals(mode))
                mimeType = GeckoAppShell.getMimeTypeFromExtensions(message.optString("extensions"));

            Log.i(LOGTAG, "Mime: " + mimeType);

            showFilePickerAsync(GeckoAppShell.getGeckoInterface().getActivity(), mimeType, new FileResultHandler() {
                public void gotFile(String filename) {
                    try {
                        message.put("file", filename);
                    } catch (JSONException ex) {
                        Log.i(LOGTAG, "Can't add filename to message " + filename);
                    }
                    GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent(
                        "FilePicker:Result", message.toString()));
                }
            });
        }
    }

    public int makeRequestCodeForAwesomebar() {
        return mActivityResultHandlerMap.put(mAwesomebarResultHandler);
    }

    public int makeRequestCode(ActivityResultHandler aHandler) {
        return mActivityResultHandlerMap.put(aHandler);
    }

    private int addIntentActivitiesToList(Context context, Intent intent, ArrayList<Prompt.PromptListItem> items, ArrayList<Intent> aIntents) {
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> lri = pm.queryIntentActivityOptions(GeckoAppShell.getGeckoInterface().getActivity().getComponentName(), null, intent, 0);

        if (lri == null) {
            return 0;
        }

        for (ResolveInfo ri : lri) {
            Intent rintent = new Intent(intent);
            rintent.setComponent(new ComponentName(
                    ri.activityInfo.applicationInfo.packageName,
                    ri.activityInfo.name));

            Prompt.PromptListItem item = new Prompt.PromptListItem(ri.loadLabel(pm).toString());
            item.icon = ri.loadIcon(pm);
            items.add(item);
            aIntents.add(rintent);
        }

        return lri.size();
    }

    private int addFilePickingActivities(Context context, ArrayList<Prompt.PromptListItem> aItems, String aType, ArrayList<Intent> aIntents) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(aType);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        return addIntentActivitiesToList(context, intent, aItems, aIntents);
    }

    private Prompt.PromptListItem[] getItemsAndIntentsForFilePicker(Context context, String aMimeType, ArrayList<Intent> aIntents) {
        ArrayList<Prompt.PromptListItem> items = new ArrayList<Prompt.PromptListItem>();

        if (aMimeType.equals("audio/*")) {
            if (addFilePickingActivities(context, items, "audio/*", aIntents) <= 0) {
                addFilePickingActivities(context, items, "*/*", aIntents);
            }
        } else if (aMimeType.equals("image/*")) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                                  CameraImageResultHandler.generateImageName())));
            addIntentActivitiesToList(context, intent, items, aIntents);

            if (addFilePickingActivities(context, items, "image/*", aIntents) <= 0) {
                addFilePickingActivities(context, items, "*/*", aIntents);
            }
        } else if (aMimeType.equals("video/*")) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            addIntentActivitiesToList(context, intent, items, aIntents);

            if (addFilePickingActivities(context, items, "video/*", aIntents) <= 0) {
                addFilePickingActivities(context, items, "*/*", aIntents);
            }
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                                  CameraImageResultHandler.generateImageName())));
            addIntentActivitiesToList(context, intent, items, aIntents);

            intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            addIntentActivitiesToList(context, intent, items, aIntents);

            addFilePickingActivities(context, items, "*/*", aIntents);
        }

        return items.toArray(new Prompt.PromptListItem[] {});
    }

    private String getFilePickerTitle(Context context, String aMimeType) {
        if (aMimeType.equals("audio/*")) {
            return context.getString(R.string.filepicker_audio_title);
        } else if (aMimeType.equals("image/*")) {
            return context.getString(R.string.filepicker_image_title);
        } else if (aMimeType.equals("video/*")) {
            return context.getString(R.string.filepicker_video_title);
        } else {
            return context.getString(R.string.filepicker_title);
        }
    }

    private interface IntentHandler {
        public void gotIntent(Intent intent);
    }

    /* Gets an intent that can open a particular mimetype. Will show a prompt with a list
     * of Activities that can handle the mietype. Asynchronously calls the handler when
     * one of the intents is selected. If the caller passes in null for the handler, will still
     * prompt for the activity, but will throw away the result.
     */
    private void getFilePickerIntentAsync(final Context context, String aMimeType, final IntentHandler handler) {
        final ArrayList<Intent> intents = new ArrayList<Intent>();
        final Prompt.PromptListItem[] items =
            getItemsAndIntentsForFilePicker(context, aMimeType, intents);

        if (intents.size() == 0) {
            Log.i(LOGTAG, "no activities for the file picker!");
            handler.gotIntent(null);
            return;
        }

        if (intents.size() == 1) {
            handler.gotIntent(intents.get(0));
            return;
        }

        final Prompt prompt = new Prompt(context, new Prompt.PromptCallback() {
            public void onPromptFinished(String promptServiceResult) {
                if (handler == null) {
                    return;
                }

                int itemId = -1;
                try {
                    itemId = new JSONObject(promptServiceResult).getInt("button");
                } catch (JSONException e) {
                    Log.e(LOGTAG, "result from promptservice was invalid: ", e);
                }

                if (itemId == -1) {
                    handler.gotIntent(null);
                } else {
                    handler.gotIntent(intents.get(itemId));
                }
            }
        });

        final String title = getFilePickerTitle(context, aMimeType);
        // Runnable has to be called to show an intent-like
        // context menu UI using the PromptService.
        ThreadUtils.postToUiThread(new Runnable() {
            @Override public void run() {
                prompt.show(title, "", items, false);
            }
        });
    }

    private Intent getFilePickerIntent(Context context, String aMimeType) {
        ArrayList<Intent> intents = new ArrayList<Intent>();
        final Prompt.PromptListItem[] items =
            getItemsAndIntentsForFilePicker(context, aMimeType, intents);

        if (intents.size() == 0) {
            Log.i(LOGTAG, "no activities for the file picker!");
            return null;
        }

        if (intents.size() == 1) {
            return intents.get(0);
        }

        final PromptService ps = GeckoAppShell.getGeckoInterface().getPromptService();
        final String title = getFilePickerTitle(context, aMimeType);

        // Runnable has to be called to show an intent-like
        // context menu UI using the PromptService.
        ThreadUtils.postToUiThread(new Runnable() {
            @Override public void run() {
                ps.show(title, "", items, false, null);
            }
        });

        String promptServiceResult = ps.getResponse(null);
        int itemId = -1;
        try {
            itemId = new JSONObject(promptServiceResult).getInt("button");

            if (itemId == -1) {
                return null;
            }
        } catch (JSONException e) {
            Log.e(LOGTAG, "result from promptservice was invalid: ", e);
            return null;
        }

        return intents.get(itemId);
    }

    boolean showFilePicker(Activity parentActivity, String aMimeType, ActivityResultHandler handler) {
        Intent intent = getFilePickerIntent(parentActivity, aMimeType);

        if (intent == null) {
            return false;
        }
        parentActivity.startActivityForResult(intent, mActivityResultHandlerMap.put(handler));
        return true;
    }

    String showFilePicker(Activity parentActivity, String aMimeType) {
        Intent intent = getFilePickerIntent(parentActivity, aMimeType);

        if (intent == null) {
            return "";
        }

        if (intent.getAction().equals(MediaStore.ACTION_IMAGE_CAPTURE)) {
            parentActivity.startActivityForResult(intent, mActivityResultHandlerMap.put(mCameraImageResultHandler));
        } else if (intent.getAction().equals(MediaStore.ACTION_VIDEO_CAPTURE)) {
            parentActivity.startActivityForResult(intent, mActivityResultHandlerMap.put(mCameraVideoResultHandler));
        } else if (intent.getAction().equals(Intent.ACTION_GET_CONTENT)) {
            parentActivity.startActivityForResult(intent, mActivityResultHandlerMap.put(mFilePickerResultHandlerSync));
        } else {
            Log.e(LOGTAG, "We should not get an intent with another action!");
            return "";
        }

        String filePickerResult;
        while (null == (filePickerResult = mFilePickerResult.poll())) {
            GeckoAppShell.processNextNativeEvent(true);
        }
        return filePickerResult;
    }

    /* Allows the user to pick an activity to load files from using a list prompt. Then opens the activity and
     * sends the file returned to the passed in handler. If a null handler is passed in, will still
     * pick and launch the file picker, but will throw away the result.
     */
    public void showFilePickerAsync(final Activity parentActivity, String aMimeType, final FileResultHandler handler) {
        getFilePickerIntentAsync(parentActivity, aMimeType, new IntentHandler() {
            public void gotIntent(Intent intent) {
                if (handler == null) {
                    return;
                }

                if (intent == null) {
                    handler.gotFile("");
                    return;
                }

                if (MediaStore.ACTION_IMAGE_CAPTURE.equals(intent.getAction())) {
                    CameraImageResultHandler cam = new CameraImageResultHandler(handler);
                    parentActivity.startActivityForResult(intent, mActivityResultHandlerMap.put(cam));
                } else if (MediaStore.ACTION_VIDEO_CAPTURE.equals(intent.getAction())) {
                    CameraVideoResultHandler vid = new CameraVideoResultHandler(handler);
                    parentActivity.startActivityForResult(intent, mActivityResultHandlerMap.put(vid));
                } else if (Intent.ACTION_GET_CONTENT.equals(intent.getAction())) {
                    FilePickerResultHandlerSync file = new FilePickerResultHandlerSync(handler);
                    parentActivity.startActivityForResult(intent, mActivityResultHandlerMap.put(file));
                } else {
                    Log.e(LOGTAG, "We should not get an intent with another action!");
                    handler.gotFile("");
                    return;
                }
            }
        });
    }

    boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
        ActivityResultHandler handler = mActivityResultHandlerMap.getAndRemove(requestCode);
        if (handler != null) {
            handler.onActivityResult(resultCode, data);
            return true;
        }
        return false;
    }
}