Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c6aefc5ee6eee5c23e2e441fa9b355555a361cff (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
/*******************************************************************************
 * Copyright (c) 2007, 2011 Wind River Systems, Inc. and others.
 * 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:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tm.internal.tcf.debug.ui.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IExpressionManager;
import org.eclipse.debug.core.IExpressionsListener;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.commands.IDisconnectHandler;
import org.eclipse.debug.core.commands.IDropToFrameHandler;
import org.eclipse.debug.core.commands.IResumeHandler;
import org.eclipse.debug.core.commands.IStepIntoHandler;
import org.eclipse.debug.core.commands.IStepOverHandler;
import org.eclipse.debug.core.commands.IStepReturnHandler;
import org.eclipse.debug.core.commands.ISuspendHandler;
import org.eclipse.debug.core.commands.ITerminateHandler;
import org.eclipse.debug.core.model.IDebugModelProvider;
import org.eclipse.debug.core.model.IExpression;
import org.eclipse.debug.core.model.IMemoryBlockRetrieval;
import org.eclipse.debug.core.model.IMemoryBlockRetrievalExtension;
import org.eclipse.debug.core.model.ISourceLocator;
import org.eclipse.debug.core.sourcelookup.ISourceLookupDirector;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenCountUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IColumnPresentation;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IColumnPresentationFactory;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementContentProvider;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementLabelProvider;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelProxy;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelProxyFactory;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelSelectionPolicy;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelSelectionPolicyFactory;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputProvider;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputUpdate;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.debug.ui.IDebugView;
import org.eclipse.debug.ui.ISourcePresentation;
import org.eclipse.debug.ui.contexts.ISuspendTrigger;
import org.eclipse.debug.ui.contexts.ISuspendTriggerListener;
import org.eclipse.debug.ui.sourcelookup.CommonSourceNotFoundEditorInput;
import org.eclipse.debug.ui.sourcelookup.ISourceDisplay;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.tm.internal.tcf.debug.actions.TCFAction;
import org.eclipse.tm.internal.tcf.debug.launch.TCFSourceLookupDirector;
import org.eclipse.tm.internal.tcf.debug.launch.TCFSourceLookupParticipant;
import org.eclipse.tm.internal.tcf.debug.model.ITCFConstants;
import org.eclipse.tm.internal.tcf.debug.model.TCFContextState;
import org.eclipse.tm.internal.tcf.debug.model.TCFLaunch;
import org.eclipse.tm.internal.tcf.debug.model.TCFSourceRef;
import org.eclipse.tm.internal.tcf.debug.ui.Activator;
import org.eclipse.tm.internal.tcf.debug.ui.commands.BackIntoCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.BackOverCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.BackResumeCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.BackReturnCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.DisconnectCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.DropToFrameCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.ResumeCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.StepIntoCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.StepOverCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.StepReturnCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.SuspendCommand;
import org.eclipse.tm.internal.tcf.debug.ui.commands.TerminateCommand;
import org.eclipse.tm.internal.tcf.debug.ui.preferences.TCFPreferences;
import org.eclipse.tm.tcf.core.Command;
import org.eclipse.tm.tcf.protocol.IChannel;
import org.eclipse.tm.tcf.protocol.IErrorReport;
import org.eclipse.tm.tcf.protocol.IToken;
import org.eclipse.tm.tcf.protocol.Protocol;
import org.eclipse.tm.tcf.services.IDisassembly;
import org.eclipse.tm.tcf.services.ILineNumbers;
import org.eclipse.tm.tcf.services.IMemory;
import org.eclipse.tm.tcf.services.IMemoryMap;
import org.eclipse.tm.tcf.services.IProcesses;
import org.eclipse.tm.tcf.services.IRegisters;
import org.eclipse.tm.tcf.services.IRunControl;
import org.eclipse.tm.tcf.services.IRunControl.RunControlContext;
import org.eclipse.tm.tcf.services.ISymbols;
import org.eclipse.tm.tcf.util.TCFDataCache;
import org.eclipse.tm.tcf.util.TCFTask;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPersistableElement;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

/**
 * TCFModel represents remote target state as it is known to host.
 * The main job of the model is caching remote data,
 * keeping the cache in a coherent state,
 * and feeding UI with up-to-date data.
 */
public class TCFModel implements IElementContentProvider, IElementLabelProvider, IViewerInputProvider,
        IModelProxyFactory, IColumnPresentationFactory, ISourceDisplay, ISuspendTrigger {

    /** The id of the expression hover presentation context */
    public static final String ID_EXPRESSION_HOVER = Activator.PLUGIN_ID + ".expression_hover";

    /**
     * A dummy editor input to open the disassembly view as editor.
     */
    public static class DisassemblyEditorInput implements IEditorInput {
        final static String EDITOR_ID = "org.eclipse.cdt.dsf.ui.disassembly";
        final static DisassemblyEditorInput INSTANCE = new DisassemblyEditorInput();

        @SuppressWarnings("rawtypes")
        public Object getAdapter(Class adapter) {
            return null;
        }

        public boolean exists() {
            return false;
        }

        public ImageDescriptor getImageDescriptor() {
            return null;
        }

        public String getName() {
            return "Disassembly";
        }

        public IPersistableElement getPersistable() {
            return null;
        }

        public String getToolTipText() {
            return "Disassembly";
        }
    }

    private final TCFLaunch launch;
    private final Display display;
    private final IExpressionManager expr_manager;
    private final TCFAnnotationManager annotation_manager;

    private final List<ISuspendTriggerListener> suspend_trigger_listeners =
        new LinkedList<ISuspendTriggerListener>();

    private int display_source_generation;
    private int suspend_trigger_generation;
    private int auto_disconnect_generation;

    private long min_view_updates_interval;
    private boolean view_updates_throttle_enabled;
    private boolean channel_throttle_enabled;
    private boolean wait_for_pc_update_after_step;
    private boolean wait_for_views_update_after_step;
    private boolean delay_stack_update_until_last_step;
    private boolean stack_frames_limit_enabled;
    private int stack_frames_limit_value;
    private boolean show_function_arg_names;
    private boolean show_function_arg_values;

    private final Map<String,String> action_results = new HashMap<String,String>();
    private final HashMap<String,TCFAction> active_actions = new HashMap<String,TCFAction>();

    private final Map<IPresentationContext,TCFModelProxy> model_proxies =
        new HashMap<IPresentationContext,TCFModelProxy>();

    private final Map<String,TCFNode> id2node = new HashMap<String,TCFNode>();

    private final Map<Class<?>,Object> adapters = new HashMap<Class<?>,Object>();

    private class MemoryBlocksUpdate extends TCFDataCache<Map<String,TCFMemoryBlockRetrieval>> {

        final Set<String> changeset = new HashSet<String>();

        MemoryBlocksUpdate(IChannel channel) {
            super(channel);
            Protocol.invokeLater(new Runnable() {
                public void run() {
                    if (!validate(this)) return;
                    Map<String,TCFMemoryBlockRetrieval> map = getData();
                    if (map != null) { // map can be null if, for example, the channel was closed
                        for (TCFMemoryBlockRetrieval r : map.values()) r.onMemoryChanged();
                    }
                    launch.removePendingClient(mem_blocks_update);
                    mem_blocks_update = null;
                }
            });
        }

        void add(String id) {
            changeset.add(id);
        }

        public boolean startDataRetrieval() {
            // Map changed contexts to memory nodes, and then to memory block retrieval objects
            Map<String,TCFMemoryBlockRetrieval> map = new HashMap<String,TCFMemoryBlockRetrieval>();
            for (String id : changeset) {
                if (map.get(id) != null) continue;
                TCFNode node = id2node.get(id);
                if (node == null) {
                    if (!createNode(id, this)) return false;
                    if (isValid()) {
                        Activator.log("Cannot create debug model node", getError());
                        reset();
                        continue;
                    }
                    node = id2node.get(id);
                }
                if (node instanceof TCFNodeExecContext) {
                    TCFDataCache<TCFNodeExecContext> c = ((TCFNodeExecContext)node).getMemoryNode();
                    if (!c.validate(this)) return false;
                    node = c.getData();
                    if (node == null) continue;
                    if (map.get(node.id) != null) continue;
                    TCFMemoryBlockRetrieval r = mem_retrieval.get(node.id);
                    if (r != null) map.put(node.id, r);
                }
            }
            set(null, null, map);
            return true;
        }
    }

    private final Map<String,TCFMemoryBlockRetrieval> mem_retrieval = new HashMap<String,TCFMemoryBlockRetrieval>();
    private MemoryBlocksUpdate mem_blocks_update;

    private final Map<String,String> cast_to_type_map = new HashMap<String,String>();

    private final Map<String,Object> context_map = new HashMap<String,Object>();

    private final Set<String> expanded_nodes = new HashSet<String>();

    private TCFConsole console;

    private static final Map<ILaunchConfiguration,IEditorInput> editor_not_found =
        new HashMap<ILaunchConfiguration,IEditorInput>();

    private final IModelSelectionPolicyFactory model_selection_factory = new IModelSelectionPolicyFactory() {

        public IModelSelectionPolicy createModelSelectionPolicyAdapter(
                Object element, IPresentationContext context) {
            return selection_policy;
        }
    };

    private final IModelSelectionPolicy selection_policy;

    private IChannel channel;
    private TCFNodeLaunch launch_node;
    private boolean disposed;

    private final IMemory.MemoryListener mem_listener = new IMemory.MemoryListener() {

        public void contextAdded(IMemory.MemoryContext[] contexts) {
            for (IMemory.MemoryContext ctx : contexts) {
                String id = ctx.getParentID();
                if (id == null) {
                    launch_node.onContextAdded(ctx);
                }
                else {
                    TCFNode node = getNode(id);
                    if (node instanceof TCFNodeExecContext) {
                        ((TCFNodeExecContext)node).onContextAdded(ctx);
                    }
                }
            }
            launch_node.onAnyContextAddedOrRemoved();
        }

        public void contextChanged(IMemory.MemoryContext[] contexts) {
            for (IMemory.MemoryContext ctx : contexts) {
                TCFNode node = getNode(ctx.getID());
                if (node instanceof TCFNodeExecContext) {
                    ((TCFNodeExecContext)node).onContextChanged(ctx);
                }
                onMemoryChanged(ctx.getID());
            }
        }

        public void contextRemoved(final String[] context_ids) {
            onContextRemoved(context_ids);
        }

        public void memoryChanged(String context_id, Number[] addr, long[] size) {
            TCFNode node = getNode(context_id);
            if (node instanceof TCFNodeExecContext) {
                ((TCFNodeExecContext)node).onMemoryChanged(addr, size);
            }
            onMemoryChanged(context_id);
        }
    };

    private final IRunControl.RunControlListener run_listener = new IRunControl.RunControlListener() {

        public void containerResumed(String[] context_ids) {
            for (String id : context_ids) {
                TCFNode node = getNode(id);
                if (node instanceof TCFNodeExecContext) {
                    ((TCFNodeExecContext)node).onContainerResumed();
                }
            }
            annotation_manager.updateAnnotations(null, launch);
        }

        public void containerSuspended(String context, String pc, String reason,
                Map<String,Object> params, String[] suspended_ids) {
            int action_cnt = 0;
            for (String id : suspended_ids) {
                TCFNode node = getNode(id);
                action_results.remove(id);
                if (active_actions.get(id) != null) action_cnt++;
                if (!id.equals(context) && node instanceof TCFNodeExecContext) {
                    ((TCFNodeExecContext)node).onContainerSuspended();
                }
                onMemoryChanged(id);
            }
            TCFNode node = getNode(context);
            if (node instanceof TCFNodeExecContext) {
                ((TCFNodeExecContext)node).onContextSuspended(pc, reason, params);
            }
            launch_node.onAnyContextSuspendedOrChanged();
            if (action_cnt == 0) {
                setDebugViewSelection(node, reason);
                annotation_manager.updateAnnotations(null, launch);
            }
            action_results.remove(context);
        }

        public void contextAdded(IRunControl.RunControlContext[] contexts) {
            for (IRunControl.RunControlContext ctx : contexts) {
                String id = ctx.getParentID();
                if (id == null) {
                    launch_node.onContextAdded(ctx);
                }
                else {
                    TCFNode node = getNode(id);
                    if (node instanceof TCFNodeExecContext) {
                        ((TCFNodeExecContext)node).onContextAdded(ctx);
                    }
                }
                context_map.put(ctx.getID(), ctx);
            }
            launch_node.onAnyContextAddedOrRemoved();
        }

        public void contextChanged(IRunControl.RunControlContext[] contexts) {
            for (IRunControl.RunControlContext ctx : contexts) {
                String id = ctx.getID();
                context_map.put(id, ctx);
                TCFNode node = getNode(id);
                if (node instanceof TCFNodeExecContext) {
                    ((TCFNodeExecContext)node).onContextChanged(ctx);
                }
                onMemoryChanged(id);
            }
            launch_node.onAnyContextSuspendedOrChanged();
        }

        public void contextException(String context, String msg) {
            TCFNode node = getNode(context);
            if (node instanceof TCFNodeExecContext) {
                ((TCFNodeExecContext)node).onContextException(msg);
            }
        }

        public void contextRemoved(final String[] context_ids) {
            onContextRemoved(context_ids);
        }

        public void contextResumed(String id) {
            TCFNode node = getNode(id);
            if (node instanceof TCFNodeExecContext) {
                ((TCFNodeExecContext)node).onContextResumed();
            }
            annotation_manager.updateAnnotations(null, launch);
        }

        public void contextSuspended(String id, String pc, String reason, Map<String,Object> params) {
            TCFNode node = getNode(id);
            action_results.remove(id);
            if (node instanceof TCFNodeExecContext) {
                ((TCFNodeExecContext)node).onContextSuspended(pc, reason, params);
            }
            launch_node.onAnyContextSuspendedOrChanged();
            if (active_actions.get(id) == null) {
                setDebugViewSelection(node, reason);
                annotation_manager.updateAnnotations(null, launch);
            }
            onMemoryChanged(id);
        }
    };

    private final IMemoryMap.MemoryMapListener mmap_listenr = new IMemoryMap.MemoryMapListener() {

        public void changed(String context) {
            TCFNode node = getNode(context);
            if (node instanceof TCFNodeExecContext) {
                TCFNodeExecContext exe = (TCFNodeExecContext)node;
                exe.onMemoryMapChanged();
            }
            display.asyncExec(new Runnable() {
                public void run() {
                    if (PlatformUI.isWorkbenchRunning()) {
                        for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
                            IWorkbenchPage page = window.getActivePage();
                            if (page != null) displaySource(null, page, true);
                        }
                    }
                }
            });
        }
    };

    private final IRegisters.RegistersListener reg_listener = new IRegisters.RegistersListener() {

        public void contextChanged() {
            for (TCFNode node : id2node.values()) {
                if (node instanceof TCFNodeExecContext) {
                    ((TCFNodeExecContext)node).onRegistersChanged();
                }
            }
        }

        public void registerChanged(String context) {
            TCFNode node = getNode(context);
            if (node instanceof TCFNodeRegister) {
                ((TCFNodeRegister)node).onValueChanged();
            }
        }
    };

    private final IProcesses.ProcessesListener prs_listener = new IProcesses.ProcessesListener() {

        public void exited(String process_id, int exit_code) {
            IProcesses.ProcessContext prs = launch.getProcessContext();
            if (prs != null && process_id.equals(prs.getID())) onContextOrProcessRemoved();
        }
    };

    private final IExpressionsListener expressions_listener = new IExpressionsListener() {

        int generation;

        public void expressionsAdded(IExpression[] expressions) {
            expressionsRemoved(expressions);
        }

        public void expressionsChanged(IExpression[] expressions) {
            expressionsRemoved(expressions);
        }

        public void expressionsRemoved(IExpression[] expressions) {
            final int g = ++generation;
            Protocol.invokeLater(new Runnable() {
                public void run() {
                    if (g != generation) return;
                    for (TCFNode n : id2node.values()) {
                        if (n instanceof TCFNodeExecContext) {
                            ((TCFNodeExecContext)n).onExpressionAddedOrRemoved();
                        }
                    }
                    for (TCFModelProxy p : model_proxies.values()) {
                        String id = p.getPresentationContext().getId();
                        if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(id)) {
                            Object o = p.getInput();
                            if (o instanceof TCFNode) {
                                TCFNode n = (TCFNode)o;
                                if (n.model == TCFModel.this) p.addDelta(n, IModelDelta.CONTENT);
                            }
                        }
                    }
                }
            });
        }
    };

    private final TCFLaunch.ActionsListener actions_listener = new TCFLaunch.ActionsListener() {

        public void onContextActionStart(TCFAction action) {
            final String id = action.getContextID();
            active_actions.put(id, action);
            annotation_manager.updateAnnotations(null, launch);
        }

        public void onContextActionResult(String id, String reason) {
            if (reason == null) action_results.remove(id);
            else action_results.put(id, reason);
        }

        public void onContextActionDone(TCFAction action) {
            String id = action.getContextID();
            active_actions.remove(id);
            TCFNode node = getNode(id);
            if (node instanceof TCFNodeExecContext) {
                ((TCFNodeExecContext)node).onContextActionDone();
            }
            setDebugViewSelection(id2node.get(id), "Action");
            for (TCFModelProxy p : model_proxies.values()) p.post();
            annotation_manager.updateAnnotations(null, launch);
        }
    };

    private final IDebugModelProvider debug_model_provider = new IDebugModelProvider() {
        public String[] getModelIdentifiers() {
            return new String[] { ITCFConstants.ID_TCF_DEBUG_MODEL };
        }
    };

    private class InitialSelection implements Runnable {
        boolean done;
        public void run() {
            if (done) return;
            ArrayList<TCFNodeExecContext> nodes = new ArrayList<TCFNodeExecContext>();
            if (!searchSuspendedThreads(launch_node.getFilteredChildren(), nodes)) return;
            if (nodes.size() == 0) {
                setDebugViewSelection(launch_node, "Launch");
            }
            else if (nodes.size() == 1) {
                TCFNodeExecContext n = nodes.get(0);
                setDebugViewSelection(n, "Launch");
            }
            else {
                for (TCFNodeExecContext n : nodes) {
                    String reason = n.getState().getData().suspend_reason;
                    setDebugViewSelection(n, reason);
                }
            }
            done = true;
        }
        private boolean searchSuspendedThreads(TCFChildren c, ArrayList<TCFNodeExecContext> nodes) {
            if (!c.validate(this)) return false;
            for (TCFNode n : c.toArray()) {
                if (!searchSuspendedThreads((TCFNodeExecContext)n, nodes)) return false;
            }
            return true;
        }
        private boolean searchSuspendedThreads(TCFNodeExecContext n, ArrayList<TCFNodeExecContext> nodes) {
            TCFDataCache<IRunControl.RunControlContext> run_context = n.getRunContext();
            if (!run_context.validate(this)) return false;
            IRunControl.RunControlContext ctx = run_context.getData();
            if (ctx != null && ctx.hasState()) {
                TCFDataCache<TCFContextState> state = n.getState();
                if (!state.validate(this)) return false;
                TCFContextState s = state.getData();
                if (s != null && s.is_suspended) nodes.add(n);
                return true;
            }
            return searchSuspendedThreads(n.getChildren(), nodes);
        }
    }

    private volatile boolean instruction_stepping_enabled;

    TCFModel(final TCFLaunch launch) {
        this.launch = launch;
        display = PlatformUI.getWorkbench().getDisplay();
        selection_policy = new TCFModelSelectionPolicy(this);
        adapters.put(ILaunch.class, launch);
        adapters.put(IModelSelectionPolicy.class, selection_policy);
        adapters.put(IModelSelectionPolicyFactory.class, model_selection_factory);
        adapters.put(IDebugModelProvider.class, debug_model_provider);
        adapters.put(ISuspendHandler.class, new SuspendCommand(this));
        adapters.put(IResumeHandler.class, new ResumeCommand(this));
        adapters.put(BackResumeCommand.class, new BackResumeCommand(this));
        adapters.put(ITerminateHandler.class, new TerminateCommand(this));
        adapters.put(IDisconnectHandler.class, new DisconnectCommand(this));
        adapters.put(IStepIntoHandler.class, new StepIntoCommand(this));
        adapters.put(IStepOverHandler.class, new StepOverCommand(this));
        adapters.put(IStepReturnHandler.class, new StepReturnCommand(this));
        adapters.put(BackIntoCommand.class, new BackIntoCommand(this));
        adapters.put(BackOverCommand.class, new BackOverCommand(this));
        adapters.put(BackReturnCommand.class, new BackReturnCommand(this));
        adapters.put(IDropToFrameHandler.class, new DropToFrameCommand(this));
        expr_manager = DebugPlugin.getDefault().getExpressionManager();
        expr_manager.addExpressionListener(expressions_listener);
        annotation_manager = Activator.getAnnotationManager();
        launch.addActionsListener(actions_listener);
        final IPreferenceStore prefs = TCFPreferences.getPreferenceStore();
        IPropertyChangeListener listener = new IPropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                launch.setContextActionsInterval(prefs.getLong(TCFPreferences.PREF_MIN_STEP_INTERVAL));
                min_view_updates_interval = prefs.getLong(TCFPreferences.PREF_MIN_UPDATE_INTERVAL);
                view_updates_throttle_enabled = prefs.getBoolean(TCFPreferences.PREF_VIEW_UPDATES_THROTTLE);
                channel_throttle_enabled = prefs.getBoolean(TCFPreferences.PREF_TARGET_TRAFFIC_THROTTLE);
                wait_for_pc_update_after_step = prefs.getBoolean(TCFPreferences.PREF_WAIT_FOR_PC_UPDATE_AFTER_STEP);
                wait_for_views_update_after_step = prefs.getBoolean(TCFPreferences.PREF_WAIT_FOR_VIEWS_UPDATE_AFTER_STEP);
                delay_stack_update_until_last_step = prefs.getBoolean(TCFPreferences.PREF_DELAY_STACK_UPDATE_UNTIL_LAST_STEP);
                stack_frames_limit_enabled = prefs.getBoolean(TCFPreferences.PREF_STACK_FRAME_LIMIT_ENABLED);
                stack_frames_limit_value = prefs.getInt(TCFPreferences.PREF_STACK_FRAME_LIMIT_VALUE);
                show_function_arg_names = prefs.getBoolean(TCFPreferences.PREF_STACK_FRAME_ARG_NAMES);
                show_function_arg_values = prefs.getBoolean(TCFPreferences.PREF_STACK_FRAME_ARG_VALUES);
                Protocol.invokeLater(new Runnable() {
                    public void run() {
                        for (TCFNode n : id2node.values()) {
                            if (n instanceof TCFNodeExecContext) {
                                ((TCFNodeExecContext)n).onPreferencesChanged();
                            }
                        }
                    }
                });
            }
        };
        listener.propertyChange(null);
        prefs.addPropertyChangeListener(listener);
    }

    /**
     * Add an adapter for given type.
     *
     * @param adapterType  the type the adapter implements
     * @param adapter  the adapter implementing <code>adapterType</code>
     */
    public void setAdapter(Class<?> adapterType, Object adapter) {
        synchronized (adapters) {
            assert adapterType.isInstance(adapter);
            adapters.put(adapterType, adapter);
        }
    }

    @SuppressWarnings("rawtypes")
    public Object getAdapter(final Class adapter, final TCFNode node) {
        synchronized (adapters) {
            Object o = adapters.get(adapter);
            if (o != null) return o;
        }
        if (adapter == IMemoryBlockRetrieval.class || adapter == IMemoryBlockRetrievalExtension.class) {
            return new TCFTask<Object>() {
                public void run() {
                    Object o = null;
                    TCFDataCache<TCFNodeExecContext> cache = searchMemoryContext(node);
                    if (cache != null) {
                        if (!cache.validate(this)) return;
                        if (cache.getData() != null) {
                            TCFNodeExecContext ctx = cache.getData();
                            o = mem_retrieval.get(ctx.id);
                            if (o == null) {
                                TCFMemoryBlockRetrieval m = new TCFMemoryBlockRetrieval(ctx);
                                mem_retrieval.put(ctx.id, m);
                                o = m;
                            }
                        }
                    }
                    assert o == null || adapter.isInstance(o);
                    done(o);
                }
            }.getE();
        }
        return null;
    }

    void onConnected() {
        assert Protocol.isDispatchThread();
        assert launch_node == null;
        channel = launch.getChannel();
        launch_node = new TCFNodeLaunch(this);
        IMemory mem = launch.getService(IMemory.class);
        if (mem != null) mem.addListener(mem_listener);
        IRunControl run = launch.getService(IRunControl.class);
        if (run != null) run.addListener(run_listener);
        IMemoryMap mmap = launch.getService(IMemoryMap.class);
        if (mmap != null) mmap.addListener(mmap_listenr);
        IRegisters reg = launch.getService(IRegisters.class);
        if (reg != null) reg.addListener(reg_listener);
        IProcesses prs = launch.getService(IProcesses.class);
        if (prs != null) prs.addListener(prs_listener);
        launchChanged();
        for (TCFModelProxy p : model_proxies.values()) {
            String id = p.getPresentationContext().getId();
            if (IDebugUIConstants.ID_DEBUG_VIEW.equals(id)) {
                Protocol.invokeLater(new InitialSelection());
            }
        }
    }

    void onDisconnected() {
        assert Protocol.isDispatchThread();
        if (launch_node != null) {
            launch_node.dispose();
            launch_node = null;
        }
        refreshLaunchView();
        assert id2node.size() == 0;
    }

    void onProcessOutput(String process_id, final int stream_id, byte[] data) {
        IProcesses.ProcessContext prs = launch.getProcessContext();
        if (prs == null || !process_id.equals(prs.getID())) return;
        if (console == null) console = new TCFConsole(this, process_id);
        console.write(stream_id, data);
    }

    void onProcessStreamError(String process_id, int stream_id, Exception x, int lost_size) {
        if (channel != null && channel.getState() == IChannel.STATE_CLOSED) return;
        StringBuffer bf = new StringBuffer();
        bf.append("Debugger console IO error");
        if (process_id != null) {
            bf.append(". Process ID ");
            bf.append(process_id);
        }
        bf.append(". Stream ");
        bf.append(stream_id);
        if (lost_size > 0) {
            bf.append(". Lost data size ");
            bf.append(lost_size);
        }
        Activator.log(bf.toString(), x);
    }

    void onMemoryChanged(String id) {
        if (channel == null) return;
        if (mem_retrieval.size() == 0) return;
        if (mem_blocks_update == null) {
            mem_blocks_update = new MemoryBlocksUpdate(channel);
            if (wait_for_views_update_after_step) {
                launch.addPendingClient(mem_blocks_update);
            }
        }
        mem_blocks_update.add(id);
    }

    public TCFAction getActiveAction(String id) {
        return active_actions.get(id);
    }

    String getContextActionResult(String id) {
        return action_results.get(id);
    }

    public long getMinViewUpdatesInterval() {
        return min_view_updates_interval;
    }

    public boolean getViewUpdatesThrottleEnabled() {
        return view_updates_throttle_enabled;
    }

    public boolean getWaitForViewsUpdateAfterStep() {
        return wait_for_views_update_after_step;
    }

    public boolean getDelayStackUpdateUtilLastStep() {
        return delay_stack_update_until_last_step;
    }

    public boolean getChannelThrottleEnabled() {
        return channel_throttle_enabled;
    }

    public boolean getStackFramesLimitEnabled() {
        return stack_frames_limit_enabled;
    }

    public int getStackFramesLimitValue() {
        return stack_frames_limit_value;
    }

    public boolean getShowFunctionArgNames() {
        return show_function_arg_names;
    }

    public boolean getShowFunctionArgValues() {
        return show_function_arg_values;
    }

    void onProxyInstalled(TCFModelProxy mp) {
        IPresentationContext pc = mp.getPresentationContext();
        model_proxies.put(mp.getPresentationContext(), mp);
        if (launch_node != null && pc.getId().equals(IDebugUIConstants.ID_DEBUG_VIEW)) {
            Protocol.invokeLater(new InitialSelection());
        }
    }

    void onProxyDisposed(TCFModelProxy mp) {
        IPresentationContext ctx = mp.getPresentationContext();
        assert model_proxies.get(ctx) == mp;
        model_proxies.remove(ctx);
    }

    private void onContextRemoved(String[] context_ids) {
        for (String id : context_ids) {
            TCFNode node = getNode(id);
            if (node instanceof TCFNodeExecContext) {
                ((TCFNodeExecContext)node).onContextRemoved();
            }
            action_results.remove(id);
            context_map.remove(id);
            expanded_nodes.remove(id);
            if (mem_blocks_update != null) mem_blocks_update.changeset.remove(id);
        }
        launch_node.onAnyContextAddedOrRemoved();
        // Close debug session if the last context is removed:
        onContextOrProcessRemoved();
        annotation_manager.updateAnnotations(null, launch);
    }

    void onContextRunning() {
        annotation_manager.updateAnnotations(null, launch);
    }

    private void onContextOrProcessRemoved() {
        final int generation = ++auto_disconnect_generation;
        Protocol.invokeLater(1000, new Runnable() {
            public void run() {
                if (generation != auto_disconnect_generation) return;
                if (launch_node == null) return;
                if (launch_node.isDisposed()) return;
                TCFChildren children = launch_node.getFilteredChildren();
                if (!children.validate(this)) return;
                if (children.size() > 0) return;
                launch.onLastContextRemoved();
            }
        });
    }

    void launchChanged() {
        if (launch_node != null) {
            for (TCFModelProxy p : model_proxies.values()) {
                String id = p.getPresentationContext().getId();
                if (IDebugUIConstants.ID_DEBUG_VIEW.equals(id)) {
                    p.addDelta(launch_node, IModelDelta.STATE | IModelDelta.CONTENT);
                }
            }
        }
        else {
            refreshLaunchView();
        }
    }

    Collection<TCFModelProxy> getModelProxies() {
        return model_proxies.values();
    }

    void dispose() {
        launch.removeActionsListener(actions_listener);
        expr_manager.removeExpressionListener(expressions_listener);
        if (console != null) console.close();
    }

    void addNode(String id, TCFNode node) {
        assert id != null;
        assert Protocol.isDispatchThread();
        assert id2node.get(id) == null;
        assert !node.isDisposed();
        id2node.put(id, node);
    }

    void removeNode(String id) {
        assert id != null;
        assert Protocol.isDispatchThread();
        id2node.remove(id);
        mem_retrieval.remove(id);
    }

    void flushAllCaches() {
        for (TCFNode n : id2node.values()) n.flushAllCaches();
    }

    public IExpressionManager getExpressionManager() {
        return expr_manager;
    }

    public Display getDisplay() {
        return display;
    }

    /**
     * @return debug model launch object.
     */
    public TCFLaunch getLaunch() {
        return launch;
    }

    /**
     * @return communication channel that this model is using.
     */
    public IChannel getChannel() {
        return channel;
    }

    /**
     * Get top level (root) debug model node.
     * Same as getNode("").
     * @return root node.
     */
    public TCFNodeLaunch getRootNode() {
        return launch_node;
    }

    /**
     * Set current hover expression for a given model node,
     * and return a cache of expression nodes that represents given expression.
     * The model allows only one current hover expression per node at any time,
     * however it will cache results of recent expression evaluations,
     * and it will re-use cached results when current hover expression changes.
     * The cache getData() method should not return more then 1 node,
     * and it can return an empty collection.
     * @param parent - a thread or stack frame where the expression should be evaluated.
     * @param expression - the expression text, can be null.
     * @return a cache of expression nodes.
     */
    public TCFChildren getHoverExpressionCache(TCFNode parent, String expression) {
        assert Protocol.isDispatchThread();
        if (parent instanceof TCFNodeStackFrame) {
            return ((TCFNodeStackFrame)parent).getHoverExpressionCache(expression);
        }
        if (parent instanceof TCFNodeExecContext) {
            return ((TCFNodeExecContext)parent).getHoverExpressionCache(expression);
        }
        return null;
    }

    /**
     * Get a model node with given ID.
     * ID == "" means launch node.
     * @param id - node ID.
     * @return debug model node or null if no node exists with such ID.
     */
    public TCFNode getNode(String id) {
        if (id == null) return null;
        if (id.equals("")) return launch_node;
        assert Protocol.isDispatchThread();
        return id2node.get(id);
    }

    /**
     * Get a type that should be used to cast a value of an expression when it is shown in a view.
     * Return null if original type of the value should be used.
     * @param id - expression node ID.
     * @return a string that designates a type or null.
     */
    public String getCastToType(String id) {
        return cast_to_type_map.get(id);
    }

    /**
     * Register a type that should be used to cast a value of an expression when it is shown in a view.
     * 'type' == null means original type of the value should be used.
     * @param id - expression node ID.
     * @param type - a string that designates a type.
     */
    public void setCastToType(String id, String type) {
        if (type != null && type.trim().length() == 0) type = null;
        if (type == null) cast_to_type_map.remove(id);
        else cast_to_type_map.put(id, type);
        TCFNode node = id2node.get(id);
        if (node instanceof ICastToType) {
            ((ICastToType)node).onCastToTypeChanged();
        }
    }

    /**
     * Get a data cache that contains properties of a symbol.
     * New cache object is created if it does not exist yet.
     * @param sym_id - the symbol ID.
     * @return data cache object.
     */
    public TCFDataCache<ISymbols.Symbol> getSymbolInfoCache(final String sym_id) {
        if (sym_id == null) return null;
        TCFNodeSymbol n = (TCFNodeSymbol)getNode(sym_id);
        if (n == null) n = new TCFNodeSymbol(launch_node, sym_id);
        return n.getContext();
    }

    /**
     * Get a data cache that contains children of a symbol.
     * New cache object is created if it does not exist yet.
     * @param sym_id - the symbol ID.
     * @return data cache object.
     */
    public TCFDataCache<String[]> getSymbolChildrenCache(final String sym_id) {
        if (sym_id == null) return null;
        TCFNodeSymbol n = (TCFNodeSymbol)getNode(sym_id);
        if (n == null) n = new TCFNodeSymbol(launch_node, sym_id);
        return n.getChildren();
    }

    /**
     * Search memory context that owns the object represented by given node.
     * @return data cache item that holds the memory context node.
     */
    public TCFDataCache<TCFNodeExecContext> searchMemoryContext(final TCFNode node) {
        TCFNode n = node;
        while (n != null && !n.isDisposed()) {
            if (n instanceof TCFNodeExecContext) return ((TCFNodeExecContext)n).getMemoryNode();
            n = n.parent;
        }
        return null;
    }

    /**
     * Asynchronously create model node for given ID.
     * Only nodes for IDs recognized by Run Control service can be created this way.
     * If 'cache' is valid after the method returns, the node cannot be created, and
     * the cache will contain an error report.
     * @param id - Run Control service context ID.
     * @param cache - data cache object that need the node for validation.
     * @return - true if all done, false if 'cache' is waiting for remote data.
     */
    public boolean createNode(String id, final TCFDataCache<?> cache) {
        TCFNode parent = getNode(id);
        if (parent != null) return true;
        LinkedList<IRunControl.RunControlContext> path = null;
        for (;;) {
            Object obj = context_map.get(id);
            if (obj == null) {
                final String command_id = id;
                IRunControl rc = channel.getRemoteService(IRunControl.class);
                if (rc == null) {
                    cache.set(null, new Exception("Target does not provide Run Control service"), null);
                    return true;
                }
                cache.start(rc.getContext(command_id, new IRunControl.DoneGetContext() {
                    public void doneGetContext(IToken token, Exception error, RunControlContext context) {
                        if (error == null && context == null) {
                            error = new Exception("Invalid context ID");
                        }
                        context_map.put(command_id, error != null ? error : context);
                        cache.done(token);
                    }
                }));
                return false;
            }
            if (obj instanceof Throwable) {
                cache.set(null, (Throwable)obj, null);
                return true;
            }
            IRunControl.RunControlContext ctx = (IRunControl.RunControlContext)obj;
            if (path == null) path = new LinkedList<IRunControl.RunControlContext>();
            path.add(ctx);
            String parent_id = ctx.getParentID();
            parent = parent_id == null ? launch_node : getNode(parent_id);
            if (parent != null) break;
            id = parent_id;
        }
        while (path.size() > 0) {
            IRunControl.RunControlContext ctx = path.removeLast();
            TCFNodeExecContext n = new TCFNodeExecContext(parent, ctx.getID());
            if (parent instanceof TCFNodeLaunch) ((TCFNodeLaunch)parent).getChildren().add(n);
            else ((TCFNodeExecContext)parent).getChildren().add(n);
            n.setRunContext(ctx);
            parent = n;
        }
        return true;
    }

    public void update(IChildrenCountUpdate[] updates) {
        for (int i = 0; i < updates.length; i++) {
            Object o = updates[i].getElement();
            if (o instanceof TCFLaunch) {
                if (launch_node != null) {
                    launch_node.update(updates[i]);
                }
                else {
                    updates[i].setChildCount(0);
                    updates[i].done();
                }
            }
            else {
                ((TCFNode)o).update(updates[i]);
            }
        }
    }

    public void update(IChildrenUpdate[] updates) {
        for (int i = 0; i < updates.length; i++) {
            Object o = updates[i].getElement();
            if (o instanceof TCFLaunch) {
                if (launch_node != null) {
                    launch_node.update(updates[i]);
                }
                else {
                    updates[i].done();
                }
            }
            else {
                ((TCFNode)o).update(updates[i]);
            }
        }
    }

    public void update(IHasChildrenUpdate[] updates) {
        for (int i = 0; i < updates.length; i++) {
            Object o = updates[i].getElement();
            if (o instanceof TCFLaunch) {
                if (launch_node != null) {
                    launch_node.update(updates[i]);
                }
                else {
                    updates[i].setHasChilren(false);
                    updates[i].done();
                }
            }
            else {
                ((TCFNode)o).update(updates[i]);
            }
        }
    }

    public void update(ILabelUpdate[] updates) {
        for (int i = 0; i < updates.length; i++) {
            Object o = updates[i].getElement();
            // Launch label is provided by TCFLaunchLabelProvider class.
            assert !(o instanceof TCFLaunch);
            ((TCFNode)o).update(updates[i]);
        }
    }

    public void update(IViewerInputUpdate update) {
        if (IDebugUIConstants.ID_BREAKPOINT_VIEW.equals(update.getPresentationContext().getId())) {
            // Current implementation does not support flexible hierarchy for breakpoints
            IViewerInputProvider p = (IViewerInputProvider)launch.getAdapter(IViewerInputProvider.class);
            if (p != null) {
                p.update(update);
                return;
            }
        }
        Object o = update.getElement();
        if (o instanceof TCFLaunch) {
            update.setInputElement(o);
            update.done();
        }
        else {
            ((TCFNode)o).update(update);
        }
    }

    public IModelProxy createModelProxy(Object element, IPresentationContext context) {
        return new TCFModelProxy(this);
    }

    public IColumnPresentation createColumnPresentation(IPresentationContext context, Object element) {
        String id = getColumnPresentationId(context, element);
        if (id == null) return null;
        if (id.equals(TCFColumnPresentationRegister.PRESENTATION_ID)) return new TCFColumnPresentationRegister();
        if (id.equals(TCFColumnPresentationExpression.PRESENTATION_ID)) return new TCFColumnPresentationExpression();
        if (id.equals(TCFColumnPresentationModules.PRESENTATION_ID)) return new TCFColumnPresentationModules();
        return null;
    }

    public String getColumnPresentationId(IPresentationContext context, Object element) {
        if (IDebugUIConstants.ID_REGISTER_VIEW.equals(context.getId())) {
            return TCFColumnPresentationRegister.PRESENTATION_ID;
        }
        if (IDebugUIConstants.ID_VARIABLE_VIEW.equals(context.getId())) {
            return TCFColumnPresentationExpression.PRESENTATION_ID;
        }
        if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(context.getId())) {
            return TCFColumnPresentationExpression.PRESENTATION_ID;
        }
        if (ID_EXPRESSION_HOVER.equals(context.getId())) {
            return TCFColumnPresentationExpression.PRESENTATION_ID;
        }
        if (IDebugUIConstants.ID_MODULE_VIEW.equals(context.getId())) {
            return TCFColumnPresentationModules.PRESENTATION_ID;
        }
        return null;
    }

    public void setDebugViewSelection(TCFNode node, String reason) {
        assert Protocol.isDispatchThread();
        if (node == null) return;
        if (node.isDisposed()) return;
        runSuspendTrigger(node);
        if (reason == null) return;
        if (reason.equals(IRunControl.REASON_USER_REQUEST)) return;
        for (TCFModelProxy proxy : model_proxies.values()) {
            if (proxy.getPresentationContext().getId().equals(IDebugUIConstants.ID_DEBUG_VIEW)) {
                proxy.setSelection(node);
                if (reason.equals(IRunControl.REASON_STEP)) continue;
                if (reason.equals(IRunControl.REASON_CONTAINER)) continue;
                if (delay_stack_update_until_last_step && launch.getContextActionsCount(node.id) != 0) continue;
                if (expanded_nodes.add(node.id)) proxy.expand(node);
            }
        }
    }

    /**
     * Reveal source code associated with given model element.
     * The method is part of ISourceDisplay interface.
     * The method is normally called from SourceLookupService.
     */
    public void displaySource(Object model_element, final IWorkbenchPage page, boolean forceSourceLookup) {
        if (wait_for_pc_update_after_step) launch.addPendingClient(TCFModel.this);
        final int cnt = ++display_source_generation;
        /* Because of racing in Eclipse Debug infrastructure, 'model_element' value can be invalid.
         * As a workaround, get current debug view selection.
         */
        if (page != null) {
            ISelection context = DebugUITools.getDebugContextManager().getContextService(page.getWorkbenchWindow()).getActiveContext();
            if (context instanceof IStructuredSelection) {
                IStructuredSelection selection = (IStructuredSelection)context;
                model_element = selection.isEmpty() ? null : selection.getFirstElement();
            }
        }
        final Object element = model_element;
        Protocol.invokeLater(25, new Runnable() {
            public void run() {
                if (cnt != display_source_generation) return;
                TCFNodeStackFrame stack_frame = null;
                if (!disposed && channel.getState() == IChannel.STATE_OPEN) {
                    if (element instanceof TCFNodeExecContext) {
                        TCFNodeExecContext exec_ctx = (TCFNodeExecContext)element;
                        if (!exec_ctx.isDisposed() && active_actions.get(exec_ctx.id) == null) {
                            TCFDataCache<TCFContextState> state_cache = exec_ctx.getState();
                            if (!state_cache.validate(this)) return;
                            if (!exec_ctx.isNotActive()) {
                                TCFContextState state_data = state_cache.getData();
                                if (state_data != null && state_data.is_suspended) {
                                    TCFChildrenStackTrace stack_trace = exec_ctx.getStackTrace();
                                    if (!stack_trace.validate(this)) return;
                                    stack_frame = stack_trace.getTopFrame();
                                }
                            }
                        }
                    }
                    else if (element instanceof TCFNodeStackFrame) {
                        TCFNodeStackFrame f = (TCFNodeStackFrame)element;
                        TCFNodeExecContext exec_ctx = (TCFNodeExecContext)f.parent;
                        if (!f.isDisposed() && !exec_ctx.isDisposed() && active_actions.get(exec_ctx.id) == null) {
                            TCFDataCache<TCFContextState> state_cache = exec_ctx.getState();
                            if (!state_cache.validate(this)) return;
                            if (!exec_ctx.isNotActive()) {
                                TCFContextState state_data = state_cache.getData();
                                if (state_data != null && state_data.is_suspended) stack_frame = f;
                            }
                        }
                    }
                }
                String ctx_id = null;
                boolean top_frame = false;
                ILineNumbers.CodeArea area = null;
                if (stack_frame != null) {
                    TCFDataCache<TCFSourceRef> line_info = stack_frame.getLineInfo();
                    if (!line_info.validate(this)) return;
                    Throwable error = line_info.getError();
                    TCFSourceRef src_ref = line_info.getData();
                    if (error == null && src_ref != null) error = src_ref.error;
                    if (error != null) Activator.log("Error retrieving source mapping for a stack frame", error);
                    if (src_ref != null) area = src_ref.area;
                    top_frame = stack_frame.getFrameNo() == 0;
                    ctx_id = stack_frame.parent.id;
                }
                displaySource(cnt, page, element, ctx_id, top_frame, area);
            }
        });
    }

    private void displaySource(final int cnt, final IWorkbenchPage page,
            final Object element, final String exe_id, final boolean top_frame, final ILineNumbers.CodeArea area) {
        final boolean disassembly_available = channel.getRemoteService(IDisassembly.class) != null;
        display.asyncExec(new Runnable() {
            public void run() {
                try {
                    if (cnt != display_source_generation) return;
                    String editor_id = null;
                    IEditorInput editor_input = null;
                    int line = 0;
                    if (area != null) {
                        ISourceLocator locator = getLaunch().getSourceLocator();
                        Object source_element = null;
                        if (locator instanceof TCFSourceLookupDirector) {
                            source_element = ((TCFSourceLookupDirector)locator).getSourceElement(area);
                        }
                        else if (locator instanceof ISourceLookupDirector) {
                            // support for foreign (CDT) source locator
                            String filename = TCFSourceLookupParticipant.toFileName(area);
                            if (filename != null) {
                                source_element = ((ISourceLookupDirector)locator).getSourceElement(filename);
                                if (source_element == null && !filename.equals(area.file)) {
                                    // retry with relative path
                                    source_element = ((ISourceLookupDirector)locator).getSourceElement(area.file);
                                }
                            }
                        }
                        if (source_element != null) {
                            ISourcePresentation presentation = TCFModelPresentation.getDefault();
                            editor_input = presentation.getEditorInput(source_element);
                            if (editor_input != null) editor_id = presentation.getEditorId(editor_input, source_element);
                            line = area.start_line;
                        }
                    }
                    if (area != null && !instruction_stepping_enabled && (editor_input == null || editor_id == null)) {
                        ILaunchConfiguration cfg = launch.getLaunchConfiguration();
                        ISourceNotFoundPresentation presentation = (ISourceNotFoundPresentation) DebugPlugin.getAdapter(element, ISourceNotFoundPresentation.class);
                        if (presentation != null) {
                            String filename = TCFSourceLookupParticipant.toFileName(area);
                            editor_input = presentation.getEditorInput(element, cfg, filename);
                            editor_id = presentation.getEditorId(editor_input, element);
                        }
                        if (editor_id == null || editor_input == null) {
                            editor_id = IDebugUIConstants.ID_COMMON_SOURCE_NOT_FOUND_EDITOR;
                            editor_input = editor_not_found.get(cfg);
                            if (editor_input == null) {
                                editor_input = new CommonSourceNotFoundEditorInput(cfg);
                                editor_not_found.put(cfg, editor_input);
                            }
                        }
                    }
                    if (exe_id != null && disassembly_available &&
                            (editor_input == null || editor_id == null || instruction_stepping_enabled) &&
                            PlatformUI.getWorkbench().getEditorRegistry().findEditor(
                                    DisassemblyEditorInput.EDITOR_ID) != null) {
                        editor_id = DisassemblyEditorInput.EDITOR_ID;
                        editor_input = DisassemblyEditorInput.INSTANCE;
                    }
                    if (cnt != display_source_generation) return;
                    ITextEditor text_editor = null;
                    if (page != null && editor_input != null && editor_id != null) {
                        IEditorPart editor = openEditor(editor_input, editor_id, page);
                        if (editor instanceof ITextEditor) {
                            text_editor = (ITextEditor)editor;
                        }
                        else {
                            text_editor = (ITextEditor)editor.getAdapter(ITextEditor.class);
                        }
                    }
                    IRegion region = null;
                    if (text_editor != null) {
                        region = getLineInformation(text_editor, line);
                        if (region != null) text_editor.selectAndReveal(region.getOffset(), 0);
                    }
                    if (wait_for_pc_update_after_step) launch.addPendingClient(annotation_manager);
                    annotation_manager.updateAnnotations(page.getWorkbenchWindow(), launch);
                }
                finally {
                    if (cnt == display_source_generation) launch.removePendingClient(TCFModel.this);
                }
            }
        });
    }

    /*
     * Refresh Launch View.
     * Normally the view is updated by sending deltas through model proxy.
     * This method is used only when launch is not yet connected or already disconnected.
     */
    private void refreshLaunchView() {
        // TODO: there should be a better way to refresh Launch View
        synchronized (Device.class) {
            if (display.isDisposed()) return;
            display.asyncExec(new Runnable() {
                public void run() {
                    IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
                    if (windows == null) return;
                    for (IWorkbenchWindow window : windows) {
                        IDebugView view = (IDebugView)window.getActivePage().findView(IDebugUIConstants.ID_DEBUG_VIEW);
                        if (view != null) ((StructuredViewer)view.getViewer()).refresh(launch);
                    }
                }
            });
        }
    }

    /**
     * Show error message box in active workbench window.
     * @param title - message box title.
     * @param error - error to be shown.
     */
    public void showMessageBox(final String title, final Throwable error) {
        display.asyncExec(new Runnable() {
            public void run() {
                Shell shell = display.getActiveShell();
                if (shell == null) {
                    Shell[] shells = display.getShells();
                    HashSet<Shell> set = new HashSet<Shell>();
                    for (Shell s : shells) set.add(s);
                    for (Shell s : shells) {
                        if (s.getParent() != null) set.remove(s.getParent().getShell());
                    }
                    for (Shell s : shells) shell = s;
                }
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText(title);
                mb.setMessage(getErrorMessage(error, true));
                mb.open();
            }
        });
    }

    /**
     * Create human readable error message from a Throwable object.
     * @param error - a Throwable object.
     * @param multiline - true if multi-line text is allowed.
     * @return
     */
    public static String getErrorMessage(Throwable error, boolean multiline) {
        StringBuffer buf = new StringBuffer();
        while (error != null) {
            String msg = null;
            if (!multiline && error instanceof IErrorReport) {
                msg = Command.toErrorString(((IErrorReport)error).getAttributes());
            }
            else {
                msg = error.getLocalizedMessage();
            }
            if (msg == null || msg.length() == 0) msg = error.getClass().getName();
            buf.append(msg);
            error = error.getCause();
            if (error != null) {
                char ch = buf.charAt(buf.length() - 1);
                if (multiline && ch != '\n') {
                    buf.append('\n');
                }
                else if (ch != '.' && ch != ';') {
                    buf.append(';');
                }
                buf.append("Caused by:");
                buf.append(multiline ? '\n' : ' ');
            }
        }
        if (buf.length() > 0) {
            char ch = buf.charAt(buf.length() - 1);
            if (multiline && ch != '\n') {
                buf.append('\n');
            }
        }
        return buf.toString();
    }

    /*
     * Open an editor for given editor input.
     * @param input - IEditorInput representing a source file to be shown in the editor
     * @param id - editor type ID
     * @param page - workbench page that will contain the editor
     * @return - IEditorPart if the editor was opened successfully, or null otherwise.
     */
    private IEditorPart openEditor(final IEditorInput input, final String id, final IWorkbenchPage page) {
        final IEditorPart[] editor = new IEditorPart[]{ null };
        Runnable r = new Runnable() {
            public void run() {
                if (!page.getWorkbenchWindow().getWorkbench().isClosing()) {
                    try {
                        editor[0] = page.openEditor(input, id, false, IWorkbenchPage.MATCH_ID|IWorkbenchPage.MATCH_INPUT);
                    }
                    catch (PartInitException e) {
                        Activator.log("Cannot open editor", e);
                    }
                }
            }
        };
        BusyIndicator.showWhile(display, r);
        return editor[0];
    }

    /*
     * Returns the line information for the given line in the given editor
     */
    private IRegion getLineInformation(ITextEditor editor, int line) {
        IDocumentProvider provider = editor.getDocumentProvider();
        IEditorInput input = editor.getEditorInput();
        try {
            provider.connect(input);
        }
        catch (CoreException e) {
            return null;
        }
        try {
            IDocument document = provider.getDocument(input);
            if (document != null) return document.getLineInformation(line - 1);
        }
        catch (BadLocationException e) {
        }
        finally {
            provider.disconnect(input);
        }
        return null;
    }

    /**
     * Registers the given listener for suspend notifications.
     * @param listener suspend listener
     */
    public synchronized void addSuspendTriggerListener(ISuspendTriggerListener listener) {
        suspend_trigger_listeners.add(listener);
    }

    /**
     * Unregisters the given listener for suspend notifications.
     * @param listener suspend listener
     */
    public synchronized void removeSuspendTriggerListener(ISuspendTriggerListener listener) {
        suspend_trigger_listeners.remove(listener);
    }

    /*
     * Lazily run registered suspend listeners.
     * @param node - suspended context.
     */
    private synchronized void runSuspendTrigger(final TCFNode node) {
        if (suspend_trigger_listeners.size() == 0) return;
        final ISuspendTriggerListener[] listeners = suspend_trigger_listeners.toArray(
                new ISuspendTriggerListener[suspend_trigger_listeners.size()]);

        final int generation = ++suspend_trigger_generation;
        if (wait_for_pc_update_after_step || wait_for_views_update_after_step) {
            launch.addPendingClient(suspend_trigger_listeners);
        }
        display.asyncExec(new Runnable() {
            public void run() {
                synchronized (TCFModel.this) {
                    if (generation != suspend_trigger_generation) return;
                }
                for (final ISuspendTriggerListener listener : listeners) {
                    try {
                        listener.suspended(launch, node);
                    }
                    catch (Throwable x) {
                        Activator.log(x);
                    }
                }
                synchronized (TCFModel.this) {
                    if (generation != suspend_trigger_generation) return;
                    launch.removePendingClient(suspend_trigger_listeners);
                }
            }
        });
    }

    /**
     * Set whether instruction stepping mode should be enabled or not.
     * @param enabled
     */
    public void setInstructionSteppingEnabled(boolean enabled) {
        instruction_stepping_enabled = enabled;
    }

    /**
     * @return whether instruction stepping is enabled
     */
    public boolean isInstructionSteppingEnabled() {
        return instruction_stepping_enabled;
    }
}

Back to the top