aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/com/sun/tools/example/debug/gui/SourceTool.java
blob: a358c71efe883a2a5862a0fb9d8b1c01be4a9b0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
 * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * This source code is provided to illustrate the usage of a given feature
 * or technique and has been deliberately simplified. Additional steps
 * required for a production-quality application, such as security checks,
 * input validation and proper error handling, might not be present in
 * this sample code.
 */


package com.sun.tools.example.debug.gui;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import com.sun.jdi.*;
import com.sun.jdi.request.*;

import com.sun.tools.example.debug.bdi.*;

public class SourceTool extends JPanel {

    private static final long serialVersionUID = -5461299294186395257L;

    private Environment env;

    private ExecutionManager runtime;
    private ContextManager context;
    private SourceManager sourceManager;

    private JList list;
    private ListModel sourceModel;

    // Information on source file that is on display, or failed to be
    // displayed due to inaccessible source.  Used to update display
    // when sourcepath is changed.

    private String sourceName;          // relative path name, if showSourceFile
    private Location sourceLocn;        // location, if showSourceForLocation
    private CommandInterpreter interpreter;

    public SourceTool(Environment env) {

        super(new BorderLayout());

        this.env = env;

        runtime = env.getExecutionManager();
        sourceManager = env.getSourceManager();
        this.context = env.getContextManager();
        this.interpreter = new CommandInterpreter(env, true);

        sourceModel = new DefaultListModel();  // empty

        list = new JList(sourceModel);
        list.setCellRenderer(new SourceLineRenderer());

        list.setPrototypeCellValue(SourceModel.prototypeCellValue);

        SourceToolListener listener = new SourceToolListener();
        context.addContextListener(listener);
        runtime.addSpecListener(listener);
        sourceManager.addSourceListener(listener);

        MouseListener squeek = new STMouseListener();
        list.addMouseListener(squeek);

        add(new JScrollPane(list));
    }

    public void setTextFont(Font f) {
        list.setFont(f);
        list.setPrototypeCellValue(SourceModel.prototypeCellValue);
    }

    private class SourceToolListener
               implements ContextListener, SourceListener, SpecListener
    {

        // ContextListener

        @Override
        public void currentFrameChanged(CurrentFrameChangedEvent e) {
            showSourceContext(e.getThread(), e.getIndex());
        }

            // Clear source view.
            //      sourceModel = new DefaultListModel();  // empty

        // SourceListener

        @Override
        public void sourcepathChanged(SourcepathChangedEvent e) {
            // Reload source view if its contents depend
            // on the source path.
            if (sourceName != null) {
                showSourceFile(sourceName);
            } else if (sourceLocn != null) {
                showSourceForLocation(sourceLocn);
            }
        }

        // SpecListener

        @Override
        public void breakpointSet(SpecEvent e) {
            breakpointResolved(e);
        }

        @Override
        public void breakpointDeferred(SpecEvent e) { }

        @Override
        public void breakpointDeleted(SpecEvent e) {
            BreakpointRequest req = (BreakpointRequest)e.getEventRequest();
            Location loc = req.location();
            if (loc != null) {
                try {
                    SourceModel sm = sourceManager.sourceForLocation(loc);
                    sm.showBreakpoint(loc.lineNumber(), false);
                    showSourceForLocation(loc);
                } catch (Exception exc) {
                }
            }
        }

        @Override
        public void breakpointResolved(SpecEvent e) {
            BreakpointRequest req = (BreakpointRequest)e.getEventRequest();
            Location loc = req.location();
            try {
                SourceModel sm = sourceManager.sourceForLocation(loc);
                sm.showBreakpoint(loc.lineNumber(), true);
                showSourceForLocation(loc);
            } catch (Exception exc) {
            }
        }

        @Override
        public void breakpointError(SpecErrorEvent e) {
            breakpointDeleted(e);
        }

        @Override
        public void watchpointSet(SpecEvent e) {
        }
        @Override
        public void watchpointDeferred(SpecEvent e) {
        }
        @Override
        public void watchpointDeleted(SpecEvent e) {
        }
        @Override
        public void watchpointResolved(SpecEvent e) {
        }
        @Override
        public void watchpointError(SpecErrorEvent e) {
        }

        @Override
        public void exceptionInterceptSet(SpecEvent e) {
        }
        @Override
        public void exceptionInterceptDeferred(SpecEvent e) {
        }
        @Override
        public void exceptionInterceptDeleted(SpecEvent e) {
        }
        @Override
        public void exceptionInterceptResolved(SpecEvent e) {
        }
        @Override
        public void exceptionInterceptError(SpecErrorEvent e) {
        }
    }

