aboutsummaryrefslogtreecommitdiffstats
path: root/ddms/libs/ddmuilib/src/com/android/ddmuilib/logcat/LogCatPanel.java
blob: e7dcec9553dc808c499136cf40b1708613a958c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ddmuilib.logcat;

import com.android.ddmlib.DdmConstants;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmuilib.ITableFocusListener;
import com.android.ddmuilib.ITableFocusListener.IFocusedTableActivator;
import com.android.ddmuilib.FindDialog;
import com.android.ddmuilib.ImageLoader;
import com.android.ddmuilib.SelectionDependentPanel;
import com.android.ddmuilib.TableHelper;
import com.android.ddmuilib.AbstractBufferFindTarget;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * LogCatPanel displays a table listing the logcat messages.
 */
public final class LogCatPanel extends SelectionDependentPanel
                        implements ILogCatBufferChangeListener {
    /** Preference key to use for storing list of logcat filters. */
    public static final String LOGCAT_FILTERS_LIST = "logcat.view.filters.list";

    /** Preference key to use for storing font settings. */
    public static final String LOGCAT_VIEW_FONT_PREFKEY = "logcat.view.font";

    // Preference keys for message colors based on severity level
    private static final String MSG_COLOR_PREFKEY_PREFIX = "logcat.msg.color.";
    public static final String VERBOSE_COLOR_PREFKEY = MSG_COLOR_PREFKEY_PREFIX + "verbose"; //$NON-NLS-1$
    public static final String DEBUG_COLOR_PREFKEY = MSG_COLOR_PREFKEY_PREFIX + "debug"; //$NON-NLS-1$
    public static final String INFO_COLOR_PREFKEY = MSG_COLOR_PREFKEY_PREFIX + "info"; //$NON-NLS-1$
    public static final String WARN_COLOR_PREFKEY = MSG_COLOR_PREFKEY_PREFIX + "warn"; //$NON-NLS-1$
    public static final String ERROR_COLOR_PREFKEY = MSG_COLOR_PREFKEY_PREFIX + "error"; //$NON-NLS-1$
    public static final String ASSERT_COLOR_PREFKEY = MSG_COLOR_PREFKEY_PREFIX + "assert"; //$NON-NLS-1$

    // Use a monospace font family
    private static final String FONT_FAMILY =
            DdmConstants.CURRENT_PLATFORM == DdmConstants.PLATFORM_DARWIN ? "Monaco":"Courier New";

    // Use the default system font size
    private static final FontData DEFAULT_LOGCAT_FONTDATA;
    static {
        int h = Display.getDefault().getSystemFont().getFontData()[0].getHeight();
        DEFAULT_LOGCAT_FONTDATA = new FontData(FONT_FAMILY, h, SWT.NORMAL);
    }

    private static final String LOGCAT_VIEW_COLSIZE_PREFKEY_PREFIX = "logcat.view.colsize.";
    private static final String DISPLAY_FILTERS_COLUMN_PREFKEY = "logcat.view.display.filters";

    /** Default message to show in the message search field. */
    private static final String DEFAULT_SEARCH_MESSAGE =
            "Search for messages. Accepts Java regexes. "
            + "Prefix with pid:, app:, tag: or text: to limit scope.";

    /** Tooltip to show in the message search field. */
    private static final String DEFAULT_SEARCH_TOOLTIP =
            "Example search patterns:\n"
          + "    sqlite (search for sqlite in text field)\n"
          + "    app:browser (search for messages generated by the browser application)";

    private static final String IMAGE_ADD_FILTER = "add.png"; //$NON-NLS-1$
    private static final String IMAGE_DELETE_FILTER = "delete.png"; //$NON-NLS-1$
    private static final String IMAGE_EDIT_FILTER = "edit.png"; //$NON-NLS-1$
    private static final String IMAGE_SAVE_LOG_TO_FILE = "save.png"; //$NON-NLS-1$
    private static final String IMAGE_CLEAR_LOG = "clear.png"; //$NON-NLS-1$
    private static final String IMAGE_DISPLAY_FILTERS = "displayfilters.png"; //$NON-NLS-1$
    private static final String IMAGE_SCROLL_LOCK = "scroll_lock.png"; //$NON-NLS-1$

    private static final int[] WEIGHTS_SHOW_FILTERS = new int[] {15, 85};
    private static final int[] WEIGHTS_LOGCAT_ONLY = new int[] {0, 100};

    /** Index of the default filter in the saved filters column. */
    private static final int DEFAULT_FILTER_INDEX = 0;

    /* Text colors for the filter box */
    private static final Color VALID_FILTER_REGEX_COLOR =
            Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
    private static final Color INVALID_FILTER_REGEX_COLOR =
            Display.getDefault().getSystemColor(SWT.COLOR_RED);

    private LogCatReceiver mReceiver;
    private IPreferenceStore mPrefStore;

    private List<LogCatFilter> mLogCatFilters;
    private int mCurrentSelectedFilterIndex;

    private ToolItem mNewFilterToolItem;
    private ToolItem mDeleteFilterToolItem;
    private ToolItem mEditFilterToolItem;
    private TableViewer mFiltersTableViewer;

    private Combo mLiveFilterLevelCombo;
    private Text mLiveFilterText;

    private List<LogCatFilter> mCurrentFilters = Collections.emptyList();

    private Table mTable;

    private boolean mShouldScrollToLatestLog = true;
    private ToolItem mScrollLockCheckBox;

    private String mLogFileExportFolder;

    private Font mFont;
    private int mWrapWidthInChars;

    private Color mVerboseColor;
    private Color mDebugColor;
    private Color mInfoColor;
    private Color mWarnColor;
    private Color mErrorColor;
    private Color mAssertColor;

    private SashForm mSash;

    // messages added since last refresh, synchronized on mLogBuffer
    private List<LogCatMessage> mLogBuffer;

    // # of messages deleted since last refresh, synchronized on mLogBuffer
    private int mDeletedLogCount;

    /**
     * Construct a logcat panel.
     * @param prefStore preference store where UI preferences will be saved
     */
    public LogCatPanel(IPreferenceStore prefStore) {
        mPrefStore = prefStore;
        mLogBuffer = new ArrayList<LogCatMessage>(LogCatMessageList.MAX_MESSAGES_DEFAULT);

        initializeFilters();

        setupDefaultPreferences();
        initializePreferenceUpdateListeners();

        mFont = getFontFromPrefStore();
        loadMessageColorPreferences();
    }

    private void loadMessageColorPreferences() {
        if (mVerboseColor != null) {
            disposeMessageColors();
        }

        mVerboseColor = getColorFromPrefStore(VERBOSE_COLOR_PREFKEY);
        mDebugColor = getColorFromPrefStore(DEBUG_COLOR_PREFKEY);
        mInfoColor = getColorFromPrefStore(INFO_COLOR_PREFKEY);
        mWarnColor = getColorFromPrefStore(WARN_COLOR_PREFKEY);
        mErrorColor = getColorFromPrefStore(ERROR_COLOR_PREFKEY);
        mAssertColor = getColorFromPrefStore(ASSERT_COLOR_PREFKEY);
    }

    private void initializeFilters() {
        mLogCatFilters = new ArrayList<LogCatFilter>();

        /* add default filter matching all messages */
        String tag = "";
        String text = "";
        String pid = "";
        String app = "";
        mLogCatFilters.add(new LogCatFilter("All messages (no filters)",
                tag, text, pid, app, LogLevel.VERBOSE));

        /* restore saved filters from prefStore */
        List<LogCatFilter> savedFilters = getSavedFilters();
        mLogCatFilters.addAll(savedFilters);
    }

    private void setupDefaultPreferences() {
        PreferenceConverter.setDefault(mPrefStore, LogCatPanel.LOGCAT_VIEW_FONT_PREFKEY,
                DEFAULT_LOGCAT_FONTDATA);
        mPrefStore.setDefault(LogCatMessageList.MAX_MESSAGES_PREFKEY,
                LogCatMessageList.MAX_MESSAGES_DEFAULT);
        mPrefStore.setDefault(DISPLAY_FILTERS_COLUMN_PREFKEY, true);

        /* Default Colors for different log levels. */
        PreferenceConverter.setDefault(mPrefStore, LogCatPanel.VERBOSE_COLOR_PREFKEY,
                new RGB(0, 0, 0));
        PreferenceConverter.setDefault(mPrefStore, LogCatPanel.DEBUG_COLOR_PREFKEY,
                new RGB(0, 0, 127));
        PreferenceConverter.setDefault(mPrefStore, LogCatPanel.INFO_COLOR_PREFKEY,
                new RGB(0, 127, 0));
        PreferenceConverter.setDefault(mPrefStore, LogCatPanel.WARN_COLOR_PREFKEY,
                new RGB(255, 127, 0));
        PreferenceConverter.setDefault(mPrefStore, LogCatPanel.ERROR_COLOR_PREFKEY,
                new RGB(255, 0, 0));
        PreferenceConverter.setDefault(mPrefStore, LogCatPanel.ASSERT_COLOR_PREFKEY,
                new RGB(255, 0, 0));
    }

    private void initializePreferenceUpdateListeners() {
        mPrefStore.addPropertyChangeListener(new IPropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent event) {
                String changedProperty = event.getProperty();
                if (changedProperty.equals(LogCatPanel.LOGCAT_VIEW_FONT_PREFKEY)) {
                    if (mFont != null) {
                        mFont.dispose();
                    }
                    mFont = getFontFromPrefStore();
                    recomputeWrapWidth();
                    Display.getDefault().syncExec(new Runnable() {
                        @Override
                        public void run() {
                            for (TableItem it: mTable.getItems()) {
                                it.setFont(mFont);
                            }
                        }
                    });
                } else if (changedProperty.startsWith(MSG_COLOR_PREFKEY_PREFIX)) {
                    loadMessageColorPreferences();
                    Display.getDefault().syncExec(new Runnable() {
                       @Override
                       public void run() {
                           Color c = mVerboseColor;
                           for (TableItem it: mTable.getItems()) {
                               Object data = it.getData();
                               if (data instanceof LogCatMessage) {
                                   c = getForegroundColor((LogCatMessage) data);
                               }
                               it.setForeground(c);
                           }
                       }
                    });
                } else if (changedProperty.equals(LogCatMessageList.MAX_MESSAGES_PREFKEY)) {
                    mReceiver.resizeFifo(mPrefStore.getInt(
                            LogCatMessageList.MAX_MESSAGES_PREFKEY));
                    reloadLogBuffer();
                }
            }
        });
    }

    private void saveFilterPreferences() {
        LogCatFilterSettingsSerializer serializer = new LogCatFilterSettingsSerializer();

        /* save all filter settings except the first one which is the default */
        String e = serializer.encodeToPreferenceString(
                mLogCatFilters.subList(1, mLogCatFilters.size()));
        mPrefStore.setValue(LOGCAT_FILTERS_LIST, e);
    }

    private List<LogCatFilter> getSavedFilters() {
        LogCatFilterSettingsSerializer serializer = new LogCatFilterSettingsSerializer();
        String e = mPrefStore.getString(LOGCAT_FILTERS_LIST);
        return serializer.decodeFromPreferenceString(e);
    }

    @Override
    public void deviceSelected() {
        IDevice device = getCurrentDevice();
        if (device == null) {
            // If the device is not working properly, getCurrentDevice() could return null.
            // In such a case, we don't launch logcat, nor switch the display.
            return;
        }

        if (mReceiver != null) {
            // Don't need to listen to new logcat messages from previous device anymore.
            mReceiver.removeMessageReceivedEventListener(this);

            // When switching between devices, existing filter match count should be reset.
            for (LogCatFilter f : mLogCatFilters) {
                f.resetUnreadCount();
            }
        }

        mReceiver = LogCatReceiverFactory.INSTANCE.newReceiver(device, mPrefStore);
        mReceiver.addMessageReceivedEventListener(this);
        reloadLogBuffer();

        // Always scroll to last line whenever the selected device changes.
        // Run this in a separate async thread to give the table some time to update after the
        // setInput above.
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                scrollToLatestLog();
            }
        });
    }

    @Override
    public void clientSelected() {
    }

    @Override
    protected void postCreation() {
    }

    @Override
    protected Control createControl(Composite parent) {
        GridLayout layout = new GridLayout(1, false);
        parent.setLayout(layout);

        createViews(parent);
        setupDefaults();

        return null;
    }

    private void createViews(Composite parent) {
        mSash = createSash(parent);

        createListOfFilters(mSash);
        createLogTableView(mSash);

        boolean showFilters = mPrefStore.getBoolean(DISPLAY_FILTERS_COLUMN_PREFKEY);
        updateFiltersColumn(showFilters);
    }

    private SashForm createSash(Composite parent) {
        SashForm sash = new SashForm(parent, SWT.HORIZONTAL);
        sash.setLayoutData(new GridData(GridData.FILL_BOTH));
        return sash;
    }

    private void createListOfFilters(SashForm sash) {
        Composite c = new Composite(sash, SWT.BORDER);
        GridLayout layout = new GridLayout(2, false);
        c.setLayout(layout);
        c.setLayoutData(new GridData(GridData.FILL_BOTH));

        createFiltersToolbar(c);
        createFiltersTable(c);
    }

    private void createFiltersToolbar(Composite parent) {
        Label l = new Label(parent, SWT.NONE);
        l.setText("Saved Filters");
        GridData gd = new GridData();
        gd.horizontalAlignment = SWT.LEFT;
        l.setLayoutData(gd);

        ToolBar t = new ToolBar(parent, SWT.FLAT);
        gd = new GridData();
        gd.horizontalAlignment = SWT.RIGHT;
        t.setLayoutData(gd);

        /* new filter */
        mNewFilterToolItem = new ToolItem(t, SWT.PUSH);
        mNewFilterToolItem.setImage(
                ImageLoader.getDdmUiLibLoader().loadImage(IMAGE_ADD_FILTER, t.getDisplay()));
        mNewFilterToolItem.setToolTipText("Add a new logcat filter");
        mNewFilterToolItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                addNewFilter();
            }
        });

        /* delete filter */
        mDeleteFilterToolItem = new ToolItem(t, SWT.PUSH);
        mDeleteFilterToolItem.setImage(
                ImageLoader.getDdmUiLibLoader().loadImage(IMAGE_DELETE_FILTER, t.getDisplay()));
        mDeleteFilterToolItem.setToolTipText("Delete selected logcat filter");
        mDeleteFilterToolItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                deleteSelectedFilter();
            }
        });

        /* edit filter */
        mEditFilterToolItem = new ToolItem(t, SWT.PUSH);
        mEditFilterToolItem.setImage(
                ImageLoader.getDdmUiLibLoader().loadImage(IMAGE_EDIT_FILTER, t.getDisplay()));
        mEditFilterToolItem.setToolTipText("Edit selected logcat filter");
        mEditFilterToolItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                editSelectedFilter();
            }
        });
    }

    private void addNewFilter(String defaultTag, String defaultText, String defaultPid,
            String defaultAppName, LogLevel defaultLevel) {
        LogCatFilterSettingsDialog d = new LogCatFilterSettingsDialog(
                Display.getCurrent().getActiveShell());
        d.setDefaults("", defaultTag, defaultText, defaultPid, defaultAppName, defaultLevel);
        if (d.open() != Window.OK) {
            return;
        }

        LogCatFilter f = new LogCatFilter(d.getFilterName().trim(),
                d.getTag().trim(),
                d.getText().trim(),
                d.getPid().trim(),
                d.getAppName().trim(),
                LogLevel.getByString(d.getLogLevel()));

        mLogCatFilters.add(f);
        mFiltersTableViewer.refresh();

        /* select the newly added entry */
        int idx = mLogCatFilters.size() - 1;
        mFiltersTableViewer.getTable().setSelection(idx);

        filterSelectionChanged();
        saveFilterPreferences();
    }

    private void addNewFilter() {
        addNewFilter("", "", "",
                "", LogLevel.VERBOSE);
    }

    private void deleteSelectedFilter() {
        int selectedIndex = mFiltersTableViewer.getTable().getSelectionIndex();
        if (selectedIndex <= 0) {
            /* return if no selected filter, or the default filter was selected (0th). */
            return;
        }

        mLogCatFilters.remove(selectedIndex);
        mFiltersTableViewer.refresh();
        mFiltersTableViewer.getTable().setSelection(selectedIndex - 1);

        filterSelectionChanged();
        saveFilterPreferences();
    }

    private void editSelectedFilter() {
        int selectedIndex = mFiltersTableViewer.getTable().getSelectionIndex();
        if (selectedIndex < 0) {
            return;
        }

        LogCatFilter curFilter = mLogCatFilters.get(selectedIndex);

        LogCatFilterSettingsDialog dialog = new LogCatFilterSettingsDialog(
                Display.getCurrent().getActiveShell());
        dialog.setDefaults(curFilter.getName(), curFilter.getTag(), curFilter.getText(),
                curFilter.getPid(), curFilter.getAppName(), curFilter.getLogLevel());
        if (dialog.open() != Window.OK) {
            return;
        }

        LogCatFilter f = new LogCatFilter(dialog.getFilterName(),
                dialog.getTag(),
                dialog.getText(),
                dialog.getPid(),
                dialog.getAppName(),
                LogLevel.getByString(dialog.getLogLevel()));
        mLogCatFilters.set(selectedIndex, f);
        mFiltersTableViewer.refresh();

        mFiltersTableViewer.getTable().setSelection(selectedIndex);
        filterSelectionChanged();
        saveFilterPreferences();
    }

    /**
     * Select the transient filter for the specified application. If no such filter
     * exists, then create one and then select that. This method should be called from
     * the UI thread.
     * @param appName application name to filter by
     */
    public void selectTransientAppFilter(String appName) {
        assert mTable.getDisplay().getThread() == Thread.currentThread();

        LogCatFilter f = findTransientAppFilter(appName);
        if (f == null) {
            f = createTransientAppFilter(appName);
            mLogCatFilters.add(f);
        }

        selectFilterAt(mLogCatFilters.indexOf(f));
    }

    private LogCatFilter findTransientAppFilter(String appName) {
        for (LogCatFilter f : mLogCatFilters) {
            if (f.isTransient() && f.getAppName().equals(appName)) {
                return f;
            }
        }
        return null;
    }

    private LogCatFilter createTransientAppFilter(String appName) {
        LogCatFilter f = new LogCatFilter(appName + " (Session Filter)",
                "",
                "",
                "",
                appName,
                LogLevel.VERBOSE);
        f.setTransient();
        return f;
    }

    private void selectFilterAt(final int index) {
        mFiltersTableViewer.refresh();

        if (index != mFiltersTableViewer.getTable().getSelectionIndex()) {
            mFiltersTableViewer.getTable().setSelection(index);
            filterSelectionChanged();
        }
    }

    private void createFiltersTable(Composite parent) {
        final Table table = new Table(parent, SWT.FULL_SELECTION);

        GridData gd = new GridData(GridData.FILL_BOTH);
        gd.horizontalSpan = 2;
        table.setLayoutData(gd);

        mFiltersTableViewer = new TableViewer(table);
        mFiltersTableViewer.setContentProvider(new LogCatFilterContentProvider());
        mFiltersTableViewer.setLabelProvider(new LogCatFilterLabelProvider());
        mFiltersTableViewer.setInput(mLogCatFilters);

        mFiltersTableViewer.getTable().addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent event) {
                filterSelectionChanged();
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent arg0) {
                editSelectedFilter();
            }
        });
    }

    private void createLogTableView(SashForm sash) {
        Composite c = new Composite(sash, SWT.NONE);
        c.setLayout(new GridLayout());
        c.setLayoutData(new GridData(GridData.FILL_BOTH));

        createLiveFilters(c);
        createLogcatViewTable(c);
    }

    /** Create the search bar at the top of the logcat messages table. */
    private void createLiveFilters(Composite parent) {
        Composite c = new Composite(parent, SWT.NONE);
        c.setLayout(new GridLayout(3, false));
        c.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        mLiveFilterText = new Text(c, SWT.BORDER | SWT.SEARCH);
        mLiveFilterText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        mLiveFilterText.setMessage(DEFAULT_SEARCH_MESSAGE);
        mLiveFilterText.setToolTipText(DEFAULT_SEARCH_TOOLTIP);
        mLiveFilterText.addModifyListener(new ModifyListener() {
            @Override
            public void modifyText(ModifyEvent arg0) {
                updateFilterTextColor();
                updateAppliedFilters();
            }
        });

        mLiveFilterLevelCombo = new Combo(c, SWT.READ_ONLY | SWT.DROP_DOWN);
        mLiveFilterLevelCombo.setItems(
                LogCatFilterSettingsDialog.getLogLevels().toArray(new String[0]));
        mLiveFilterLevelCombo.select(0);
        mLiveFilterLevelCombo.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                updateAppliedFilters();
            }
        });

        ToolBar toolBar = new ToolBar(c, SWT.FLAT);

        ToolItem saveToLog = new ToolItem(toolBar, SWT.PUSH);
        saveToLog.setImage(ImageLoader.getDdmUiLibLoader().loadImage(IMAGE_SAVE_LOG_TO_FILE,
                toolBar.getDisplay()));
        saveToLog.setToolTipText("Export Selected Items To Text File..");
        saveToLog.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                saveLogToFile();
            }
        });

        ToolItem clearLog = new ToolItem(toolBar, SWT.PUSH);
        clearLog.setImage(
                ImageLoader.getDdmUiLibLoader().loadImage(IMAGE_CLEAR_LOG, toolBar.getDisplay()));
        clearLog.setToolTipText("Clear Log");
        clearLog.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                if (mReceiver != null) {
                    mReceiver.clearMessages();
                    refreshLogCatTable();

                    // the filters view is not cleared unless the filters are re-applied.
                    updateAppliedFilters();
                }
            }
        });

        final ToolItem showFiltersColumn = new ToolItem(toolBar, SWT.CHECK);
        showFiltersColumn.setImage(
                ImageLoader.getDdmUiLibLoader().loadImage(IMAGE_DISPLAY_FILTERS,
                        toolBar.getDisplay()));
        showFiltersColumn.setSelection(mPrefStore.getBoolean(DISPLAY_FILTERS_COLUMN_PREFKEY));
        showFiltersColumn.setToolTipText("Display Saved Filters View");
        showFiltersColumn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent event) {
                boolean showFilters = showFiltersColumn.getSelection();
                mPrefStore.setValue(DISPLAY_FILTERS_COLUMN_PREFKEY, showFilters);
                updateFiltersColumn(showFilters);
            }
        });

        mScrollLockCheckBox = new ToolItem(toolBar, SWT.CHECK);
        mScrollLockCheckBox.setImage(
                ImageLoader.getDdmUiLibLoader().loadImage(IMAGE_SCROLL_LOCK,
                        toolBar.getDisplay()));
        mScrollLockCheckBox.setSelection(false);
        mScrollLockCheckBox.setToolTipText("Scroll Lock");
        mScrollLockCheckBox.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent event) {
                boolean scrollLock = mScrollLockCheckBox.getSelection();
                setScrollToLatestLog(!scrollLock);
            }
        });
    }

    /** Sets the foreground color of filter text based on whether the regex is valid. */
    private void updateFilterTextColor() {
        String text = mLiveFilterText.getText();
        Color c;
        try {
            Pattern.compile(text.trim());
            c = VALID_FILTER_REGEX_COLOR;
        } catch (PatternSyntaxException e) {
            c = INVALID_FILTER_REGEX_COLOR;
        }
        mLiveFilterText.setForeground(c);
    }

    private void updateFiltersColumn(boolean showFilters) {
        if (showFilters) {
            mSash.setWeights(WEIGHTS_SHOW_FILTERS);
        } else {
            mSash.setWeights(WEIGHTS_LOGCAT_ONLY);
        }
    }

    /**
     * Save logcat messages selected in the table to a file.
     */
    private void saveLogToFile() {
        /* show dialog box and get target file name */
        final String fName = getLogFileTargetLocation();
        if (fName == null) {
            return;
        }

        /* obtain list of selected messages */
        final List<LogCatMessage> selectedMessages = getSelectedLogCatMessages();

        /* save messages to file in a different (non UI) thread */
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedWriter w = null;
                try {
                    w = new BufferedWriter(new FileWriter(fName));
                    for (LogCatMessage m : selectedMessages) {
                        w.append(m.toString());
                        w.newLine();
                    }
                } catch (final IOException e) {
                    Display.getDefault().asyncExec(new Runnable() {
                        @Override
                        public void run() {
                            MessageDialog.openError(Display.getCurrent().getActiveShell(),
                                    "Unable to export selection to file.",
                                    "Unexpected error while saving selected messages to file: "
                                            + e.getMessage());
                        }
                    });
                } finally {
                    if (w != null) {
                        try {
                            w.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                }
            }
        });
        t.setName("Saving selected items to logfile..");
        t.start();
    }

    /**
     * Display a {@link FileDialog} to the user and obtain the location for the log file.
     * @return path to target file, null if user canceled the dialog
     */
    private String getLogFileTargetLocation() {
        FileDialog fd = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);

        fd.setText("Save Log..");
        fd.setFileName("log.txt");

        if (mLogFileExportFolder == null) {
            mLogFileExportFolder = System.getProperty("user.home");
        }
        fd.setFilterPath(mLogFileExportFolder);

        fd.setFilterNames(new String[] {
                "Text Files (*.txt)"
        });
        fd.setFilterExtensions(new String[] {
                "*.txt"
        });

        String fName = fd.open();
        if (fName != null) {
            mLogFileExportFolder = fd.getFilterPath();  /* save path to restore on future calls */
        }

        return fName;
    }

    private List<LogCatMessage> getSelectedLogCatMessages() {
        int[] indices = mTable.getSelectionIndices();
        Arrays.sort(indices); /* Table.getSelectionIndices() does not specify an order */

        List<LogCatMessage> selectedMessages = new ArrayList<LogCatMessage>(indices.length);
        for (int i : indices) {
            Object data = mTable.getItem(i).getData();
            if (data instanceof LogCatMessage) {
                selectedMessages.add((LogCatMessage) data);
            }
        }

        return selectedMessages;
    }

    private List<LogCatMessage> applyCurrentFilters(List<LogCatMessage> msgList) {
        List<LogCatMessage> filteredItems = new ArrayList<LogCatMessage>(msgList.size());

        for (LogCatMessage msg: msgList) {
            if (isMessageAccepted(msg, mCurrentFilters)) {
                filteredItems.add(msg);
            }
        }

        return filteredItems;
    }

    private boolean isMessageAccepted(LogCatMessage msg, List<LogCatFilter> filters) {
        for (LogCatFilter f : filters) {
            if (!f.matches(msg)) {
                // not accepted by this filter
                return false;
            }
        }

        // accepted by all filters
        return true;
    }

    private void createLogcatViewTable(Composite parent) {
        mTable = new Table(parent, SWT.FULL_SELECTION | SWT.MULTI);

        mTable.setLayoutData(new GridData(GridData.FILL_BOTH));
        mTable.getHorizontalBar().setVisible(true);

        /** Columns to show in the table. */
        String[] properties = {
                "Level",
                "Time",
                "PID",
                "TID",
                "Application",
                "Tag",
                "Text",
        };

        /** The sampleText for each column is used to determine the default widths
         * for each column. The contents do not matter, only their lengths are needed. */
        String[] sampleText = {
                "    ",
                "    00-00 00:00:00.0000 ",
                "    0000",
                "    0000",
                "    com.android.launcher",
                "    SampleTagText",
                "    Log Message field should be pretty long by default. As long as possible for correct display on Mac.",
        };

        for (int i = 0; i < properties.length; i++) {
            TableHelper.createTableColumn(mTable,
                    properties[i],                      /* Column title */
                    SWT.LEFT,                           /* Column Style */
                    sampleText[i],                      /* String to compute default col width */
                    getColPreferenceKey(properties[i]), /* Preference Store key for this column */
                    mPrefStore);
        }

        // don't zebra stripe the table: When the buffer is full, and scroll lock is on, having
        // zebra striping means that the background could keep changing depending on the number
        // of new messages added to the bottom of the log.
        mTable.setLinesVisible(false);
        mTable.setHeaderVisible(true);

        // Set the row height to be sufficient enough to display the current font.
        // This is not strictly necessary, except that on WinXP, the rows showed up clipped. So
        // we explicitly set it to be sure.
        mTable.addListener(SWT.MeasureItem, new Listener() {
            @Override
            public void handleEvent(Event event) {
                event.height = event.gc.getFontMetrics().getHeight();
            }
        });

        // Update the label provider whenever the text column's width changes
        TableColumn textColumn = mTable.getColumn(properties.length - 1);
        textColumn.addControlListener(new ControlAdapter() {
            @Override
            public void controlResized(ControlEvent event) {
                recomputeWrapWidth();
            }
        });

        addRightClickMenu(mTable);
        initDoubleClickListener();
        recomputeWrapWidth();

        mTable.addDisposeListener(new DisposeListener() {
            @Override
            public void widgetDisposed(DisposeEvent arg0) {
                dispose();
            }
        });
    }

    /** Setup menu to be displayed when right clicking a log message. */
    private void addRightClickMenu(final Table table) {
        // This action will pop up a create filter dialog pre-populated with current selection
        final Action filterAction = new Action("Filter similar messages...") {
            @Override
            public void run() {
                List<LogCatMessage> selectedMessages = getSelectedLogCatMessages();
                if (selectedMessages.size() == 0) {
                    addNewFilter();
                } else {
                    LogCatMessage m = selectedMessages.get(0);
                    addNewFilter(m.getTag(), m.getMessage(), m.getPid(), m.getAppName(),
                            m.getLogLevel());
                }
            }
        };

        final Action findAction = new Action("Find...") {
            @Override
            public void run() {
                showFindDialog();
            };
        };

        final MenuManager mgr = new MenuManager();
        mgr.add(filterAction);
        mgr.add(findAction);
        final Menu menu = mgr.createContextMenu(table);

        table.addListener(SWT.MenuDetect, new Listener() {
            @Override
            public void handleEvent(Event event) {
                Point pt = table.getDisplay().map(null, table, new Point(event.x, event.y));
                Rectangle clientArea = table.getClientArea();

                // The click location is in the header if it is between
                // clientArea.y and clientArea.y + header height
                boolean header = pt.y > clientArea.y
                                    && pt.y < (clientArea.y + table.getHeaderHeight());

                // Show the menu only if it is not inside the header
                table.setMenu(header ? null : menu);
            }
        });
    }

    public void recomputeWrapWidth() {
        if (mTable == null || mTable.isDisposed()) {
            return;
        }

        // get width of the last column (log message)
        TableColumn tc = mTable.getColumn(mTable.getColumnCount() - 1);
        int colWidth = tc.getWidth();

        // get font width
        GC gc = new GC(tc.getParent());
        gc.setFont(mFont);
        int avgCharWidth = gc.getFontMetrics().getAverageCharWidth();
        gc.dispose();

        int MIN_CHARS_PER_LINE = 50;    // show atleast these many chars per line
        mWrapWidthInChars = Math.max(colWidth/avgCharWidth, MIN_CHARS_PER_LINE);

        int OFFSET_AT_END_OF_LINE = 10; // leave some space at the end of the line
        mWrapWidthInChars -= OFFSET_AT_END_OF_LINE;
    }

    private void setScrollToLatestLog(boolean scroll) {
        mShouldScrollToLatestLog = scroll;

        if (scroll) {
            scrollToLatestLog();
        }
    }

    private String getColPreferenceKey(String field) {
        return LOGCAT_VIEW_COLSIZE_PREFKEY_PREFIX + field;
    }

    private Font getFontFromPrefStore() {
        FontData fd = PreferenceConverter.getFontData(mPrefStore,
                LogCatPanel.LOGCAT_VIEW_FONT_PREFKEY);
        return new Font(Display.getDefault(), fd);
    }

    private Color getColorFromPrefStore(String key) {
        RGB rgb = PreferenceConverter.getColor(mPrefStore, key);
        return new Color(Display.getDefault(), rgb);
    }

    private void setupDefaults() {
        int defaultFilterIndex = 0;
        mFiltersTableViewer.getTable().setSelection(defaultFilterIndex);

        filterSelectionChanged();
    }

    /**
     * Perform all necessary updates whenever a filter is selected (by user or programmatically).
     */
    private void filterSelectionChanged() {
        int idx = mFiltersTableViewer.getTable().getSelectionIndex();
        if (idx == -1) {
            /* One of the filters should always be selected.
             * On Linux, there is no way to deselect an item.
             * On Mac, clicking inside the list view, but not an any item will result
             * in all items being deselected. In such a case, we simply reselect the
             * first entry. */
            idx = 0;
            mFiltersTableViewer.getTable().setSelection(idx);
        }

        mCurrentSelectedFilterIndex = idx;

        resetUnreadCountForSelectedFilter();
        updateFiltersToolBar();
        updateAppliedFilters();
    }

    private void resetUnreadCountForSelectedFilter() {
        mLogCatFilters.get(mCurrentSelectedFilterIndex).resetUnreadCount();
        refreshFiltersTable();
    }

    private void updateFiltersToolBar() {
        /* The default filter at index 0 can neither be edited, nor removed. */
        boolean en = mCurrentSelectedFilterIndex != DEFAULT_FILTER_INDEX;
        mEditFilterToolItem.setEnabled(en);
        mDeleteFilterToolItem.setEnabled(en);
    }

    private void updateAppliedFilters() {
        mCurrentFilters = getFiltersToApply();
        reloadLogBuffer();
    }

    private List<LogCatFilter> getFiltersToApply() {
        /* list of filters to apply = saved filter + live filters */
        List<LogCatFilter> filters = new ArrayList<LogCatFilter>();

        if (mCurrentSelectedFilterIndex != DEFAULT_FILTER_INDEX) {
            filters.add(getSelectedSavedFilter());
        }

        filters.addAll(getCurrentLiveFilters());
        return filters;
    }

    private List<LogCatFilter> getCurrentLiveFilters() {
        return LogCatFilter.fromString(
                mLiveFilterText.getText(),                                  /* current query */
                LogLevel.getByString(mLiveFilterLevelCombo.getText()));     /* current log level */
    }

    private LogCatFilter getSelectedSavedFilter() {
        return mLogCatFilters.get(mCurrentSelectedFilterIndex);
    }

    @Override
    public void setFocus() {
    }

    @Override
    public void bufferChanged(List<LogCatMessage> addedMessages,
            List<LogCatMessage> deletedMessages) {

        synchronized (mLogBuffer) {
            addedMessages = applyCurrentFilters(addedMessages);
            deletedMessages = applyCurrentFilters(deletedMessages);

            mLogBuffer.addAll(addedMessages);
            mDeletedLogCount += deletedMessages.size();
        }

        refreshLogCatTable();
        updateUnreadCount(addedMessages);
        refreshFiltersTable();
    }

    private void reloadLogBuffer() {
        mTable.removeAll();

        synchronized (mLogBuffer) {
            mLogBuffer.clear();
            mDeletedLogCount = 0;
        }

        if (mReceiver == null || mReceiver.getMessages() == null) {
            return;
        }

        List<LogCatMessage> addedMessages = mReceiver.getMessages().getAllMessages();
        List<LogCatMessage> deletedMessages = Collections.emptyList();
        bufferChanged(addedMessages, deletedMessages);
    }

    /**
     * When new messages are received, and they match a saved filter, update
     * the unread count associated with that filter.
     * @param receivedMessages list of new messages received
     */
    private void updateUnreadCount(List<LogCatMessage> receivedMessages) {
        for (int i = 0; i < mLogCatFilters.size(); i++) {
            if (i == mCurrentSelectedFilterIndex) {
                /* no need to update unread count for currently selected filter */
                continue;
            }
            mLogCatFilters.get(i).updateUnreadCount(receivedMessages);
        }
    }

    private void refreshFiltersTable() {
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                if (mFiltersTableViewer.getTable().isDisposed()) {
                    return;
                }
                mFiltersTableViewer.refresh();
            }
        });
    }

    /** Task currently submitted to {@link Display#asyncExec} to be run in UI thread. */
    private LogCatTableRefresherTask mCurrentRefresher;

    /**
     * Refresh the logcat table asynchronously from the UI thread.
     * This method adds a new async refresh only if there are no pending refreshes for the table.
     * Doing so eliminates redundant refresh threads from being queued up to be run on the
     * display thread.
     */
    private void refreshLogCatTable() {
        synchronized (this) {
            if (mCurrentRefresher == null) {
                mCurrentRefresher = new LogCatTableRefresherTask();
                Display.getDefault().asyncExec(mCurrentRefresher);
            }
        }
    }

    /**
     * The {@link LogCatTableRefresherTask} takes care of refreshing the table with the
     * new log messages that have been received. Since the log behaves like a circular buffer,
     * the first step is to remove items from the top of the table (if necessary). This step
     * is complicated by the fact that a single log message may span multiple rows if the message
     * was wrapped. Once the deleted items are removed, the new messages are added to the bottom
     * of the table. If scroll lock is enabled, the item that was original visible is made visible
     * again, if not, the last item is made visible.
     */
    private class LogCatTableRefresherTask implements Runnable {
        @Override
        public void run() {
            if (mTable.isDisposed()) {
                return;
            }
            synchronized (LogCatPanel.this) {
                mCurrentRefresher = null;
            }

            // Current topIndex so that it can be restored if scroll locked.
            int topIndex = mTable.getTopIndex();

            mTable.setRedraw(false);

            // Obtain the list of new messages, and the number of deleted messages.
            List<LogCatMessage> newMessages;
            int deletedMessageCount;
            synchronized (mLogBuffer) {
                newMessages = new ArrayList<LogCatMessage>(mLogBuffer);
                mLogBuffer.clear();

                deletedMessageCount = mDeletedLogCount;
                mDeletedLogCount = 0;

                mFindTarget.scrollBy(deletedMessageCount);
            }

            int originalItemCount = mTable.getItemCount();

            // Remove entries from the start of the table if they were removed in the log buffer
            // This is complicated by the fact that a single message may span multiple TableItems
            // if it was word-wrapped.
            deletedMessageCount -= removeFromTable(mTable, deletedMessageCount);

            // Compute number of table items that were deleted from the table.
            int deletedItemCount = originalItemCount - mTable.getItemCount();

            // If there are more messages to delete (after deleting messages from the table),
            // then delete them from the start of the newly added messages list
            if (deletedMessageCount > 0) {
                assert deletedMessageCount < newMessages.size();
                for (int i = 0; i < deletedMessageCount; i++) {
                    newMessages.remove(0);
                }
            }

            // Add the remaining messages to the table.
            for (LogCatMessage m: newMessages) {
                List<String> wrappedMessageList = wrapMessage(m.getMessage(), mWrapWidthInChars);
                Color c = getForegroundColor(m);
                for (int i = 0; i < wrappedMessageList.size(); i++) {
                    TableItem item = new TableItem(mTable, SWT.NONE);

                    if (i == 0) {
                        // Only set the message data in the first item. This allows code that
                        // examines the table item data (such as copy selection) to distinguish
                        // between real messages versus lines that are really just wrapped
                        // content from the previous message.
                        item.setData(m);

                        item.setText(new String[] {
                                Character.toString(m.getLogLevel().getPriorityLetter()),
                                m.getTime(),
                                m.getPid(),
                                m.getTid(),
                                m.getAppName(),
                                m.getTag(),
                                wrappedMessageList.get(i)
                        });
                    } else {
                        item.setText(new String[] {
                                "", "", "", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                                "", "", "", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                                wrappedMessageList.get(i)
                        });
                    }
                    item.setForeground(c);
                    item.setFont(mFont);
                }
            }

            if (mShouldScrollToLatestLog) {
                scrollToLatestLog();
            } else {
                // If scroll locked, show the same item that was original visible in the table.
                int index = Math.max(topIndex - deletedItemCount, 0);
                mTable.setTopIndex(index);
            }

            mTable.setRedraw(true);
        }

        /**
         * Removes given number of messages from the table, starting at the top of the table.
         * Note that the number of messages deleted is not equal to the number of rows
         * deleted since a single message could span multiple rows. This method first calculates
         * the number of rows that correspond to the number of messages to delete, and then
         * removes all those rows.
         * @param table table from which messages should be removed
         * @param msgCount number of messages to be removed
         * @return number of messages that were actually removed
         */
        private int removeFromTable(Table table, int msgCount) {
            int deletedMessageCount = 0; // # of messages that have been deleted
            int lastItemToDelete = 0;    // index of the last item that should be deleted

            while (deletedMessageCount < msgCount && lastItemToDelete < table.getItemCount()) {
                // only rows that begin a message have their item data set
                TableItem item = table.getItem(lastItemToDelete);
                if (item.getData() != null) {
                    deletedMessageCount++;
                }

                lastItemToDelete++;
            }

            // If there are any table items left over at the end that are wrapped over from the
            // previous message, mark them for deletion as well.
            if (lastItemToDelete < table.getItemCount()
                    && table.getItem(lastItemToDelete).getData() == null) {
                lastItemToDelete++;
            }

            table.remove(0, lastItemToDelete - 1);

            return deletedMessageCount;
        }
    }

    /** Scroll to the last line. */
    private void scrollToLatestLog() {
        mTable.setTopIndex(mTable.getItemCount() - 1);
    }

    /**
     * Splits the message into multiple lines if the message length exceeds given width.
     * If the message was split, then a wrap character \u23ce is appended to the end of all
     * lines but the last one.
     */
    private List<String> wrapMessage(String msg, int wrapWidth) {
        if (msg.length() < wrapWidth) {
            return Collections.singletonList(msg);
        }

        List<String> wrappedMessages = new ArrayList<String>();

        int offset = 0;
        int len = msg.length();

        while (len > 0) {
            int copylen = Math.min(wrapWidth, len);
            String s = msg.substring(offset, offset + copylen);

            offset += copylen;
            len -= copylen;

            if (len > 0) { // if there are more lines following, then append a wrap marker
                s += " \u23ce"; //$NON-NLS-1$
            }

            wrappedMessages.add(s);
        }

        return wrappedMessages;
    }

    private Color getForegroundColor(LogCatMessage m) {
        LogLevel l = m.getLogLevel();

        if (l.equals(LogLevel.VERBOSE)) {
            return mVerboseColor;
        } else if (l.equals(LogLevel.INFO)) {
            return mInfoColor;
        } else if (l.equals(LogLevel.DEBUG)) {
            return mDebugColor;
        } else if (l.equals(LogLevel.ERROR)) {
            return mErrorColor;
        } else if (l.equals(LogLevel.WARN)) {
            return mWarnColor;
        } else if (l.equals(LogLevel.ASSERT)) {
            return mAssertColor;
        }

        return mVerboseColor;
    }

    private List<ILogCatMessageSelectionListener> mMessageSelectionListeners;

    private void initDoubleClickListener() {
        mMessageSelectionListeners = new ArrayList<ILogCatMessageSelectionListener>(1);

        mTable.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetDefaultSelected(SelectionEvent arg0) {
                List<LogCatMessage> selectedMessages = getSelectedLogCatMessages();
                if (selectedMessages.size() == 0) {
                    return;
                }

                for (ILogCatMessageSelectionListener l : mMessageSelectionListeners) {
                    l.messageDoubleClicked(selectedMessages.get(0));
                }
            }
        });
    }

    public void addLogCatMessageSelectionListener(ILogCatMessageSelectionListener l) {
        mMessageSelectionListeners.add(l);
    }

    private ITableFocusListener mTableFocusListener;

    /**
     * Specify the listener to be called when the logcat view gets focus. This interface is
     * required by DDMS to hook up the menu items for Copy and Select All.
     * @param listener listener to be notified when logcat view is in focus
     */
    public void setTableFocusListener(ITableFocusListener listener) {
        mTableFocusListener = listener;

        final IFocusedTableActivator activator = new IFocusedTableActivator() {
            @Override
            public void copy(Clipboard clipboard) {
                copySelectionToClipboard(clipboard);
            }

            @Override
            public void selectAll() {
                mTable.selectAll();
            }
        };

        mTable.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                mTableFocusListener.focusGained(activator);
            }

            @Override
            public void focusLost(FocusEvent e) {
                mTableFocusListener.focusLost(activator);
            }
        });
    }

    /** Copy all selected messages to clipboard. */
    public void copySelectionToClipboard(Clipboard clipboard) {
        StringBuilder sb = new StringBuilder();

        for (LogCatMessage m : getSelectedLogCatMessages()) {
            sb.append(m.toString());
            sb.append('\n');
        }

        if (sb.length() > 0) {
            clipboard.setContents(
                    new Object[] {sb.toString()},
                    new Transfer[] {TextTransfer.getInstance()}
                    );
        }
    }

    /** Select all items in the logcat table. */
    public void selectAll() {
        mTable.selectAll();
    }

    private void dispose() {
        if (mFont != null && !mFont.isDisposed()) {
            mFont.dispose();
        }

        if (mVerboseColor != null && !mVerboseColor.isDisposed()) {
            disposeMessageColors();
        }
    }

    private void disposeMessageColors() {
        mVerboseColor.dispose();
        mDebugColor.dispose();
        mInfoColor.dispose();
        mWarnColor.dispose();
        mErrorColor.dispose();
        mAssertColor.dispose();
    }

    private class LogcatFindTarget extends AbstractBufferFindTarget {
        @Override
        public void selectAndReveal(int index) {
            mTable.deselectAll();
            mTable.select(index);
            mTable.showSelection();
        }

        @Override
        public int getItemCount() {
            return mTable.getItemCount();
        }

        @Override
        public String getItem(int index) {
            Object data = mTable.getItem(index).getData();
            if (data != null) {
                return data.toString();
            }

            return null;
        }

        @Override
        public int getStartingIndex() {
            // start searches from current selection if present, otherwise from the tail end
            // of the buffer
            int s = mTable.getSelectionIndex();
            if (s != -1) {
                return s;
            } else {
                return getItemCount() - 1;
            }
        };
    };

    private FindDialog mFindDialog;
    private LogcatFindTarget mFindTarget = new LogcatFindTarget();
    public void showFindDialog() {
        if (mFindDialog != null) {
            // if the dialog is already displayed
            return;
        }

        mFindDialog = new FindDialog(Display.getDefault().getActiveShell(), mFindTarget);
        mFindDialog.open(); // blocks until find dialog is closed
        mFindDialog = null;
    }
}