BugreportProgressService.java revision 85ae3cf46ad66d71e5a29a93e89a0f569d74288b
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.shell;
18
19import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
20import static com.android.shell.BugreportPrefs.STATE_SHOW;
21import static com.android.shell.BugreportPrefs.getWarningState;
22
23import java.io.BufferedOutputStream;
24import java.io.ByteArrayInputStream;
25import java.io.File;
26import java.io.FileDescriptor;
27import java.io.FileInputStream;
28import java.io.FileOutputStream;
29import java.io.IOException;
30import java.io.InputStream;
31import java.io.PrintWriter;
32import java.nio.charset.StandardCharsets;
33import java.text.NumberFormat;
34import java.util.ArrayList;
35import java.util.Enumeration;
36import java.util.List;
37import java.util.zip.ZipEntry;
38import java.util.zip.ZipFile;
39import java.util.zip.ZipOutputStream;
40
41import libcore.io.Streams;
42
43import com.android.internal.annotations.VisibleForTesting;
44import com.android.internal.logging.MetricsLogger;
45import com.android.internal.logging.MetricsProto.MetricsEvent;
46import com.google.android.collect.Lists;
47
48import android.accounts.Account;
49import android.accounts.AccountManager;
50import android.annotation.SuppressLint;
51import android.app.AlertDialog;
52import android.app.Notification;
53import android.app.Notification.Action;
54import android.app.NotificationManager;
55import android.app.PendingIntent;
56import android.app.Service;
57import android.content.ClipData;
58import android.content.Context;
59import android.content.ContextWrapper;
60import android.content.DialogInterface;
61import android.content.Intent;
62import android.content.res.Configuration;
63import android.net.Uri;
64import android.os.AsyncTask;
65import android.os.Handler;
66import android.os.HandlerThread;
67import android.os.IBinder;
68import android.os.Looper;
69import android.os.Message;
70import android.os.Parcel;
71import android.os.Parcelable;
72import android.os.SystemProperties;
73import android.os.Vibrator;
74import android.support.v4.content.FileProvider;
75import android.text.TextUtils;
76import android.text.format.DateUtils;
77import android.util.Log;
78import android.util.Patterns;
79import android.util.SparseArray;
80import android.view.View;
81import android.view.WindowManager;
82import android.view.View.OnFocusChangeListener;
83import android.view.inputmethod.EditorInfo;
84import android.widget.Button;
85import android.widget.EditText;
86import android.widget.Toast;
87
88/**
89 * Service used to keep progress of bugreport processes ({@code dumpstate}).
90 * <p>
91 * The workflow is:
92 * <ol>
93 * <li>When {@code dumpstate} starts, it sends a {@code BUGREPORT_STARTED} with a sequential id,
94 * its pid, and the estimated total effort.
95 * <li>{@link BugreportReceiver} receives the intent and delegates it to this service.
96 * <li>Upon start, this service:
97 * <ol>
98 * <li>Issues a system notification so user can watch the progresss (which is 0% initially).
99 * <li>Polls the {@link SystemProperties} for updates on the {@code dumpstate} progress.
100 * <li>If the progress changed, it updates the system notification.
101 * </ol>
102 * <li>As {@code dumpstate} progresses, it updates the system property.
103 * <li>When {@code dumpstate} finishes, it sends a {@code BUGREPORT_FINISHED} intent.
104 * <li>{@link BugreportReceiver} receives the intent and delegates it to this service, which in
105 * turn:
106 * <ol>
107 * <li>Updates the system notification so user can share the bugreport.
108 * <li>Stops monitoring that {@code dumpstate} process.
109 * <li>Stops itself if it doesn't have any process left to monitor.
110 * </ol>
111 * </ol>
112 */
113public class BugreportProgressService extends Service {
114    private static final String TAG = "BugreportProgressService";
115    private static final boolean DEBUG = false;
116
117    private static final String AUTHORITY = "com.android.shell";
118
119    // External intents sent by dumpstate.
120    static final String INTENT_BUGREPORT_STARTED = "android.intent.action.BUGREPORT_STARTED";
121    static final String INTENT_BUGREPORT_FINISHED = "android.intent.action.BUGREPORT_FINISHED";
122    static final String INTENT_REMOTE_BUGREPORT_FINISHED =
123            "android.intent.action.REMOTE_BUGREPORT_FINISHED";
124    static final String INTENT_REMOTE_BUGREPORT_DISPATCH =
125            "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
126
127    // Internal intents used on notification actions.
128    static final String INTENT_BUGREPORT_CANCEL = "android.intent.action.BUGREPORT_CANCEL";
129    static final String INTENT_BUGREPORT_SHARE = "android.intent.action.BUGREPORT_SHARE";
130    static final String INTENT_BUGREPORT_INFO_LAUNCH =
131            "android.intent.action.BUGREPORT_INFO_LAUNCH";
132    static final String INTENT_BUGREPORT_SCREENSHOT =
133            "android.intent.action.BUGREPORT_SCREENSHOT";
134
135    static final String EXTRA_BUGREPORT = "android.intent.extra.BUGREPORT";
136    static final String EXTRA_SCREENSHOT = "android.intent.extra.SCREENSHOT";
137    static final String EXTRA_ID = "android.intent.extra.ID";
138    static final String EXTRA_PID = "android.intent.extra.PID";
139    static final String EXTRA_MAX = "android.intent.extra.MAX";
140    static final String EXTRA_NAME = "android.intent.extra.NAME";
141    static final String EXTRA_TITLE = "android.intent.extra.TITLE";
142    static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION";
143    static final String EXTRA_ORIGINAL_INTENT = "android.intent.extra.ORIGINAL_INTENT";
144    static final String EXTRA_INFO = "android.intent.extra.INFO";
145
146    private static final int MSG_SERVICE_COMMAND = 1;
147    private static final int MSG_POLL = 2;
148    private static final int MSG_DELAYED_SCREENSHOT = 3;
149    private static final int MSG_SCREENSHOT_REQUEST = 4;
150    private static final int MSG_SCREENSHOT_RESPONSE = 5;
151
152    /**
153     * Delay before a screenshot is taken.
154     * <p>
155     * Should be at least 3 seconds, otherwise its toast might show up in the screenshot.
156     */
157    static final int SCREENSHOT_DELAY_SECONDS = 3;
158
159    /** Polling frequency, in milliseconds. */
160    static final long POLLING_FREQUENCY = 2 * DateUtils.SECOND_IN_MILLIS;
161
162    /** How long (in ms) a dumpstate process will be monitored if it didn't show progress. */
163    private static final long INACTIVITY_TIMEOUT = 10 * DateUtils.MINUTE_IN_MILLIS;
164
165    /** System properties used for monitoring progress. */
166    private static final String DUMPSTATE_PREFIX = "dumpstate.";
167    private static final String PROGRESS_SUFFIX = ".progress";
168    private static final String MAX_SUFFIX = ".max";
169    private static final String NAME_SUFFIX = ".name";
170
171    /** System property (and value) used to stop dumpstate. */
172    // TODO: should call ActiveManager API instead
173    private static final String CTL_STOP = "ctl.stop";
174    private static final String BUGREPORT_SERVICE = "bugreportplus";
175
176    /**
177     * Directory on Shell's data storage where screenshots will be stored.
178     * <p>
179     * Must be a path supported by its FileProvider.
180     */
181    private static final String SCREENSHOT_DIR = "bugreports";
182
183    /** Managed dumpstate processes (keyed by id) */
184    private final SparseArray<BugreportInfo> mProcesses = new SparseArray<>();
185
186    private Context mContext;
187    private ServiceHandler mMainHandler;
188    private ScreenshotHandler mScreenshotHandler;
189
190    private final BugreportInfoDialog mInfoDialog = new BugreportInfoDialog();
191
192    private File mScreenshotsDir;
193
194    /**
195     * Flag indicating whether a screenshot is being taken.
196     * <p>
197     * This is the only state that is shared between the 2 handlers and hence must have synchronized
198     * access.
199     */
200    private boolean mTakingScreenshot;
201
202    @Override
203    public void onCreate() {
204        mContext = getApplicationContext();
205        mMainHandler = new ServiceHandler("BugreportProgressServiceMainThread");
206        mScreenshotHandler = new ScreenshotHandler("BugreportProgressServiceScreenshotThread");
207
208        mScreenshotsDir = new File(new ContextWrapper(mContext).getFilesDir(), SCREENSHOT_DIR);
209        if (!mScreenshotsDir.exists()) {
210            Log.i(TAG, "Creating directory " + mScreenshotsDir + " to store temporary screenshots");
211            if (!mScreenshotsDir.mkdir()) {
212                Log.w(TAG, "Could not create directory " + mScreenshotsDir);
213            }
214        }
215    }
216
217    @Override
218    public int onStartCommand(Intent intent, int flags, int startId) {
219        if (intent != null) {
220            // Handle it in a separate thread.
221            final Message msg = mMainHandler.obtainMessage();
222            msg.what = MSG_SERVICE_COMMAND;
223            msg.obj = intent;
224            mMainHandler.sendMessage(msg);
225        }
226
227        // If service is killed it cannot be recreated because it would not know which
228        // dumpstate IDs it would have to watch.
229        return START_NOT_STICKY;
230    }
231
232    @Override
233    public IBinder onBind(Intent intent) {
234        return null;
235    }
236
237    @Override
238    public void onDestroy() {
239        mMainHandler.getLooper().quit();
240        mScreenshotHandler.getLooper().quit();
241        super.onDestroy();
242    }
243
244    @Override
245    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
246        final int size = mProcesses.size();
247        if (size == 0) {
248            writer.printf("No monitored processes");
249            return;
250        }
251        writer.printf("Monitored dumpstate processes\n");
252        writer.printf("-----------------------------\n");
253        for (int i = 0; i < size; i++) {
254            writer.printf("%s\n", mProcesses.valueAt(i));
255        }
256    }
257
258    /**
259     * Main thread used to handle all requests but taking screenshots.
260     */
261    private final class ServiceHandler extends Handler {
262        public ServiceHandler(String name) {
263            super(newLooper(name));
264        }
265
266        @Override
267        public void handleMessage(Message msg) {
268            if (msg.what == MSG_POLL) {
269                poll();
270                return;
271            }
272
273            if (msg.what == MSG_DELAYED_SCREENSHOT) {
274                takeScreenshot(msg.arg1, msg.arg2);
275                return;
276            }
277
278            if (msg.what == MSG_SCREENSHOT_RESPONSE) {
279                handleScreenshotResponse(msg);
280                return;
281            }
282
283            if (msg.what != MSG_SERVICE_COMMAND) {
284                // Sanity check.
285                Log.e(TAG, "Invalid message type: " + msg.what);
286                return;
287            }
288
289            // At this point it's handling onStartCommand(), with the intent passed as an Extra.
290            if (!(msg.obj instanceof Intent)) {
291                // Sanity check.
292                Log.wtf(TAG, "handleMessage(): invalid msg.obj type: " + msg.obj);
293                return;
294            }
295            final Parcelable parcel = ((Intent) msg.obj).getParcelableExtra(EXTRA_ORIGINAL_INTENT);
296            final Intent intent;
297            if (parcel instanceof Intent) {
298                // The real intent was passed to BugreportReceiver, which delegated to the service.
299                intent = (Intent) parcel;
300            } else {
301                intent = (Intent) msg.obj;
302            }
303            final String action = intent.getAction();
304            final int pid = intent.getIntExtra(EXTRA_PID, 0);
305            final int id = intent.getIntExtra(EXTRA_ID, 0);
306            final int max = intent.getIntExtra(EXTRA_MAX, -1);
307            final String name = intent.getStringExtra(EXTRA_NAME);
308
309            if (DEBUG)
310                Log.v(TAG, "action: " + action + ", name: " + name + ", id: " + id + ", pid: "
311                        + pid + ", max: " + max);
312            switch (action) {
313                case INTENT_BUGREPORT_STARTED:
314                    if (!startProgress(name, id, pid, max)) {
315                        stopSelfWhenDone();
316                        return;
317                    }
318                    poll();
319                    break;
320                case INTENT_BUGREPORT_FINISHED:
321                    if (id == 0) {
322                        // Shouldn't happen, unless BUGREPORT_FINISHED is received from a legacy,
323                        // out-of-sync dumpstate process.
324                        Log.w(TAG, "Missing " + EXTRA_ID + " on intent " + intent);
325                    }
326                    onBugreportFinished(id, intent);
327                    break;
328                case INTENT_BUGREPORT_INFO_LAUNCH:
329                    launchBugreportInfoDialog(id);
330                    break;
331                case INTENT_BUGREPORT_SCREENSHOT:
332                    takeScreenshot(id, true);
333                    break;
334                case INTENT_BUGREPORT_SHARE:
335                    shareBugreport(id, (BugreportInfo) intent.getParcelableExtra(EXTRA_INFO));
336                    break;
337                case INTENT_BUGREPORT_CANCEL:
338                    cancel(id);
339                    break;
340                default:
341                    Log.w(TAG, "Unsupported intent: " + action);
342            }
343            return;
344
345        }
346
347        private void poll() {
348            if (pollProgress()) {
349                // Keep polling...
350                sendEmptyMessageDelayed(MSG_POLL, POLLING_FREQUENCY);
351            } else {
352                Log.i(TAG, "Stopped polling");
353            }
354        }
355    }
356
357    /**
358     * Separate thread used only to take screenshots so it doesn't block the main thread.
359     */
360    private final class ScreenshotHandler extends Handler {
361        public ScreenshotHandler(String name) {
362            super(newLooper(name));
363        }
364
365        @Override
366        public void handleMessage(Message msg) {
367            if (msg.what != MSG_SCREENSHOT_REQUEST) {
368                Log.e(TAG, "Invalid message type: " + msg.what);
369                return;
370            }
371            handleScreenshotRequest(msg);
372        }
373    }
374
375    private BugreportInfo getInfo(int id) {
376        final BugreportInfo info = mProcesses.get(id);
377        if (info == null) {
378            Log.w(TAG, "Not monitoring process with ID " + id);
379        }
380        return info;
381    }
382
383    /**
384     * Creates the {@link BugreportInfo} for a process and issue a system notification to
385     * indicate its progress.
386     *
387     * @return whether it succeeded or not.
388     */
389    private boolean startProgress(String name, int id, int pid, int max) {
390        if (name == null) {
391            Log.w(TAG, "Missing " + EXTRA_NAME + " on start intent");
392        }
393        if (id == -1) {
394            Log.e(TAG, "Missing " + EXTRA_ID + " on start intent");
395            return false;
396        }
397        if (pid == -1) {
398            Log.e(TAG, "Missing " + EXTRA_PID + " on start intent");
399            return false;
400        }
401        if (max <= 0) {
402            Log.e(TAG, "Invalid value for extra " + EXTRA_MAX + ": " + max);
403            return false;
404        }
405
406        final BugreportInfo info = new BugreportInfo(mContext, id, pid, name, max);
407        if (mProcesses.indexOfKey(id) >= 0) {
408            Log.w(TAG, "ID " + id + " already watched");
409        } else {
410            mProcesses.put(info.id, info);
411        }
412        // Take initial screenshot.
413        takeScreenshot(id, false);
414        updateProgress(info);
415        return true;
416    }
417
418    /**
419     * Updates the system notification for a given bugreport.
420     */
421    private void updateProgress(BugreportInfo info) {
422        if (info.max <= 0 || info.progress < 0) {
423            Log.e(TAG, "Invalid progress values for " + info);
424            return;
425        }
426
427        final NumberFormat nf = NumberFormat.getPercentInstance();
428        nf.setMinimumFractionDigits(2);
429        nf.setMaximumFractionDigits(2);
430        final String percentText = nf.format((double) info.progress / info.max);
431        final Action cancelAction = new Action.Builder(null, mContext.getString(
432                com.android.internal.R.string.cancel), newCancelIntent(mContext, info)).build();
433        final Intent infoIntent = new Intent(mContext, BugreportProgressService.class);
434        infoIntent.setAction(INTENT_BUGREPORT_INFO_LAUNCH);
435        infoIntent.putExtra(EXTRA_ID, info.id);
436        final Action infoAction = new Action.Builder(null,
437                mContext.getString(R.string.bugreport_info_action),
438                PendingIntent.getService(mContext, info.id, infoIntent,
439                        PendingIntent.FLAG_UPDATE_CURRENT)).build();
440        final Intent screenshotIntent = new Intent(mContext, BugreportProgressService.class);
441        screenshotIntent.setAction(INTENT_BUGREPORT_SCREENSHOT);
442        screenshotIntent.putExtra(EXTRA_ID, info.id);
443        PendingIntent screenshotPendingIntent = mTakingScreenshot ? null : PendingIntent
444                .getService(mContext, info.id, screenshotIntent,
445                        PendingIntent.FLAG_UPDATE_CURRENT);
446        final Action screenshotAction = new Action.Builder(null,
447                mContext.getString(R.string.bugreport_screenshot_action),
448                screenshotPendingIntent).build();
449
450        final String title = mContext.getString(R.string.bugreport_in_progress_title, info.id);
451
452        final String name =
453                info.name != null ? info.name : mContext.getString(R.string.bugreport_unnamed);
454
455        final Notification notification = new Notification.Builder(mContext)
456                .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
457                .setContentTitle(title)
458                .setTicker(title)
459                .setContentText(name)
460                .setContentInfo(percentText)
461                .setProgress(info.max, info.progress, false)
462                .setOngoing(true)
463                .setLocalOnly(true)
464                .setColor(mContext.getColor(
465                        com.android.internal.R.color.system_notification_accent_color))
466                .addAction(infoAction)
467                .addAction(screenshotAction)
468                .addAction(cancelAction)
469                .build();
470
471        if (info.finished) {
472            Log.w(TAG, "Not sending progress notification because bugreport has finished already ("
473                    + info + ")");
474            return;
475        }
476        Log.d(TAG, "Sending 'Progress' notification for id " + info.id + "(pid " + info.pid + "): "
477                + percentText);
478        NotificationManager.from(mContext).notify(TAG, info.id, notification);
479    }
480
481    /**
482     * Creates a {@link PendingIntent} for a notification action used to cancel a bugreport.
483     */
484    private static PendingIntent newCancelIntent(Context context, BugreportInfo info) {
485        final Intent intent = new Intent(INTENT_BUGREPORT_CANCEL);
486        intent.setClass(context, BugreportProgressService.class);
487        intent.putExtra(EXTRA_ID, info.id);
488        return PendingIntent.getService(context, info.id, intent,
489                PendingIntent.FLAG_UPDATE_CURRENT);
490    }
491
492    /**
493     * Finalizes the progress on a given bugreport and cancel its notification.
494     */
495    private void stopProgress(int id) {
496        if (mProcesses.indexOfKey(id) < 0) {
497            Log.w(TAG, "ID not watched: " + id);
498        } else {
499            Log.d(TAG, "Removing ID " + id);
500            mProcesses.remove(id);
501        }
502        stopSelfWhenDone();
503        Log.v(TAG, "stopProgress(" + id + "): cancel notification");
504        NotificationManager.from(mContext).cancel(TAG, id);
505    }
506
507    /**
508     * Cancels a bugreport upon user's request.
509     */
510    private void cancel(int id) {
511        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_CANCEL);
512        Log.v(TAG, "cancel: ID=" + id);
513        final BugreportInfo info = getInfo(id);
514        if (info != null && !info.finished) {
515            Log.i(TAG, "Cancelling bugreport service (ID=" + id + ") on user's request");
516            setSystemProperty(CTL_STOP, BUGREPORT_SERVICE);
517            deleteScreenshots(info);
518        }
519        stopProgress(id);
520    }
521
522    /**
523     * Poll {@link SystemProperties} to get the progress on each monitored process.
524     *
525     * @return whether it should keep polling.
526     */
527    private boolean pollProgress() {
528        final int total = mProcesses.size();
529        if (total == 0) {
530            Log.d(TAG, "No process to poll progress.");
531        }
532        int activeProcesses = 0;
533        for (int i = 0; i < total; i++) {
534            final BugreportInfo info = mProcesses.valueAt(i);
535            if (info == null) {
536                Log.wtf(TAG, "pollProgress(): null info at index " + i + "(ID = "
537                        + mProcesses.keyAt(i) + ")");
538                continue;
539            }
540
541            final int pid = info.pid;
542            final int id = info.id;
543            if (info.finished) {
544                if (DEBUG) Log.v(TAG, "Skipping finished process " + pid + " (id: " + id + ")");
545                continue;
546            }
547            activeProcesses++;
548            final String progressKey = DUMPSTATE_PREFIX + pid + PROGRESS_SUFFIX;
549            final int progress = SystemProperties.getInt(progressKey, 0);
550            if (progress == 0) {
551                Log.v(TAG, "System property " + progressKey + " is not set yet");
552            }
553            final int max = SystemProperties.getInt(DUMPSTATE_PREFIX + pid + MAX_SUFFIX, 0);
554            final boolean maxChanged = max > 0 && max != info.max;
555            final boolean progressChanged = progress > 0 && progress != info.progress;
556
557            if (progressChanged || maxChanged) {
558                if (progressChanged) {
559                    if (DEBUG) Log.v(TAG, "Updating progress for PID " + pid + "(id: " + id
560                            + ") from " + info.progress + " to " + progress);
561                    info.progress = progress;
562                }
563                if (maxChanged) {
564                    Log.i(TAG, "Updating max progress for PID " + pid + "(id: " + id
565                            + ") from " + info.max + " to " + max);
566                    info.max = max;
567                }
568                info.lastUpdate = System.currentTimeMillis();
569                updateProgress(info);
570            } else {
571                long inactiveTime = System.currentTimeMillis() - info.lastUpdate;
572                if (inactiveTime >= INACTIVITY_TIMEOUT) {
573                    Log.w(TAG, "No progress update for PID " + pid + " since "
574                            + info.getFormattedLastUpdate());
575                    stopProgress(info.id);
576                }
577            }
578        }
579        if (DEBUG) Log.v(TAG, "pollProgress() total=" + total + ", actives=" + activeProcesses);
580        return activeProcesses > 0;
581    }
582
583    /**
584     * Fetches a {@link BugreportInfo} for a given process and launches a dialog where the user can
585     * change its values.
586     */
587    private void launchBugreportInfoDialog(int id) {
588        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_DETAILS);
589        // Copy values so it doesn't lock mProcesses while UI is being updated
590        final String name, title, description;
591        final BugreportInfo info = getInfo(id);
592        if (info == null) {
593            // Most likely am killed Shell before user tapped the notification. Since system might
594            // be too busy anwyays, it's better to ignore the notification and switch back to the
595            // non-interactive mode (where the bugerport will be shared upon completion).
596            Log.d(TAG, "launchBugreportInfoDialog(" + id + "): cancel notification");
597            // TODO: add test case to make sure notification is canceled.
598            NotificationManager.from(mContext).cancel(TAG, id);
599            return;
600        }
601
602        collapseNotificationBar();
603        mInfoDialog.initialize(mContext, info);
604    }
605
606    /**
607     * Starting point for taking a screenshot.
608     * <p>
609     * If {@code delayed} is set, it first display a toast message and waits
610     * {@link #SCREENSHOT_DELAY_SECONDS} seconds before taking it, otherwise it takes the screenshot
611     * right away.
612     * <p>
613     * Typical usage is delaying when taken from the notification action, and taking it right away
614     * upon receiving a {@link #INTENT_BUGREPORT_STARTED}.
615     */
616    private void takeScreenshot(int id, boolean delayed) {
617        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_SCREENSHOT);
618        if (getInfo(id) == null) {
619            // Most likely am killed Shell before user tapped the notification. Since system might
620            // be too busy anwyays, it's better to ignore the notification and switch back to the
621            // non-interactive mode (where the bugerport will be shared upon completion).
622            Log.d(TAG, "takeScreenshot(" + id + ", " + delayed + "): cancel notification");
623            // TODO: add test case to make sure notification is canceled.
624            NotificationManager.from(mContext).cancel(TAG, id);
625            return;
626        }
627        setTakingScreenshot(true);
628        if (delayed) {
629            collapseNotificationBar();
630            final String msg = mContext.getResources()
631                    .getQuantityString(com.android.internal.R.plurals.bugreport_countdown,
632                            SCREENSHOT_DELAY_SECONDS, SCREENSHOT_DELAY_SECONDS);
633            Log.i(TAG, msg);
634            // Show a toast just once, otherwise it might be captured in the screenshot.
635            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
636
637            takeScreenshot(id, SCREENSHOT_DELAY_SECONDS);
638        } else {
639            takeScreenshot(id, 0);
640        }
641    }
642
643    /**
644     * Takes a screenshot after {@code delay} seconds.
645     */
646    private void takeScreenshot(int id, int delay) {
647        if (delay > 0) {
648            Log.d(TAG, "Taking screenshot for " + id + " in " + delay + " seconds");
649            final Message msg = mMainHandler.obtainMessage();
650            msg.what = MSG_DELAYED_SCREENSHOT;
651            msg.arg1 = id;
652            msg.arg2 = delay - 1;
653            mMainHandler.sendMessageDelayed(msg, DateUtils.SECOND_IN_MILLIS);
654            return;
655        }
656
657        // It's time to take the screenshot: let the proper thread handle it
658        final BugreportInfo info = getInfo(id);
659        if (info == null) {
660            return;
661        }
662        final String screenshotPath =
663                new File(mScreenshotsDir, info.getPathNextScreenshot()).getAbsolutePath();
664
665        final Message requestMsg = new Message();
666        requestMsg.what = MSG_SCREENSHOT_REQUEST;
667        requestMsg.arg1 = id;
668        requestMsg.obj = screenshotPath;
669        mScreenshotHandler.sendMessage(requestMsg);
670    }
671
672    /**
673     * Sets the internal {@code mTakingScreenshot} state and updates all notifications so their
674     * SCREENSHOT button is enabled or disabled accordingly.
675     */
676    private void setTakingScreenshot(boolean flag) {
677        synchronized (BugreportProgressService.this) {
678            mTakingScreenshot = flag;
679            for (int i = 0; i < mProcesses.size(); i++) {
680                final BugreportInfo info = mProcesses.valueAt(i);
681                if (info.finished) {
682                    Log.d(TAG, "Not updating progress because share notification was already sent");
683                    continue;
684                }
685                updateProgress(info);
686            }
687        }
688    }
689
690    private void handleScreenshotRequest(Message requestMsg) {
691        String screenshotFile = (String) requestMsg.obj;
692        boolean taken = takeScreenshot(mContext, screenshotFile);
693        setTakingScreenshot(false);
694
695        final Message resultMsg = new Message();
696        resultMsg.what = MSG_SCREENSHOT_RESPONSE;
697        resultMsg.arg1 = requestMsg.arg1;
698        resultMsg.arg2 = taken ? 1 : 0;
699        resultMsg.obj = screenshotFile;
700        mMainHandler.sendMessage(resultMsg);
701    }
702
703    private void handleScreenshotResponse(Message resultMsg) {
704        final boolean taken = resultMsg.arg2 != 0;
705        final BugreportInfo info = getInfo(resultMsg.arg1);
706        if (info == null) {
707            return;
708        }
709        final File screenshotFile = new File((String) resultMsg.obj);
710
711        final int msgId;
712        if (taken) {
713            info.addScreenshot(screenshotFile);
714            if (info.finished) {
715                Log.d(TAG, "Screenshot finished after bugreport; updating share notification");
716                info.renameScreenshots(mScreenshotsDir);
717                sendBugreportNotification(mContext, info);
718            }
719            msgId = R.string.bugreport_screenshot_taken;
720        } else {
721            // TODO: try again using Framework APIs instead of relying on screencap.
722            msgId = R.string.bugreport_screenshot_failed;
723        }
724        final String msg = mContext.getString(msgId);
725        Log.d(TAG, msg);
726        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
727    }
728
729    /**
730     * Deletes all screenshots taken for a given bugreport.
731     */
732    private void deleteScreenshots(BugreportInfo info) {
733        for (File file : info.screenshotFiles) {
734            Log.i(TAG, "Deleting screenshot file " + file);
735            file.delete();
736        }
737    }
738
739    /**
740     * Finishes the service when it's not monitoring any more processes.
741     */
742    private void stopSelfWhenDone() {
743        if (mProcesses.size() > 0) {
744            if (DEBUG) Log.d(TAG, "Staying alive, waiting for IDs " + mProcesses);
745            return;
746        }
747        Log.v(TAG, "No more processes to handle, shutting down");
748        stopSelf();
749    }
750
751    /**
752     * Handles the BUGREPORT_FINISHED intent sent by {@code dumpstate}.
753     */
754    private void onBugreportFinished(int id, Intent intent) {
755        final File bugreportFile = getFileExtra(intent, EXTRA_BUGREPORT);
756        if (bugreportFile == null) {
757            // Should never happen, dumpstate always set the file.
758            Log.wtf(TAG, "Missing " + EXTRA_BUGREPORT + " on intent " + intent);
759            return;
760        }
761        mInfoDialog.onBugreportFinished(id);
762        BugreportInfo info = getInfo(id);
763        if (info == null) {
764            // Happens when BUGREPORT_FINISHED was received without a BUGREPORT_STARTED first.
765            Log.v(TAG, "Creating info for untracked ID " + id);
766            info = new BugreportInfo(mContext, id);
767            mProcesses.put(id, info);
768        }
769        info.renameScreenshots(mScreenshotsDir);
770        info.bugreportFile = bugreportFile;
771
772        final int max = intent.getIntExtra(EXTRA_MAX, -1);
773        if (max != -1) {
774            MetricsLogger.histogram(this, "dumpstate_duration", max);
775            info.max = max;
776        }
777
778        final File screenshot = getFileExtra(intent, EXTRA_SCREENSHOT);
779        if (screenshot != null) {
780            info.addScreenshot(screenshot);
781        }
782        info.finished = true;
783
784        final Configuration conf = mContext.getResources().getConfiguration();
785        if ((conf.uiMode & Configuration.UI_MODE_TYPE_MASK) != Configuration.UI_MODE_TYPE_WATCH) {
786            triggerLocalNotification(mContext, info);
787        }
788    }
789
790    /**
791     * Responsible for triggering a notification that allows the user to start a "share" intent with
792     * the bugreport. On watches we have other methods to allow the user to start this intent
793     * (usually by triggering it on another connected device); we don't need to display the
794     * notification in this case.
795     */
796    private void triggerLocalNotification(final Context context, final BugreportInfo info) {
797        if (!info.bugreportFile.exists() || !info.bugreportFile.canRead()) {
798            Log.e(TAG, "Could not read bugreport file " + info.bugreportFile);
799            Toast.makeText(context, R.string.bugreport_unreadable_text, Toast.LENGTH_LONG).show();
800            stopProgress(info.id);
801            return;
802        }
803
804        boolean isPlainText = info.bugreportFile.getName().toLowerCase().endsWith(".txt");
805        if (!isPlainText) {
806            // Already zipped, send it right away.
807            sendBugreportNotification(context, info);
808        } else {
809            // Asynchronously zip the file first, then send it.
810            sendZippedBugreportNotification(context, info);
811        }
812    }
813
814    private static Intent buildWarningIntent(Context context, Intent sendIntent) {
815        final Intent intent = new Intent(context, BugreportWarningActivity.class);
816        intent.putExtra(Intent.EXTRA_INTENT, sendIntent);
817        return intent;
818    }
819
820    /**
821     * Build {@link Intent} that can be used to share the given bugreport.
822     */
823    private static Intent buildSendIntent(Context context, BugreportInfo info) {
824        // Files are kept on private storage, so turn into Uris that we can
825        // grant temporary permissions for.
826        final Uri bugreportUri = getUri(context, info.bugreportFile);
827
828        final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
829        final String mimeType = "application/vnd.android.bugreport";
830        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
831        intent.addCategory(Intent.CATEGORY_DEFAULT);
832        intent.setType(mimeType);
833
834        final String subject = !TextUtils.isEmpty(info.title) ?
835                info.title : bugreportUri.getLastPathSegment();
836        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
837
838        // EXTRA_TEXT should be an ArrayList, but some clients are expecting a single String.
839        // So, to avoid an exception on Intent.migrateExtraStreamToClipData(), we need to manually
840        // create the ClipData object with the attachments URIs.
841        final StringBuilder messageBody = new StringBuilder("Build info: ")
842            .append(SystemProperties.get("ro.build.description"))
843            .append("\nSerial number: ")
844            .append(SystemProperties.get("ro.serialno"));
845        if (!TextUtils.isEmpty(info.description)) {
846            messageBody.append("\nDescription: ").append(info.description);
847        }
848        intent.putExtra(Intent.EXTRA_TEXT, messageBody.toString());
849        final ClipData clipData = new ClipData(null, new String[] { mimeType },
850                new ClipData.Item(null, null, null, bugreportUri));
851        final ArrayList<Uri> attachments = Lists.newArrayList(bugreportUri);
852        for (File screenshot : info.screenshotFiles) {
853            final Uri screenshotUri = getUri(context, screenshot);
854            clipData.addItem(new ClipData.Item(null, null, null, screenshotUri));
855            attachments.add(screenshotUri);
856        }
857        intent.setClipData(clipData);
858        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
859
860        final Account sendToAccount = findSendToAccount(context);
861        if (sendToAccount != null) {
862            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { sendToAccount.name });
863        }
864
865        return intent;
866    }
867
868    /**
869     * Shares the bugreport upon user's request by issuing a {@link Intent#ACTION_SEND_MULTIPLE}
870     * intent, but issuing a warning dialog the first time.
871     */
872    private void shareBugreport(int id, BugreportInfo sharedInfo) {
873        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_SHARE);
874        BugreportInfo info = getInfo(id);
875        if (info == null) {
876            // Service was terminated but notification persisted
877            info = sharedInfo;
878            Log.d(TAG, "shareBugreport(): no info for ID " + id + " on managed processes ("
879                    + mProcesses + "), using info from intent instead (" + info + ")");
880        }
881
882        addDetailsToZipFile(mContext, info);
883
884        final Intent sendIntent = buildSendIntent(mContext, info);
885        final Intent notifIntent;
886
887        // Send through warning dialog by default
888        if (getWarningState(mContext, STATE_SHOW) == STATE_SHOW) {
889            notifIntent = buildWarningIntent(mContext, sendIntent);
890        } else {
891            notifIntent = sendIntent;
892        }
893        notifIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
894
895        // Send the share intent...
896        mContext.startActivity(notifIntent);
897
898        // ... and stop watching this process.
899        stopProgress(id);
900    }
901
902    /**
903     * Sends a notification indicating the bugreport has finished so use can share it.
904     */
905    private static void sendBugreportNotification(Context context, BugreportInfo info) {
906
907        // Since adding the details can take a while, do it before notifying user.
908        addDetailsToZipFile(context, info);
909
910        final Intent shareIntent = new Intent(INTENT_BUGREPORT_SHARE);
911        shareIntent.setClass(context, BugreportProgressService.class);
912        shareIntent.setAction(INTENT_BUGREPORT_SHARE);
913        shareIntent.putExtra(EXTRA_ID, info.id);
914        shareIntent.putExtra(EXTRA_INFO, info);
915
916        final String title = context.getString(R.string.bugreport_finished_title, info.id);
917        final Notification.Builder builder = new Notification.Builder(context)
918                .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
919                .setContentTitle(title)
920                .setTicker(title)
921                .setContentText(context.getString(R.string.bugreport_finished_text))
922                .setContentIntent(PendingIntent.getService(context, info.id, shareIntent,
923                        PendingIntent.FLAG_UPDATE_CURRENT))
924                .setDeleteIntent(newCancelIntent(context, info))
925                .setLocalOnly(true)
926                .setColor(context.getColor(
927                        com.android.internal.R.color.system_notification_accent_color));
928
929        if (!TextUtils.isEmpty(info.name)) {
930            builder.setContentInfo(info.name);
931        }
932
933        Log.v(TAG, "Sending 'Share' notification for ID " + info.id + ": " + title);
934        NotificationManager.from(context).notify(TAG, info.id, builder.build());
935    }
936
937    /**
938     * Sends a notification indicating the bugreport is being updated so the user can wait until it
939     * finishes - at this point there is nothing to be done other than waiting, hence it has no
940     * pending action.
941     */
942    private static void sendBugreportBeingUpdatedNotification(Context context, int id) {
943        final String title = context.getString(R.string.bugreport_updating_title);
944        final Notification.Builder builder = new Notification.Builder(context)
945                .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
946                .setContentTitle(title)
947                .setTicker(title)
948                .setContentText(context.getString(R.string.bugreport_updating_wait))
949                .setLocalOnly(true)
950                .setColor(context.getColor(
951                        com.android.internal.R.color.system_notification_accent_color));
952        Log.v(TAG, "Sending 'Updating zip' notification for ID " + id + ": " + title);
953        NotificationManager.from(context).notify(TAG, id, builder.build());
954    }
955
956    /**
957     * Sends a zipped bugreport notification.
958     */
959    private static void sendZippedBugreportNotification(final Context context,
960            final BugreportInfo info) {
961        new AsyncTask<Void, Void, Void>() {
962            @Override
963            protected Void doInBackground(Void... params) {
964                zipBugreport(info);
965                sendBugreportNotification(context, info);
966                return null;
967            }
968        }.execute();
969    }
970
971    /**
972     * Zips a bugreport file, returning the path to the new file (or to the
973     * original in case of failure).
974     */
975    private static void zipBugreport(BugreportInfo info) {
976        final String bugreportPath = info.bugreportFile.getAbsolutePath();
977        final String zippedPath = bugreportPath.replace(".txt", ".zip");
978        Log.v(TAG, "zipping " + bugreportPath + " as " + zippedPath);
979        final File bugreportZippedFile = new File(zippedPath);
980        try (InputStream is = new FileInputStream(info.bugreportFile);
981                ZipOutputStream zos = new ZipOutputStream(
982                        new BufferedOutputStream(new FileOutputStream(bugreportZippedFile)))) {
983            addEntry(zos, info.bugreportFile.getName(), is);
984            // Delete old file
985            final boolean deleted = info.bugreportFile.delete();
986            if (deleted) {
987                Log.v(TAG, "deleted original bugreport (" + bugreportPath + ")");
988            } else {
989                Log.e(TAG, "could not delete original bugreport (" + bugreportPath + ")");
990            }
991            info.bugreportFile = bugreportZippedFile;
992        } catch (IOException e) {
993            Log.e(TAG, "exception zipping file " + zippedPath, e);
994        }
995    }
996
997    /**
998     * Adds the user-provided info into the bugreport zip file.
999     * <p>
1000     * If user provided a title, it will be saved into a {@code title.txt} entry; similarly, the
1001     * description will be saved on {@code description.txt}.
1002     */
1003    private static void addDetailsToZipFile(Context context, BugreportInfo info) {
1004        if (info.bugreportFile == null) {
1005            // One possible reason is a bug in the Parcelization code.
1006            Log.wtf(TAG, "addDetailsToZipFile(): no bugreportFile on " + info);
1007            return;
1008        }
1009        if (TextUtils.isEmpty(info.title) && TextUtils.isEmpty(info.description)) {
1010            Log.d(TAG, "Not touching zip file since neither title nor description are set");
1011            return;
1012        }
1013        if (info.addedDetailsToZip || info.addingDetailsToZip) {
1014            Log.d(TAG, "Already added details to zip file for " + info);
1015            return;
1016        }
1017        info.addingDetailsToZip = true;
1018
1019        // It's not possible to add a new entry into an existing file, so we need to create a new
1020        // zip, copy all entries, then rename it.
1021        sendBugreportBeingUpdatedNotification(context, info.id); // ...and that takes time
1022        final File dir = info.bugreportFile.getParentFile();
1023        final File tmpZip = new File(dir, "tmp-" + info.bugreportFile.getName());
1024        Log.d(TAG, "Writing temporary zip file (" + tmpZip + ") with title and/or description");
1025        try (ZipFile oldZip = new ZipFile(info.bugreportFile);
1026                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tmpZip))) {
1027
1028            // First copy contents from original zip.
1029            Enumeration<? extends ZipEntry> entries = oldZip.entries();
1030            while (entries.hasMoreElements()) {
1031                final ZipEntry entry = entries.nextElement();
1032                final String entryName = entry.getName();
1033                if (!entry.isDirectory()) {
1034                    addEntry(zos, entryName, entry.getTime(), oldZip.getInputStream(entry));
1035                } else {
1036                    Log.w(TAG, "skipping directory entry: " + entryName);
1037                }
1038            }
1039
1040            // Then add the user-provided info.
1041            addEntry(zos, "title.txt", info.title);
1042            addEntry(zos, "description.txt", info.description);
1043        } catch (IOException e) {
1044            info.addingDetailsToZip = false;
1045            Log.e(TAG, "exception zipping file " + tmpZip, e);
1046            return;
1047        }
1048
1049        if (!tmpZip.renameTo(info.bugreportFile)) {
1050            Log.e(TAG, "Could not rename " + tmpZip + " to " + info.bugreportFile);
1051        }
1052        info.addedDetailsToZip = true;
1053        info.addingDetailsToZip = false;
1054    }
1055
1056    private static void addEntry(ZipOutputStream zos, String entry, String text)
1057            throws IOException {
1058        if (DEBUG) Log.v(TAG, "adding entry '" + entry + "': " + text);
1059        if (!TextUtils.isEmpty(text)) {
1060            addEntry(zos, entry, new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
1061        }
1062    }
1063
1064    private static void addEntry(ZipOutputStream zos, String entryName, InputStream is)
1065            throws IOException {
1066        addEntry(zos, entryName, System.currentTimeMillis(), is);
1067    }
1068
1069    private static void addEntry(ZipOutputStream zos, String entryName, long timestamp,
1070            InputStream is) throws IOException {
1071        final ZipEntry entry = new ZipEntry(entryName);
1072        entry.setTime(timestamp);
1073        zos.putNextEntry(entry);
1074        final int totalBytes = Streams.copy(is, zos);
1075        if (DEBUG) Log.v(TAG, "size of '" + entryName + "' entry: " + totalBytes + " bytes");
1076        zos.closeEntry();
1077    }
1078
1079    /**
1080     * Find the best matching {@link Account} based on build properties.
1081     */
1082    private static Account findSendToAccount(Context context) {
1083        final AccountManager am = (AccountManager) context.getSystemService(
1084                Context.ACCOUNT_SERVICE);
1085
1086        String preferredDomain = SystemProperties.get("sendbug.preferred.domain");
1087        if (!preferredDomain.startsWith("@")) {
1088            preferredDomain = "@" + preferredDomain;
1089        }
1090
1091        final Account[] accounts = am.getAccounts();
1092        Account foundAccount = null;
1093        for (Account account : accounts) {
1094            if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
1095                if (!preferredDomain.isEmpty()) {
1096                    // if we have a preferred domain and it matches, return; otherwise keep
1097                    // looking
1098                    if (account.name.endsWith(preferredDomain)) {
1099                        return account;
1100                    } else {
1101                        foundAccount = account;
1102                    }
1103                    // if we don't have a preferred domain, just return since it looks like
1104                    // an email address
1105                } else {
1106                    return account;
1107                }
1108            }
1109        }
1110        return foundAccount;
1111    }
1112
1113    static Uri getUri(Context context, File file) {
1114        return file != null ? FileProvider.getUriForFile(context, AUTHORITY, file) : null;
1115    }
1116
1117    static File getFileExtra(Intent intent, String key) {
1118        final String path = intent.getStringExtra(key);
1119        if (path != null) {
1120            return new File(path);
1121        } else {
1122            return null;
1123        }
1124    }
1125
1126    private static boolean setSystemProperty(String key, String value) {
1127        try {
1128            if (DEBUG) Log.v(TAG, "Setting system property " + key + " to " + value);
1129            SystemProperties.set(key, value);
1130        } catch (IllegalArgumentException e) {
1131            Log.e(TAG, "Could not set property " + key + " to " + value, e);
1132            return false;
1133        }
1134        return true;
1135    }
1136
1137    /**
1138     * Updates the system property used by {@code dumpstate} to rename the final bugreport files.
1139     */
1140    private boolean setBugreportNameProperty(int pid, String name) {
1141        Log.d(TAG, "Updating bugreport name to " + name);
1142        final String key = DUMPSTATE_PREFIX + pid + NAME_SUFFIX;
1143        return setSystemProperty(key, name);
1144    }
1145
1146    /**
1147     * Updates the user-provided details of a bugreport.
1148     */
1149    private void updateBugreportInfo(int id, String name, String title, String description) {
1150        final BugreportInfo info = getInfo(id);
1151        if (info == null) {
1152            return;
1153        }
1154        if (title != null && !title.equals(info.title)) {
1155            MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_DETAILS_TITLE_CHANGED);
1156        }
1157        info.title = title;
1158        if (description != null && !description.equals(info.description)) {
1159            MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_DETAILS_DESCRIPTION_CHANGED);
1160        }
1161        info.description = description;
1162        if (name != null && !name.equals(info.name)) {
1163            MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_DETAILS_NAME_CHANGED);
1164            info.name = name;
1165            updateProgress(info);
1166        }
1167    }
1168
1169    private void collapseNotificationBar() {
1170        sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
1171    }
1172
1173    private static Looper newLooper(String name) {
1174        final HandlerThread thread = new HandlerThread(name, THREAD_PRIORITY_BACKGROUND);
1175        thread.start();
1176        return thread.getLooper();
1177    }
1178
1179    /**
1180     * Takes a screenshot and save it to the given location.
1181     */
1182    private static boolean takeScreenshot(Context context, String screenshotFile) {
1183        ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE))
1184                .vibrate(150);
1185        final ProcessBuilder screencap = new ProcessBuilder()
1186                .command("/system/bin/screencap", "-p", screenshotFile);
1187        Log.d(TAG, "Taking screenshot using " + screencap.command());
1188        try {
1189            final int exitValue = screencap.start().waitFor();
1190            if (exitValue == 0) {
1191                return true;
1192            }
1193            Log.e(TAG, "screencap (" + screencap.command() + ") failed: " + exitValue);
1194        } catch (IOException e) {
1195            Log.e(TAG, "screencap (" + screencap.command() + ") failed", e);
1196        } catch (InterruptedException e) {
1197            Log.w(TAG, "Thread interrupted while screencap still running");
1198            Thread.currentThread().interrupt();
1199        }
1200        return false;
1201    }
1202
1203    /**
1204     * Checks whether a character is valid on bugreport names.
1205     */
1206    @VisibleForTesting
1207    static boolean isValid(char c) {
1208        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
1209                || c == '_' || c == '-';
1210    }
1211
1212    /**
1213     * Helper class encapsulating the UI elements and logic used to display a dialog where user
1214     * can change the details of a bugreport.
1215     */
1216    private final class BugreportInfoDialog {
1217        private EditText mInfoName;
1218        private EditText mInfoTitle;
1219        private EditText mInfoDescription;
1220        private AlertDialog mDialog;
1221        private Button mOkButton;
1222        private int mId;
1223        private int mPid;
1224
1225        /**
1226         * Last "committed" value of the bugreport name.
1227         * <p>
1228         * Once initially set, it's only updated when user clicks the OK button.
1229         */
1230        private String mSavedName;
1231
1232        /**
1233         * Last value of the bugreport name as entered by the user.
1234         * <p>
1235         * Every time it's changed the equivalent system property is changed as well, but if the
1236         * user clicks CANCEL, the old value (stored on {@code mSavedName} is restored.
1237         * <p>
1238         * This logic handles the corner-case scenario where {@code dumpstate} finishes after the
1239         * user changed the name but didn't clicked OK yet (for example, because the user is typing
1240         * the description). The only drawback is that if the user changes the name while
1241         * {@code dumpstate} is running but clicks CANCEL after it finishes, then the final name
1242         * will be the one that has been canceled. But when {@code dumpstate} finishes the {code
1243         * name} UI is disabled and the old name restored anyways, so the user will be "alerted" of
1244         * such drawback.
1245         */
1246        private String mTempName;
1247
1248        /**
1249         * Sets its internal state and displays the dialog.
1250         */
1251        private void initialize(final Context context, BugreportInfo info) {
1252            // First initializes singleton.
1253            if (mDialog == null) {
1254                @SuppressLint("InflateParams")
1255                // It's ok pass null ViewRoot on AlertDialogs.
1256                final View view = View.inflate(context, R.layout.dialog_bugreport_info, null);
1257
1258                mInfoName = (EditText) view.findViewById(R.id.name);
1259                mInfoTitle = (EditText) view.findViewById(R.id.title);
1260                mInfoDescription = (EditText) view.findViewById(R.id.description);
1261
1262                mInfoName.setOnFocusChangeListener(new OnFocusChangeListener() {
1263
1264                    @Override
1265                    public void onFocusChange(View v, boolean hasFocus) {
1266                        if (hasFocus) {
1267                            return;
1268                        }
1269                        sanitizeName();
1270                    }
1271                });
1272
1273                mDialog = new AlertDialog.Builder(context)
1274                        .setView(view)
1275                        .setTitle(context.getString(R.string.bugreport_info_dialog_title, info.id))
1276                        .setCancelable(false)
1277                        .setPositiveButton(context.getString(com.android.internal.R.string.ok),
1278                                null)
1279                        .setNegativeButton(context.getString(com.android.internal.R.string.cancel),
1280                                new DialogInterface.OnClickListener()
1281                                {
1282                                    @Override
1283                                    public void onClick(DialogInterface dialog, int id)
1284                                    {
1285                                        MetricsLogger.action(context,
1286                                                MetricsEvent.ACTION_BUGREPORT_DETAILS_CANCELED);
1287                                        if (!mTempName.equals(mSavedName)) {
1288                                            // Must restore dumpstate's name since it was changed
1289                                            // before user clicked OK.
1290                                            setBugreportNameProperty(mPid, mSavedName);
1291                                        }
1292                                    }
1293                                })
1294                        .create();
1295
1296                mDialog.getWindow().setAttributes(
1297                        new WindowManager.LayoutParams(
1298                                WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG));
1299
1300            }
1301
1302            // Then set fields.
1303            mSavedName = mTempName = info.name;
1304            mId = info.id;
1305            mPid = info.pid;
1306            if (!TextUtils.isEmpty(info.name)) {
1307                mInfoName.setText(info.name);
1308            }
1309            if (!TextUtils.isEmpty(info.title)) {
1310                mInfoTitle.setText(info.title);
1311            }
1312            if (!TextUtils.isEmpty(info.description)) {
1313                mInfoDescription.setText(info.description);
1314            }
1315
1316            // And finally display it.
1317            mDialog.show();
1318
1319            // TODO: in a traditional AlertDialog, when the positive button is clicked the
1320            // dialog is always closed, but we need to validate the name first, so we need to
1321            // get a reference to it, which is only available after it's displayed.
1322            // It would be cleaner to use a regular dialog instead, but let's keep this
1323            // workaround for now and change it later, when we add another button to take
1324            // extra screenshots.
1325            if (mOkButton == null) {
1326                mOkButton = mDialog.getButton(DialogInterface.BUTTON_POSITIVE);
1327                mOkButton.setOnClickListener(new View.OnClickListener() {
1328
1329                    @Override
1330                    public void onClick(View view) {
1331                        MetricsLogger.action(context, MetricsEvent.ACTION_BUGREPORT_DETAILS_SAVED);
1332                        sanitizeName();
1333                        final String name = mInfoName.getText().toString();
1334                        final String title = mInfoTitle.getText().toString();
1335                        final String description = mInfoDescription.getText().toString();
1336
1337                        updateBugreportInfo(mId, name, title, description);
1338                        mDialog.dismiss();
1339                    }
1340                });
1341            }
1342        }
1343
1344        /**
1345         * Sanitizes the user-provided value for the {@code name} field, automatically replacing
1346         * invalid characters if necessary.
1347         */
1348        private void sanitizeName() {
1349            String name = mInfoName.getText().toString();
1350            if (name.equals(mTempName)) {
1351                if (DEBUG) Log.v(TAG, "name didn't change, no need to sanitize: " + name);
1352                return;
1353            }
1354            final StringBuilder safeName = new StringBuilder(name.length());
1355            boolean changed = false;
1356            for (int i = 0; i < name.length(); i++) {
1357                final char c = name.charAt(i);
1358                if (isValid(c)) {
1359                    safeName.append(c);
1360                } else {
1361                    changed = true;
1362                    safeName.append('_');
1363                }
1364            }
1365            if (changed) {
1366                Log.v(TAG, "changed invalid name '" + name + "' to '" + safeName + "'");
1367                name = safeName.toString();
1368                mInfoName.setText(name);
1369            }
1370            mTempName = name;
1371
1372            // Must update system property for the cases where dumpstate finishes
1373            // while the user is still entering other fields (like title or
1374            // description)
1375            setBugreportNameProperty(mPid, name);
1376        }
1377
1378       /**
1379         * Notifies the dialog that the bugreport has finished so it disables the {@code name}
1380         * field.
1381         * <p>Once the bugreport is finished dumpstate has already generated the final files, so
1382         * changing the name would have no effect.
1383         */
1384        private void onBugreportFinished(int id) {
1385            if (mInfoName != null) {
1386                mInfoName.setEnabled(false);
1387                mInfoName.setText(mSavedName);
1388            }
1389        }
1390
1391    }
1392
1393    /**
1394     * Information about a bugreport process while its in progress.
1395     */
1396    private static final class BugreportInfo implements Parcelable {
1397        private final Context context;
1398
1399        /**
1400         * Sequential, user-friendly id used to identify the bugreport.
1401         */
1402        final int id;
1403
1404        /**
1405         * {@code pid} of the {@code dumpstate} process generating the bugreport.
1406         */
1407        final int pid;
1408
1409        /**
1410         * Name of the bugreport, will be used to rename the final files.
1411         * <p>
1412         * Initial value is the bugreport filename reported by {@code dumpstate}, but user can
1413         * change it later to a more meaningful name.
1414         */
1415        String name;
1416
1417        /**
1418         * User-provided, one-line summary of the bug; when set, will be used as the subject
1419         * of the {@link Intent#ACTION_SEND_MULTIPLE} intent.
1420         */
1421        String title;
1422
1423        /**
1424         * User-provided, detailed description of the bugreport; when set, will be added to the body
1425         * of the {@link Intent#ACTION_SEND_MULTIPLE} intent.
1426         */
1427        String description;
1428
1429        /**
1430         * Maximum progress of the bugreport generation.
1431         */
1432        int max;
1433
1434        /**
1435         * Current progress of the bugreport generation.
1436         */
1437        int progress;
1438
1439        /**
1440         * Time of the last progress update.
1441         */
1442        long lastUpdate = System.currentTimeMillis();
1443
1444        /**
1445         * Time of the last progress update when Parcel was created.
1446         */
1447        String formattedLastUpdate;
1448
1449        /**
1450         * Path of the main bugreport file.
1451         */
1452        File bugreportFile;
1453
1454        /**
1455         * Path of the screenshot files.
1456         */
1457        List<File> screenshotFiles = new ArrayList<>(1);
1458
1459        /**
1460         * Whether dumpstate sent an intent informing it has finished.
1461         */
1462        boolean finished;
1463
1464        /**
1465         * Whether the details entries have been added to the bugreport yet.
1466         */
1467        boolean addingDetailsToZip;
1468        boolean addedDetailsToZip;
1469
1470        /**
1471         * Internal counter used to name screenshot files.
1472         */
1473        int screenshotCounter;
1474
1475        /**
1476         * Constructor for tracked bugreports - typically called upon receiving BUGREPORT_STARTED.
1477         */
1478        BugreportInfo(Context context, int id, int pid, String name, int max) {
1479            this.context = context;
1480            this.id = id;
1481            this.pid = pid;
1482            this.name = name;
1483            this.max = max;
1484        }
1485
1486        /**
1487         * Constructor for untracked bugreports - typically called upon receiving BUGREPORT_FINISHED
1488         * without a previous call to BUGREPORT_STARTED.
1489         */
1490        BugreportInfo(Context context, int id) {
1491            this(context, id, id, null, 0);
1492            this.finished = true;
1493        }
1494
1495        /**
1496         * Gets the name for next screenshot file.
1497         */
1498        String getPathNextScreenshot() {
1499            screenshotCounter ++;
1500            return "screenshot-" + pid + "-" + screenshotCounter + ".png";
1501        }
1502
1503        /**
1504         * Saves the location of a taken screenshot so it can be sent out at the end.
1505         */
1506        void addScreenshot(File screenshot) {
1507            screenshotFiles.add(screenshot);
1508        }
1509
1510        /**
1511         * Rename all screenshots files so that they contain the user-generated name instead of pid.
1512         */
1513        void renameScreenshots(File screenshotDir) {
1514            if (TextUtils.isEmpty(name)) {
1515                return;
1516            }
1517            final List<File> renamedFiles = new ArrayList<>(screenshotFiles.size());
1518            for (File oldFile : screenshotFiles) {
1519                final String oldName = oldFile.getName();
1520                final String newName = oldName.replaceFirst(Integer.toString(pid), name);
1521                final File newFile;
1522                if (!newName.equals(oldName)) {
1523                    final File renamedFile = new File(screenshotDir, newName);
1524                    newFile = oldFile.renameTo(renamedFile) ? renamedFile : oldFile;
1525                } else {
1526                    Log.w(TAG, "Name didn't change: " + oldName); // Shouldn't happen.
1527                    newFile = oldFile;
1528                }
1529                renamedFiles.add(newFile);
1530            }
1531            screenshotFiles = renamedFiles;
1532        }
1533
1534        String getFormattedLastUpdate() {
1535            if (context == null) {
1536                // Restored from Parcel
1537                return formattedLastUpdate == null ?
1538                        Long.toString(lastUpdate) : formattedLastUpdate;
1539            }
1540            return DateUtils.formatDateTime(context, lastUpdate,
1541                    DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
1542        }
1543
1544        @Override
1545        public String toString() {
1546            final float percent = ((float) progress * 100 / max);
1547            return "id: " + id + ", pid: " + pid + ", name: " + name + ", finished: " + finished
1548                    + "\n\ttitle: " + title + "\n\tdescription: " + description
1549                    + "\n\tfile: " + bugreportFile + "\n\tscreenshots: " + screenshotFiles
1550                    + "\n\tprogress: " + progress + "/" + max + " (" + percent + ")"
1551                    + "\n\tlast_update: " + getFormattedLastUpdate()
1552                    + "\naddingDetailsToZip: " + addingDetailsToZip
1553                    + " addedDetailsToZip: " + addedDetailsToZip;
1554        }
1555
1556        // Parcelable contract
1557        protected BugreportInfo(Parcel in) {
1558            context = null;
1559            id = in.readInt();
1560            pid = in.readInt();
1561            name = in.readString();
1562            title = in.readString();
1563            description = in.readString();
1564            max = in.readInt();
1565            progress = in.readInt();
1566            lastUpdate = in.readLong();
1567            formattedLastUpdate = in.readString();
1568            bugreportFile = readFile(in);
1569
1570            int screenshotSize = in.readInt();
1571            for (int i = 1; i <= screenshotSize; i++) {
1572                  screenshotFiles.add(readFile(in));
1573            }
1574
1575            finished = in.readInt() == 1;
1576            screenshotCounter = in.readInt();
1577        }
1578
1579        @Override
1580        public void writeToParcel(Parcel dest, int flags) {
1581            dest.writeInt(id);
1582            dest.writeInt(pid);
1583            dest.writeString(name);
1584            dest.writeString(title);
1585            dest.writeString(description);
1586            dest.writeInt(max);
1587            dest.writeInt(progress);
1588            dest.writeLong(lastUpdate);
1589            dest.writeString(getFormattedLastUpdate());
1590            writeFile(dest, bugreportFile);
1591
1592            dest.writeInt(screenshotFiles.size());
1593            for (File screenshotFile : screenshotFiles) {
1594                writeFile(dest, screenshotFile);
1595            }
1596
1597            dest.writeInt(finished ? 1 : 0);
1598            dest.writeInt(screenshotCounter);
1599        }
1600
1601        @Override
1602        public int describeContents() {
1603            return 0;
1604        }
1605
1606        private void writeFile(Parcel dest, File file) {
1607            dest.writeString(file == null ? null : file.getPath());
1608        }
1609
1610        private File readFile(Parcel in) {
1611            final String path = in.readString();
1612            return path == null ? null : new File(path);
1613        }
1614
1615        public static final Parcelable.Creator<BugreportInfo> CREATOR =
1616                new Parcelable.Creator<BugreportInfo>() {
1617            public BugreportInfo createFromParcel(Parcel source) {
1618                return new BugreportInfo(source);
1619            }
1620
1621            public BugreportInfo[] newArray(int size) {
1622                return new BugreportInfo[size];
1623            }
1624        };
1625
1626    }
1627}
1628