    private void showSourceContext(ThreadReference thread, int index) {
        //### Should use ThreadInfo here.
        StackFrame frame = null;
        if (thread != null) {
            try {
                frame = thread.frame(index);
            } catch (IncompatibleThreadStateException e) {}
        }
        if (frame == null) {
            return;
        }
        Location locn = frame.location();
        /*****
        if (!showSourceForLocation(locn)) {
            env.notice("Could not display source for "
                       + Utils.locationString(locn));
        }
        *****/
        showSourceForLocation(locn);
    }

    public boolean showSourceForLocation(Location locn) {
        sourceName = null;
        sourceLocn = locn;
        int lineNo = locn.lineNumber();
        if (lineNo != -1) {
            SourceModel source = sourceManager.sourceForLocation(locn);
            if (source != null) {
                showSourceAtLine(source, lineNo-1);
                return true;
            }
        }
        // Here if we could not display source.
        showSourceUnavailable();
        return false;
    }

    public boolean showSourceFile(String fileName) {
        sourceLocn = null;
        File file;
        if (!fileName.startsWith(File.separator)) {
            sourceName = fileName;
            SearchPath sourcePath = sourceManager.getSourcePath();
            file = sourcePath.resolve(fileName);
            if (file == null) {
                //env.failure("Source not found on current source path.");
                showSourceUnavailable();
                return false;
            }
        } else {
            sourceName = null;  // Absolute pathname does not depend on sourcepath.
            file = new File(fileName);
        }
        SourceModel source = sourceManager.sourceForFile(file);
        if (source != null) {
            showSource(source);
            return true;
        }
        showSourceUnavailable();
        return false;
    }

    private void showSource(SourceModel model) {
        setViewModel(model);
    }

    private void showSourceAtLine(SourceModel model, int lineNo) {
        setViewModel(model);
        if (model.isActuallySource && (lineNo < model.getSize())) {
            list.setSelectedIndex(lineNo);
            if (lineNo+4 < model.getSize()) {
                list.ensureIndexIsVisible(lineNo+4);  // give some context
            }
            list.ensureIndexIsVisible(lineNo);
        }
    }

    private void showSourceUnavailable() {
        SourceModel model = new SourceModel("[Source code is not available]");
        setViewModel(model);
    }

    private void setViewModel(SourceModel model) {
        if (model != sourceModel) {
            // install new model
            list.setModel(model);
            sourceModel = model;
        }
    }

    private class SourceLineRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list,
                                                      Object value,
                                                      int index,
                                                      boolean isSelected,
                                                      boolean cellHasFocus) {

            //### Should set background highlight and/or icon if breakpoint on this line.
            // Configures "this"
            super.getListCellRendererComponent(list, value, index,
                                               isSelected, cellHasFocus);

            SourceModel.Line line = (SourceModel.Line)value;

            //### Tab expansion is now done when source file is read in,
            //### to speed up display.  This costs a lot of space, slows
            //### down source file loading, and has not been demonstrated
            //### to yield an observable improvement in display performance.
            //### Measurements may be appropriate here.
            //String sourceLine = expandTabs((String)value);
            setText(line.text);
            if (line.hasBreakpoint) {
                setIcon(Icons.stopSignIcon);
            } else if (line.isExecutable()) {
                setIcon(Icons.execIcon);
            } else {
                setIcon(Icons.blankIcon);
            }


            return this;
        }

        @Override
        public Dimension getPreferredSize() {
            Dimension dim = super.getPreferredSize();
            return new Dimension(dim.width, dim.height-5);
        }

    }

    private class STMouseListener extends MouseAdapter implements MouseListener {
        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                showPopupMenu((Component)e.getSource(),
                              e.getX(), e.getY());
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                showPopupMenu((Component)e.getSource(),
                              e.getX(), e.getY());
            }
        }

        private void showPopupMenu(Component invoker, int x, int y) {
            JList list = (JList)invoker;
            int ln = list.getSelectedIndex() + 1;
            SourceModel.Line line =
                (SourceModel.Line)list.getSelectedValue();
            JPopupMenu popup = new JPopupMenu();

            if (line == null) {
                popup.add(new JMenuItem("please select a line"));
            } else if (line.isExecutable()) {
                String className = line.refType.name();
                if (line.hasBreakpoint()) {
                    popup.add(commandItem("Clear Breakpoint",
                                          "clear " + className +
                                          ":" + ln));
                } else {
                    popup.add(commandItem("Set Breakpoint",
                                          "stop at " + className +
                                          ":" + ln));
                }
            } else {
                popup.add(new JMenuItem("not an executable line"));
            }

            popup.show(invoker,
                       x + popup.getWidth()/2, y + popup.getHeight()/2);
        }

        private JMenuItem commandItem(String label, final String cmd) {
            JMenuItem item = new JMenuItem(label);
            item.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    interpreter.executeCommand(cmd);
                }
            });
            return item;
        }
    }
}