Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 05321a237480f70a85fb79226ce82ae358d2ca83 (plain) (blame)
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
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
/*******************************************************************************
 * Copyright (c) 2012 Red Hat.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat - Sami Wagiaalla
 *     Red Hat - Andrew Ferrazzutti
 *******************************************************************************/

package org.eclipse.linuxtools.internal.systemtap.ui.ide.launcher;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.CommentRemover;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.IDEPlugin;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataSet;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataSetParser;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IFilteredDataSet;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.row.LineParser;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.row.RowDataSet;
import org.eclipse.linuxtools.systemtap.graphing.core.structures.GraphData;
import org.eclipse.linuxtools.systemtap.graphing.ui.widgets.ExceptionErrorDialog;
import org.eclipse.linuxtools.systemtap.graphing.ui.wizards.dataset.DataSetFactory;
import org.eclipse.linuxtools.systemtap.graphing.ui.wizards.graph.GraphFactory;
import org.eclipse.linuxtools.systemtap.graphing.ui.wizards.graph.SelectGraphAndSeriesWizard;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
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.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

public class SystemTapScriptGraphOptionsTab extends
            AbstractLaunchConfigurationTab {

    /**
     * The maximum number of regular expressions that can be stored in a configuration.
     */
    static final int MAX_NUMBER_OF_REGEXS = 20;

    /**
     * The maximum length of an output-parsing regular expression.
     */
    static final int MAX_REGEX_LENGTH = 200;

    // Note: any non-private String key with a trailing underscore is to be appended with an integer when looking up values.
    static final String RUN_WITH_CHART = "runWithChart"; //$NON-NLS-1$
    static final String NUMBER_OF_REGEXS = "numberOfRegexs"; //$NON-NLS-1$
    static final String NUMBER_OF_COLUMNS = "numberOfColumns_"; //$NON-NLS-1$
    static final String REGEX_BOX = "regexBox_"; //$NON-NLS-1$
    static final String NUMBER_OF_EXTRAS = "numberOfExtras_"; //$NON-NLS-1$
    static final String EXTRA_BOX = "extraBox_"; //$NON-NLS-1$
    static final String REGULAR_EXPRESSION = "regularExpression_"; //$NON-NLS-1$
    static final String SAMPLE_OUTPUT = "sampleOutput_"; //$NON-NLS-1$

    // Note: all graph-related keys point to 2D lists (regular expression & graph number),
    // except for GRAPH_Y_SERIES (which is a 3D list).
    private static final String NUMBER_OF_GRAPHS = "numberOfGraphs"; //$NON-NLS-1$
    private static final String GRAPH_TITLE = "graphTitle"; //$NON-NLS-1$
    private static final String GRAPH_KEY = "graphKey"; //$NON-NLS-1$
    private static final String GRAPH_X_SERIES = "graphXSeries"; //$NON-NLS-1$
    private static final String GRAPH_ID = "graphID"; //$NON-NLS-1$
    private static final String GRAPH_Y_SERIES_LENGTH = "graphYSeriesLength"; //$NON-NLS-1$
    private static final String GRAPH_Y_SERIES = "graphYSeries"; //$NON-NLS-1$
    protected Pattern pattern;
    protected Matcher matcher;

    private Combo regularExpressionCombo;
    private Button removeRegexButton;
    private Button generateExpsButton;

    private Text sampleOutputText;
    private Composite textFieldsComposite;

    /**
     * This value controls whether or not the ModifyListeners associated with
     * the Texts will perform when dispatched. Sometimes the listeners should
     * be disabled to prevent needless/unsafe operations.
     */
    private boolean textListenersEnabled = true;

    private ScrolledComposite regexTextScrolledComposite;
    private Group outputParsingGroup;
    private Button runWithChartCheckButton;

    private Table graphsTable;
    private Button addGraphButton, duplicateGraphButton, editGraphButton, removeGraphButton;
    private TableItem selectedTableItem;
    private Group graphsGroup;
    private int numberOfVisibleColumns = 0;
    private boolean graphingEnabled = true;

    /**
     * A list of error messages, each entry corresponding to an entered regular expression.
     */
    private List<String> regexErrorMessages = new ArrayList<>();

    /**
     * The index of the selected regular expression.
     */
    private int selectedRegex = -1;

    /**
     * A list containing the user-defined sample outputs associated with the regex of every index.
     */
    private List<String> outputList = new ArrayList<>();

    /**
     * A name is given to each group captured by a regular expression. This stack contains
     * the names of all of a regex's groups that have been deleted, so each name may be
     * restored (without having to retype it) when a group is added again.
     */
    private Stack<String> cachedNames;

    /**
     * A list of cachedNames stacks, containing one entry for each regular expression stored.
     */
    private List<Stack<String>> cachedNamesList = new ArrayList<>();

    /**
     * A two-dimensional list that holds references to the names given to each regular expression's captured groups.
     */
    private List<ArrayList<String>> columnNamesList = new ArrayList<>();

    /**
     * A list holding the data of every graph for the selected regular expression.
     */
    private List<GraphData> graphsData = new LinkedList<>();

    /**
     * A list of graphsData lists. This is needed because each regular expression has its own set of graphs.
     */
    private List<LinkedList<GraphData>> graphsDataList = new ArrayList<>();

    /**
     * A list of GraphDatas that rely on series information that has been deleted from their relying regex.
     */
    private List<GraphData> badGraphs = new LinkedList<>();

    private ModifyListener regexListener = new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent event) {
            if (!textListenersEnabled || regularExpressionCombo.getSelectionIndex() != -1) {
                return;
            }
            regularExpressionCombo.setItem(selectedRegex, regularExpressionCombo.getText());
            regularExpressionCombo.select(selectedRegex);
            refreshRegexRows();
            updateLaunchConfigurationDialog();
        }
    };

    private ModifyListener sampleOutputListener = new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent event) {
            if (!textListenersEnabled) {
                return;
            }
            outputList.set(selectedRegex, sampleOutputText.getText());
            refreshRegexRows();
            updateLaunchConfigurationDialog();
        }
    };

    private ModifyListener columnNameListener = new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent event) {
            if (!textListenersEnabled) {
                return;
            }

            ArrayList<String> columnNames = new ArrayList<>();
            Control[] children = textFieldsComposite.getChildren();
            for (int i = 0; i < numberOfVisibleColumns; i++) {
                columnNames.add(((Text)children[i*4 + 2]).getText());
            }
            columnNamesList.set(selectedRegex, columnNames);
            updateLaunchConfigurationDialog();
        }
    };

    private SelectionAdapter regexGenerator = new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            MessageDialog dialog;
            IWorkbench workbench = PlatformUI.getWorkbench();
            IPath scriptPath = null;
            for (ILaunchConfigurationTab tab : getLaunchConfigurationDialog().getTabs()) {
                if (tab instanceof SystemTapScriptLaunchConfigurationTab) {
                    scriptPath = ((SystemTapScriptLaunchConfigurationTab) tab).getScriptPath();
                    break;
                }
            }
            if (scriptPath == null) {
                dialog = new MessageDialog(workbench
                        .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
                        Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsError,
                        MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
                dialog.open();
                return;
            }

            dialog = new MessageDialog(workbench
                    .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTitle, null,
                    Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsMessage,
                    MessageDialog.QUESTION, new String[]{"Yes", "Cancel"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
            int result = dialog.open();
            if (result != 0) { // Cancel
                return;
            }

            textListenersEnabled = false;
            // If editor of this file is open, take current file contents.
            String contents = null;
            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            IEditorPart editor = ResourceUtil.findEditor(workbench.getActiveWorkbenchWindow().getActivePage(), root.getFile(scriptPath.makeRelativeTo(root.getLocation())));
            if (editor != null) {
                ITextEditor tEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
                if (tEditor != null) {
                    IDocumentProvider provider = tEditor.getDocumentProvider();
                    IDocument document = provider.getDocument(tEditor.getEditorInput());
                    contents = document.get();
                }
            }

            // If chosen file is not being edited or is outside of the workspace, use the saved contents of the file itself.
            if (contents == null) {
                File scriptFile = scriptPath.toFile();
                try (FileInputStream f = new FileInputStream(scriptFile)) {
                    byte[] data = new byte[(int)scriptFile.length()];
                    f.read(data);
                    f.close();
                    contents = new String(data, Charset.defaultCharset());
                } catch (IOException e1) {
                    dialog = new MessageDialog(workbench
                            .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
                            Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsError,
                            MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
                    dialog.open();
                    return;
                }
            }

            // Delete comments from the file contents. Ignore comment markers between quotes.
            contents = CommentRemover.exec(contents);

            // Now actually search the contents for "printf(...)" statements. (^|[\s({;])printf\("(.+?)",.+\)
            Pattern pattern = Pattern.compile("(?<=[^\\w])printf\\(\"(.+?)\",.+?\\)"); //$NON-NLS-1$
            Matcher matcher = pattern.matcher(contents);
            boolean firstfound = false;
            while (matcher.find() && (!firstfound || getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS)) {
                String regex = null;

                // Note: allow optional "long" modifier 'l'. Not captured because it doesn't impact output format.
                // Also, don't support variable width/precision modifiers (*).
                // TODO: Consider %m & %M support.
                Pattern format = Pattern.compile("%([-\\+ \\#0])?(\\d+)?(\\.\\d*)?l?([bcdiopsuxX%])"); //$NON-NLS-1$

                // Only capture until newlines to preserve the "column" format.
                // Don't try gluing together output from multiple printfs
                // since asynchronous prints would make things messy.
                String[] printls = matcher.group(1).split("\\\\n"); //$NON-NLS-1$
                for (int i = 0; i < printls.length; i++) {
                    String printl = printls[i];
                    // Ignore newlines if they are escaped ("\\n").
                    if (printl.endsWith("\\")) { //$NON-NLS-1$
                        printls[i+1] = printl.concat("\\n" + printls[i+1]); //$NON-NLS-1$
                        continue;
                    }

                    Matcher fmatch = format.matcher(printl);
                    int lastend = 0;
                    ArrayList<String> columnNames = new ArrayList<>();
                    int r = 0;

                    while (fmatch.find()) {
                        char chr = fmatch.group(4) == null ? '\0' : fmatch.group(4).charAt(0);
                        if (chr == '\0') {
                            // Skip this statement if an invalid regex is found.
                            regex = null;
                            break;
                        }
                        char flag = fmatch.group(1) == null ? '\0' : fmatch.group(1).charAt(0);
                        int width = fmatch.group(2) == null ? 0 : Integer.parseInt(fmatch.group(2));
                        String precision = fmatch.group(3) == null ? null : fmatch.group(3).substring(1);

                        // First, add any non-capturing characters.
                        String pre = addRegexEscapes(printl.substring(lastend, fmatch.start()));
                        regex = lastend > 0 ? regex.concat(pre) : pre;
                        lastend = fmatch.end();

                        // Now add what will be captured.
                        String target = "("; //$NON-NLS-1$
                        if (chr == 'u' || (flag != '#' && chr == 'o')) {
                            target = target.concat("\\d+"); //$NON-NLS-1$
                        }
                        else if (chr == 'd' || chr == 'i') {
                            if (flag == '+') {
                                target = target.concat("\\+|"); //$NON-NLS-1$
                            } else if (flag == ' ') {
                                target = target.concat(" |"); //$NON-NLS-1$
                            }
                            target = target.concat("-?\\d+"); //$NON-NLS-1$
                        }
                        else if (flag == '#' && chr == 'o') {
                            target = target.concat("0\\d+"); //$NON-NLS-1$
                        }
                        else if (chr == 'p') {
                            target = target.concat("0x[a-f0-9]+"); //$NON-NLS-1$
                        }
                        else if (chr == 'x') {
                            if (flag == '#') {
                                target = target.concat("0x"); //$NON-NLS-1$
                            }
                            target = target.concat("[a-f0-9]+"); //$NON-NLS-1$
                        }
                        else if (chr == 'X') {
                            if (flag == '#') {
                                target = target.concat("0X"); //$NON-NLS-1$
                            }
                            target = target.concat("[A-F0-9]+"); //$NON-NLS-1$
                        }
                        else if (chr == 'b') {
                            target = target.concat("."); //$NON-NLS-1$
                        }
                        else if (chr == 'c') {
                            if (flag != '#') {
                                target = target.concat("."); //$NON-NLS-1$
                            } else {
                                target = target.concat("\\([a-z]|[0-9]{3})|.|\\\\"); //$NON-NLS-1$
                            }
                        }
                        else if (chr == 's') {
                            if (precision != null) {
                                target = target.concat(".{" + precision + "}"); //$NON-NLS-1$ //$NON-NLS-2$
                            } else {
                                target = target.concat(".+"); //$NON-NLS-1$
                            }
                        }
                        else {
                            // Invalid or unhandled format specifier. Skip this regex.
                            regex = null;
                            break;
                        }

                        target = target.concat(")"); //$NON-NLS-1$

                        // Handle the optional width specifier.
                        // Ignore it for %b, which uses the width value in a different way.
                        if (chr != 'b' && --width > 0) {
                            if (flag == '-') {
                                target = target.concat(" {0," + width + "}"); //$NON-NLS-1$ //$NON-NLS-2$
                            } else if (flag != '0' || chr == 's' || chr == 'c') {
                                target = " {0," + width + "}".concat(target); //$NON-NLS-1$ //$NON-NLS-2$
                            }
                        }

                        regex = regex.concat(target);
                        columnNames.add(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, ++r));
                    }
                    if (regex != null) {
                        if (!firstfound) {
                            // Since script output has been found, reset the configuration's regexs.
                            // Only reset once/if something is found, and do it only one time.
                            regularExpressionCombo.removeAll();
                            outputList.clear();
                            regexErrorMessages.clear();
                            columnNamesList.clear();
                            cachedNamesList.clear();
                            graphsTable.removeAll();
                            graphsDataList.clear();
                            badGraphs.clear();
                            firstfound = true;
                        }
                        // Finally, add the uncaptured remainder of the print statement to the regex.
                        regex = regex.concat(addRegexEscapes(printl.substring(lastend)));

                        regularExpressionCombo.add(regex);
                        outputList.add(""); //$NON-NLS-1$ //For empty "sample output" entry.
                        regexErrorMessages.add(null);
                        columnNamesList.add(columnNames);
                        cachedNamesList.add(new Stack<String>());
                        graphsDataList.add(new LinkedList<GraphData>());
                    }
                }
            }
            textListenersEnabled = true;

            if (!firstfound) {
                dialog = new MessageDialog(workbench
                        .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
                        Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsEmpty,
                        MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
                dialog.open();
                return;
            }

            if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
                regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
            }

            removeRegexButton.setEnabled(getNumberOfRegexs() > 1);
            regularExpressionCombo.select(0);
            updateRegexSelection(0, true);
            checkAllOtherErrors(); // Check for errors in case there was a problem with regex generation
            updateLaunchConfigurationDialog();
        }

        /**
         * This escapes all special regex characters in a string. Escapes must be added
         * to the generated regexs to capture printf output that doesn't
         * come from format specifiers (aka literal strings).
         * @param s The string to add escapes to.
         * @return The same string, after it has been modified with escapes.
         */
        private String addRegexEscapes(String s) {
            String schars = "[^$.|?*+(){}"; //$NON-NLS-1$
            for (int i = 0; i < schars.length(); i++) {
                s = s.replaceAll("(\\" + schars.substring(i,i+1) + ")", "\\\\$1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            }
            return s;
        }
    };

    /**
     * Returns the list of the names given to reach regular expression.
     * @param configuration
     * @return
     */
    public static List<String> createDatasetNames(ILaunchConfiguration configuration) {
        try {
            int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
            ArrayList<String> names = new ArrayList<>(numberOfRegexs);
            for (int r = 0; r < numberOfRegexs; r++) {
                names.add(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, r + 1));
            }
            return names;
        } catch (CoreException e) {
            ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
        }
        return null;
    }

    /**
     * Creates a list of parsers, one for each regular expression created, that will be used
     * to parse the output of a running script.
     * @param configuration The desired run configuration.
     * @return A list of parsers.
     */
    public static List<IDataSetParser> createDatasetParsers(ILaunchConfiguration configuration) {
        try {
            int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
            ArrayList<IDataSetParser> parsers = new ArrayList<>(numberOfRegexs);
            for (int r = 0; r < numberOfRegexs; r++) {
                parsers.add(new LineParser("^" + configuration.getAttribute(REGULAR_EXPRESSION + r, "") + "$")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            }
            return parsers;
        } catch (CoreException e) {
            ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
        }
        return null;
    }

    /**
     * Creates a data set corresponding to the titles given to each output column
     * from each of a run configuration's regular expressions.
     * @param configuration
     * @return
     */
    public static List<IFilteredDataSet> createDataset(ILaunchConfiguration configuration) {
        try {
            int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
            ArrayList<IFilteredDataSet> datasets = new ArrayList<>(numberOfRegexs);

            for (int r = 0; r < numberOfRegexs; r++) {
                int numberOfColumns = configuration.getAttribute(NUMBER_OF_COLUMNS + r, 0);
                ArrayList<String> labels = new ArrayList<>(numberOfColumns);

                for (int c = 0; c < numberOfColumns; c++) {
                    labels.add(configuration.getAttribute(get2DConfigData(REGEX_BOX, r, c), "")); //$NON-NLS-1$
                }
                datasets.add(DataSetFactory.createFilteredDataSet(RowDataSet.ID, labels.toArray(new String[] {})));
            }

            return datasets;
        } catch (CoreException e) {
            ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
        }
        return null;
    }

    /**
     * Creates graph data corresponding to the graphs that will plot a script's parsed output data.
     * @param configuration The desired run configuration.
     * @return A data set.
     */
    public static List<LinkedList<GraphData>> createGraphsFromConfiguration (ILaunchConfiguration configuration)
            throws CoreException {
        // Restrict number of regexs to at least one, so at least
        // one inner list will exist in the return value.
        int numberOfRegexs = Math.max(configuration.getAttribute(NUMBER_OF_REGEXS, 1), 1);
        ArrayList<LinkedList<GraphData>> graphsList = new ArrayList<>(numberOfRegexs);

        for (int r = 0; r < numberOfRegexs; r++) {
            int numberOfGraphs = configuration.getAttribute(NUMBER_OF_GRAPHS + r, 0);
            LinkedList<GraphData> graphs = new LinkedList<>();
            for (int i = 0; i < numberOfGraphs; i++) {
                GraphData graphData = new GraphData();
                graphData.title = configuration.getAttribute(get2DConfigData(GRAPH_TITLE, r, i), (String) null);

                graphData.key = configuration.getAttribute(get2DConfigData(GRAPH_KEY, r, i), (String) null);
                graphData.xSeries = configuration.getAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), 0);
                graphData.graphID = configuration.getAttribute(get2DConfigData(GRAPH_ID, r, i), (String) null);

                int ySeriesLength = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), 0);
                if (ySeriesLength == 0) {
                    graphData.ySeries = null;
                } else {
                    int[] ySeries = new int[ySeriesLength];
                    for (int j = 0; j < ySeriesLength; j++) {
                        ySeries[j] = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), 0); //$NON-NLS-1$
                    }
                    graphData.ySeries = ySeries;
                }

                graphs.add(graphData);
            }
            graphsList.add(graphs);
        }

        return graphsList;
    }

    /**
     * Returns the key associated with the i'th data item of the r'th regular expression.
     * @param configDataName The type of data to access from the configuration.
     * @param r The index of the regular expression.
     * @param i The index of the data item to access.
     */
    private static String get2DConfigData(String configDataName, int r, int i) {
        return configDataName + r + "_" + i; //$NON-NLS-1$
    }

    /**
     * Returns the key associated with the data item of the r'th regular expression, tagged by string s.
     * @param configDataName The type of data to access from the configuration.
     * @param r The index of the regular expression.
     * @param s The string to put at the end of the key.
     */
    private static String get2DConfigData(String configDataName, int r, String s) {
        return configDataName + r + "_" + s; //$NON-NLS-1$
    }

    /**
     * Returns the total number of regular expressions of the current configuration.
     */
    private int getNumberOfRegexs() {
        return outputList.size();
    }

    @Override
    public void createControl(Composite parent) {
        GridLayout layout = new GridLayout();
        Composite top = new Composite(parent, SWT.NONE);
        setControl(top);
        top.setLayout(layout);
        top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        this.runWithChartCheckButton = new Button(top, SWT.CHECK);
        runWithChartCheckButton.setText(Messages.SystemTapScriptGraphOptionsTab_graphOutputRun);
        runWithChartCheckButton.addSelectionListener(new SelectionListener() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                setGraphingEnabled(runWithChartCheckButton.getSelection());
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
                setGraphingEnabled(runWithChartCheckButton.getSelection());
            }
        });

        runWithChartCheckButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_graphOutput);

        this.outputParsingGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
        outputParsingGroup.setText(Messages.SystemTapScriptGraphOptionsTab_outputLabel);
        outputParsingGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        this.createColumnSelector(outputParsingGroup);

        this.graphsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
        // Set the text here just to allow proper sizing.
        graphsGroup.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, 1));
        graphsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        createGraphCreateArea(graphsGroup);

        setGraphingEnabled(false);
        runWithChartCheckButton.setSelection(false);
    }

    private void createColumnSelector(Composite parent) {

        GridLayout layout = new GridLayout();
        parent.setLayout(layout);

        Composite topLayout = new Composite(parent, SWT.NONE);
        topLayout.setLayout(new GridLayout(1, false));
        topLayout.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));

        generateExpsButton = new Button(topLayout, SWT.PUSH);
        generateExpsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        generateExpsButton.setText(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsButton);
        generateExpsButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTooltip);
        generateExpsButton.addSelectionListener(regexGenerator);

        Composite regexButtonLayout = new Composite(parent, SWT.NONE);
        regexButtonLayout.setLayout(new GridLayout(3, false));
        regexButtonLayout.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

        Label selectedRegexLabel = new Label(regexButtonLayout, SWT.NONE);
        selectedRegexLabel.setText(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
        selectedRegexLabel.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_regexTooltip);
        regularExpressionCombo = new Combo(regexButtonLayout, SWT.DROP_DOWN);
        regularExpressionCombo.setTextLimit(MAX_REGEX_LENGTH);
        regularExpressionCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        regularExpressionCombo.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                int selected = regularExpressionCombo.getSelectionIndex();
                if (selected == selectedRegex) {
                    return;
                }

                // If deselecting an empty regular expression, delete it automatically.
                if (regularExpressionCombo.getItem(selectedRegex).isEmpty()
                        && graphsDataList.get(selectedRegex).size() == 0
                        && outputList.get(selectedRegex).isEmpty()) {

                    // If the deselected regex is the last one in the combo, just quit.
                    // Otherwise, the deleted blank entry would be replaced by another blank entry.
                    if (selected == regularExpressionCombo.getItemCount() - 1) {
                        regularExpressionCombo.select(selectedRegex); // To keep the text blank.
                        return;
                    }
                    removeRegex(false);
                    if (selected > selectedRegex) {
                        selected--;
                    }
                }

                // When selecting the "Add New Regex" item in the combo (which is always the last item),
                // update all appropriate values to make room for a new regular expression.
                if (selected == regularExpressionCombo.getItemCount() - 1 && getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
                    outputList.add(""); //$NON-NLS-1$
                    regexErrorMessages.add(null);
                    columnNamesList.add(new ArrayList<String>());
                    cachedNamesList.add(new Stack<String>());
                    graphsDataList.add(new LinkedList<GraphData>());

                    // Remove "Add New Regex" from the selected combo item; make it blank.
                    regularExpressionCombo.setItem(selected, ""); //$NON-NLS-1$
                    regularExpressionCombo.select(selected);
                    updateRegexSelection(selected, false);
                    updateLaunchConfigurationDialog();

                    // Enable the "remove" button if only one item was present before.
                    // (Don't do this _every_ time something is added.)
                    if (getNumberOfRegexs() == 2) {
                        removeRegexButton.setEnabled(true);
                    }
                    if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
                        regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
                    }
                } else {
                    updateRegexSelection(selected, false);
                }
            }
        });
        regularExpressionCombo.addModifyListener(regexListener);

        removeRegexButton = new Button(regexButtonLayout, SWT.PUSH);
        removeRegexButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
        removeRegexButton.setText(Messages.SystemTapScriptGraphOptionsTab_regexRemove);
        removeRegexButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                IWorkbench workbench = PlatformUI.getWorkbench();
                MessageDialog dialog = new MessageDialog(workbench
                        .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_removeRegexTitle, null,
                        MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_removeRegexAsk,
                                regularExpressionCombo.getItem(selectedRegex)),
                                MessageDialog.QUESTION, new String[]{"Yes", "No"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
                int result = dialog.open();
                if (result == 0) { //Yes
                    removeRegex(true);
                }
            }
        });

        GridLayout twoColumns = new GridLayout(2, false);

        Composite regexSummaryComposite = new Composite(parent, SWT.NONE);
        regexSummaryComposite.setLayout(twoColumns);
        regexSummaryComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        Label sampleOutputLabel = new Label(regexSummaryComposite, SWT.NONE);
        sampleOutputLabel.setText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
        sampleOutputLabel.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputTooltip);
        this.sampleOutputText = new Text(regexSummaryComposite, SWT.BORDER);
        this.sampleOutputText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        this.sampleOutputText.addModifyListener(sampleOutputListener);
        sampleOutputText.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputTooltip);


        Composite expressionTableLabels = new Composite(parent, SWT.NONE);
        expressionTableLabels.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
        expressionTableLabels.setLayout(twoColumns);

        Label label = new Label(expressionTableLabels, SWT.NONE);
        label.setText(Messages.SystemTapScriptGraphOptionsTab_columnTitle);
        label.setAlignment(SWT.LEFT);

        Label label2 = new Label(expressionTableLabels, SWT.NONE);
        label2.setAlignment(SWT.LEFT);
        label2.setText(Messages.SystemTapScriptGraphOptionsTab_extractedValueLabel);

        this.regexTextScrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.BORDER);
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
        data.heightHint = 200;
        regexTextScrolledComposite.setLayoutData(data);

        textFieldsComposite = new Composite(regexTextScrolledComposite, SWT.NONE);
        textFieldsComposite.setLayout(new GridLayout(4, false));
        regexTextScrolledComposite.setContent(textFieldsComposite);
        regexTextScrolledComposite.setExpandHorizontal(true);

        // To position the column labels properly, add a dummy column and use its children's sizes for reference.
        // This is necessary since expressionTableLabels can't share a layout with textFieldsComposite.
        textListenersEnabled = false;
        addColumn(""); //$NON-NLS-1$
        data = new GridData(SWT.FILL, SWT.FILL, false, false);
        data.horizontalIndent = textFieldsComposite.getChildren()[2].getLocation().x;
        data.widthHint = textFieldsComposite.getChildren()[2].getSize().x;
        label.setLayoutData(data);
        label2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
        removeColumn(false);
        textListenersEnabled = true;
    }

    private IDataSet getCurrentDataset() {
        return DataSetFactory.createDataSet(RowDataSet.ID, columnNamesList.get(selectedRegex).toArray(new String[] {}));
    }

    private void createGraphCreateArea(Composite comp) {
        comp.setLayout(new GridLayout(2, false));

        graphsTable = new Table(comp, SWT.SINGLE | SWT.BORDER);
        GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
        graphsTable.setLayoutData(layoutData);

        // Button to add another graph
        Composite buttonComposite = new Composite(comp, SWT.NONE);
        buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));

        GridLayout gridLayout = new GridLayout();
        gridLayout.numColumns = 1;

        buttonComposite.setLayout(gridLayout);
        // Button to add a new graph
        addGraphButton = new Button(buttonComposite, SWT.PUSH);
        addGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton);
        addGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_AddGraphButtonToolTip);
        addGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

        // Button to copy an existing graph
        duplicateGraphButton = new Button(buttonComposite, SWT.PUSH);
        duplicateGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButton);
        duplicateGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButtonToolTip);
        duplicateGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

        // Button to edit an existing graph
        editGraphButton = new Button(buttonComposite, SWT.PUSH);
        editGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_EditGraphButton);
        editGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_EditGraphButtonToolTip);
        editGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

        // Button to remove the selected graph/filter
        removeGraphButton = new Button(buttonComposite, SWT.PUSH);
        removeGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButton);
        removeGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButtonToolTip);
        removeGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

        // Action to notify the buttons when to enable/disable themselves based
        // on list selection
        graphsTable.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                selectedTableItem = (TableItem) e.item;
                setSelectionControlsEnabled(true);
            }
        });

        // Brings up a new dialog box when user clicks the add button. Allows
        // selecting a new graph to display.
        addGraphButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(getCurrentDataset(), null);
                IWorkbench workbench = PlatformUI.getWorkbench();
                wizard.init(workbench, null);
                WizardDialog dialog = new WizardDialog(workbench
                        .getActiveWorkbenchWindow().getShell(), wizard);
                dialog.create();
                dialog.open();

                GraphData gd = wizard.getGraphData();

                if (null != gd) {
                    TableItem item = new TableItem(graphsTable, SWT.NONE);
                    graphsData.add(gd);
                    setUpGraphTableItem(item, gd, false);
                    updateLaunchConfigurationDialog();
                }
            }
        });

        // Adds a new entry to the list of graphs that is a copy of the one selected.
        duplicateGraphButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                GraphData gd = ((GraphData) selectedTableItem.getData()).getCopy();

                TableItem item = new TableItem(graphsTable, SWT.NONE);
                graphsData.add(gd);
                if (badGraphs.contains(selectedTableItem.getData())) {
                    badGraphs.add(gd);
                    setUpGraphTableItem(item, gd, true);
                } else {
                    setUpGraphTableItem(item, gd, false);
                }
                updateLaunchConfigurationDialog();
            }
        });

        // When button is clicked, brings up same wizard as the one for adding
        // a graph. Data in the wizard is filled out to match the properties
        // of the selected graph.
        editGraphButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(getCurrentDataset(),
                        (GraphData) selectedTableItem.getData());
                IWorkbench workbench = PlatformUI.getWorkbench();
                wizard.init(workbench, null);
                WizardDialog dialog = new WizardDialog(workbench
                        .getActiveWorkbenchWindow().getShell(), wizard);
                dialog.create();
                dialog.open();

                GraphData gd = wizard.getGraphData();
                if (null == gd) {
                    return;
                }
                GraphData old_gd = (GraphData) selectedTableItem.getData();
                if (!gd.equals(old_gd)) {
                    badGraphs.remove(old_gd);
                    setUpGraphTableItem(selectedTableItem, gd, false);
                    graphsData.set(graphsTable.indexOf(selectedTableItem), gd);
                    checkErrors(selectedRegex);
                    updateLaunchConfigurationDialog();
                }
            }
        });

        // Removes the selected graph/filter from the table
        removeGraphButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                GraphData gd = (GraphData) selectedTableItem.getData();
                graphsData.remove(gd);
                badGraphs.remove(gd);
                selectedTableItem.dispose();
                setSelectionControlsEnabled(false);
                checkErrors(selectedRegex);
                updateLaunchConfigurationDialog();
            }
        });
    }

    private void removeRegex(boolean autoSelect) {
        int removedRegex = selectedRegex;
        if (autoSelect) {
            // The current selection is to be removed, so select something else that will be available.
            regularExpressionCombo.select(selectedRegex != 0 ? selectedRegex - 1 : 1);
            updateRegexSelection(regularExpressionCombo.getSelectionIndex(), false);
        }

        regularExpressionCombo.remove(removedRegex);
        outputList.remove(removedRegex);
        regexErrorMessages.remove(removedRegex);
        columnNamesList.remove(removedRegex);
        cachedNamesList.remove(removedRegex);
        graphsDataList.remove(removedRegex);

        if (autoSelect) {
            // Make sure the index of the selection is accurate.
            selectedRegex = regularExpressionCombo.getSelectionIndex();
        }

        // Re-add the "Add New Regex" entry if it is missing.
        if (getNumberOfRegexs() == MAX_NUMBER_OF_REGEXS - 1) {
            regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
        }

        // Disable the "remove" button if only one selection is left; never want zero items.
        if (getNumberOfRegexs() == 1) {
            removeRegexButton.setEnabled(false);
        }
        updateLaunchConfigurationDialog();
    }

    /**
     * This handles UI & list updating whenever a different regular expression is selected.
     * @param newSelection The index of the regex to be selected.
     * @param force If true, the UI will update even if the index of the selected regex did not change.
     */
    private void updateRegexSelection(int newSelection, boolean force) {
        // Quit if the selection didn't change anything, or if the selection is invalid (-1).
        if (newSelection == -1 || (!force && selectedRegex == newSelection)) {
            return;
        }
        selectedRegex = newSelection;

        boolean textListenersDisabled = !textListenersEnabled;
        if (!textListenersDisabled) {
            textListenersEnabled = false;
        }

        sampleOutputText.setText(outputList.get(selectedRegex));
        cachedNames = cachedNamesList.get(selectedRegex);

        // Update the number of columns and their titles here, and not in refreshRegexRows,
        // using the list of saved active names instead of a cachedNames stack.
        ArrayList<String> columnNames = columnNamesList.get(selectedRegex);
        int desiredNumberOfColumns = columnNames.size();
        // Remove all columns to easily update them all immediately afterwards.
        while (numberOfVisibleColumns > 0) {
            removeColumn(false);
        }
        while (numberOfVisibleColumns < desiredNumberOfColumns) {
            addColumn(columnNames.get(numberOfVisibleColumns));
        }

        refreshRegexRows();

        // Now, only display graphs that are associated with the selected regex.
        graphsData = graphsDataList.get(selectedRegex);
        graphsTable.removeAll();
        selectedTableItem = null;
        setSelectionControlsEnabled(false);

        for (GraphData gd : graphsData) {
            TableItem item = new TableItem(graphsTable, SWT.NONE);
            setUpGraphTableItem(item, gd, badGraphs.contains(gd));
        }
        graphsGroup.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase,
                selectedRegex + 1));

        if (!textListenersDisabled) {
            textListenersEnabled = true;
        }
    }

    private void refreshRegexRows() {
        try {
            pattern = Pattern.compile(regularExpressionCombo.getText());
            matcher = pattern.matcher(sampleOutputText.getText());
            regexErrorMessages.set(selectedRegex, null);
        } catch (PatternSyntaxException e) {
            regexErrorMessages.set(selectedRegex, e.getMessage());
            return;
        }
        regexErrorMessages.set(selectedRegex, checkRegex(regularExpressionCombo.getText()));
        if (regexErrorMessages.get(selectedRegex) != null) {
            return;
        }

        int desiredNumberOfColumns = matcher.groupCount();

        while (numberOfVisibleColumns < desiredNumberOfColumns) {
            addColumn(null);
        }

        while (numberOfVisibleColumns > desiredNumberOfColumns) {
            removeColumn(true);
        }

        // Set values
        Control[] children = textFieldsComposite.getChildren();
        for (int i = 0; i < numberOfVisibleColumns; i++) {
            String sampleOutputResults;
            if (matcher.matches()) {
                sampleOutputResults = matcher.group(i+1);
            }
            else if (sampleOutputText.getText().length() == 0) {
                sampleOutputResults = Messages.SystemTapScriptGraphOptionsTab_sampleOutputIsEmpty;
            } else {
                sampleOutputResults = Messages.SystemTapScriptGraphOptionsTab_sampleOutputNoMatch;
            }
            ((Label)children[i*4+3]).setText(" " + sampleOutputResults); //$NON-NLS-1$
        }

        // May only add/edit graphs if there is output data being captured.
        addGraphButton.setEnabled(numberOfVisibleColumns > 0);
        if (selectedTableItem != null) {
            editGraphButton.setEnabled(numberOfVisibleColumns > 0);
        }

        regexErrorMessages.set(selectedRegex, findBadGraphs(selectedRegex));
    }

    /**
     * Checks if a provided regular expression is valid.
     * @param regex The regular expression to check for validity.
     * @return <code>null</code> if the regular expression is valid, or an error message.
     */
    private static String checkRegex(String regex) {
        //TODO may add more invalid regexs here, each with its own error message.
        if (regex.contains("()")) { //$NON-NLS-1$
            return Messages.SystemTapScriptGraphOptionsTab_emptyGroup;
        }
        return null;
    }

    /**
     * Adds one column to the list of the currently-selected regex's columns.
     * This creates an extra Text in which the name of the column may be entered,
     * and a corresponding Label containing sample expected output.
     * @param nameToAdd If non-null, the name of the newly-created column will
     * match this String. If null, the column will be given a name recovered from
     * the active stack of cached names, or a default name if one doesn't exist.
     */
    private void addColumn(String nameToAdd) {
        // Show the "shift" buttons of the previous column, if it exists.
        if (this.numberOfVisibleColumns > 0) {
            textFieldsComposite.getChildren()[(this.numberOfVisibleColumns - 1) * 4].setVisible(true);
            textFieldsComposite.getChildren()[(this.numberOfVisibleColumns - 1) * 4 + 1].setVisible(true);
        }

        // Add buttons for shifting column names up/down in the list.
        Button buttonUp = new Button(textFieldsComposite, SWT.PUSH);
        buttonUp.setText(Messages.SystemTapScriptGraphOptionsTab_columnShiftUp);
        buttonUp.setVisible(false);
        Button buttonDown = new Button(textFieldsComposite, SWT.PUSH);
        buttonDown.setText(Messages.SystemTapScriptGraphOptionsTab_columnShiftDown);
        buttonDown.setVisible(false);

        Text text = new Text(textFieldsComposite, SWT.BORDER);
        GridData data = new GridData(SWT.FILL, SWT.FILL, false, false);
        data.minimumWidth = 200;
        data.widthHint = 200;
        text.setLayoutData(data);

        numberOfVisibleColumns++;
        text.addModifyListener(columnNameListener);
        if (nameToAdd == null) {
            // Restore a deleted name by popping from the stack.
            if (cachedNames.size() > 0) {
                text.setText(cachedNames.pop());
            } else {
                text.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase,
                        numberOfVisibleColumns));
            }
        } else {
            text.setText(nameToAdd);
        }

        Label label = new Label(textFieldsComposite, SWT.BORDER);
        label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

        textFieldsComposite.layout();
        textFieldsComposite.pack();

        // Special value: if an empty string is given, don't add button listeners.
        if (nameToAdd == "") { //$NON-NLS-1$
            return;
        }

        // Add button listeners for shifting column names.
        buttonUp.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                Control clickedButton = (Control) e.widget;
                Control[] children = textFieldsComposite.getChildren();
                int currentColumn = 0;
                for (; currentColumn < numberOfVisibleColumns - 1; currentColumn++) {
                    if (children[currentColumn*4].equals(clickedButton)) {
                        break;
                    }
                }
                String edgeName = ((Text)children[currentColumn*4 + 2]).getText();
                for (int i = currentColumn; i < numberOfVisibleColumns - 1; i++) {
                    ((Text)children[i*4 + 2]).setText(((Text)children[(i + 1)*4 + 2]).getText());
                }
                ((Text)children[(numberOfVisibleColumns - 1)*4 + 2]).setText(edgeName);
            }
        });

        buttonDown.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                Control clickedButton = (Control) e.widget;
                Control[] children = textFieldsComposite.getChildren();
                int currentColumn = 0;
                for (; currentColumn < numberOfVisibleColumns - 1; currentColumn++) {
                    if (children[currentColumn*4 + 1].equals(clickedButton)) {
                        break;
                    }
                }
                String edgeName = ((Text)children[(numberOfVisibleColumns - 1)*4 + 2]).getText();
                for (int i = numberOfVisibleColumns - 1; i > currentColumn; i--) {
                    ((Text)children[i*4 + 2]).setText(((Text)children[(i - 1)*4 + 2]).getText());
                }
                ((Text)children[currentColumn*4 + 2]).setText(edgeName);
            }
        });
    }

    /**
     * Removes a column from the currently-selected regex, and removes its
     * corresponding Text & Label from the UI.
     * @param saveNames Set to <code>true</code> if the contents of removed
     * columns are to be saved in a stack for later use.
     */
    private void removeColumn(Boolean saveNames) {
        Control[] children = textFieldsComposite.getChildren();
        int i = this.numberOfVisibleColumns*4 - 1;

        if (saveNames) {
            // Push the removed name on a stack.
            String name = ((Text)children[i-1]).getText();
            if (name != null && name != "") { //$NON-NLS-1$
                cachedNames.push(name);
            }
            columnNamesList.get(selectedRegex).remove(numberOfVisibleColumns - 1);
        }

        children[i].dispose();
        children[i-1].dispose();
        children[i-2].dispose();
        children[i-3].dispose();

        // Hide the previous column's "shift" buttons, if it exists.
        if (this.numberOfVisibleColumns > 2) {
            children[i - 6].setVisible(false);
            children[i - 7].setVisible(false);
        }

        this.numberOfVisibleColumns--;

        textFieldsComposite.layout();
        textFieldsComposite.pack();
    }

    /**
     * Marks all graphs belonging to the indicated regular expression that have an
     * error (missing column data, invalid graphID), or unmarks graphs that don't.
     * @param    regex The index of the regular expression to check for invalid graphs.
     * @return    An appropriate error message if an invalid graph is found, or if the
     * selected regular expression parses nothing.
     */
    private String findBadGraphs(int regex) {
        boolean foundBadID = false;
        boolean foundRemoved = false;
        int numberOfColumns = columnNamesList.get(regex).size();

        for (GraphData gd : graphsDataList.get(regex)) {
            boolean singleBadID = false;
            boolean singleRemoved = false;

            if (GraphFactory.getGraphName(gd.graphID) == null) {
                singleBadID = true;
            } else {
                if (gd.xSeries >= numberOfColumns) {
                    singleRemoved = true;
                }
                for (int s = 0; s < gd.ySeries.length && !singleRemoved; s++) {
                    if (gd.ySeries[s] >= numberOfColumns) {
                        singleRemoved = true;
                    }
                }
            }
            if (singleRemoved || singleBadID) {
                if (!badGraphs.contains(gd)) {
                    badGraphs.add(gd);
                    setUpGraphTableItem(findGraphTableItem(gd), null, true);
                }
            } else if (badGraphs.contains(gd)) {
                badGraphs.remove(gd);
                setUpGraphTableItem(findGraphTableItem(gd), null, false);
            }

            foundBadID |= singleBadID;
            foundRemoved |= singleRemoved;
        }

        if (numberOfColumns == 0) {
            return Messages.SystemTapScriptGraphOptionsTab_noGroups;
        }
        if (foundBadID) {
            return Messages.SystemTapScriptGraphOptionsTab_badGraphID;
        }
        if (foundRemoved) {
            return Messages.SystemTapScriptGraphOptionsTab_deletedGraphData;
        }
        return null;
    }

    private TableItem findGraphTableItem(GraphData gd) {
        for (TableItem item : graphsTable.getItems()) {
            if (item.getData().equals(gd)) {
                return item;
            }
        }
        return null;
    }

    /**
     * Sets up a given {@link TableItem} with the proper title & appearance based on
     * its graph data & (in)valid status.
     * @param item The {@link TableItem} to set up.
     * @param gd The {@link GraphData} that the item will hold. Set to <code>null</code>
     * to preserve the item's existing data.
     * @param bad <code>true</code> if the item should appear as invalid, <code>false</code> otherwise.
     */
    private void setUpGraphTableItem(TableItem item, GraphData gd, boolean bad) {
        // Include a null check to avoid accidentally marking non-visible items.
        if (item == null) {
            return;
        }
        if (gd != null) {
            item.setData(gd);
        } else {
            gd = (GraphData) item.getData();
        }
        item.setForeground(item.getDisplay().getSystemColor(bad ? SWT.COLOR_RED : SWT.COLOR_BLACK));
        String graphName = GraphFactory.getGraphName(gd.graphID);
        if (graphName == null) {
            graphName = Messages.SystemTapScriptGraphOptionsTab_invalidGraphID;
        }
        item.setText(graphName + ":" + gd.title //$NON-NLS-1$
                + (bad ? " " + Messages.SystemTapScriptGraphOptionsTab_invalidGraph : "")); //$NON-NLS-1$ //$NON-NLS-2$
    }

    @Override
    public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
        configuration.setAttribute(RUN_WITH_CHART, false);
        configuration.setAttribute(NUMBER_OF_REGEXS, 1);
        configuration.setAttribute(NUMBER_OF_COLUMNS + 0, 0);
        configuration.setAttribute(NUMBER_OF_EXTRAS + 0, 0);
        configuration.setAttribute(REGULAR_EXPRESSION + 0, ""); //$NON-NLS-1$
        configuration.setAttribute(SAMPLE_OUTPUT + 0, ""); //$NON-NLS-1$
        configuration.setAttribute(NUMBER_OF_GRAPHS + 0, 0);
    }

    @Override
    public void initializeFrom(ILaunchConfiguration configuration) {
        try {
            textListenersEnabled = false;

            // Reset lists & settings to keep things idempotent.
            regularExpressionCombo.removeAll();
            outputList.clear();
            regexErrorMessages.clear();
            columnNamesList.clear();
            cachedNamesList.clear();
            graphsTable.removeAll();
            badGraphs.clear();

            // There should always be at least one regular expression (a blank one still counts).
            // If configuration's number of regexs is zero, it is outdated.
            int numberOfRegexs = Math.max(configuration.getAttribute(NUMBER_OF_REGEXS, 1), 1);

            // Only allow removing regexs if there are more than one.
            removeRegexButton.setEnabled(numberOfRegexs > 1);

            for (int r = 0; r < numberOfRegexs; r++) {
                // Save all of the configuration's regular expressions & sample outputs in a list.
                regularExpressionCombo.add(configuration.getAttribute(REGULAR_EXPRESSION + r, "")); //$NON-NLS-1$
                outputList.add(configuration.getAttribute(SAMPLE_OUTPUT + r, "")); //$NON-NLS-1$

                // Save each regex's list of group names.
                int numberOfColumns = configuration.getAttribute(NUMBER_OF_COLUMNS + r, 0);
                ArrayList<String> namelist = new ArrayList<>(numberOfColumns);
                for (int i = 0; i < numberOfColumns; i++) {
                    namelist.add(configuration.getAttribute(get2DConfigData(REGEX_BOX, r, i), (String)null));
                }
                columnNamesList.add(namelist);

                //Reclaim missing column data that was required for existing graphs at the time of the previous "apply".
                int numberOfExtras = configuration.getAttribute(NUMBER_OF_EXTRAS + r, 0);
                Stack<String> oldnames = new Stack<>();
                for (int i = 0; i < numberOfExtras; i++) {
                    oldnames.push(configuration.getAttribute(get2DConfigData(EXTRA_BOX, r, i), (String)null));
                }
                cachedNamesList.add(oldnames);

                regexErrorMessages.add(null);
            }
            if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
                regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
            }

            // When possible, preserve the selection on subsequent initializations, for user convenience.
            int defaultSelectedRegex = 0 <= selectedRegex && selectedRegex < numberOfRegexs ? selectedRegex : 0;
            regularExpressionCombo.select(defaultSelectedRegex);

            // Add graphs
            graphsDataList = createGraphsFromConfiguration(configuration);
            graphsData = graphsDataList.get(defaultSelectedRegex);
            for (GraphData graphData : graphsData) {
                TableItem item = new TableItem(graphsTable, SWT.NONE);
                setUpGraphTableItem(item, graphData, true);
            }

            updateRegexSelection(defaultSelectedRegex, true); // Handles all remaining updates.
            checkAllOtherErrors();

            boolean chart = configuration.getAttribute(RUN_WITH_CHART, false);
            setGraphingEnabled(chart);
            this.runWithChartCheckButton.setSelection(chart);

        } catch (CoreException e) {
            ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
        } finally {
            textListenersEnabled = true;
        }
    }

    @Override
    public void performApply(ILaunchConfigurationWorkingCopy configuration) {
        configuration.setAttribute(RUN_WITH_CHART, this.runWithChartCheckButton.getSelection());

        int numberOfRegexs = getNumberOfRegexs();
        for (int r = 0; r < numberOfRegexs; r++) {
            // Save data sets, and clear removed ones.
            configuration.setAttribute(REGULAR_EXPRESSION + r, regularExpressionCombo.getItem(r));
            configuration.setAttribute(SAMPLE_OUTPUT + r, outputList.get(r));

            ArrayList<String> columnNames = columnNamesList.get(r);
            int numberOfColumns = columnNames.size();
            for (int i = 0; i < numberOfColumns; i++) {
                configuration.setAttribute(get2DConfigData(REGEX_BOX, r, i), columnNames.get(i));
            }
            cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, REGEX_BOX, r, numberOfColumns);
            configuration.setAttribute(NUMBER_OF_COLUMNS + r, numberOfColumns);

            // If the current regex has graphs with missing data, store all cached names
            // in the configuration so that they will be easily restorable for next time.
            Stack<String> extranames = cachedNamesList.get(r);
            int numberOfExtras = findBadGraphs(r) == null ? 0 : extranames.size();
            for (int i = 0; i < numberOfExtras; i++) {
                configuration.setAttribute(get2DConfigData(EXTRA_BOX, r, i), extranames.get(i));
            }
            cleanUpConfigurationItem(configuration, NUMBER_OF_EXTRAS, EXTRA_BOX, r, numberOfExtras);
            configuration.setAttribute(NUMBER_OF_EXTRAS + r, numberOfExtras);

            // Save new graphs, and clear removed ones.
            LinkedList<GraphData> list = graphsDataList.get(r);
            int numberOfGraphs = list.size();
            for (int i = 0; i < numberOfGraphs; i++) {
                GraphData graphData = list.get(i);
                configuration.setAttribute(get2DConfigData(GRAPH_TITLE, r, i), graphData.title);
                configuration.setAttribute(get2DConfigData(GRAPH_KEY, r, i), graphData.key);
                configuration.setAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), graphData.xSeries);
                configuration.setAttribute(get2DConfigData(GRAPH_ID, r, i), graphData.graphID);

                int ySeriesLength = graphData.ySeries.length;
                for (int j = 0; j < ySeriesLength; j++) {
                    configuration.setAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), //$NON-NLS-1$
                            graphData.ySeries[j]);
                }
                cleanUpConfigurationGraphYSeries(configuration, r, i, ySeriesLength);
                configuration.setAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), ySeriesLength);
            }
            cleanUpConfigurationGraphs(configuration, r, numberOfGraphs);
            configuration.setAttribute(NUMBER_OF_GRAPHS + r, numberOfGraphs);
        }
        cleanUpConfiguration(configuration, numberOfRegexs);
        configuration.setAttribute(NUMBER_OF_REGEXS, numberOfRegexs);
    }

    /**
     * Removes all configuration attributes associated with deleted regular expressions.
     * @param configuration The configuration to remove attributes from.
     * @param numberOfRegexs The number of regex-related properties to exist in the
     * configuration after cleanup.
     */
    private void cleanUpConfiguration(ILaunchConfigurationWorkingCopy configuration, int numberOfRegexs) {
        int oldNumberOfRegexs = 0;
        try {
            oldNumberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
        } catch (CoreException e) {}
        for (int r = numberOfRegexs; r < oldNumberOfRegexs; r++) {
            configuration.removeAttribute(REGULAR_EXPRESSION + r);
            configuration.removeAttribute(SAMPLE_OUTPUT + r);

            cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, REGEX_BOX, r, 0);
            configuration.removeAttribute(NUMBER_OF_COLUMNS + r);

            cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, EXTRA_BOX, r, 0);
            configuration.removeAttribute(NUMBER_OF_EXTRAS + r);

            cleanUpConfigurationGraphs(configuration, r, 0);
            configuration.removeAttribute(NUMBER_OF_GRAPHS + r);
        }
    }

    private void cleanUpConfigurationGraphs(ILaunchConfigurationWorkingCopy configuration, int regex, int newNumberOfGraphs) {
        int oldNumberOfGraphs = 0;
        try {
            oldNumberOfGraphs = configuration.getAttribute(NUMBER_OF_GRAPHS + regex, 0);
        } catch (CoreException e) {}
        for (int i = newNumberOfGraphs; i < oldNumberOfGraphs; i++) {
            configuration.removeAttribute(get2DConfigData(GRAPH_TITLE, regex, i));
            configuration.removeAttribute(get2DConfigData(GRAPH_KEY, regex, i));
            configuration.removeAttribute(get2DConfigData(GRAPH_X_SERIES, regex, i));
            configuration.removeAttribute(get2DConfigData(GRAPH_ID, regex, i));

            cleanUpConfigurationGraphYSeries(configuration, regex, i, 0);
            configuration.removeAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, regex, i));
        }
    }

    private void cleanUpConfigurationItem(ILaunchConfigurationWorkingCopy configuration, String counter, String property, int regex, int newNumberOfItems) {
        int oldNumberOfItems = 0;
        try {
            oldNumberOfItems = configuration.getAttribute(counter + regex, 0);
        } catch (CoreException e) {}
        for (int i = newNumberOfItems; i < oldNumberOfItems; i++) {
            configuration.removeAttribute(get2DConfigData(property, regex, i));
        }
    }

    private void cleanUpConfigurationGraphYSeries(ILaunchConfigurationWorkingCopy configuration, int regex, int graph, int newLength) {
        int oldYSeriesLength = 0;
        try {
            oldYSeriesLength = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, regex, graph), 0);
        } catch (CoreException e) {}
        for (int i = newLength; i < oldYSeriesLength; i++) {
            configuration.removeAttribute(get2DConfigData(GRAPH_Y_SERIES, regex, graph + "_" + i)); //$NON-NLS-1$
        }
    }

    /**
     * Checks all regular expressions for errors, except for the currently-selected
     * expression (as it should be checked by {@link #refreshRegexRows}).
     */
    private void checkAllOtherErrors() {
        for (int i = 0, n = getNumberOfRegexs(); i < n; i++) {
            if (i == selectedRegex) {
                continue;
            }
            checkErrors(i);
        }
    }

    /**
     * Checks the regular expression of the provided index for errors.
     * Sets the associated error message to contain relevant error information.
     * @param i The index of the regular expression to check for errors.
     */
    private void checkErrors(int i) {
        String regex = regularExpressionCombo.getItem(i);
        try {
            Pattern.compile(regex);
        } catch (PatternSyntaxException e) {
            regexErrorMessages.set(i, e.getMessage());
            return;
        }

        String error = findBadGraphs(i);
        if (error == null) {
            error = checkRegex(regex);
        }

        regexErrorMessages.set(i, error);
    }

    @Override
    public boolean isValid(ILaunchConfiguration launchConfig) {
        setErrorMessage(null);

        // If graphic is disabled then everything is valid.
        if (!this.graphingEnabled) {
            return true;
        }

        for (int r = 0, n = getNumberOfRegexs(); r < n; r++) {
            String regexErrorMessage = regexErrorMessages.get(r);
            if (regexErrorMessage != null) {
                setErrorMessage(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_regexErrorMsgFormat,
                        regularExpressionCombo.getItems()[r], regexErrorMessage));
                return false;
            }
        }

        return true;
    }

    /**
     * Checks if a launch configuration's Systemtap Graphing settings are valid.
     * @param launchConfig The launch configuration to check for graph validity.
     * @return <code>true</code> if the launch settings are valid, or <code>false</code> if
     * its graph settings are invalid in some way.
     * @since 2.2
     */
    public static boolean isValidLaunch(ILaunchConfiguration launchConfig) throws CoreException {
        // If graphic is disabled then everything is valid.
        if (!launchConfig.getAttribute(RUN_WITH_CHART, false)) {
            return true;
        }

        for (int r = 0, n = launchConfig.getAttribute(NUMBER_OF_REGEXS, 1); r < n; r++) {
            // Check for any invalid regexs.
            String regex = launchConfig.getAttribute(REGULAR_EXPRESSION + r, (String) null);
            if (regex == null || checkRegex(regex) != null) {
                return false;
            }
            try {
                Pattern.compile(regex);
            } catch (PatternSyntaxException e) {
                return false;
            }

            // If graphs are plotted but no data is captured by one of them, report this as a problem.
            int numberOfColumns = launchConfig.getAttribute(NUMBER_OF_COLUMNS + r, 0);
            if (numberOfColumns == 0) {
                return false;
            }

            // Check for graphs that are missing required data.
            for (int i = 0, g = launchConfig.getAttribute(NUMBER_OF_GRAPHS + r, 0); i < g; i++) {
                if (GraphFactory.getGraphName(launchConfig.getAttribute(get2DConfigData(GRAPH_ID, r, i), (String) null)) == null) {
                    return false;
                }
                if (launchConfig.getAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), 0) >= numberOfColumns) {
                    return false;
                }
                for (int j = 0, y = launchConfig.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), 0); j < y; j++) {
                    if (launchConfig.getAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), 0) >= numberOfColumns) { //$NON-NLS-1$
                        return false;
                    }
                }
            }
        }

        return true;
    }

    @Override
    public String getName() {
        return Messages.SystemTapScriptGraphOptionsTab_graphingTitle;
    }

    @Override
    public Image getImage() {
        return AbstractUIPlugin.imageDescriptorFromPlugin(IDEPlugin.PLUGIN_ID,
                "icons/graphing_tab.gif").createImage(); //$NON-NLS-1$
    }

    private void setGraphingEnabled(boolean enabled) {
        this.graphingEnabled = enabled;
        this.setControlEnabled(outputParsingGroup, enabled);
        this.setControlEnabled(graphsGroup, enabled);
        // Disable buttons that rely on a selected graph if no graph is selected.
        this.setSelectionControlsEnabled(selectedTableItem != null);
        this.addGraphButton.setEnabled(enabled && numberOfVisibleColumns > 0);
        this.removeRegexButton.setEnabled(enabled && getNumberOfRegexs() > 1);
        updateLaunchConfigurationDialog();
    }

    private void setControlEnabled(Composite composite, boolean enabled) {
        composite.setEnabled(enabled);
        for (Control child : composite.getChildren()) {
            child.setEnabled(enabled);
            if (child instanceof Composite) {
                setControlEnabled((Composite)child, enabled);
            }
        }
    }

    /**
     * Call this to enable/disable all buttons whose actions depend on a selected graph.
     * @param enabled Set to true to enable the buttons; set to false to disable them.
     */
    private void setSelectionControlsEnabled(boolean enabled) {
        duplicateGraphButton.setEnabled(enabled);
        editGraphButton.setEnabled(enabled && numberOfVisibleColumns > 0);
        removeGraphButton.setEnabled(enabled);
    }
}

Back to the top