BugreportProgressService.java revision 5d9000aa45c19de0e7ec4131c1aca3d366e9a793
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        if (DEBUG) {
477            Log.d(TAG, "Sending 'Progress' notification for id " + info.id + "(pid " + info.pid
478                    + "): " + percentText);
479        }
480        NotificationManager.from(mContext).notify(TAG, info.id, notification);
481    }
482
483    /**
484     * Creates a {@link PendingIntent} for a notification action used to cancel a bugreport.
485     */
486    private static PendingIntent newCancelIntent(Context context, BugreportInfo info) {
487        final Intent intent = new Intent(INTENT_BUGREPORT_CANCEL);
488        intent.setClass(context, BugreportProgressService.class);
489        intent.putExtra(EXTRA_ID, info.id);
490        return PendingIntent.getService(context, info.id, intent,
491                PendingIntent.FLAG_UPDATE_CURRENT);
492    }
493
494    /**
495     * Finalizes the progress on a given bugreport and cancel its notification.
496     */
497    private void stopProgress(int id) {
498        if (mProcesses.indexOfKey(id) < 0) {
499            Log.w(TAG, "ID not watched: " + id);
500        } else {
501            Log.d(TAG, "Removing ID " + id);
502            mProcesses.remove(id);
503        }
504        stopSelfWhenDone();
505        Log.v(TAG, "stopProgress(" + id + "): cancel notification");
506        NotificationManager.from(mContext).cancel(TAG, id);
507    }
508
509    /**
510     * Cancels a bugreport upon user's request.
511     */
512    private void cancel(int id) {
513        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_CANCEL);
514        Log.v(TAG, "cancel: ID=" + id);
515        final BugreportInfo info = getInfo(id);
516        if (info != null && !info.finished) {
517            Log.i(TAG, "Cancelling bugreport service (ID=" + id + ") on user's request");
518            setSystemProperty(CTL_STOP, BUGREPORT_SERVICE);
519            deleteScreenshots(info);
520        }
521        stopProgress(id);
522    }
523
524    /**
525     * Poll {@link SystemProperties} to get the progress on each monitored process.
526     *
527     * @return whether it should keep polling.
528     */
529    private boolean pollProgress() {
530        final int total = mProcesses.size();
531        if (total == 0) {
532            Log.d(TAG, "No process to poll progress.");
533        }
534        int activeProcesses = 0;
535        for (int i = 0; i < total; i++) {
536            final BugreportInfo info = mProcesses.valueAt(i);
537            if (info == null) {
538                Log.wtf(TAG, "pollProgress(): null info at index " + i + "(ID = "
539                        + mProcesses.keyAt(i) + ")");
540                continue;
541            }
542
543            final int pid = info.pid;
544            final int id = info.id;
545            if (info.finished) {
546                if (DEBUG) Log.v(TAG, "Skipping finished process " + pid + " (id: " + id + ")");
547                continue;
548            }
549            activeProcesses++;
550            final String progressKey = DUMPSTATE_PREFIX + pid + PROGRESS_SUFFIX;
551            final int progress = SystemProperties.getInt(progressKey, 0);
552            if (progress == 0) {
553                Log.v(TAG, "System property " + progressKey + " is not set yet");
554            }
555            final int max = SystemProperties.getInt(DUMPSTATE_PREFIX + pid + MAX_SUFFIX, 0);
556            final boolean maxChanged = max > 0 && max != info.max;
557            final boolean progressChanged = progress > 0 && progress != info.progress;
558
559            if (progressChanged || maxChanged) {
560                if (progressChanged) {
561                    if (DEBUG) Log.v(TAG, "Updating progress for PID " + pid + "(id: " + id
562                            + ") from " + info.progress + " to " + progress);
563                    info.progress = progress;
564                }
565                if (maxChanged) {
566                    Log.i(TAG, "Updating max progress for PID " + pid + "(id: " + id
567                            + ") from " + info.max + " to " + max);
568                    info.max = max;
569                }
570                info.lastUpdate = System.currentTimeMillis();
571                updateProgress(info);
572            } else {
573                long inactiveTime = System.currentTimeMillis() - info.lastUpdate;
574                if (inactiveTime >= INACTIVITY_TIMEOUT) {
575                    Log.w(TAG, "No progress update for PID " + pid + " since "
576                            + info.getFormattedLastUpdate());
577                    stopProgress(info.id);
578                }
579            }
580        }
581        if (DEBUG) Log.v(TAG, "pollProgress() total=" + total + ", actives=" + activeProcesses);
582        return activeProcesses > 0;
583    }
584
585    /**
586     * Fetches a {@link BugreportInfo} for a given process and launches a dialog where the user can
587     * change its values.
588     */
589    private void launchBugreportInfoDialog(int id) {
590        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_DETAILS);
591        // Copy values so it doesn't lock mProcesses while UI is being updated
592        final String name, title, description;
593        final BugreportInfo info = getInfo(id);
594        if (info == null) {
595            // Most likely am killed Shell before user tapped the notification. Since system might
596            // be too busy anwyays, it's better to ignore the notification and switch back to the
597            // non-interactive mode (where the bugerport will be shared upon completion).
598            Log.d(TAG, "launchBugreportInfoDialog(" + id + "): cancel notification");
599            // TODO: add test case to make sure notification is canceled.
600            NotificationManager.from(mContext).cancel(TAG, id);
601            return;
602        }
603
604        collapseNotificationBar();
605        mInfoDialog.initialize(mContext, info);
606    }
607
608    /**
609     * Starting point for taking a screenshot.
610     * <p>
611     * If {@code delayed} is set, it first display a toast message and waits
612     * {@link #SCREENSHOT_DELAY_SECONDS} seconds before taking it, otherwise it takes the screenshot
613     * right away.
614     * <p>
615     * Typical usage is delaying when taken from the notification action, and taking it right away
616     * upon receiving a {@link #INTENT_BUGREPORT_STARTED}.
617     */
618    private void takeScreenshot(int id, boolean delayed) {
619        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_SCREENSHOT);
620        if (getInfo(id) == null) {
621            // Most likely am killed Shell before user tapped the notification. Since system might
622            // be too busy anwyays, it's better to ignore the notification and switch back to the
623            // non-interactive mode (where the bugerport will be shared upon completion).
624            Log.d(TAG, "takeScreenshot(" + id + ", " + delayed + "): cancel notification");
625            // TODO: add test case to make sure notification is canceled.
626            NotificationManager.from(mContext).cancel(TAG, id);
627            return;
628        }
629        setTakingScreenshot(true);
630        if (delayed) {
631            collapseNotificationBar();
632            final String msg = mContext.getResources()
633                    .getQuantityString(com.android.internal.R.plurals.bugreport_countdown,
634                            SCREENSHOT_DELAY_SECONDS, SCREENSHOT_DELAY_SECONDS);
635            Log.i(TAG, msg);
636            // Show a toast just once, otherwise it might be captured in the screenshot.
637            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
638
639            takeScreenshot(id, SCREENSHOT_DELAY_SECONDS);
640        } else {
641            takeScreenshot(id, 0);
642        }
643    }
644
645    /**
646     * Takes a screenshot after {@code delay} seconds.
647     */
648    private void takeScreenshot(int id, int delay) {
649        if (delay > 0) {
650            Log.d(TAG, "Taking screenshot for " + id + " in " + delay + " seconds");
651            final Message msg = mMainHandler.obtainMessage();
652            msg.what = MSG_DELAYED_SCREENSHOT;
653            msg.arg1 = id;
654            msg.arg2 = delay - 1;
655            mMainHandler.sendMessageDelayed(msg, DateUtils.SECOND_IN_MILLIS);
656            return;
657        }
658
659        // It's time to take the screenshot: let the proper thread handle it
660        final BugreportInfo info = getInfo(id);
661        if (info == null) {
662            return;
663        }
664        final String screenshotPath =
665                new File(mScreenshotsDir, info.getPathNextScreenshot()).getAbsolutePath();
666
667        final Message requestMsg = new Message();
668        requestMsg.what = MSG_SCREENSHOT_REQUEST;
669        requestMsg.arg1 = id;
670        requestMsg.obj = screenshotPath;
671        mScreenshotHandler.sendMessage(requestMsg);
672    }
673
674    /**
675     * Sets the internal {@code mTakingScreenshot} state and updates all notifications so their
676     * SCREENSHOT button is enabled or disabled accordingly.
677     */
678    private void setTakingScreenshot(boolean flag) {
679        synchronized (BugreportProgressService.this) {
680            mTakingScreenshot = flag;
681            for (int i = 0; i < mProcesses.size(); i++) {
682                final BugreportInfo info = mProcesses.valueAt(i);
683                if (info.finished) {
684                    Log.d(TAG, "Not updating progress because share notification was already sent");
685                    continue;
686                }
687                updateProgress(info);
688            }
689        }
690    }
691
692    private void handleScreenshotRequest(Message requestMsg) {
693        String screenshotFile = (String) requestMsg.obj;
694        boolean taken = takeScreenshot(mContext, screenshotFile);
695        setTakingScreenshot(false);
696
697        final Message resultMsg = new Message();
698        resultMsg.what = MSG_SCREENSHOT_RESPONSE;
699        resultMsg.arg1 = requestMsg.arg1;
700        resultMsg.arg2 = taken ? 1 : 0;
701        resultMsg.obj = screenshotFile;
702        mMainHandler.sendMessage(resultMsg);
703    }
704
705    private void handleScreenshotResponse(Message resultMsg) {
706        final boolean taken = resultMsg.arg2 != 0;
707        final BugreportInfo info = getInfo(resultMsg.arg1);
708        if (info == null) {
709            return;
710        }
711        final File screenshotFile = new File((String) resultMsg.obj);
712
713        final String msg;
714        if (taken) {
715            info.addScreenshot(screenshotFile);
716            if (info.finished) {
717                Log.d(TAG, "Screenshot finished after bugreport; updating share notification");
718                info.renameScreenshots(mScreenshotsDir);
719                sendBugreportNotification(mContext, info);
720            }
721            msg = mContext.getString(R.string.bugreport_screenshot_taken);
722        } else {
723            // TODO: try again using Framework APIs instead of relying on screencap.
724            msg = mContext.getString(R.string.bugreport_screenshot_failed);
725            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
726        }
727        Log.d(TAG, msg);
728    }
729
730    /**
731     * Deletes all screenshots taken for a given bugreport.
732     */
733    private void deleteScreenshots(BugreportInfo info) {
734        for (File file : info.screenshotFiles) {
735            Log.i(TAG, "Deleting screenshot file " + file);
736            file.delete();
737        }
738    }
739
740    /**
741     * Finishes the service when it's not monitoring any more processes.
742     */
743    private void stopSelfWhenDone() {
744        if (mProcesses.size() > 0) {
745            if (DEBUG) Log.d(TAG, "Staying alive, waiting for IDs " + mProcesses);
746            return;
747        }
748        Log.v(TAG, "No more processes to handle, shutting down");
749        stopSelf();
750    }
751
752    /**
753     * Handles the BUGREPORT_FINISHED intent sent by {@code dumpstate}.
754     */
755    private void onBugreportFinished(int id, Intent intent) {
756        final File bugreportFile = getFileExtra(intent, EXTRA_BUGREPORT);
757        if (bugreportFile == null) {
758            // Should never happen, dumpstate always set the file.
759            Log.wtf(TAG, "Missing " + EXTRA_BUGREPORT + " on intent " + intent);
760            return;
761        }
762        mInfoDialog.onBugreportFinished(id);
763        BugreportInfo info = getInfo(id);
764        if (info == null) {
765            // Happens when BUGREPORT_FINISHED was received without a BUGREPORT_STARTED first.
766            Log.v(TAG, "Creating info for untracked ID " + id);
767            info = new BugreportInfo(mContext, id);
768            mProcesses.put(id, info);
769        }
770        info.renameScreenshots(mScreenshotsDir);
771        info.bugreportFile = bugreportFile;
772
773        final int max = intent.getIntExtra(EXTRA_MAX, -1);
774        if (max != -1) {
775            MetricsLogger.histogram(this, "dumpstate_duration", max);
776            info.max = max;
777        }
778
779        final File screenshot = getFileExtra(intent, EXTRA_SCREENSHOT);
780        if (screenshot != null) {
781            info.addScreenshot(screenshot);
782        }
783        info.finished = true;
784
785        final Configuration conf = mContext.getResources().getConfiguration();
786        if ((conf.uiMode & Configuration.UI_MODE_TYPE_MASK) != Configuration.UI_MODE_TYPE_WATCH) {
787            triggerLocalNotification(mContext, info);
788        }
789    }
790
791    /**
792     * Responsible for triggering a notification that allows the user to start a "share" intent with
793     * the bugreport. On watches we have other methods to allow the user to start this intent
794     * (usually by triggering it on another connected device); we don't need to display the
795     * notification in this case.
796     */
797    private void triggerLocalNotification(final Context context, final BugreportInfo info) {
798        if (!info.bugreportFile.exists() || !info.bugreportFile.canRead()) {
799            Log.e(TAG, "Could not read bugreport file " + info.bugreportFile);
800            Toast.makeText(context, R.string.bugreport_unreadable_text, Toast.LENGTH_LONG).show();
801            stopProgress(info.id);
802            return;
803        }
804
805        boolean isPlainText = info.bugreportFile.getName().toLowerCase().endsWith(".txt");
806        if (!isPlainText) {
807            // Already zipped, send it right away.
808            sendBugreportNotification(context, info);
809        } else {
810            // Asynchronously zip the file first, then send it.
811            sendZippedBugreportNotification(context, info);
812        }
813    }
814
815    private static Intent buildWarningIntent(Context context, Intent sendIntent) {
816        final Intent intent = new Intent(context, BugreportWarningActivity.class);
817        intent.putExtra(Intent.EXTRA_INTENT, sendIntent);
818        return intent;
819    }
820
821    /**
822     * Build {@link Intent} that can be used to share the given bugreport.
823     */
824    private static Intent buildSendIntent(Context context, BugreportInfo info) {
825        // Files are kept on private storage, so turn into Uris that we can
826        // grant temporary permissions for.
827        final Uri bugreportUri = getUri(context, info.bugreportFile);
828
829        final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
830        final String mimeType = "application/vnd.android.bugreport";
831        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
832        intent.addCategory(Intent.CATEGORY_DEFAULT);
833        intent.setType(mimeType);
834
835        final String subject = !TextUtils.isEmpty(info.title) ?
836                info.title : bugreportUri.getLastPathSegment();
837        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
838
839        // EXTRA_TEXT should be an ArrayList, but some clients are expecting a single String.
840        // So, to avoid an exception on Intent.migrateExtraStreamToClipData(), we need to manually
841        // create the ClipData object with the attachments URIs.
842        final StringBuilder messageBody = new StringBuilder("Build info: ")
843            .append(SystemProperties.get("ro.build.description"))
844            .append("\nSerial number: ")
845            .append(SystemProperties.get("ro.serialno"));
846        if (!TextUtils.isEmpty(info.description)) {
847            messageBody.append("\nDescription: ").append(info.description);
848        }
849        intent.putExtra(Intent.EXTRA_TEXT, messageBody.toString());
850        final ClipData clipData = new ClipData(null, new String[] { mimeType },
851                new ClipData.Item(null, null, null, bugreportUri));
852        final ArrayList<Uri> attachments = Lists.newArrayList(bugreportUri);
853        for (File screenshot : info.screenshotFiles) {
854            final Uri screenshotUri = getUri(context, screenshot);
855            clipData.addItem(new ClipData.Item(null, null, null, screenshotUri));
856            attachments.add(screenshotUri);
857        }
858        intent.setClipData(clipData);
859        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
860
861        final Account sendToAccount = findSendToAccount(context);
862        if (sendToAccount != null) {
863            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { sendToAccount.name });
864        }
865
866        return intent;
867    }
868
869    /**
870     * Shares the bugreport upon user's request by issuing a {@link Intent#ACTION_SEND_MULTIPLE}
871     * intent, but issuing a warning dialog the first time.
872     */
873    private void shareBugreport(int id, BugreportInfo sharedInfo) {
874        MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_NOTIFICATION_ACTION_SHARE);
875        BugreportInfo info = getInfo(id);
876        if (info == null) {
877            // Service was terminated but notification persisted
878            info = sharedInfo;
879            Log.d(TAG, "shareBugreport(): no info for ID " + id + " on managed processes ("
880                    + mProcesses + "), using info from intent instead (" + info + ")");
881        }
882
883        addDetailsToZipFile(mContext, info);
884
885        final Intent sendIntent = buildSendIntent(mContext, info);
886        final Intent notifIntent;
887
888        // Send through warning dialog by default
889        if (getWarningState(mContext, STATE_SHOW) == STATE_SHOW) {
890            notifIntent = buildWarningIntent(mContext, sendIntent);
891        } else {
892            notifIntent = sendIntent;
893        }
894        notifIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
895
896        // Send the share intent...
897        mContext.startActivity(notifIntent);
898
899        // ... and stop watching this process.
900        stopProgress(id);
901    }
902
903    /**
904     * Sends a notification indicating the bugreport has finished so use can share it.
905     */
906    private static void sendBugreportNotification(Context context, BugreportInfo info) {
907
908        // Since adding the details can take a while, do it before notifying user.
909        addDetailsToZipFile(context, info);
910
911        final Intent shareIntent = new Intent(INTENT_BUGREPORT_SHARE);
912        shareIntent.setClass(context, BugreportProgressService.class);
913        shareIntent.setAction(INTENT_BUGREPORT_SHARE);
914        shareIntent.putExtra(EXTRA_ID, info.id);
915        shareIntent.putExtra(EXTRA_INFO, info);
916
917        final String title = context.getString(R.string.bugreport_finished_title, info.id);
918        final Notification.Builder builder = new Notification.Builder(context)
919                .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
920                .setContentTitle(title)
921                .setTicker(title)
922                .setContentText(context.getString(R.string.bugreport_finished_text))
923                .setContentIntent(PendingIntent.getService(context, info.id, shareIntent,
924                        PendingIntent.FLAG_UPDATE_CURRENT))
925                .setDeleteIntent(newCancelIntent(context, info))
926                .setLocalOnly(true)
927                .setColor(context.getColor(
928                        com.android.internal.R.color.system_notification_accent_color));
929
930        if (!TextUtils.isEmpty(info.name)) {
931            builder.setContentInfo(info.name);
932        }
933
934        Log.v(TAG, "Sending 'Share' notification for ID " + info.id + ": " + title);
935        NotificationManager.from(context).notify(TAG, info.id, builder.build());
936    }
937
938    /**
939     * Sends a notification indicating the bugreport is being updated so the user can wait until it
940     * finishes - at this point there is nothing to be done other than waiting, hence it has no
941     * pending action.
942     */
943    private static void sendBugreportBeingUpdatedNotification(Context context, int id) {
944        final String title = context.getString(R.string.bugreport_updating_title);
945        final Notification.Builder builder = new Notification.Builder(context)
946                .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
947                .setContentTitle(title)
948                .setTicker(title)
949                .setContentText(context.getString(R.string.bugreport_updating_wait))
950                .setLocalOnly(true)
951                .setColor(context.getColor(
952                        com.android.internal.R.color.system_notification_accent_color));
953        Log.v(TAG, "Sending 'Updating zip' notification for ID " + id + ": " + title);
954        NotificationManager.from(context).notify(TAG, id, builder.build());
955    }
956
957    /**
958     * Sends a zipped bugreport notification.
959     */
960    private static void sendZippedBugreportNotification(final Context context,
961            final BugreportInfo info) {
962        new AsyncTask<Void, Void, Void>() {
963            @Override
964            protected Void doInBackground(Void... params) {
965                zipBugreport(info);
966                sendBugreportNotification(context, info);
967                return null;
968            }
969        }.execute();
970    }
971
972    /**
973     * Zips a bugreport file, returning the path to the new file (or to the
974     * original in case of failure).
975     */
976    private static void zipBugreport(BugreportInfo info) {
977        final String bugreportPath = info.bugreportFile.getAbsolutePath();
978        final String zippedPath = bugreportPath.replace(".txt", ".zip");
979        Log.v(TAG, "zipping " + bugreportPath + " as " + zippedPath);
980        final File bugreportZippedFile = new File(zippedPath);
981        try (InputStream is = new FileInputStream(info.bugreportFile);
982                ZipOutputStream zos = new ZipOutputStream(
983                        new BufferedOutputStream(new FileOutputStream(bugreportZippedFile)))) {
984            addEntry(zos, info.bugreportFile.getName(), is);
985            // Delete old file
986            final boolean deleted = info.bugreportFile.delete();
987            if (deleted) {
988                Log.v(TAG, "deleted original bugreport (" + bugreportPath + ")");
989            } else {
990                Log.e(TAG, "could not delete original bugreport (" + bugreportPath + ")");
991            }
992            info.bugreportFile = bugreportZippedFile;
993        } catch (IOException e) {
994            Log.e(TAG, "exception zipping file " + zippedPath, e);
995        }
996    }
997
998    /**
999     * Adds the user-provided info into the bugreport zip file.
1000     * <p>
1001     * If user provided a title, it will be saved into a {@code title.txt} entry; similarly, the
1002     * description will be saved on {@code description.txt}.
1003     */
1004    private static void addDetailsToZipFile(Context context, BugreportInfo info) {
1005        if (info.bugreportFile == null) {
1006            // One possible reason is a bug in the Parcelization code.
1007            Log.wtf(TAG, "addDetailsToZipFile(): no bugreportFile on " + info);
1008            return;
1009        }
1010        if (TextUtils.isEmpty(info.title) && TextUtils.isEmpty(info.description)) {
1011            Log.d(TAG, "Not touching zip file since neither title nor description are set");
1012            return;
1013        }
1014        if (info.addedDetailsToZip || info.addingDetailsToZip) {
1015            Log.d(TAG, "Already added details to zip file for " + info);
1016            return;
1017        }
1018        info.addingDetailsToZip = true;
1019
1020        // It's not possible to add a new entry into an existing file, so we need to create a new
1021        // zip, copy all entries, then rename it.
1022        sendBugreportBeingUpdatedNotification(context, info.id); // ...and that takes time
1023        final File dir = info.bugreportFile.getParentFile();
1024        final File tmpZip = new File(dir, "tmp-" + info.bugreportFile.getName());
1025        Log.d(TAG, "Writing temporary zip file (" + tmpZip + ") with title and/or description");
1026        try (ZipFile oldZip = new ZipFile(info.bugreportFile);
1027                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tmpZip))) {
1028
1029            // First copy contents from original zip.
1030            Enumeration<? extends ZipEntry> entries = oldZip.entries();
1031            while (entries.hasMoreElements()) {
1032                final ZipEntry entry = entries.nextElement();
1033                final String entryName = entry.getName();
1034                if (!entry.isDirectory()) {
1035                    addEntry(zos, entryName, entry.getTime(), oldZip.getInputStream(entry));
1036                } else {
1037                    Log.w(TAG, "skipping directory entry: " + entryName);
1038                }
1039            }
1040
1041            // Then add the user-provided info.
1042            addEntry(zos, "title.txt", info.title);
1043            addEntry(zos, "description.txt", info.description);
1044        } catch (IOException e) {
1045            info.addingDetailsToZip = false;
1046            Log.e(TAG, "exception zipping file " + tmpZip, e);
1047            return;
1048        }
1049
1050        if (!tmpZip.renameTo(info.bugreportFile)) {
1051            Log.e(TAG, "Could not rename " + tmpZip + " to " + info.bugreportFile);
1052        }
1053        info.addedDetailsToZip = true;
1054        info.addingDetailsToZip = false;
1055    }
1056
1057    private static void addEntry(ZipOutputStream zos, String entry, String text)
1058            throws IOException {
1059        if (DEBUG) Log.v(TAG, "adding entry '" + entry + "': " + text);
1060        if (!TextUtils.isEmpty(text)) {
1061            addEntry(zos, entry, new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
1062        }
1063    }
1064
1065    private static void addEntry(ZipOutputStream zos, String entryName, InputStream is)
1066            throws IOException {
1067        addEntry(zos, entryName, System.currentTimeMillis(), is);
1068    }
1069
1070    private static void addEntry(ZipOutputStream zos, String entryName, long timestamp,
1071            InputStream is) throws IOException {
1072        final ZipEntry entry = new ZipEntry(entryName);
1073        entry.setTime(timestamp);
1074        zos.putNextEntry(entry);
1075        final int totalBytes = Streams.copy(is, zos);
1076        if (DEBUG) Log.v(TAG, "size of '" + entryName + "' entry: " + totalBytes + " bytes");
1077        zos.closeEntry();
1078    }
1079
1080    /**
1081     * Find the best matching {@link Account} based on build properties.
1082     */
1083    private static Account findSendToAccount(Context context) {
1084        final AccountManager am = (AccountManager) context.getSystemService(
1085                Context.ACCOUNT_SERVICE);
1086
1087        String preferredDomain = SystemProperties.get("sendbug.preferred.domain");
1088        if (!preferredDomain.startsWith("@")) {
1089            preferredDomain = "@" + preferredDomain;
1090        }
1091
1092        final Account[] accounts = am.getAccounts();
1093        Account foundAccount = null;
1094        for (Account account : accounts) {
1095            if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
1096                if (!preferredDomain.isEmpty()) {
1097                    // if we have a preferred domain and it matches, return; otherwise keep
1098                    // looking
1099                    if (account.name.endsWith(preferredDomain)) {
1100                        return account;
1101                    } else {
1102                        foundAccount = account;
1103                    }
1104                    // if we don't have a preferred domain, just return since it looks like
1105                    // an email address
1106                } else {
1107                    return account;
1108                }
1109            }
1110        }
1111        return foundAccount;
1112    }
1113
1114    static Uri getUri(Context context, File file) {
1115        return file != null ? FileProvider.getUriForFile(context, AUTHORITY, file) : null;
1116    }
1117
1118    static File getFileExtra(Intent intent, String key) {
1119        final String path = intent.getStringExtra(key);
1120        if (path != null) {
1121            return new File(path);
1122        } else {
1123            return null;
1124        }
1125    }
1126
1127    private static boolean setSystemProperty(String key, String value) {
1128        try {
1129            if (DEBUG) Log.v(TAG, "Setting system property " + key + " to " + value);
1130            SystemProperties.set(key, value);
1131        } catch (IllegalArgumentException e) {
1132            Log.e(TAG, "Could not set property " + key + " to " + value, e);
1133            return false;
1134        }
1135        return true;
1136    }
1137
1138    /**
1139     * Updates the system property used by {@code dumpstate} to rename the final bugreport files.
1140     */
1141    private boolean setBugreportNameProperty(int pid, String name) {
1142        Log.d(TAG, "Updating bugreport name to " + name);
1143        final String key = DUMPSTATE_PREFIX + pid + NAME_SUFFIX;
1144        return setSystemProperty(key, name);
1145    }
1146
1147    /**
1148     * Updates the user-provided details of a bugreport.
1149     */
1150    private void updateBugreportInfo(int id, String name, String title, String description) {
1151        final BugreportInfo info = getInfo(id);
1152        if (info == null) {
1153            return;
1154        }
1155        if (title != null && !title.equals(info.title)) {
1156            MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_DETAILS_TITLE_CHANGED);
1157        }
1158        info.title = title;
1159        if (description != null && !description.equals(info.description)) {
1160            MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_DETAILS_DESCRIPTION_CHANGED);
1161        }
1162        info.description = description;
1163        if (name != null && !name.equals(info.name)) {
1164            MetricsLogger.action(this, MetricsEvent.ACTION_BUGREPORT_DETAILS_NAME_CHANGED);
1165            info.name = name;
1166            updateProgress(info);
1167        }
1168    }
1169
1170    private void collapseNotificationBar() {
1171        sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
1172    }
1173
1174    private static Looper newLooper(String name) {
1175        final HandlerThread thread = new HandlerThread(name, THREAD_PRIORITY_BACKGROUND);
1176        thread.start();
1177        return thread.getLooper();
1178    }
1179
1180    /**
1181     * Takes a screenshot and save it to the given location.
1182     */
1183    private static boolean takeScreenshot(Context context, String screenshotFile) {
1184        ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE))
1185                .vibrate(150);
1186        final ProcessBuilder screencap = new ProcessBuilder()
1187                .command("/system/bin/screencap", "-p", screenshotFile);
1188        Log.d(TAG, "Taking screenshot using " + screencap.command());
1189        try {
1190            final int exitValue = screencap.start().waitFor();
1191            if (exitValue == 0) {
1192                return true;
1193            }
1194            Log.e(TAG, "screencap (" + screencap.command() + ") failed: " + exitValue);
1195        } catch (IOException e) {
1196            Log.e(TAG, "screencap (" + screencap.command() + ") failed", e);
1197        } catch (InterruptedException e) {
1198            Log.w(TAG, "Thread interrupted while screencap still running");
1199            Thread.currentThread().interrupt();
1200        }
1201        return false;
1202    }
1203
1204    /**
1205     * Checks whether a character is valid on bugreport names.
1206     */
1207    @VisibleForTesting
1208    static boolean isValid(char c) {
1209        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
1210                || c == '_' || c == '-';
1211    }
1212
1213    /**
1214     * Helper class encapsulating the UI elements and logic used to display a dialog where user
1215     * can change the details of a bugreport.
1216     */
1217    private final class BugreportInfoDialog {
1218        private EditText mInfoName;
1219        private EditText mInfoTitle;
1220        private EditText mInfoDescription;
1221        private AlertDialog mDialog;
1222        private Button mOkButton;
1223        private int mId;
1224        private int mPid;
1225
1226        /**
1227         * Last "committed" value of the bugreport name.
1228         * <p>
1229         * Once initially set, it's only updated when user clicks the OK button.
1230         */
1231        private String mSavedName;
1232
1233        /**
1234         * Last value of the bugreport name as entered by the user.
1235         * <p>
1236         * Every time it's changed the equivalent system property is changed as well, but if the
1237         * user clicks CANCEL, the old value (stored on {@code mSavedName} is restored.
1238         * <p>
1239         * This logic handles the corner-case scenario where {@code dumpstate} finishes after the
1240         * user changed the name but didn't clicked OK yet (for example, because the user is typing
1241         * the description). The only drawback is that if the user changes the name while
1242         * {@code dumpstate} is running but clicks CANCEL after it finishes, then the final name
1243         * will be the one that has been canceled. But when {@code dumpstate} finishes the {code
1244         * name} UI is disabled and the old name restored anyways, so the user will be "alerted" of
1245         * such drawback.
1246         */
1247        private String mTempName;
1248
1249        /**
1250         * Sets its internal state and displays the dialog.
1251         */
1252        private void initialize(final Context context, BugreportInfo info) {
1253            final String dialogTitle =
1254                    context.getString(R.string.bugreport_info_dialog_title, info.id);
1255            // First initializes singleton.
1256            if (mDialog == null) {
1257                @SuppressLint("InflateParams")
1258                // It's ok pass null ViewRoot on AlertDialogs.
1259                final View view = View.inflate(context, R.layout.dialog_bugreport_info, null);
1260
1261                mInfoName = (EditText) view.findViewById(R.id.name);
1262                mInfoTitle = (EditText) view.findViewById(R.id.title);
1263                mInfoDescription = (EditText) view.findViewById(R.id.description);
1264
1265                mInfoName.setOnFocusChangeListener(new OnFocusChangeListener() {
1266
1267                    @Override
1268                    public void onFocusChange(View v, boolean hasFocus) {
1269                        if (hasFocus) {
1270                            return;
1271                        }
1272                        sanitizeName();
1273                    }
1274                });
1275
1276                mDialog = new AlertDialog.Builder(context)
1277                        .setView(view)
1278                        .setTitle(dialogTitle)
1279                        .setCancelable(false)
1280                        .setPositiveButton(context.getString(com.android.internal.R.string.ok),
1281                                null)
1282                        .setNegativeButton(context.getString(com.android.internal.R.string.cancel),
1283                                new DialogInterface.OnClickListener()
1284                                {
1285                                    @Override
1286                                    public void onClick(DialogInterface dialog, int id)
1287                                    {
1288                                        MetricsLogger.action(context,
1289                                                MetricsEvent.ACTION_BUGREPORT_DETAILS_CANCELED);
1290                                        if (!mTempName.equals(mSavedName)) {
1291                                            // Must restore dumpstate's name since it was changed
1292                                            // before user clicked OK.
1293                                            setBugreportNameProperty(mPid, mSavedName);
1294                                        }
1295                                    }
1296                                })
1297                        .create();
1298
1299                mDialog.getWindow().setAttributes(
1300                        new WindowManager.LayoutParams(
1301                                WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG));
1302
1303            } else {
1304                // Re-use view, but reset fields first.
1305                mDialog.setTitle(dialogTitle);
1306                mInfoName.setText(null);
1307                mInfoTitle.setText(null);
1308                mInfoDescription.setText(null);
1309            }
1310
1311            // Then set fields.
1312            mSavedName = mTempName = info.name;
1313            mId = info.id;
1314            mPid = info.pid;
1315            if (!TextUtils.isEmpty(info.name)) {
1316                mInfoName.setText(info.name);
1317            }
1318            if (!TextUtils.isEmpty(info.title)) {
1319                mInfoTitle.setText(info.title);
1320            }
1321            if (!TextUtils.isEmpty(info.description)) {
1322                mInfoDescription.setText(info.description);
1323            }
1324
1325            // And finally display it.
1326            mDialog.show();
1327
1328            // TODO: in a traditional AlertDialog, when the positive button is clicked the
1329            // dialog is always closed, but we need to validate the name first, so we need to
1330            // get a reference to it, which is only available after it's displayed.
1331            // It would be cleaner to use a regular dialog instead, but let's keep this
1332            // workaround for now and change it later, when we add another button to take
1333            // extra screenshots.
1334            if (mOkButton == null) {
1335                mOkButton = mDialog.getButton(DialogInterface.BUTTON_POSITIVE);
1336                mOkButton.setOnClickListener(new View.OnClickListener() {
1337
1338                    @Override
1339                    public void onClick(View view) {
1340                        MetricsLogger.action(context, MetricsEvent.ACTION_BUGREPORT_DETAILS_SAVED);
1341                        sanitizeName();
1342                        final String name = mInfoName.getText().toString();
1343                        final String title = mInfoTitle.getText().toString();
1344                        final String description = mInfoDescription.getText().toString();
1345
1346                        updateBugreportInfo(mId, name, title, description);
1347                        mDialog.dismiss();
1348                    }
1349                });
1350            }
1351        }
1352
1353        /**
1354         * Sanitizes the user-provided value for the {@code name} field, automatically replacing
1355         * invalid characters if necessary.
1356         */
1357        private void sanitizeName() {
1358            String name = mInfoName.getText().toString();
1359            if (name.equals(mTempName)) {
1360                if (DEBUG) Log.v(TAG, "name didn't change, no need to sanitize: " + name);
1361                return;
1362            }
1363            final StringBuilder safeName = new StringBuilder(name.length());
1364            boolean changed = false;
1365            for (int i = 0; i < name.length(); i++) {
1366                final char c = name.charAt(i);
1367                if (isValid(c)) {
1368                    safeName.append(c);
1369                } else {
1370                    changed = true;
1371                    safeName.append('_');
1372                }
1373            }
1374            if (changed) {
1375                Log.v(TAG, "changed invalid name '" + name + "' to '" + safeName + "'");
1376                name = safeName.toString();
1377                mInfoName.setText(name);
1378            }
1379            mTempName = name;
1380
1381            // Must update system property for the cases where dumpstate finishes
1382            // while the user is still entering other fields (like title or
1383            // description)
1384            setBugreportNameProperty(mPid, name);
1385        }
1386
1387       /**
1388         * Notifies the dialog that the bugreport has finished so it disables the {@code name}
1389         * field.
1390         * <p>Once the bugreport is finished dumpstate has already generated the final files, so
1391         * changing the name would have no effect.
1392         */
1393        private void onBugreportFinished(int id) {
1394            if (mInfoName != null) {
1395                mInfoName.setEnabled(false);
1396                mInfoName.setText(mSavedName);
1397            }
1398        }
1399
1400    }
1401
1402    /**
1403     * Information about a bugreport process while its in progress.
1404     */
1405    private static final class BugreportInfo implements Parcelable {
1406        private final Context context;
1407
1408        /**
1409         * Sequential, user-friendly id used to identify the bugreport.
1410         */
1411        final int id;
1412
1413        /**
1414         * {@code pid} of the {@code dumpstate} process generating the bugreport.
1415         */
1416        final int pid;
1417
1418        /**
1419         * Name of the bugreport, will be used to rename the final files.
1420         * <p>
1421         * Initial value is the bugreport filename reported by {@code dumpstate}, but user can
1422         * change it later to a more meaningful name.
1423         */
1424        String name;
1425
1426        /**
1427         * User-provided, one-line summary of the bug; when set, will be used as the subject
1428         * of the {@link Intent#ACTION_SEND_MULTIPLE} intent.
1429         */
1430        String title;
1431
1432        /**
1433         * User-provided, detailed description of the bugreport; when set, will be added to the body
1434         * of the {@link Intent#ACTION_SEND_MULTIPLE} intent.
1435         */
1436        String description;
1437
1438        /**
1439         * Maximum progress of the bugreport generation.
1440         */
1441        int max;
1442
1443        /**
1444         * Current progress of the bugreport generation.
1445         */
1446        int progress;
1447
1448        /**
1449         * Time of the last progress update.
1450         */
1451        long lastUpdate = System.currentTimeMillis();
1452
1453        /**
1454         * Time of the last progress update when Parcel was created.
1455         */
1456        String formattedLastUpdate;
1457
1458        /**
1459         * Path of the main bugreport file.
1460         */
1461        File bugreportFile;
1462
1463        /**
1464         * Path of the screenshot files.
1465         */
1466        List<File> screenshotFiles = new ArrayList<>(1);
1467
1468        /**
1469         * Whether dumpstate sent an intent informing it has finished.
1470         */
1471        boolean finished;
1472
1473        /**
1474         * Whether the details entries have been added to the bugreport yet.
1475         */
1476        boolean addingDetailsToZip;
1477        boolean addedDetailsToZip;
1478
1479        /**
1480         * Internal counter used to name screenshot files.
1481         */
1482        int screenshotCounter;
1483
1484        /**
1485         * Constructor for tracked bugreports - typically called upon receiving BUGREPORT_STARTED.
1486         */
1487        BugreportInfo(Context context, int id, int pid, String name, int max) {
1488            this.context = context;
1489            this.id = id;
1490            this.pid = pid;
1491            this.name = name;
1492            this.max = max;
1493        }
1494
1495        /**
1496         * Constructor for untracked bugreports - typically called upon receiving BUGREPORT_FINISHED
1497         * without a previous call to BUGREPORT_STARTED.
1498         */
1499        BugreportInfo(Context context, int id) {
1500            this(context, id, id, null, 0);
1501            this.finished = true;
1502        }
1503
1504        /**
1505         * Gets the name for next screenshot file.
1506         */
1507        String getPathNextScreenshot() {
1508            screenshotCounter ++;
1509            return "screenshot-" + pid + "-" + screenshotCounter + ".png";
1510        }
1511
1512        /**
1513         * Saves the location of a taken screenshot so it can be sent out at the end.
1514         */
1515        void addScreenshot(File screenshot) {
1516            screenshotFiles.add(screenshot);
1517        }
1518
1519        /**
1520         * Rename all screenshots files so that they contain the user-generated name instead of pid.
1521         */
1522        void renameScreenshots(File screenshotDir) {
1523            if (TextUtils.isEmpty(name)) {
1524                return;
1525            }
1526            final List<File> renamedFiles = new ArrayList<>(screenshotFiles.size());
1527            for (File oldFile : screenshotFiles) {
1528                final String oldName = oldFile.getName();
1529                final String newName = oldName.replaceFirst(Integer.toString(pid), name);
1530                final File newFile;
1531                if (!newName.equals(oldName)) {
1532                    final File renamedFile = new File(screenshotDir, newName);
1533                    newFile = oldFile.renameTo(renamedFile) ? renamedFile : oldFile;
1534                } else {
1535                    Log.w(TAG, "Name didn't change: " + oldName); // Shouldn't happen.
1536                    newFile = oldFile;
1537                }
1538                renamedFiles.add(newFile);
1539            }
1540            screenshotFiles = renamedFiles;
1541        }
1542
1543        String getFormattedLastUpdate() {
1544            if (context == null) {
1545                // Restored from Parcel
1546                return formattedLastUpdate == null ?
1547                        Long.toString(lastUpdate) : formattedLastUpdate;
1548            }
1549            return DateUtils.formatDateTime(context, lastUpdate,
1550                    DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
1551        }
1552
1553        @Override
1554        public String toString() {
1555            final float percent = ((float) progress * 100 / max);
1556            return "id: " + id + ", pid: " + pid + ", name: " + name + ", finished: " + finished
1557                    + "\n\ttitle: " + title + "\n\tdescription: " + description
1558                    + "\n\tfile: " + bugreportFile + "\n\tscreenshots: " + screenshotFiles
1559                    + "\n\tprogress: " + progress + "/" + max + " (" + percent + ")"
1560                    + "\n\tlast_update: " + getFormattedLastUpdate()
1561                    + "\naddingDetailsToZip: " + addingDetailsToZip
1562                    + " addedDetailsToZip: " + addedDetailsToZip;
1563        }
1564
1565        // Parcelable contract
1566        protected BugreportInfo(Parcel in) {
1567            context = null;
1568            id = in.readInt();
1569            pid = in.readInt();
1570            name = in.readString();
1571            title = in.readString();
1572            description = in.readString();
1573            max = in.readInt();
1574            progress = in.readInt();
1575            lastUpdate = in.readLong();
1576            formattedLastUpdate = in.readString();
1577            bugreportFile = readFile(in);
1578
1579            int screenshotSize = in.readInt();
1580            for (int i = 1; i <= screenshotSize; i++) {
1581                  screenshotFiles.add(readFile(in));
1582            }
1583
1584            finished = in.readInt() == 1;
1585            screenshotCounter = in.readInt();
1586        }
1587
1588        @Override
1589        public void writeToParcel(Parcel dest, int flags) {
1590            dest.writeInt(id);
1591            dest.writeInt(pid);
1592            dest.writeString(name);
1593            dest.writeString(title);
1594            dest.writeString(description);
1595            dest.writeInt(max);
1596            dest.writeInt(progress);
1597            dest.writeLong(lastUpdate);
1598            dest.writeString(getFormattedLastUpdate());
1599            writeFile(dest, bugreportFile);
1600
1601            dest.writeInt(screenshotFiles.size());
1602            for (File screenshotFile : screenshotFiles) {
1603                writeFile(dest, screenshotFile);
1604            }
1605
1606            dest.writeInt(finished ? 1 : 0);
1607            dest.writeInt(screenshotCounter);
1608        }
1609
1610        @Override
1611        public int describeContents() {
1612            return 0;
1613        }
1614
1615        private void writeFile(Parcel dest, File file) {
1616            dest.writeString(file == null ? null : file.getPath());
1617        }
1618
1619        private File readFile(Parcel in) {
1620            final String path = in.readString();
1621            return path == null ? null : new File(path);
1622        }
1623
1624        public static final Parcelable.Creator<BugreportInfo> CREATOR =
1625                new Parcelable.Creator<BugreportInfo>() {
1626            public BugreportInfo createFromParcel(Parcel source) {
1627                return new BugreportInfo(source);
1628            }
1629
1630            public BugreportInfo[] newArray(int size) {
1631                return new BugreportInfo[size];
1632            }
1633        };
1634
1635    }
1636}
1637