Debian Codegraph @

rhino/toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 package org.mozilla.javascript.tools.debugger;
7
8 import javax.swing.*;
9 import javax.swing.text.*;
10 import javax.swing.event.*;
11 import javax.swing.table.*;
12 import java.awt.EventQueue;
13 import java.awt.ActiveEvent;
14 import java.awt.AWTEvent;
15 import java.awt.BorderLayout;
16 import java.awt.Color;
17 import java.awt.Component;
18 import java.awt.Container;
19 import java.awt.Dimension;
20 import java.awt.Event;
21 import java.awt.Font;
22 import java.awt.FontMetrics;
23 import java.awt.Frame;
24 import java.awt.Graphics;
25 import java.awt.GridBagConstraints;
26 import java.awt.GridBagLayout;
27 import java.awt.GridLayout;
28 import java.awt.MenuComponent;
29 import java.awt.Point;
30 import java.awt.Polygon;
31 import java.awt.Rectangle;
32 import java.awt.Toolkit;
33 import java.awt.event.*;
34
35 import java.util.List;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.EventObject;
41 import java.util.Map;
42 import java.util.HashMap;
43 import java.util.Properties;
44 import java.io.*;
45 import javax.swing.tree.DefaultTreeCellRenderer;
46 import javax.swing.tree.TreePath;
47 import java.lang.reflect.Method;
48
49 import org.mozilla.javascript.Kit;
50 import org.mozilla.javascript.SecurityUtilities;
51
52 import org.mozilla.javascript.tools.shell.ConsoleTextArea;
53
54 import org.mozilla.javascript.tools.debugger.treetable.JTreeTable;
55 import org.mozilla.javascript.tools.debugger.treetable.TreeTableModel;
56 import org.mozilla.javascript.tools.debugger.treetable.TreeTableModelAdapter;
57
58 /**
59 * GUI for the Rhino debugger.
60 */
61 public class SwingGui extends JFrame implements GuiCallback {
62
63 /**
64 * Serializable magic number.
65 */
66 private static final long serialVersionUID = -8217029773456711621L;
67
68 /**
69 * The debugger.
70 */
71 Dim dim;
72
73 /**
74 * The action to run when the 'Exit' menu item is chosen or the
75 * frame is closed.
76 */
77 private Runnable exitAction;
78
79 /**
80 * The {@link JDesktopPane} that holds the script windows.
81 */
82 private JDesktopPane desk;
83
84 /**
85 * The {@link JPanel} that shows information about the context.
86 */
87 private ContextWindow context;
88
89 /**
90 * The menu bar.
91 */
92 private Menubar menubar;
93
94 /**
95 * The tool bar.
96 */
97 private JToolBar toolBar;
98
99 /**
100 * The console that displays I/O from the script.
101 */
102 private JSInternalConsole console;
103
104 /**
105 * The {@link JSplitPane} that separates {@link #desk} from
106 * {@link org.mozilla.javascript.Context}.
107 */
108 private JSplitPane split1;
109
110 /**
111 * The status bar.
112 */
113 private JLabel statusBar;
114
115 /**
116 * Hash table of internal frame names to the internal frames themselves.
117 */
118 private final Map<String,JFrame> toplevels =
119 Collections.synchronizedMap(new HashMap<String,JFrame>());
120
121 /**
122 * Hash table of script URLs to their internal frames.
123 */
124 private final Map<String,FileWindow> fileWindows =
125 Collections.synchronizedMap(new HashMap<String,FileWindow>());
126
127
128 /**
129 * The {@link FileWindow} that last had the focus.
130 */
131 private FileWindow currentWindow;
132
133 /**
134 * File choose dialog for loading a script.
135 */
136 JFileChooser dlg;
137
138 /**
139 * The AWT EventQueue. Used for manually pumping AWT events from
140 * {@link #dispatchNextGuiEvent()}.
141 */
142 private EventQueue awtEventQueue;
143
144 /**
145 * Creates a new SwingGui.
146 */
147 public SwingGui(Dim dim, String title) {
148 super(title);
149 this.dim = dim;
150 init();
151 dim.setGuiCallback(this);
152 }
153
154 /**
155 * Returns the Menubar of this debugger frame.
156 */
157 public Menubar getMenubar() {
158 return menubar;
159 }
160
161 /**
162 * Sets the {@link Runnable} that will be run when the "Exit" menu
163 * item is chosen.
164 */
165 public void setExitAction(Runnable r) {
166 exitAction = r;
167 }
168
169 /**
170 * Returns the debugger console component.
171 */
172 public JSInternalConsole getConsole() {
173 return console;
174 }
175
176 /**
177 * Sets the visibility of the debugger GUI.
178 */
179 @Override
180 public void setVisible(boolean b) {
181 super.setVisible(b);
182 if (b) {
183 // this needs to be done after the window is visible
184 console.consoleTextArea.requestFocus();
185 context.split.setDividerLocation(0.5);
186 try {
187 console.setMaximum(true);
188 console.setSelected(true);
189 console.show();
190 console.consoleTextArea.requestFocus();
191 } catch (Exception exc) {
192 }
193 }
194 }
195
196 /**
197 * Records a new internal frame.
198 */
199 void addTopLevel(String key, JFrame frame) {
200 if (frame != this) {
201 toplevels.put(key, frame);
202 }
203 }
204
205 /**
206 * Constructs the debugger GUI.
207 */
208 private void init() {
209 menubar = new Menubar(this);
210 setJMenuBar(menubar);
211 toolBar = new JToolBar();
212 JButton button;
213 JButton breakButton, goButton, stepIntoButton,
214 stepOverButton, stepOutButton;
215 String [] toolTips = {"Break (Pause)",
216 "Go (F5)",
217 "Step Into (F11)",
218 "Step Over (F7)",
219 "Step Out (F8)"};
220 int count = 0;
221 button = breakButton = new JButton("Break");
222 button.setToolTipText("Break");
223 button.setActionCommand("Break");
224 button.addActionListener(menubar);
225 button.setEnabled(true);
226 button.setToolTipText(toolTips[count++]);
227
228 button = goButton = new JButton("Go");
229 button.setToolTipText("Go");
230 button.setActionCommand("Go");
231 button.addActionListener(menubar);
232 button.setEnabled(false);
233 button.setToolTipText(toolTips[count++]);
234
235 button = stepIntoButton = new JButton("Step Into");
236 button.setToolTipText("Step Into");
237 button.setActionCommand("Step Into");
238 button.addActionListener(menubar);
239 button.setEnabled(false);
240 button.setToolTipText(toolTips[count++]);
241
242 button = stepOverButton = new JButton("Step Over");
243 button.setToolTipText("Step Over");
244 button.setActionCommand("Step Over");
245 button.setEnabled(false);
246 button.addActionListener(menubar);
247 button.setToolTipText(toolTips[count++]);
248
249 button = stepOutButton = new JButton("Step Out");
250 button.setToolTipText("Step Out");
251 button.setActionCommand("Step Out");
252 button.setEnabled(false);
253 button.addActionListener(menubar);
254 button.setToolTipText(toolTips[count++]);
255
256 Dimension dim = stepOverButton.getPreferredSize();
257 breakButton.setPreferredSize(dim);
258 breakButton.setMinimumSize(dim);
259 breakButton.setMaximumSize(dim);
260 breakButton.setSize(dim);
261 goButton.setPreferredSize(dim);
262 goButton.setMinimumSize(dim);
263 goButton.setMaximumSize(dim);
264 stepIntoButton.setPreferredSize(dim);
265 stepIntoButton.setMinimumSize(dim);
266 stepIntoButton.setMaximumSize(dim);
267 stepOverButton.setPreferredSize(dim);
268 stepOverButton.setMinimumSize(dim);
269 stepOverButton.setMaximumSize(dim);
270 stepOutButton.setPreferredSize(dim);
271 stepOutButton.setMinimumSize(dim);
272 stepOutButton.setMaximumSize(dim);
273 toolBar.add(breakButton);
274 toolBar.add(goButton);
275 toolBar.add(stepIntoButton);
276 toolBar.add(stepOverButton);
277 toolBar.add(stepOutButton);
278
279 JPanel contentPane = new JPanel();
280 contentPane.setLayout(new BorderLayout());
281 getContentPane().add(toolBar, BorderLayout.NORTH);
282 getContentPane().add(contentPane, BorderLayout.CENTER);
283 desk = new JDesktopPane();
284 desk.setPreferredSize(new Dimension(600, 300));
285 desk.setMinimumSize(new Dimension(150, 50));
286 desk.add(console = new JSInternalConsole("JavaScript Console"));
287 context = new ContextWindow(this);
288 context.setPreferredSize(new Dimension(600, 120));
289 context.setMinimumSize(new Dimension(50, 50));
290
291 split1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, desk,
292 context);
293 split1.setOneTouchExpandable(true);
294 SwingGui.setResizeWeight(split1, 0.66);
295 contentPane.add(split1, BorderLayout.CENTER);
296 statusBar = new JLabel();
297 statusBar.setText("Thread: ");
298 contentPane.add(statusBar, BorderLayout.SOUTH);
299 dlg = new JFileChooser();
300
301 javax.swing.filechooser.FileFilter filter =
302 new javax.swing.filechooser.FileFilter() {
303 @Override
304 public boolean accept(File f) {
305 if (f.isDirectory()) {
306 return true;
307 }
308 String n = f.getName();
309 int i = n.lastIndexOf('.');
310 if (i > 0 && i < n.length() -1) {
311 String ext = n.substring(i + 1).toLowerCase();
312 if (ext.equals("js")) {
313 return true;
314 }
315 }
316 return false;
317 }
318
319 @Override
320 public String getDescription() {
321 return "JavaScript Files (*.js)";
322 }
323 };
324 dlg.addChoosableFileFilter(filter);
325 addWindowListener(new WindowAdapter() {
326 @Override
327 public void windowClosing(WindowEvent e) {
328 exit();
329 }
330 });
331 }
332
333 /**
334 * Runs the {@link #exitAction}.
335 */
336 private void exit() {
337 if (exitAction != null) {
338 SwingUtilities.invokeLater(exitAction);
339 }
340 dim.setReturnValue(Dim.EXIT);
341 }
342
343 /**
344 * Returns the {@link FileWindow} for the given URL.
345 */
346 FileWindow getFileWindow(String url) {
347 if (url == null || url.equals("<stdin>")) {
348 return null;
349 }
350 return fileWindows.get(url);
351 }
352
353 /**
354 * Returns a short version of the given URL.
355 */
356 static String getShortName(String url) {
357 int lastSlash = url.lastIndexOf('/');
358 if (lastSlash < 0) {
359 lastSlash = url.lastIndexOf('\\');
360 }
361 String shortName = url;
362 if (lastSlash >= 0 && lastSlash + 1 < url.length()) {
363 shortName = url.substring(lastSlash + 1);
364 }
365 return shortName;
366 }
367
368 /**
369 * Closes the given {@link FileWindow}.
370 */
371 void removeWindow(FileWindow w) {
372 fileWindows.remove(w.getUrl());
373 JMenu windowMenu = getWindowMenu();
374 int count = windowMenu.getItemCount();
375 JMenuItem lastItem = windowMenu.getItem(count -1);
376 String name = getShortName(w.getUrl());
377 for (int i = 5; i < count; i++) {
378 JMenuItem item = windowMenu.getItem(i);
379 if (item == null) continue; // separator
380 String text = item.getText();
381 //1 D:\foo.js
382 //2 D:\bar.js
383 int pos = text.indexOf(' ');
384 if (text.substring(pos + 1).equals(name)) {
385 windowMenu.remove(item);
386 // Cascade [0]
387 // Tile [1]
388 // ------- [2]
389 // Console [3]
390 // ------- [4]
391 if (count == 6) {
392 // remove the final separator
393 windowMenu.remove(4);
394 } else {
395 int j = i - 4;
396 for (;i < count -1; i++) {
397 JMenuItem thisItem = windowMenu.getItem(i);
398 if (thisItem != null) {
399 //1 D:\foo.js
400 //2 D:\bar.js
401 text = thisItem.getText();
402 if (text.equals("More Windows...")) {
403 break;
404 } else {
405 pos = text.indexOf(' ');
406 thisItem.setText((char)('0' + j) + " " +
407 text.substring(pos + 1));
408 thisItem.setMnemonic('0' + j);
409 j++;
410 }
411 }
412 }
413 if (count - 6 == 0 && lastItem != item) {
414 if (lastItem.getText().equals("More Windows...")) {
415 windowMenu.remove(lastItem);
416 }
417 }
418 }
419 break;
420 }
421 }
422 windowMenu.revalidate();
423 }
424
425 /**
426 * Shows the line at which execution in the given stack frame just stopped.
427 */
428 void showStopLine(Dim.StackFrame frame) {
429 String sourceName = frame.getUrl();
430 if (sourceName == null || sourceName.equals("<stdin>")) {
431 if (console.isVisible()) {
432 console.show();
433 }
434 } else {
435 showFileWindow(sourceName, -1);
436 int lineNumber = frame.getLineNumber();
437 FileWindow w = getFileWindow(sourceName);
438 if (w != null) {
439 setFilePosition(w, lineNumber);
440 }
441 }
442 }
443
444 /**
445 * Shows a {@link FileWindow} for the given source, creating it
446 * if it doesn't exist yet. if <code>lineNumber</code> is greater
447 * than -1, it indicates the line number to select and display.
448 * @param sourceUrl the source URL
449 * @param lineNumber the line number to select, or -1
450 */
451 protected void showFileWindow(String sourceUrl, int lineNumber) {
452 FileWindow w = getFileWindow(sourceUrl);
453 if (w == null) {
454 Dim.SourceInfo si = dim.sourceInfo(sourceUrl);
455 createFileWindow(si, -1);
456 w = getFileWindow(sourceUrl);
457 }
458 if (lineNumber > -1) {
459 int start = w.getPosition(lineNumber-1);
460 int end = w.getPosition(lineNumber)-1;
461 w.textArea.select(start);
462 w.textArea.setCaretPosition(start);
463 w.textArea.moveCaretPosition(end);
464 }
465 try {
466 if (w.isIcon()) {
467 w.setIcon(false);
468 }
469 w.setVisible(true);
470 w.moveToFront();
471 w.setSelected(true);
472 requestFocus();
473 w.requestFocus();
474 w.textArea.requestFocus();
475 } catch (Exception exc) {
476 }
477 }
478
479 /**
480 * Creates and shows a new {@link FileWindow} for the given source.
481 */
482 protected void createFileWindow(Dim.SourceInfo sourceInfo, int line) {
483 boolean activate = true;
484
485 String url = sourceInfo.url();
486 FileWindow w = new FileWindow(this, sourceInfo);
487 fileWindows.put(url, w);
488 if (line != -1) {
489 if (currentWindow != null) {
490 currentWindow.setPosition(-1);
491 }
492 try {
493 w.setPosition(w.textArea.getLineStartOffset(line-1));
494 } catch (BadLocationException exc) {
495 try {
496 w.setPosition(w.textArea.getLineStartOffset(0));
497 } catch (BadLocationException ee) {
498 w.setPosition(-1);
499 }
500 }
501 }
502 desk.add(w);
503 if (line != -1) {
504 currentWindow = w;
505 }
506 menubar.addFile(url);
507 w.setVisible(true);
508
509 if (activate) {
510 try {
511 w.setMaximum(true);
512 w.setSelected(true);
513 w.moveToFront();
514 } catch (Exception exc) {
515 }
516 }
517 }
518
519 /**
520 * Update the source text for <code>sourceInfo</code>. This returns true
521 * if a {@link FileWindow} for the given source exists and could be updated.
522 * Otherwise, this does nothing and returns false.
523 * @param sourceInfo the source info
524 * @return true if a {@link FileWindow} for the given source exists
525 * and could be updated, false otherwise.
526 */
527 protected boolean updateFileWindow(Dim.SourceInfo sourceInfo) {
528 String fileName = sourceInfo.url();
529 FileWindow w = getFileWindow(fileName);
530 if (w != null) {
531 w.updateText(sourceInfo);
532 w.show();
533 return true;
534 }
535 return false;
536 }
537
538 /**
539 * Moves the current position in the given {@link FileWindow} to the
540 * given line.
541 */
542 private void setFilePosition(FileWindow w, int line) {
543 boolean activate = true;
544 JTextArea ta = w.textArea;
545 try {
546 if (line == -1) {
547 w.setPosition(-1);
548 if (currentWindow == w) {
549 currentWindow = null;
550 }
551 } else {
552 int loc = ta.getLineStartOffset(line-1);
553 if (currentWindow != null && currentWindow != w) {
554 currentWindow.setPosition(-1);
555 }
556 w.setPosition(loc);
557 currentWindow = w;
558 }
559 } catch (BadLocationException exc) {
560 // fix me
561 }
562 if (activate) {
563 if (w.isIcon()) {
564 desk.getDesktopManager().deiconifyFrame(w);
565 }
566 desk.getDesktopManager().activateFrame(w);
567 try {
568 w.show();
569 w.toFront(); // required for correct frame layering (JDK 1.4.1)
570 w.setSelected(true);
571 } catch (Exception exc) {
572 }
573 }
574 }
575
576 /**
577 * Handles script interruption.
578 */
579 void enterInterruptImpl(Dim.StackFrame lastFrame,
580 String threadTitle, String alertMessage) {
581 statusBar.setText("Thread: " + threadTitle);
582
583 showStopLine(lastFrame);
584
585 if (alertMessage != null) {
586 MessageDialogWrapper.showMessageDialog(this,
587 alertMessage,
588 "Exception in Script",
589 JOptionPane.ERROR_MESSAGE);
590 }
591
592 updateEnabled(true);
593
594 Dim.ContextData contextData = lastFrame.contextData();
595
596 JComboBox ctx = context.context;
597 List<String> toolTips = context.toolTips;
598 context.disableUpdate();
599 int frameCount = contextData.frameCount();
600 ctx.removeAllItems();
601 // workaround for JDK 1.4 bug that caches selected value even after
602 // removeAllItems() is called
603 ctx.setSelectedItem(null);
604 toolTips.clear();
605 for (int i = 0; i < frameCount; i++) {
606 Dim.StackFrame frame = contextData.getFrame(i);
607 String url = frame.getUrl();
608 int lineNumber = frame.getLineNumber();
609 String shortName = url;
610 if (url.length() > 20) {
611 shortName = "..." + url.substring(url.length() - 17);
612 }
613 String location = "\"" + shortName + "\", line " + lineNumber;
614 ctx.insertItemAt(location, i);
615 location = "\"" + url + "\", line " + lineNumber;
616 toolTips.add(location);
617 }
618 context.enableUpdate();
619 ctx.setSelectedIndex(0);
620 ctx.setMinimumSize(new Dimension(50, ctx.getMinimumSize().height));
621 }
622
623 /**
624 * Returns the 'Window' menu.
625 */
626 private JMenu getWindowMenu() {
627 return menubar.getMenu(3);
628 }
629
630 /**
631 * Displays a {@link JFileChooser} and returns the selected filename.
632 */
633 private String chooseFile(String title) {
634 dlg.setDialogTitle(title);
635 File CWD = null;
636 String dir = SecurityUtilities.getSystemProperty("user.dir");
637 if (dir != null) {
638 CWD = new File(dir);
639 }
640 if (CWD != null) {
641 dlg.setCurrentDirectory(CWD);
642 }
643 int returnVal = dlg.showOpenDialog(this);
644 if (returnVal == JFileChooser.APPROVE_OPTION) {
645 try {
646 String result = dlg.getSelectedFile().getCanonicalPath();
647 CWD = dlg.getSelectedFile().getParentFile();
648 Properties props = System.getProperties();
649 props.put("user.dir", CWD.getPath());
650 System.setProperties(props);
651 return result;
652 } catch (IOException ignored) {
653 } catch (SecurityException ignored) {
654 }
655 }
656 return null;
657 }
658
659 /**
660 * Returns the current selected internal frame.
661 */
662 private JInternalFrame getSelectedFrame() {
663 JInternalFrame[] frames = desk.getAllFrames();
664 for (int i = 0; i < frames.length; i++) {
665 if (frames[i].isShowing()) {
666 return frames[i];
667 }
668 }
669 return frames[frames.length - 1];
670 }
671
672 /**
673 * Enables or disables the menu and tool bars with respect to the
674 * state of script execution.
675 */
676 private void updateEnabled(boolean interrupted) {
677 ((Menubar)getJMenuBar()).updateEnabled(interrupted);
678 for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) {
679 boolean enableButton;
680 if (ci == 0) {
681 // Break
682 enableButton = !interrupted;
683 } else {
684 enableButton = interrupted;
685 }
686 toolBar.getComponent(ci).setEnabled(enableButton);
687 }
688 if (interrupted) {
689 toolBar.setEnabled(true);
690 // raise the debugger window
691 int state = getExtendedState();
692 if (state == Frame.ICONIFIED) {
693 setExtendedState(Frame.NORMAL);
694 }
695 toFront();
696 context.setEnabled(true);
697 } else {
698 if (currentWindow != null) currentWindow.setPosition(-1);
699 context.setEnabled(false);
700 }
701 }
702
703 /**
704 * Calls {@link JSplitPane#setResizeWeight} via reflection.
705 * For compatibility, since JDK &lt; 1.3 does not have this method.
706 */
707 static void setResizeWeight(JSplitPane pane, double weight) {
708 try {
709 Method m = JSplitPane.class.getMethod("setResizeWeight",
710 new Class[]{double.class});
711 m.invoke(pane, new Object[]{new Double(weight)});
712 } catch (NoSuchMethodException exc) {
713 } catch (IllegalAccessException exc) {
714 } catch (java.lang.reflect.InvocationTargetException exc) {
715 }
716 }
717
718 /**
719 * Reads the file with the given name and returns its contents as a String.
720 */
721 private String readFile(String fileName) {
722 String text;
723 try {
724 Reader r = new FileReader(fileName);
725 try {
726 text = Kit.readReader(r);
727 } finally {
728 r.close();
729 }
730 } catch (IOException ex) {
731 MessageDialogWrapper.showMessageDialog(this,
732 ex.getMessage(),
733 "Error reading "+fileName,
734 JOptionPane.ERROR_MESSAGE);
735 text = null;
736 }
737 return text;
738 }
739
740 // GuiCallback
741
742 /**
743 * Called when the source text for a script has been updated.
744 */
745 public void updateSourceText(Dim.SourceInfo sourceInfo) {
746 RunProxy proxy = new RunProxy(this, RunProxy.UPDATE_SOURCE_TEXT);
747 proxy.sourceInfo = sourceInfo;
748 SwingUtilities.invokeLater(proxy);
749 }
750
751 /**
752 * Called when the interrupt loop has been entered.
753 */
754 public void enterInterrupt(Dim.StackFrame lastFrame,
755 String threadTitle,
756 String alertMessage) {
757 if (SwingUtilities.isEventDispatchThread()) {
758 enterInterruptImpl(lastFrame, threadTitle, alertMessage);
759 } else {
760 RunProxy proxy = new RunProxy(this, RunProxy.ENTER_INTERRUPT);
761 proxy.lastFrame = lastFrame;
762 proxy.threadTitle = threadTitle;
763 proxy.alertMessage = alertMessage;
764 SwingUtilities.invokeLater(proxy);
765 }
766 }
767
768 /**
769 * Returns whether the current thread is the GUI event thread.
770 */
771 public boolean isGuiEventThread() {
772 return SwingUtilities.isEventDispatchThread();
773 }
774
775 /**
776 * Processes the next GUI event.
777 */
778 public void dispatchNextGuiEvent() throws InterruptedException {
779 EventQueue queue = awtEventQueue;
780 if (queue == null) {
781 queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
782 awtEventQueue = queue;
783 }
784 AWTEvent event = queue.getNextEvent();
785 if (event instanceof ActiveEvent) {
786 ((ActiveEvent)event).dispatch();
787 } else {
788 Object source = event.getSource();
789 if (source instanceof Component) {
790 Component comp = (Component)source;
791 comp.dispatchEvent(event);
792 } else if (source instanceof MenuComponent) {
793 ((MenuComponent)source).dispatchEvent(event);
794 }
795 }
796 }
797
798 // ActionListener
799
800 /**
801 * Performs an action from the menu or toolbar.
802 */
803 public void actionPerformed(ActionEvent e) {
804 String cmd = e.getActionCommand();
805 int returnValue = -1;
806 if (cmd.equals("Cut") || cmd.equals("Copy") || cmd.equals("Paste")) {
807 JInternalFrame f = getSelectedFrame();
808 if (f != null && f instanceof ActionListener) {
809 ((ActionListener)f).actionPerformed(e);
810 }
811 } else if (cmd.equals("Step Over")) {
812 returnValue = Dim.STEP_OVER;
813 } else if (cmd.equals("Step Into")) {
814 returnValue = Dim.STEP_INTO;
815 } else if (cmd.equals("Step Out")) {
816 returnValue = Dim.STEP_OUT;
817 } else if (cmd.equals("Go")) {
818 returnValue = Dim.GO;
819 } else if (cmd.equals("Break")) {
820 dim.setBreak();
821 } else if (cmd.equals("Exit")) {
822 exit();
823 } else if (cmd.equals("Open")) {
824 String fileName = chooseFile("Select a file to compile");
825 if (fileName != null) {
826 String text = readFile(fileName);
827 if (text != null) {
828 RunProxy proxy = new RunProxy(this, RunProxy.OPEN_FILE);
829 proxy.fileName = fileName;
830 proxy.text = text;
831 new Thread(proxy).start();
832 }
833 }
834 } else if (cmd.equals("Load")) {
835 String fileName = chooseFile("Select a file to execute");
836 if (fileName != null) {
837 String text = readFile(fileName);
838 if (text != null) {
839 RunProxy proxy = new RunProxy(this, RunProxy.LOAD_FILE);
840 proxy.fileName = fileName;
841 proxy.text = text;
842 new Thread(proxy).start();
843 }
844 }
845 } else if (cmd.equals("More Windows...")) {
846 MoreWindows dlg = new MoreWindows(this, fileWindows,
847 "Window", "Files");
848 dlg.showDialog(this);
849 } else if (cmd.equals("Console")) {
850 if (console.isIcon()) {
851 desk.getDesktopManager().deiconifyFrame(console);
852 }
853 console.show();
854 desk.getDesktopManager().activateFrame(console);
855 console.consoleTextArea.requestFocus();
856 } else if (cmd.equals("Cut")) {
857 } else if (cmd.equals("Copy")) {
858 } else if (cmd.equals("Paste")) {
859 } else if (cmd.equals("Go to function...")) {
860 FindFunction dlg = new FindFunction(this, "Go to function",
861 "Function");
862 dlg.showDialog(this);
863 } else if (cmd.equals("Tile")) {
864 JInternalFrame[] frames = desk.getAllFrames();
865 int count = frames.length;
866 int rows, cols;
867 rows = cols = (int)Math.sqrt(count);
868 if (rows*cols < count) {
869 cols++;
870 if (rows * cols < count) {
871 rows++;
872 }
873 }
874 Dimension size = desk.getSize();
875 int w = size.width/cols;
876 int h = size.height/rows;
877 int x = 0;
878 int y = 0;
879 for (int i = 0; i < rows; i++) {
880 for (int j = 0; j < cols; j++) {
881 int index = (i*cols) + j;
882 if (index >= frames.length) {
883 break;
884 }
885 JInternalFrame f = frames[index];
886 try {
887 f.setIcon(false);
888 f.setMaximum(false);
889 } catch (Exception exc) {
890 }
891 desk.getDesktopManager().setBoundsForFrame(f, x, y,
892 w, h);
893 x += w;
894 }
895 y += h;
896 x = 0;
897 }
898 } else if (cmd.equals("Cascade")) {
899 JInternalFrame[] frames = desk.getAllFrames();
900 int count = frames.length;
901 int x, y, w, h;
902 x = y = 0;
903 h = desk.getHeight();
904 int d = h / count;
905 if (d > 30) d = 30;
906 for (int i = count -1; i >= 0; i--, x += d, y += d) {
907 JInternalFrame f = frames[i];
908 try {
909 f.setIcon(false);
910 f.setMaximum(false);
911 } catch (Exception exc) {
912 }
913 Dimension dimen = f.getPreferredSize();
914 w = dimen.width;
915 h = dimen.height;
916 desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h);
917 }
918 } else {
919 Object obj = getFileWindow(cmd);
920 if (obj != null) {
921 FileWindow w = (FileWindow)obj;
922 try {
923 if (w.isIcon()) {
924 w.setIcon(false);
925 }
926 w.setVisible(true);
927 w.moveToFront();
928 w.setSelected(true);
929 } catch (Exception exc) {
930 }
931 }
932 }
933 if (returnValue != -1) {
934 updateEnabled(false);
935 dim.setReturnValue(returnValue);
936 }
937 }
938 }
939
940 /**
941 * Helper class for showing a message dialog.
942 */
943 class MessageDialogWrapper {
944
945 /**
946 * Shows a message dialog, wrapping the <code>msg</code> at 60
947 * columns.
948 */
949 public static void showMessageDialog(Component parent, String msg,
950 String title, int flags) {
951 if (msg.length() > 60) {
952 StringBuilder buf = new StringBuilder();
953 int len = msg.length();
954 int j = 0;
955 int i;
956 for (i = 0; i < len; i++, j++) {
957 char c = msg.charAt(i);
958 buf.append(c);
959 if (Character.isWhitespace(c)) {
960 int k;
961 for (k = i + 1; k < len; k++) {
962 if (Character.isWhitespace(msg.charAt(k))) {
963 break;
964 }
965 }
966 if (k < len) {
967 int nextWordLen = k - i;
968 if (j + nextWordLen > 60) {
969 buf.append('\n');
970 j = 0;
971 }
972 }
973 }
974 }
975 msg = buf.toString();
976 }
977 JOptionPane.showMessageDialog(parent, msg, title, flags);
978 }
979 }
980
981 /**
982 * Extension of JTextArea for script evaluation input.
983 */
984 class EvalTextArea
985 extends JTextArea
986 implements KeyListener, DocumentListener {
987
988 /**
989 * Serializable magic number.
990 */
991 private static final long serialVersionUID = -3918033649601064194L;
992
993 /**
994 * The debugger GUI.
995 */
996 private SwingGui debugGui;
997
998 /**
999 * History of expressions that have been evaluated
1000 */
1001 private List<String> history;
1002
1003 /**
1004 * Index of the selected history item.
1005 */
1006 private int historyIndex = -1;
1007
1008 /**
1009 * Position in the display where output should go.
1010 */
1011 private int outputMark;
1012
1013 /**
1014 * Creates a new EvalTextArea.
1015 */
1016 public EvalTextArea(SwingGui debugGui) {
1017 this.debugGui = debugGui;
1018 history = Collections.synchronizedList(new ArrayList<String>());
1019 Document doc = getDocument();
1020 doc.addDocumentListener(this);
1021 addKeyListener(this);
1022 setLineWrap(true);
1023 setFont(new Font("Monospaced", 0, 12));
1024 append("% ");
1025 outputMark = doc.getLength();
1026 }
1027
1028 /**
1029 * Selects a subrange of the text.
1030 */
1031 @Override
1032 public void select(int start, int end) {
1033 //requestFocus();
1034 super.select(start, end);
1035 }
1036
1037 /**
1038 * Called when Enter is pressed.
1039 */
1040 private synchronized void returnPressed() {
1041 Document doc = getDocument();
1042 int len = doc.getLength();
1043 Segment segment = new Segment();
1044 try {
1045 doc.getText(outputMark, len - outputMark, segment);
1046 } catch (javax.swing.text.BadLocationException ignored) {
1047 ignored.printStackTrace();
1048 }
1049 String text = segment.toString();
1050 if (debugGui.dim.stringIsCompilableUnit(text)) {
1051 if (text.trim().length() > 0) {
1052 history.add(text);
1053 historyIndex = history.size();
1054 }
1055 append("\n");
1056 String result = debugGui.dim.eval(text);
1057 if (result.length() > 0) {
1058 append(result);
1059 append("\n");
1060 }
1061 append("% ");
1062 outputMark = doc.getLength();
1063 } else {
1064 append("\n");
1065 }
1066 }
1067
1068 /**
1069 * Writes output into the text area.
1070 */
1071 public synchronized void write(String str) {
1072 insert(str, outputMark);
1073 int len = str.length();
1074 outputMark += len;
1075 select(outputMark, outputMark);
1076 }
1077
1078 // KeyListener
1079
1080 /**
1081 * Called when a key is pressed.
1082 */
1083 public void keyPressed(KeyEvent e) {
1084 int code = e.getKeyCode();
1085 if (code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) {
1086 if (outputMark == getCaretPosition()) {
1087 e.consume();
1088 }
1089 } else if (code == KeyEvent.VK_HOME) {
1090 int caretPos = getCaretPosition();
1091 if (caretPos == outputMark) {
1092 e.consume();
1093 } else if (caretPos > outputMark) {
1094 if (!e.isControlDown()) {
1095 if (e.isShiftDown()) {
1096 moveCaretPosition(outputMark);
1097 } else {
1098 setCaretPosition(outputMark);
1099 }
1100 e.consume();
1101 }
1102 }
1103 } else if (code == KeyEvent.VK_ENTER) {
1104 returnPressed();
1105 e.consume();
1106 } else if (code == KeyEvent.VK_UP) {
1107 historyIndex--;
1108 if (historyIndex >= 0) {
1109 if (historyIndex >= history.size()) {
1110 historyIndex = history.size() -1;
1111 }
1112 if (historyIndex >= 0) {
1113 String str = history.get(historyIndex);
1114 int len = getDocument().getLength();
1115 replaceRange(str, outputMark, len);
1116 int caretPos = outputMark + str.length();
1117 select(caretPos, caretPos);
1118 } else {
1119 historyIndex++;
1120 }
1121 } else {
1122 historyIndex++;
1123 }
1124 e.consume();
1125 } else if (code == KeyEvent.VK_DOWN) {
1126 int caretPos = outputMark;
1127 if (history.size() > 0) {
1128 historyIndex++;
1129 if (historyIndex < 0) {historyIndex = 0;}
1130 int len = getDocument().getLength();
1131 if (historyIndex < history.size()) {
1132 String str = history.get(historyIndex);
1133 replaceRange(str, outputMark, len);
1134 caretPos = outputMark + str.length();
1135 } else {
1136 historyIndex = history.size();
1137 replaceRange("", outputMark, len);
1138 }
1139 }
1140 select(caretPos, caretPos);
1141 e.consume();
1142 }
1143 }
1144
1145 /**
1146 * Called when a key is typed.
1147 */
1148 public void keyTyped(KeyEvent e) {
1149 int keyChar = e.getKeyChar();
1150 if (keyChar == 0x8 /* KeyEvent.VK_BACK_SPACE */) {
1151 if (outputMark == getCaretPosition()) {
1152 e.consume();
1153 }
1154 } else if (getCaretPosition() < outputMark) {
1155 setCaretPosition(outputMark);
1156 }
1157 }
1158
1159 /**
1160 * Called when a key is released.
1161 */
1162 public synchronized void keyReleased(KeyEvent e) {
1163 }
1164
1165 // DocumentListener
1166
1167 /**
1168 * Called when text was inserted into the text area.
1169 */
1170 public synchronized void insertUpdate(DocumentEvent e) {
1171 int len = e.getLength();
1172 int off = e.getOffset();
1173 if (outputMark > off) {
1174 outputMark += len;
1175 }
1176 }
1177
1178 /**
1179 * Called when text was removed from the text area.
1180 */
1181 public synchronized void removeUpdate(DocumentEvent e) {
1182 int len = e.getLength();
1183 int off = e.getOffset();
1184 if (outputMark > off) {
1185 if (outputMark >= off + len) {
1186 outputMark -= len;
1187 } else {
1188 outputMark = off;
1189 }
1190 }
1191 }
1192
1193 /**
1194 * Attempts to clean up the damage done by {@link #updateUI()}.
1195 */
1196 public synchronized void postUpdateUI() {
1197 //requestFocus();
1198 setCaret(getCaret());
1199 select(outputMark, outputMark);
1200 }
1201
1202 /**
1203 * Called when text has changed in the text area.
1204 */
1205 public synchronized void changedUpdate(DocumentEvent e) {
1206 }
1207 }
1208
1209 /**
1210 * An internal frame for evaluating script.
1211 */
1212 class EvalWindow extends JInternalFrame implements ActionListener {
1213
1214 /**
1215 * Serializable magic number.
1216 */
1217 private static final long serialVersionUID = -2860585845212160176L;
1218
1219 /**
1220 * The text area into which expressions can be typed.
1221 */
1222 private EvalTextArea evalTextArea;
1223
1224 /**
1225 * Creates a new EvalWindow.
1226 */
1227 public EvalWindow(String name, SwingGui debugGui) {
1228 super(name, true, false, true, true);
1229 evalTextArea = new EvalTextArea(debugGui);
1230 evalTextArea.setRows(24);
1231 evalTextArea.setColumns(80);
1232 JScrollPane scroller = new JScrollPane(evalTextArea);
1233 setContentPane(scroller);
1234 //scroller.setPreferredSize(new Dimension(600, 400));
1235 pack();
1236 setVisible(true);
1237 }
1238
1239 /**
1240 * Sets whether the text area is enabled.
1241 */
1242 @Override
1243 public void setEnabled(boolean b) {
1244 super.setEnabled(b);
1245 evalTextArea.setEnabled(b);
1246 }
1247
1248 // ActionListener
1249
1250 /**
1251 * Performs an action on the text area.
1252 */
1253 public void actionPerformed(ActionEvent e) {
1254 String cmd = e.getActionCommand();
1255 if (cmd.equals("Cut")) {
1256 evalTextArea.cut();
1257 } else if (cmd.equals("Copy")) {
1258 evalTextArea.copy();
1259 } else if (cmd.equals("Paste")) {
1260 evalTextArea.paste();
1261 }
1262 }
1263 }
1264
1265 /**
1266 * Internal frame for the console.
1267 */
1268 class JSInternalConsole extends JInternalFrame implements ActionListener {
1269
1270 /**
1271 * Serializable magic number.
1272 */
1273 private static final long serialVersionUID = -5523468828771087292L;
1274
1275 /**
1276 * Creates a new JSInternalConsole.
1277 */
1278 public JSInternalConsole(String name) {
1279 super(name, true, false, true, true);
1280 consoleTextArea = new ConsoleTextArea(null);
1281 consoleTextArea.setRows(24);
1282 consoleTextArea.setColumns(80);
1283 JScrollPane scroller = new JScrollPane(consoleTextArea);
1284 setContentPane(scroller);
1285 pack();
1286 addInternalFrameListener(new InternalFrameAdapter() {
1287 @Override
1288 public void internalFrameActivated(InternalFrameEvent e) {
1289 // hack
1290 if (consoleTextArea.hasFocus()) {
1291 consoleTextArea.getCaret().setVisible(false);
1292 consoleTextArea.getCaret().setVisible(true);
1293 }
1294 }
1295 });
1296 }
1297
1298 /**
1299 * The console text area.
1300 */
1301 ConsoleTextArea consoleTextArea;
1302
1303 /**
1304 * Returns the input stream of the console text area.
1305 */
1306 public InputStream getIn() {
1307 return consoleTextArea.getIn();
1308 }
1309
1310 /**
1311 * Returns the output stream of the console text area.
1312 */
1313 public PrintStream getOut() {
1314 return consoleTextArea.getOut();
1315 }
1316
1317 /**
1318 * Returns the error stream of the console text area.
1319 */
1320 public PrintStream getErr() {
1321 return consoleTextArea.getErr();
1322 }
1323
1324 // ActionListener
1325
1326 /**
1327 * Performs an action on the text area.
1328 */
1329 public void actionPerformed(ActionEvent e) {
1330 String cmd = e.getActionCommand();
1331 if (cmd.equals("Cut")) {
1332 consoleTextArea.cut();
1333 } else if (cmd.equals("Copy")) {
1334 consoleTextArea.copy();
1335 } else if (cmd.equals("Paste")) {
1336 consoleTextArea.paste();
1337 }
1338 }
1339 }
1340
1341 /**
1342 * Popup menu class for right-clicking on {@link FileTextArea}s.
1343 */
1344 class FilePopupMenu extends JPopupMenu {
1345
1346 /**
1347 * Serializable magic number.
1348 */
1349 private static final long serialVersionUID = 3589525009546013565L;
1350
1351 /**
1352 * The popup x position.
1353 */
1354 int x;
1355
1356 /**
1357 * The popup y position.
1358 */
1359 int y;
1360
1361 /**
1362 * Creates a new FilePopupMenu.
1363 */
1364 public FilePopupMenu(FileTextArea w) {
1365 JMenuItem item;
1366 add(item = new JMenuItem("Set Breakpoint"));
1367 item.addActionListener(w);
1368 add(item = new JMenuItem("Clear Breakpoint"));
1369 item.addActionListener(w);
1370 add(item = new JMenuItem("Run"));
1371 item.addActionListener(w);
1372 }
1373
1374 /**
1375 * Displays the menu at the given coordinates.
1376 */
1377 public void show(JComponent comp, int x, int y) {
1378 this.x = x;
1379 this.y = y;
1380 super.show(comp, x, y);
1381 }
1382 }
1383
1384 /**
1385 * Text area to display script source.
1386 */
1387 class FileTextArea
1388 extends JTextArea
1389 implements ActionListener, PopupMenuListener, KeyListener, MouseListener {
1390
1391 /**
1392 * Serializable magic number.
1393 */
1394 private static final long serialVersionUID = -25032065448563720L;
1395
1396 /**
1397 * The owning {@link FileWindow}.
1398 */
1399 private FileWindow w;
1400
1401 /**
1402 * The popup menu.
1403 */
1404 private FilePopupMenu popup;
1405
1406 /**
1407 * Creates a new FileTextArea.
1408 */
1409 public FileTextArea(FileWindow w) {
1410 this.w = w;
1411 popup = new FilePopupMenu(this);
1412 popup.addPopupMenuListener(this);
1413 addMouseListener(this);
1414 addKeyListener(this);
1415 setFont(new Font("Monospaced", 0, 12));
1416 }
1417
1418 /**
1419 * Moves the selection to the given offset.
1420 */
1421 public void select(int pos) {
1422 if (pos >= 0) {
1423 try {
1424 int line = getLineOfOffset(pos);
1425 Rectangle rect = modelToView(pos);
1426 if (rect == null) {
1427 select(pos, pos);
1428 } else {
1429 try {
1430 Rectangle nrect =
1431 modelToView(getLineStartOffset(line + 1));
1432 if (nrect != null) {
1433 rect = nrect;
1434 }
1435 } catch (Exception exc) {
1436 }
1437 JViewport vp = (JViewport)getParent();
1438 Rectangle viewRect = vp.getViewRect();
1439 if (viewRect.y + viewRect.height > rect.y) {
1440 // need to scroll up
1441 select(pos, pos);
1442 } else {
1443 // need to scroll down
1444 rect.y += (viewRect.height - rect.height)/2;
1445 scrollRectToVisible(rect);
1446 select(pos, pos);
1447 }
1448 }
1449 } catch (BadLocationException exc) {
1450 select(pos, pos);
1451 //exc.printStackTrace();
1452 }
1453 }
1454 }
1455
1456 /**
1457 * Checks if the popup menu should be shown.
1458 */
1459 private void checkPopup(MouseEvent e) {
1460 if (e.isPopupTrigger()) {
1461 popup.show(this, e.getX(), e.getY());
1462 }
1463 }
1464
1465 // MouseListener
1466
1467 /**
1468 * Called when a mouse button is pressed.
1469 */
1470 public void mousePressed(MouseEvent e) {
1471 checkPopup(e);
1472 }
1473
1474 /**
1475 * Called when the mouse is clicked.
1476 */
1477 public void mouseClicked(MouseEvent e) {
1478 checkPopup(e);
1479 requestFocus();
1480 getCaret().setVisible(true);
1481 }
1482
1483 /**
1484 * Called when the mouse enters the component.
1485 */
1486 public void mouseEntered(MouseEvent e) {
1487 }
1488
1489 /**
1490 * Called when the mouse exits the component.
1491 */
1492 public void mouseExited(MouseEvent e) {
1493 }
1494
1495 /**
1496 * Called when a mouse button is released.
1497 */
1498 public void mouseReleased(MouseEvent e) {
1499 checkPopup(e);
1500 }
1501
1502 // PopupMenuListener
1503
1504 /**
1505 * Called before the popup menu will become visible.
1506 */
1507 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
1508 }
1509
1510 /**
1511 * Called before the popup menu will become invisible.
1512 */
1513 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
1514 }
1515
1516 /**
1517 * Called when the popup menu is cancelled.
1518 */
1519 public void popupMenuCanceled(PopupMenuEvent e) {
1520 }
1521
1522 // ActionListener
1523
1524 /**
1525 * Performs an action.
1526 */
1527 public void actionPerformed(ActionEvent e) {
1528 int pos = viewToModel(new Point(popup.x, popup.y));
1529 popup.setVisible(false);
1530 String cmd = e.getActionCommand();
1531 int line = -1;
1532 try {
1533 line = getLineOfOffset(pos);
1534 } catch (Exception exc) {
1535 }
1536 if (cmd.equals("Set Breakpoint")) {
1537 w.setBreakPoint(line + 1);
1538 } else if (cmd.equals("Clear Breakpoint")) {
1539 w.clearBreakPoint(line + 1);
1540 } else if (cmd.equals("Run")) {
1541 w.load();
1542 }
1543 }
1544
1545 // KeyListener
1546
1547 /**
1548 * Called when a key is pressed.
1549 */
1550 public void keyPressed(KeyEvent e) {
1551 switch (e.getKeyCode()) {
1552 case KeyEvent.VK_BACK_SPACE:
1553 case KeyEvent.VK_ENTER:
1554 case KeyEvent.VK_DELETE:
1555 case KeyEvent.VK_TAB:
1556 e.consume();
1557 break;
1558 }
1559 }
1560
1561 /**
1562 * Called when a key is typed.
1563 */
1564 public void keyTyped(KeyEvent e) {
1565 e.consume();
1566 }
1567
1568 /**
1569 * Called when a key is released.
1570 */
1571 public void keyReleased(KeyEvent e) {
1572 e.consume();
1573 }
1574 }
1575
1576 /**
1577 * Dialog to list the available windows.
1578 */
1579 class MoreWindows extends JDialog implements ActionListener {
1580
1581 /**
1582 * Serializable magic number.
1583 */
1584 private static final long serialVersionUID = 5177066296457377546L;
1585
1586 /**
1587 * Last selected value.
1588 */
1589 private String value;
1590
1591 /**
1592 * The list component.
1593 */
1594 private JList list;
1595
1596 /**
1597 * Our parent frame.
1598 */
1599 private SwingGui swingGui;
1600
1601 /**
1602 * The "Select" button.
1603 */
1604 private JButton setButton;
1605
1606 /**
1607 * The "Cancel" button.
1608 */
1609 private JButton cancelButton;
1610
1611 /**
1612 * Creates a new MoreWindows.
1613 */
1614 MoreWindows(SwingGui frame, Map<String,FileWindow> fileWindows, String title,
1615 String labelText) {
1616 super(frame, title, true);
1617 this.swingGui = frame;
1618 //buttons
1619 cancelButton = new JButton("Cancel");
1620 setButton = new JButton("Select");
1621 cancelButton.addActionListener(this);
1622 setButton.addActionListener(this);
1623 getRootPane().setDefaultButton(setButton);
1624
1625 //dim part of the dialog
1626 list = new JList(new DefaultListModel());
1627 DefaultListModel model = (DefaultListModel)list.getModel();
1628 model.clear();
1629 //model.fireIntervalRemoved(model, 0, size);
1630 for (String data: fileWindows.keySet()) {
1631 model.addElement(data);
1632 }
1633 list.setSelectedIndex(0);
1634 //model.fireIntervalAdded(model, 0, data.length);
1635 setButton.setEnabled(true);
1636 list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
1637 list.addMouseListener(new MouseHandler());
1638 JScrollPane listScroller = new JScrollPane(list);
1639 listScroller.setPreferredSize(new Dimension(320, 240));
1640 //XXX: Must do the following, too, or else the scroller thinks
1641 //XXX: it's taller than it is:
1642 listScroller.setMinimumSize(new Dimension(250, 80));
1643 listScroller.setAlignmentX(LEFT_ALIGNMENT);
1644
1645 //Create a container so that we can add a title around
1646 //the scroll pane. Can't add a title directly to the
1647 //scroll pane because its background would be white.
1648 //Lay out the label and scroll pane from top to button.
1649 JPanel listPane = new JPanel();
1650 listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
1651 JLabel label = new JLabel(labelText);
1652 label.setLabelFor (list);
1653 listPane.add(label);
1654 listPane.add(Box.createRigidArea(new Dimension(0,5)));
1655 listPane.add(listScroller);
1656 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
1657
1658 //Lay out the buttons from left to right.
1659 JPanel buttonPane = new JPanel();
1660 buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
1661 buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
1662 buttonPane.add(Box.createHorizontalGlue());
1663 buttonPane.add(cancelButton);
1664 buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
1665 buttonPane.add(setButton);
1666
1667 //Put everything together, using the content pane's BorderLayout.
1668 Container contentPane = getContentPane();
1669 contentPane.add(listPane, BorderLayout.CENTER);
1670 contentPane.add(buttonPane, BorderLayout.SOUTH);
1671 pack();
1672 addKeyListener(new KeyAdapter() {
1673 @Override
1674 public void keyPressed(KeyEvent ke) {
1675 int code = ke.getKeyCode();
1676 if (code == KeyEvent.VK_ESCAPE) {
1677 ke.consume();
1678 value = null;
1679 setVisible(false);
1680 }
1681 }
1682 });
1683 }
1684
1685 /**
1686 * Shows the dialog.
1687 */
1688 public String showDialog(Component comp) {
1689 value = null;
1690 setLocationRelativeTo(comp);
1691 setVisible(true);
1692 return value;
1693 }
1694
1695 // ActionListener
1696
1697 /**
1698 * Performs an action.
1699 */
1700 public void actionPerformed(ActionEvent e) {
1701 String cmd = e.getActionCommand();
1702 if (cmd.equals("Cancel")) {
1703 setVisible(false);
1704 value = null;
1705 } else if (cmd.equals("Select")) {
1706 value = (String)list.getSelectedValue();
1707 setVisible(false);
1708 swingGui.showFileWindow(value, -1);
1709 }
1710 }
1711
1712 /**
1713 * MouseListener implementation for {@link #list}.
1714 */
1715 private class MouseHandler extends MouseAdapter {
1716 @Override
1717 public void mouseClicked(MouseEvent e) {
1718 if (e.getClickCount() == 2) {
1719 setButton.doClick();
1720 }
1721 }
1722 }
1723 }
1724
1725 /**
1726 * Find function dialog.
1727 */
1728 class FindFunction extends JDialog implements ActionListener {
1729
1730 /**
1731 * Serializable magic number.
1732 */
1733 private static final long serialVersionUID = 559491015232880916L;
1734
1735 /**
1736 * Last selected function.
1737 */
1738 private String value;
1739
1740 /**
1741 * List of functions.
1742 */
1743 private JList list;
1744
1745 /**
1746 * The debug GUI frame.
1747 */
1748 private SwingGui debugGui;
1749
1750 /**
1751 * The "Select" button.
1752 */
1753 private JButton setButton;
1754
1755 /**
1756 * The "Cancel" button.
1757 */
1758 private JButton cancelButton;
1759
1760 /**
1761 * Creates a new FindFunction.
1762 */
1763 public FindFunction(SwingGui debugGui, String title, String labelText) {
1764 super(debugGui, title, true);
1765 this.debugGui = debugGui;
1766
1767 cancelButton = new JButton("Cancel");
1768 setButton = new JButton("Select");
1769 cancelButton.addActionListener(this);
1770 setButton.addActionListener(this);
1771 getRootPane().setDefaultButton(setButton);
1772
1773 list = new JList(new DefaultListModel());
1774 DefaultListModel model = (DefaultListModel)list.getModel();
1775 model.clear();
1776
1777 String[] a = debugGui.dim.functionNames();
1778 java.util.Arrays.sort(a);
1779 for (int i = 0; i < a.length; i++) {
1780 model.addElement(a[i]);
1781 }
1782 list.setSelectedIndex(0);
1783
1784 setButton.setEnabled(a.length > 0);
1785 list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
1786 list.addMouseListener(new MouseHandler());
1787 JScrollPane listScroller = new JScrollPane(list);
1788 listScroller.setPreferredSize(new Dimension(320, 240));
1789 listScroller.setMinimumSize(new Dimension(250, 80));
1790 listScroller.setAlignmentX(LEFT_ALIGNMENT);
1791
1792 //Create a container so that we can add a title around
1793 //the scroll pane. Can't add a title directly to the
1794 //scroll pane because its background would be white.
1795 //Lay out the label and scroll pane from top to button.
1796 JPanel listPane = new JPanel();
1797 listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
1798 JLabel label = new JLabel(labelText);
1799 label.setLabelFor (list);
1800 listPane.add(label);
1801 listPane.add(Box.createRigidArea(new Dimension(0,5)));
1802 listPane.add(listScroller);
1803 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
1804
1805 //Lay out the buttons from left to right.
1806 JPanel buttonPane = new JPanel();
1807 buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
1808 buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
1809 buttonPane.add(Box.createHorizontalGlue());
1810 buttonPane.add(cancelButton);
1811 buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
1812 buttonPane.add(setButton);
1813
1814 //Put everything together, using the content pane's BorderLayout.
1815 Container contentPane = getContentPane();
1816 contentPane.add(listPane, BorderLayout.CENTER);
1817 contentPane.add(buttonPane, BorderLayout.SOUTH);
1818 pack();
1819 addKeyListener(new KeyAdapter() {
1820 @Override
1821 public void keyPressed(KeyEvent ke) {
1822 int code = ke.getKeyCode();
1823 if (code == KeyEvent.VK_ESCAPE) {
1824 ke.consume();
1825 value = null;
1826 setVisible(false);
1827 }
1828 }
1829 });
1830 }
1831
1832 /**
1833 * Shows the dialog.
1834 */
1835 public String showDialog(Component comp) {
1836 value = null;
1837 setLocationRelativeTo(comp);
1838 setVisible(true);
1839 return value;
1840 }
1841
1842 // ActionListener
1843
1844 /**
1845 * Performs an action.
1846 */
1847 public void actionPerformed(ActionEvent e) {
1848 String cmd = e.getActionCommand();
1849 if (cmd.equals("Cancel")) {
1850 setVisible(false);
1851 value = null;
1852 } else if (cmd.equals("Select")) {
1853 if (list.getSelectedIndex() < 0) {
1854 return;
1855 }
1856 try {
1857 value = (String)list.getSelectedValue();
1858 } catch (ArrayIndexOutOfBoundsException exc) {
1859 return;
1860 }
1861 setVisible(false);
1862 Dim.FunctionSource item = debugGui.dim.functionSourceByName(value);
1863 if (item != null) {
1864 Dim.SourceInfo si = item.sourceInfo();
1865 String url = si.url();
1866 int lineNumber = item.firstLine();
1867 debugGui.showFileWindow(url, lineNumber);
1868 }
1869 }
1870 }
1871
1872 /**
1873 * MouseListener implementation for {@link #list}.
1874 */
1875 class MouseHandler extends MouseAdapter {
1876 @Override
1877 public void mouseClicked(MouseEvent e) {
1878 if (e.getClickCount() == 2) {
1879 setButton.doClick();
1880 }
1881 }
1882 }
1883 }
1884
1885 /**
1886 * Gutter for FileWindows.
1887 */
1888 class FileHeader extends JPanel implements MouseListener {
1889
1890 /**
1891 * Serializable magic number.
1892 */
1893 private static final long serialVersionUID = -2858905404778259127L;
1894
1895 /**
1896 * The line that the mouse was pressed on.
1897 */
1898 private int pressLine = -1;
1899
1900 /**
1901 * The owning FileWindow.
1902 */
1903 private FileWindow fileWindow;
1904
1905 /**
1906 * Creates a new FileHeader.
1907 */
1908 public FileHeader(FileWindow fileWindow) {
1909 this.fileWindow = fileWindow;
1910 addMouseListener(this);
1911 update();
1912 }
1913
1914 /**
1915 * Updates the gutter.
1916 */
1917 public void update() {
1918 FileTextArea textArea = fileWindow.textArea;
1919 Font font = textArea.getFont();
1920 setFont(font);
1921 FontMetrics metrics = getFontMetrics(font);
1922 int h = metrics.getHeight();
1923 int lineCount = textArea.getLineCount() + 1;
1924 String dummy = Integer.toString(lineCount);
1925 if (dummy.length() < 2) {
1926 dummy = "99";
1927 }
1928 Dimension d = new Dimension();
1929 d.width = metrics.stringWidth(dummy) + 16;
1930 d.height = lineCount * h + 100;
1931 setPreferredSize(d);
1932 setSize(d);
1933 }
1934
1935 /**
1936 * Paints the component.
1937 */
1938 @Override
1939 public void paint(Graphics g) {
1940 super.paint(g);
1941 FileTextArea textArea = fileWindow.textArea;
1942 Font font = textArea.getFont();
1943 g.setFont(font);
1944 FontMetrics metrics = getFontMetrics(font);
1945 Rectangle clip = g.getClipBounds();
1946 g.setColor(getBackground());
1947 g.fillRect(clip.x, clip.y, clip.width, clip.height);
1948 int ascent = metrics.getMaxAscent();
1949 int h = metrics.getHeight();
1950 int lineCount = textArea.getLineCount() + 1;
1951 String dummy = Integer.toString(lineCount);
1952 if (dummy.length() < 2) {
1953 dummy = "99";
1954 }
1955 int startLine = clip.y / h;
1956 int endLine = (clip.y + clip.height) / h + 1;
1957 int width = getWidth();
1958 if (endLine > lineCount) endLine = lineCount;
1959 for (int i = startLine; i < endLine; i++) {
1960 String text;
1961 int pos = -2;
1962 try {
1963 pos = textArea.getLineStartOffset(i);
1964 } catch (BadLocationException ignored) {
1965 }
1966 boolean isBreakPoint = fileWindow.isBreakPoint(i + 1);
1967 text = Integer.toString(i + 1) + " ";
1968 int y = i * h;
1969 g.setColor(Color.blue);
1970 g.drawString(text, 0, y + ascent);
1971 int x = width - ascent;
1972 if (isBreakPoint) {
1973 g.setColor(new Color(0x80, 0x00, 0x00));
1974 int dy = y + ascent - 9;
1975 g.fillOval(x, dy, 9, 9);
1976 g.drawOval(x, dy, 8, 8);
1977 g.drawOval(x, dy, 9, 9);
1978 }
1979 if (pos == fileWindow.currentPos) {
1980 Polygon arrow = new Polygon();
1981 int dx = x;
1982 y += ascent - 10;
1983 int dy = y;
1984 arrow.addPoint(dx, dy + 3);
1985 arrow.addPoint(dx + 5, dy + 3);
1986 for (x = dx + 5; x <= dx + 10; x++, y++) {
1987 arrow.addPoint(x, y);
1988 }
1989 for (x = dx + 9; x >= dx + 5; x--, y++) {
1990 arrow.addPoint(x, y);
1991 }
1992 arrow.addPoint(dx + 5, dy + 7);
1993 arrow.addPoint(dx, dy + 7);
1994 g.setColor(Color.yellow);
1995 g.fillPolygon(arrow);
1996 g.setColor(Color.black);
1997 g.drawPolygon(arrow);
1998 }
1999 }
2000 }
2001
2002 // MouseListener
2003
2004 /**
2005 * Called when the mouse enters the component.
2006 */
2007 public void mouseEntered(MouseEvent e) {
2008 }
2009
2010 /**
2011 * Called when a mouse button is pressed.
2012 */
2013 public void mousePressed(MouseEvent e) {
2014 Font font = fileWindow.textArea.getFont();
2015 FontMetrics metrics = getFontMetrics(font);
2016 int h = metrics.getHeight();
2017 pressLine = e.getY() / h;
2018 }
2019
2020 /**
2021 * Called when the mouse is clicked.
2022 */
2023 public void mouseClicked(MouseEvent e) {
2024 }
2025
2026 /**
2027 * Called when the mouse exits the component.
2028 */
2029 public void mouseExited(MouseEvent e) {
2030 }
2031
2032 /**
2033 * Called when a mouse button is released.
2034 */
2035 public void mouseReleased(MouseEvent e) {
2036 if (e.getComponent() == this
2037 && (e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) {
2038 int y = e.getY();
2039 Font font = fileWindow.textArea.getFont();
2040 FontMetrics metrics = getFontMetrics(font);
2041 int h = metrics.getHeight();
2042 int line = y/h;
2043 if (line == pressLine) {
2044 fileWindow.toggleBreakPoint(line + 1);
2045 } else {
2046 pressLine = -1;
2047 }
2048 }
2049 }
2050 }
2051
2052 /**
2053 * An internal frame for script files.
2054 */
2055 class FileWindow extends JInternalFrame implements ActionListener {
2056
2057 /**
2058 * Serializable magic number.
2059 */
2060 private static final long serialVersionUID = -6212382604952082370L;
2061
2062 /**
2063 * The debugger GUI.
2064 */
2065 private SwingGui debugGui;
2066
2067 /**
2068 * The SourceInfo object that describes the file.
2069 */
2070 private Dim.SourceInfo sourceInfo;
2071
2072 /**
2073 * The FileTextArea that displays the file.
2074 */
2075 FileTextArea textArea;
2076
2077 /**
2078 * The FileHeader that is the gutter for {@link #textArea}.
2079 */
2080 private FileHeader fileHeader;
2081
2082 /**
2083 * Scroll pane for containing {@link #textArea}.
2084 */
2085 private JScrollPane p;
2086
2087 /**
2088 * The current offset position.
2089 */
2090 int currentPos;
2091
2092 /**
2093 * Loads the file.
2094 */
2095 void load() {
2096 String url = getUrl();
2097 if (url != null) {
2098 RunProxy proxy = new RunProxy(debugGui, RunProxy.LOAD_FILE);
2099 proxy.fileName = url;
2100 proxy.text = sourceInfo.source();
2101 new Thread(proxy).start();
2102 }
2103 }
2104
2105 /**
2106 * Returns the offset position for the given line.
2107 */
2108 public int getPosition(int line) {
2109 int result = -1;
2110 try {
2111 result = textArea.getLineStartOffset(line);
2112 } catch (javax.swing.text.BadLocationException exc) {
2113 }
2114 return result;
2115 }
2116
2117 /**
2118 * Returns whether the given line has a breakpoint.
2119 */
2120 public boolean isBreakPoint(int line) {
2121 return sourceInfo.breakableLine(line) && sourceInfo.breakpoint(line);
2122 }
2123
2124 /**
2125 * Toggles the breakpoint on the given line.
2126 */
2127 public void toggleBreakPoint(int line) {
2128 if (!isBreakPoint(line)) {
2129 setBreakPoint(line);
2130 } else {
2131 clearBreakPoint(line);
2132 }
2133 }
2134
2135 /**
2136 * Sets a breakpoint on the given line.
2137 */
2138 public void setBreakPoint(int line) {
2139 if (sourceInfo.breakableLine(line)) {
2140 boolean changed = sourceInfo.breakpoint(line, true);
2141 if (changed) {
2142 fileHeader.repaint();
2143 }
2144 }
2145 }
2146
2147 /**
2148 * Clears a breakpoint from the given line.
2149 */
2150 public void clearBreakPoint(int line) {
2151 if (sourceInfo.breakableLine(line)) {
2152 boolean changed = sourceInfo.breakpoint(line, false);
2153 if (changed) {
2154 fileHeader.repaint();
2155 }
2156 }
2157 }
2158
2159 /**
2160 * Creates a new FileWindow.
2161 */
2162 public FileWindow(SwingGui debugGui, Dim.SourceInfo sourceInfo) {
2163 super(SwingGui.getShortName(sourceInfo.url()),
2164 true, true, true, true);
2165 this.debugGui = debugGui;
2166 this.sourceInfo = sourceInfo;
2167 updateToolTip();
2168 currentPos = -1;
2169 textArea = new FileTextArea(this);
2170 textArea.setRows(24);
2171 textArea.setColumns(80);
2172 p = new JScrollPane();
2173 fileHeader = new FileHeader(this);
2174 p.setViewportView(textArea);
2175 p.setRowHeaderView(fileHeader);
2176 setContentPane(p);
2177 pack();
2178 updateText(sourceInfo);
2179 textArea.select(0);
2180 }
2181
2182 /**
2183 * Updates the tool tip contents.
2184 */
2185 private void updateToolTip() {
2186 // Try to set tool tip on frame. On Mac OS X 10.5,
2187 // the number of components is different, so try to be safe.
2188 int n = getComponentCount() - 1;
2189 if (n > 1) {
2190 n = 1;
2191 } else if (n < 0) {
2192 return;
2193 }
2194 Component c = getComponent(n);
2195 // this will work at least for Metal L&F
2196 if (c != null && c instanceof JComponent) {
2197 ((JComponent)c).setToolTipText(getUrl());
2198 }
2199 }
2200
2201 /**
2202 * Returns the URL of the source.
2203 */
2204 public String getUrl() {
2205 return sourceInfo.url();
2206 }
2207
2208 /**
2209 * Called when the text of the script has changed.
2210 */
2211 public void updateText(Dim.SourceInfo sourceInfo) {
2212 this.sourceInfo = sourceInfo;
2213 String newText = sourceInfo.source();
2214 if (!textArea.getText().equals(newText)) {
2215 textArea.setText(newText);
2216 int pos = 0;
2217 if (currentPos != -1) {
2218 pos = currentPos;
2219 }
2220 textArea.select(pos);
2221 }
2222 fileHeader.update();
2223 fileHeader.repaint();
2224 }
2225
2226 /**
2227 * Sets the cursor position.
2228 */
2229 public void setPosition(int pos) {
2230 textArea.select(pos);
2231 currentPos = pos;
2232 fileHeader.repaint();
2233 }
2234
2235 /**
2236 * Selects a range of characters.
2237 */
2238 public void select(int start, int end) {
2239 int docEnd = textArea.getDocument().getLength();
2240 textArea.select(docEnd, docEnd);
2241 textArea.select(start, end);
2242 }
2243
2244 /**
2245 * Disposes this FileWindow.
2246 */
2247 @Override
2248 public void dispose() {
2249 debugGui.removeWindow(this);
2250 super.dispose();
2251 }
2252
2253 // ActionListener
2254
2255 /**
2256 * Performs an action.
2257 */
2258 public void actionPerformed(ActionEvent e) {
2259 String cmd = e.getActionCommand();
2260 if (cmd.equals("Cut")) {
2261 // textArea.cut();
2262 } else if (cmd.equals("Copy")) {
2263 textArea.copy();
2264 } else if (cmd.equals("Paste")) {
2265 // textArea.paste();
2266 }
2267 }
2268 }
2269
2270 /**
2271 * Table model class for watched expressions.
2272 */
2273 class MyTableModel extends AbstractTableModel {
2274
2275 /**
2276 * Serializable magic number.
2277 */
2278 private static final long serialVersionUID = 2971618907207577000L;
2279
2280 /**
2281 * The debugger GUI.
2282 */
2283 private SwingGui debugGui;
2284
2285 /**
2286 * List of watched expressions.
2287 */
2288 private List<String> expressions;
2289
2290 /**
2291 * List of values from evaluated from {@link #expressions}.
2292 */
2293 private List<String> values;
2294
2295 /**
2296 * Creates a new MyTableModel.
2297 */
2298 public MyTableModel(SwingGui debugGui) {
2299 this.debugGui = debugGui;
2300 expressions = Collections.synchronizedList(new ArrayList<String>());
2301 values = Collections.synchronizedList(new ArrayList<String>());
2302 expressions.add("");
2303 values.add("");
2304 }
2305
2306 /**
2307 * Returns the number of columns in the table (2).
2308 */
2309 public int getColumnCount() {
2310 return 2;
2311 }
2312
2313 /**
2314 * Returns the number of rows in the table.
2315 */
2316 public int getRowCount() {
2317 return expressions.size();
2318 }
2319
2320 /**
2321 * Returns the name of the given column.
2322 */
2323 @Override
2324 public String getColumnName(int column) {
2325 switch (column) {
2326 case 0:
2327 return "Expression";
2328 case 1:
2329 return "Value";
2330 }
2331 return null;
2332 }
2333
2334 /**
2335 * Returns whether the given cell is editable.
2336 */
2337 @Override
2338 public boolean isCellEditable(int row, int column) {
2339 return true;
2340 }
2341
2342 /**
2343 * Returns the value in the given cell.
2344 */
2345 public Object getValueAt(int row, int column) {
2346 switch (column) {
2347 case 0:
2348 return expressions.get(row);
2349 case 1:
2350 return values.get(row);
2351 }
2352 return "";
2353 }
2354
2355 /**
2356 * Sets the value in the given cell.
2357 */
2358 @Override
2359 public void setValueAt(Object value, int row, int column) {
2360 switch (column) {
2361 case 0:
2362 String expr = value.toString();
2363 expressions.set(row, expr);
2364 String result = "";
2365 if (expr.length() > 0) {
2366 result = debugGui.dim.eval(expr);
2367 if (result == null) result = "";
2368 }
2369 values.set(row, result);
2370 updateModel();
2371 if (row + 1 == expressions.size()) {
2372 expressions.add("");
2373 values.add("");
2374 fireTableRowsInserted(row + 1, row + 1);
2375 }
2376 break;
2377 case 1:
2378 // just reset column 2; ignore edits
2379 fireTableDataChanged();
2380 }
2381 }
2382
2383 /**
2384 * Re-evaluates the expressions in the table.
2385 */
2386 void updateModel() {
2387 for (int i = 0; i < expressions.size(); ++i) {
2388 String expr = expressions.get(i);
2389 String result = "";
2390 if (expr.length() > 0) {
2391 result = debugGui.dim.eval(expr);
2392 if (result == null) result = "";
2393 } else {
2394 result = "";
2395 }
2396 result = result.replace('\n', ' ');
2397 values.set(i, result);
2398 }
2399 fireTableDataChanged();
2400 }
2401 }
2402
2403 /**
2404 * A table for evaluated expressions.
2405 */
2406 class Evaluator extends JTable {
2407
2408 /**
2409 * Serializable magic number.
2410 */
2411 private static final long serialVersionUID = 8133672432982594256L;
2412
2413 /**
2414 * The {@link TableModel} for this table.
2415 */
2416 MyTableModel tableModel;
2417
2418 /**
2419 * Creates a new Evaluator.
2420 */
2421 public Evaluator(SwingGui debugGui) {
2422 super(new MyTableModel(debugGui));
2423 tableModel = (MyTableModel)getModel();
2424 }
2425 }
2426
2427 /**
2428 * Tree model for script object inspection.
2429 */
2430 class VariableModel implements TreeTableModel {
2431
2432 /**
2433 * Serializable magic number.
2434 */
2435 private static final String[] cNames = { " Name", " Value" };
2436
2437 /**
2438 * Tree column types.
2439 */
2440 private static final Class<?>[] cTypes =
2441 { TreeTableModel.class, String.class };
2442
2443 /**
2444 * Empty {@link VariableNode} array.
2445 */
2446 private static final VariableNode[] CHILDLESS = new VariableNode[0];
2447
2448 /**
2449 * The debugger.
2450 */
2451 private Dim debugger;
2452
2453 /**
2454 * The root node.
2455 */
2456 private VariableNode root;
2457
2458 /**
2459 * Creates a new VariableModel.
2460 */
2461 public VariableModel() {
2462 }
2463
2464 /**
2465 * Creates a new VariableModel.
2466 */
2467 public VariableModel(Dim debugger, Object scope) {
2468 this.debugger = debugger;
2469 this.root = new VariableNode(scope, "this");
2470 }
2471
2472 // TreeTableModel
2473
2474 /**
2475 * Returns the root node of the tree.
2476 */
2477 public Object getRoot() {
2478 if (debugger == null) {
2479 return null;
2480 }
2481 return root;
2482 }
2483
2484 /**
2485 * Returns the number of children of the given node.
2486 */
2487 public int getChildCount(Object nodeObj) {
2488 if (debugger == null) {
2489 return 0;
2490 }
2491 VariableNode node = (VariableNode) nodeObj;
2492 return children(node).length;
2493 }
2494
2495 /**
2496 * Returns a child of the given node.
2497 */
2498 public Object getChild(Object nodeObj, int i) {
2499 if (debugger == null) {
2500 return null;
2501 }
2502 VariableNode node = (VariableNode) nodeObj;
2503 return children(node)[i];
2504 }
2505
2506 /**
2507 * Returns whether the given node is a leaf node.
2508 */
2509 public boolean isLeaf(Object nodeObj) {
2510 if (debugger == null) {
2511 return true;
2512 }
2513 VariableNode node = (VariableNode) nodeObj;
2514 return children(node).length == 0;
2515 }
2516
2517 /**
2518 * Returns the index of a node under its parent.
2519 */
2520 public int getIndexOfChild(Object parentObj, Object childObj) {
2521 if (debugger == null) {
2522 return -1;
2523 }
2524 VariableNode parent = (VariableNode) parentObj;
2525 VariableNode child = (VariableNode) childObj;
2526 VariableNode[] children = children(parent);
2527 for (int i = 0; i != children.length; i++) {
2528 if (children[i] == child) {
2529 return i;
2530 }
2531 }
2532 return -1;
2533 }
2534
2535 /**
2536 * Returns whether the given cell is editable.
2537 */
2538 public boolean isCellEditable(Object node, int column) {
2539 return column == 0;
2540 }
2541
2542 /**
2543 * Sets the value at the given cell.
2544 */
2545 public void setValueAt(Object value, Object node, int column) { }
2546
2547 /**
2548 * Adds a TreeModelListener to this tree.
2549 */
2550 public void addTreeModelListener(TreeModelListener l) { }
2551
2552 /**
2553 * Removes a TreeModelListener from this tree.
2554 */
2555 public void removeTreeModelListener(TreeModelListener l) { }
2556
2557 public void valueForPathChanged(TreePath path, Object newValue) { }
2558
2559 // TreeTableNode
2560
2561 /**
2562 * Returns the number of columns.
2563 */
2564 public int getColumnCount() {
2565 return cNames.length;
2566 }
2567
2568 /**
2569 * Returns the name of the given column.
2570 */
2571 public String getColumnName(int column) {
2572 return cNames[column];
2573 }
2574
2575 /**
2576 * Returns the type of value stored in the given column.
2577 */
2578 public Class<?> getColumnClass(int column) {
2579 return cTypes[column];
2580 }
2581
2582 /**
2583 * Returns the value at the given cell.
2584 */
2585 public Object getValueAt(Object nodeObj, int column) {
2586 if (debugger == null) { return null; }
2587 VariableNode node = (VariableNode)nodeObj;
2588 switch (column) {
2589 case 0: // Name
2590 return node.toString();
2591 case 1: // Value
2592 String result;
2593 try {
2594 result = debugger.objectToString(getValue(node));
2595 } catch (RuntimeException exc) {
2596 result = exc.getMessage();
2597 }
2598 StringBuilder buf = new StringBuilder();
2599 int len = result.length();
2600 for (int i = 0; i < len; i++) {
2601 char ch = result.charAt(i);
2602 if (Character.isISOControl(ch)) {
2603 ch = ' ';
2604 }
2605 buf.append(ch);
2606 }
2607 return buf.toString();
2608 }
2609 return null;
2610 }
2611
2612 /**
2613 * Returns an array of the children of the given node.
2614 */
2615 private VariableNode[] children(VariableNode node) {
2616 if (node.children != null) {
2617 return node.children;
2618 }
2619
2620 VariableNode[] children;
2621
2622 Object value = getValue(node);
2623 Object[] ids = debugger.getObjectIds(value);
2624 if (ids == null || ids.length == 0) {
2625 children = CHILDLESS;
2626 } else {
2627 Arrays.sort(ids, new Comparator<Object>() {
2628 public int compare(Object l, Object r)
2629 {
2630 if (l instanceof String) {
2631 if (r instanceof Integer) {
2632 return -1;
2633 }
2634 return ((String)l).compareToIgnoreCase((String)r);
2635 } else {
2636 if (r instanceof String) {
2637 return 1;
2638 }
2639 int lint = ((Integer)l).intValue();
2640 int rint = ((Integer)r).intValue();
2641 return lint - rint;
2642 }
2643 }
2644 });
2645 children = new VariableNode[ids.length];
2646 for (int i = 0; i != ids.length; ++i) {
2647 children[i] = new VariableNode(value, ids[i]);
2648 }
2649 }
2650 node.children = children;
2651 return children;
2652 }
2653
2654 /**
2655 * Returns the value of the given node.
2656 */
2657 public Object getValue(VariableNode node) {
2658 try {
2659 return debugger.getObjectProperty(node.object, node.id);
2660 } catch (Exception exc) {
2661 return "undefined";
2662 }
2663 }
2664
2665 /**
2666 * A variable node in the tree.
2667 */
2668 private static class VariableNode {
2669
2670 /**
2671 * The script object.
2672 */
2673 private Object object;
2674
2675 /**
2676 * The object name. Either a String or an Integer.
2677 */
2678 private Object id;
2679
2680 /**
2681 * Array of child nodes. This is filled with the properties of
2682 * the object.
2683 */
2684 private VariableNode[] children;
2685
2686 /**
2687 * Creates a new VariableNode.
2688 */
2689 public VariableNode(Object object, Object id) {
2690 this.object = object;
2691 this.id = id;
2692 }
2693
2694 /**
2695 * Returns a string representation of this node.
2696 */
2697 @Override
2698 public String toString() {
2699 return id instanceof String
2700 ? (String) id : "[" + ((Integer) id).intValue() + "]";
2701 }
2702 }
2703 }
2704
2705 /**
2706 * A tree table for browsing script objects.
2707 */
2708 class MyTreeTable extends JTreeTable {
2709
2710 /**
2711 * Serializable magic number.
2712 */
2713 private static final long serialVersionUID = 3457265548184453049L;
2714
2715 /**
2716 * Creates a new MyTreeTable.
2717 */
2718 public MyTreeTable(VariableModel model) {
2719 super(model);
2720 }
2721
2722 /**
2723 * Initializes a tree for this tree table.
2724 */
2725 public JTree resetTree(TreeTableModel treeTableModel) {
2726 tree = new TreeTableCellRenderer(treeTableModel);
2727
2728 // Install a tableModel representing the visible rows in the tree.
2729 super.setModel(new TreeTableModelAdapter(treeTableModel, tree));
2730
2731 // Force the JTable and JTree to share their row selection models.
2732 ListToTreeSelectionModelWrapper selectionWrapper = new
2733 ListToTreeSelectionModelWrapper();
2734 tree.setSelectionModel(selectionWrapper);
2735 setSelectionModel(selectionWrapper.getListSelectionModel());
2736
2737 // Make the tree and table row heights the same.
2738 if (tree.getRowHeight() < 1) {
2739 // Metal looks better like this.
2740 setRowHeight(18);
2741 }
2742
2743 // Install the tree editor renderer and editor.
2744 setDefaultRenderer(TreeTableModel.class, tree);
2745 setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
2746 setShowGrid(true);
2747 setIntercellSpacing(new Dimension(1,1));
2748 tree.setRootVisible(false);
2749 tree.setShowsRootHandles(true);
2750 DefaultTreeCellRenderer r = (DefaultTreeCellRenderer)tree.getCellRenderer();
2751 r.setOpenIcon(null);
2752 r.setClosedIcon(null);
2753 r.setLeafIcon(null);
2754 return tree;
2755 }
2756
2757 /**
2758 * Returns whether the cell under the coordinates of the mouse
2759 * in the {@link EventObject} is editable.
2760 */
2761 public boolean isCellEditable(EventObject e) {
2762 if (e instanceof MouseEvent) {
2763 MouseEvent me = (MouseEvent)e;
2764 // If the modifiers are not 0 (or the left mouse button),
2765 // tree may try and toggle the selection, and table
2766 // will then try and toggle, resulting in the
2767 // selection remaining the same. To avoid this, we
2768 // only dispatch when the modifiers are 0 (or the left mouse
2769 // button).
2770 if (me.getModifiers() == 0 ||
2771 ((me.getModifiers() & (InputEvent.BUTTON1_MASK|1024)) != 0 &&
2772 (me.getModifiers() &
2773 (InputEvent.SHIFT_MASK |
2774 InputEvent.CTRL_MASK |
2775 InputEvent.ALT_MASK |
2776 InputEvent.BUTTON2_MASK |
2777 InputEvent.BUTTON3_MASK |
2778 64 | //SHIFT_DOWN_MASK
2779 128 | //CTRL_DOWN_MASK
2780 512 | // ALT_DOWN_MASK
2781 2048 | //BUTTON2_DOWN_MASK
2782 4096 //BUTTON3_DOWN_MASK
2783 )) == 0)) {
2784 int row = rowAtPoint(me.getPoint());
2785 for (int counter = getColumnCount() - 1; counter >= 0;
2786 counter--) {
2787 if (TreeTableModel.class == getColumnClass(counter)) {
2788 MouseEvent newME = new MouseEvent
2789 (MyTreeTable.this.tree, me.getID(),
2790 me.getWhen(), me.getModifiers(),
2791 me.getX() - getCellRect(row, counter, true).x,
2792 me.getY(), me.getClickCount(),
2793 me.isPopupTrigger());
2794 MyTreeTable.this.tree.dispatchEvent(newME);
2795 break;
2796 }
2797 }
2798 }
2799 if (me.getClickCount() >= 3) {
2800 return true;
2801 }
2802 return false;
2803 }
2804 if (e == null) {
2805 return true;
2806 }
2807 return false;
2808 }
2809 }
2810
2811 /**
2812 * Panel that shows information about the context.
2813 */
2814 class ContextWindow extends JPanel implements ActionListener {
2815
2816 /**
2817 * Serializable magic number.
2818 */
2819 private static final long serialVersionUID = 2306040975490228051L;
2820
2821 /**
2822 * The debugger GUI.
2823 */
2824 private SwingGui debugGui;
2825
2826 /**
2827 * The combo box that holds the stack frames.
2828 */
2829 JComboBox context;
2830
2831 /**
2832 * Tool tips for the stack frames.
2833 */
2834 List<String> toolTips;
2835
2836 /**
2837 * Tabbed pane for "this" and "locals".
2838 */
2839 private JTabbedPane tabs;
2840
2841 /**
2842 * Tabbed pane for "watch" and "evaluate".
2843 */
2844 private JTabbedPane tabs2;
2845
2846 /**
2847 * The table showing the "this" object.
2848 */
2849 private MyTreeTable thisTable;
2850
2851 /**
2852 * The table showing the stack local variables.
2853 */
2854 private MyTreeTable localsTable;
2855
2856 /**
2857 * The {@link #evaluator}'s table model.
2858 */
2859 private MyTableModel tableModel;
2860
2861 /**
2862 * The script evaluator table.
2863 */
2864 private Evaluator evaluator;
2865
2866 /**
2867 * The script evaluation text area.
2868 */
2869 private EvalTextArea cmdLine;
2870
2871 /**
2872 * The split pane.
2873 */
2874 JSplitPane split;
2875
2876 /**
2877 * Whether the ContextWindow is enabled.
2878 */
2879 private boolean enabled;
2880
2881 /**
2882 * Creates a new ContextWindow.
2883 */
2884 public ContextWindow(final SwingGui debugGui) {
2885 this.debugGui = debugGui;
2886 enabled = false;
2887 JPanel left = new JPanel();
2888 JToolBar t1 = new JToolBar();
2889 t1.setName("Variables");
2890 t1.setLayout(new GridLayout());
2891 t1.add(left);
2892 JPanel p1 = new JPanel();
2893 p1.setLayout(new GridLayout());
2894 JPanel p2 = new JPanel();
2895 p2.setLayout(new GridLayout());
2896 p1.add(t1);
2897 JLabel label = new JLabel("Context:");
2898 context = new JComboBox();
2899 context.setLightWeightPopupEnabled(false);
2900 toolTips = Collections.synchronizedList(new java.util.ArrayList<String>());
2901 label.setBorder(context.getBorder());
2902 context.addActionListener(this);
2903 context.setActionCommand("ContextSwitch");
2904 GridBagLayout layout = new GridBagLayout();
2905 left.setLayout(layout);
2906 GridBagConstraints lc = new GridBagConstraints();
2907 lc.insets.left = 5;
2908 lc.anchor = GridBagConstraints.WEST;
2909 lc.ipadx = 5;
2910 layout.setConstraints(label, lc);
2911 left.add(label);
2912 GridBagConstraints c = new GridBagConstraints();
2913 c.gridwidth = GridBagConstraints.REMAINDER;
2914 c.fill = GridBagConstraints.HORIZONTAL;
2915 c.anchor = GridBagConstraints.WEST;
2916 layout.setConstraints(context, c);
2917 left.add(context);
2918 tabs = new JTabbedPane(SwingConstants.BOTTOM);
2919 tabs.setPreferredSize(new Dimension(500,300));
2920 thisTable = new MyTreeTable(new VariableModel());
2921 JScrollPane jsp = new JScrollPane(thisTable);
2922 jsp.getViewport().setViewSize(new Dimension(5,2));
2923 tabs.add("this", jsp);
2924 localsTable = new MyTreeTable(new VariableModel());
2925 localsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
2926 localsTable.setPreferredSize(null);
2927 jsp = new JScrollPane(localsTable);
2928 tabs.add("Locals", jsp);
2929 c.weightx = c.weighty = 1;
2930 c.gridheight = GridBagConstraints.REMAINDER;
2931 c.fill = GridBagConstraints.BOTH;
2932 c.anchor = GridBagConstraints.WEST;
2933 layout.setConstraints(tabs, c);
2934 left.add(tabs);
2935 evaluator = new Evaluator(debugGui);
2936 cmdLine = new EvalTextArea(debugGui);
2937 //cmdLine.requestFocus();
2938 tableModel = evaluator.tableModel;
2939 jsp = new JScrollPane(evaluator);
2940 JToolBar t2 = new JToolBar();
2941 t2.setName("Evaluate");
2942 tabs2 = new JTabbedPane(SwingConstants.BOTTOM);
2943 tabs2.add("Watch", jsp);
2944 tabs2.add("Evaluate", new JScrollPane(cmdLine));
2945 tabs2.setPreferredSize(new Dimension(500,300));
2946 t2.setLayout(new GridLayout());
2947 t2.add(tabs2);
2948 p2.add(t2);
2949 evaluator.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
2950 split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
2951 p1, p2);
2952 split.setOneTouchExpandable(true);
2953 SwingGui.setResizeWeight(split, 0.5);
2954 setLayout(new BorderLayout());
2955 add(split, BorderLayout.CENTER);
2956
2957 final JToolBar finalT1 = t1;
2958 final JToolBar finalT2 = t2;
2959 final JPanel finalP1 = p1;
2960 final JPanel finalP2 = p2;
2961 final JSplitPane finalSplit = split;
2962 final JPanel finalThis = this;
2963
2964 ComponentListener clistener = new ComponentListener() {
2965 boolean t2Docked = true;
2966 void check(Component comp) {
2967 Component thisParent = finalThis.getParent();
2968 if (thisParent == null) {
2969 return;
2970 }
2971 Component parent = finalT1.getParent();
2972 boolean leftDocked = true;
2973 boolean rightDocked = true;
2974 boolean adjustVerticalSplit = false;
2975 if (parent != null) {
2976 if (parent != finalP1) {
2977 while (!(parent instanceof JFrame)) {
2978 parent = parent.getParent();
2979 }
2980 JFrame frame = (JFrame)parent;
2981 debugGui.addTopLevel("Variables", frame);
2982
2983 // We need the following hacks because:
2984 // - We want an undocked toolbar to be
2985 // resizable.
2986 // - We are using JToolbar as a container of a
2987 // JComboBox. Without this JComboBox's popup
2988 // can get left floating when the toolbar is
2989 // re-docked.
2990 //
2991 // We make the frame resizable and then
2992 // remove JToolbar's window listener
2993 // and insert one of our own that first ensures
2994 // the JComboBox's popup window is closed
2995 // and then calls JToolbar's window listener.
2996 if (!frame.isResizable()) {
2997 frame.setResizable(true);
2998 frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
2999 final WindowListener[] l =
3000 frame.getListeners(WindowListener.class);
3001 frame.removeWindowListener(l[0]);
3002 frame.addWindowListener(new WindowAdapter() {
3003 @Override
3004 public void windowClosing(WindowEvent e) {
3005 context.hidePopup();
3006 l[0].windowClosing(e);
3007 }
3008 });
3009 //adjustVerticalSplit = true;
3010 }
3011 leftDocked = false;
3012 } else {
3013 leftDocked = true;
3014 }
3015 }
3016 parent = finalT2.getParent();
3017 if (parent != null) {
3018 if (parent != finalP2) {
3019 while (!(parent instanceof JFrame)) {
3020 parent = parent.getParent();
3021 }
3022 JFrame frame = (JFrame)parent;
3023 debugGui.addTopLevel("Evaluate", frame);
3024 frame.setResizable(true);
3025 rightDocked = false;
3026 } else {
3027 rightDocked = true;
3028 }
3029 }
3030 if (leftDocked && t2Docked && rightDocked && t2Docked) {
3031 // no change
3032 return;
3033 }
3034 t2Docked = rightDocked;
3035 JSplitPane split = (JSplitPane)thisParent;
3036 if (leftDocked) {
3037 if (rightDocked) {
3038 finalSplit.setDividerLocation(0.5);
3039 } else {
3040 finalSplit.setDividerLocation(1.0);
3041 }
3042 if (adjustVerticalSplit) {
3043 split.setDividerLocation(0.66);
3044 }
3045
3046 } else if (rightDocked) {
3047 finalSplit.setDividerLocation(0.0);
3048 split.setDividerLocation(0.66);
3049 } else {
3050 // both undocked
3051 split.setDividerLocation(1.0);
3052 }
3053 }
3054 public void componentHidden(ComponentEvent e) {
3055 check(e.getComponent());
3056 }
3057 public void componentMoved(ComponentEvent e) {
3058 check(e.getComponent());
3059 }
3060 public void componentResized(ComponentEvent e) {
3061 check(e.getComponent());
3062 }
3063 public void componentShown(ComponentEvent e) {
3064 check(e.getComponent());
3065 }
3066 };
3067 p1.addContainerListener(new ContainerListener() {
3068 public void componentAdded(ContainerEvent e) {
3069 Component thisParent = finalThis.getParent();
3070 JSplitPane split = (JSplitPane)thisParent;
3071 if (e.getChild() == finalT1) {
3072 if (finalT2.getParent() == finalP2) {
3073 // both docked
3074 finalSplit.setDividerLocation(0.5);
3075 } else {
3076 // left docked only
3077 finalSplit.setDividerLocation(1.0);
3078 }
3079 split.setDividerLocation(0.66);
3080 }
3081 }
3082 public void componentRemoved(ContainerEvent e) {
3083 Component thisParent = finalThis.getParent();
3084 JSplitPane split = (JSplitPane)thisParent;
3085 if (e.getChild() == finalT1) {
3086 if (finalT2.getParent() == finalP2) {
3087 // right docked only
3088 finalSplit.setDividerLocation(0.0);
3089 split.setDividerLocation(0.66);
3090 } else {
3091 // both undocked
3092 split.setDividerLocation(1.0);
3093 }
3094 }
3095 }
3096 });
3097 t1.addComponentListener(clistener);
3098 t2.addComponentListener(clistener);
3099 setEnabled(false);
3100 }
3101
3102 /**
3103 * Enables or disables the component.
3104 */
3105 @Override
3106 public void setEnabled(boolean enabled) {
3107 context.setEnabled(enabled);
3108 thisTable.setEnabled(enabled);
3109 localsTable.setEnabled(enabled);
3110 evaluator.setEnabled(enabled);
3111 cmdLine.setEnabled(enabled);
3112 }
3113
3114 /**
3115 * Disables updating of the component.
3116 */
3117 public void disableUpdate() {
3118 enabled = false;
3119 }
3120
3121 /**
3122 * Enables updating of the component.
3123 */
3124 public void enableUpdate() {
3125 enabled = true;
3126 }
3127
3128 // ActionListener
3129
3130 /**
3131 * Performs an action.
3132 */
3133 public void actionPerformed(ActionEvent e) {
3134 if (!enabled) return;
3135 if (e.getActionCommand().equals("ContextSwitch")) {
3136 Dim.ContextData contextData = debugGui.dim.currentContextData();
3137 if (contextData == null) { return; }
3138 int frameIndex = context.getSelectedIndex();
3139 context.setToolTipText(toolTips.get(frameIndex));
3140 int frameCount = contextData.frameCount();
3141 if (frameIndex >= frameCount) {
3142 return;
3143 }
3144 Dim.StackFrame frame = contextData.getFrame(frameIndex);
3145 Object scope = frame.scope();
3146 Object thisObj = frame.thisObj();
3147 thisTable.resetTree(new VariableModel(debugGui.dim, thisObj));
3148 VariableModel scopeModel;
3149 if (scope != thisObj) {
3150 scopeModel = new VariableModel(debugGui.dim, scope);
3151 } else {
3152 scopeModel = new VariableModel();
3153 }
3154 localsTable.resetTree(scopeModel);
3155 debugGui.dim.contextSwitch(frameIndex);
3156 debugGui.showStopLine(frame);
3157 tableModel.updateModel();
3158 }
3159 }
3160 }
3161
3162 /**
3163 * The debugger frame menu bar.
3164 */
3165 class Menubar extends JMenuBar implements ActionListener {
3166
3167 /**
3168 * Serializable magic number.
3169 */
3170 private static final long serialVersionUID = 3217170497245911461L;
3171
3172 /**
3173 * Items that are enabled only when interrupted.
3174 */
3175 private List<JMenuItem> interruptOnlyItems =
3176 Collections.synchronizedList(new ArrayList<JMenuItem>());
3177
3178 /**
3179 * Items that are enabled only when running.
3180 */
3181 private List<JMenuItem> runOnlyItems =
3182 Collections.synchronizedList(new ArrayList<JMenuItem>());
3183
3184 /**
3185 * The debugger GUI.
3186 */
3187 private SwingGui debugGui;
3188
3189 /**
3190 * The menu listing the internal frames.
3191 */
3192 private JMenu windowMenu;
3193
3194 /**
3195 * The "Break on exceptions" menu item.
3196 */
3197 private JCheckBoxMenuItem breakOnExceptions;
3198
3199 /**
3200 * The "Break on enter" menu item.
3201 */
3202 private JCheckBoxMenuItem breakOnEnter;
3203
3204 /**
3205 * The "Break on return" menu item.
3206 */
3207 private JCheckBoxMenuItem breakOnReturn;
3208
3209 /**
3210 * Creates a new Menubar.
3211 */
3212 Menubar(SwingGui debugGui) {
3213 super();
3214 this.debugGui = debugGui;
3215 String[] fileItems = {"Open...", "Run...", "", "Exit"};
3216 String[] fileCmds = {"Open", "Load", "", "Exit"};
3217 char[] fileShortCuts = {'0', 'N', 0, 'X'};
3218 int[] fileAccelerators = {KeyEvent.VK_O,
3219 KeyEvent.VK_N,
3220 0,
3221 KeyEvent.VK_Q};
3222 String[] editItems = {"Cut", "Copy", "Paste", "Go to function..."};
3223 char[] editShortCuts = {'T', 'C', 'P', 'F'};
3224 String[] debugItems = {"Break", "Go", "Step Into", "Step Over", "Step Out"};
3225 char[] debugShortCuts = {'B', 'G', 'I', 'O', 'T'};
3226 String[] plafItems = {"Metal", "Windows", "Motif"};
3227 char [] plafShortCuts = {'M', 'W', 'F'};
3228 int[] debugAccelerators = {KeyEvent.VK_PAUSE,
3229 KeyEvent.VK_F5,
3230 KeyEvent.VK_F11,
3231 KeyEvent.VK_F7,
3232 KeyEvent.VK_F8,
3233 0, 0};
3234
3235 JMenu fileMenu = new JMenu("File");
3236 fileMenu.setMnemonic('F');
3237 JMenu editMenu = new JMenu("Edit");
3238 editMenu.setMnemonic('E');
3239 JMenu plafMenu = new JMenu("Platform");
3240 plafMenu.setMnemonic('P');
3241 JMenu debugMenu = new JMenu("Debug");
3242 debugMenu.setMnemonic('D');
3243 windowMenu = new JMenu("Window");
3244 windowMenu.setMnemonic('W');
3245 for (int i = 0; i < fileItems.length; ++i) {
3246 if (fileItems[i].length() == 0) {
3247 fileMenu.addSeparator();
3248 } else {
3249 JMenuItem item = new JMenuItem(fileItems[i],
3250 fileShortCuts[i]);
3251 item.setActionCommand(fileCmds[i]);
3252 item.addActionListener(this);
3253 fileMenu.add(item);
3254 if (fileAccelerators[i] != 0) {
3255 KeyStroke k = KeyStroke.getKeyStroke(fileAccelerators[i], Event.CTRL_MASK);
3256 item.setAccelerator(k);
3257 }
3258 }
3259 }
3260 for (int i = 0; i < editItems.length; ++i) {
3261 JMenuItem item = new JMenuItem(editItems[i],
3262 editShortCuts[i]);
3263 item.addActionListener(this);
3264 editMenu.add(item);
3265 }
3266 for (int i = 0; i < plafItems.length; ++i) {
3267 JMenuItem item = new JMenuItem(plafItems[i],
3268 plafShortCuts[i]);
3269 item.addActionListener(this);
3270 plafMenu.add(item);
3271 }
3272 for (int i = 0; i < debugItems.length; ++i) {
3273 JMenuItem item = new JMenuItem(debugItems[i],
3274 debugShortCuts[i]);
3275 item.addActionListener(this);
3276 if (debugAccelerators[i] != 0) {
3277 KeyStroke k = KeyStroke.getKeyStroke(debugAccelerators[i], 0);
3278 item.setAccelerator(k);
3279 }
3280 if (i != 0) {
3281 interruptOnlyItems.add(item);
3282 } else {
3283 runOnlyItems.add(item);
3284 }
3285 debugMenu.add(item);
3286 }
3287 breakOnExceptions = new JCheckBoxMenuItem("Break on Exceptions");
3288 breakOnExceptions.setMnemonic('X');
3289 breakOnExceptions.addActionListener(this);
3290 breakOnExceptions.setSelected(false);
3291 debugMenu.add(breakOnExceptions);
3292
3293 breakOnEnter = new JCheckBoxMenuItem("Break on Function Enter");
3294 breakOnEnter.setMnemonic('E');
3295 breakOnEnter.addActionListener(this);
3296 breakOnEnter.setSelected(false);
3297 debugMenu.add(breakOnEnter);
3298
3299 breakOnReturn = new JCheckBoxMenuItem("Break on Function Return");
3300 breakOnReturn.setMnemonic('R');
3301 breakOnReturn.addActionListener(this);
3302 breakOnReturn.setSelected(false);
3303 debugMenu.add(breakOnReturn);
3304
3305 add(fileMenu);
3306 add(editMenu);
3307 //add(plafMenu);
3308 add(debugMenu);
3309 JMenuItem item;
3310 windowMenu.add(item = new JMenuItem("Cascade", 'A'));
3311 item.addActionListener(this);
3312 windowMenu.add(item = new JMenuItem("Tile", 'T'));
3313 item.addActionListener(this);
3314 windowMenu.addSeparator();
3315 windowMenu.add(item = new JMenuItem("Console", 'C'));
3316 item.addActionListener(this);
3317 add(windowMenu);
3318
3319 updateEnabled(false);
3320 }
3321
3322 /**
3323 * Returns the "Break on exceptions" menu item.
3324 */
3325 public JCheckBoxMenuItem getBreakOnExceptions() {
3326 return breakOnExceptions;
3327 }
3328
3329 /**
3330 * Returns the "Break on enter" menu item.
3331 */
3332 public JCheckBoxMenuItem getBreakOnEnter() {
3333 return breakOnEnter;
3334 }
3335
3336 /**
3337 * Returns the "Break on return" menu item.
3338 */
3339 public JCheckBoxMenuItem getBreakOnReturn() {
3340 return breakOnReturn;
3341 }
3342
3343 /**
3344 * Returns the "Debug" menu.
3345 */
3346 public JMenu getDebugMenu() {
3347 return getMenu(2);
3348 }
3349
3350 // ActionListener
3351
3352 /**
3353 * Performs an action.
3354 */
3355 public void actionPerformed(ActionEvent e) {
3356 String cmd = e.getActionCommand();
3357 String plaf_name = null;
3358 if (cmd.equals("Metal")) {
3359 plaf_name = "javax.swing.plaf.metal.MetalLookAndFeel";
3360 } else if (cmd.equals("Windows")) {
3361 plaf_name = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
3362 } else if (cmd.equals("Motif")) {
3363 plaf_name = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
3364 } else {
3365 Object source = e.getSource();
3366 if (source == breakOnExceptions) {
3367 debugGui.dim.setBreakOnExceptions(breakOnExceptions.isSelected());
3368 } else if (source == breakOnEnter) {
3369 debugGui.dim.setBreakOnEnter(breakOnEnter.isSelected());
3370 } else if (source == breakOnReturn) {
3371 debugGui.dim.setBreakOnReturn(breakOnReturn.isSelected());
3372 } else {
3373 debugGui.actionPerformed(e);
3374 }
3375 return;
3376 }
3377 try {
3378 UIManager.setLookAndFeel(plaf_name);
3379 SwingUtilities.updateComponentTreeUI(debugGui);
3380 SwingUtilities.updateComponentTreeUI(debugGui.dlg);
3381 } catch (Exception ignored) {
3382 //ignored.printStackTrace();
3383 }
3384 }
3385
3386 /**
3387 * Adds a file to the window menu.
3388 */
3389 public void addFile(String url) {
3390 int count = windowMenu.getItemCount();
3391 JMenuItem item;
3392 if (count == 4) {
3393 windowMenu.addSeparator();
3394 count++;
3395 }
3396 JMenuItem lastItem = windowMenu.getItem(count -1);
3397 boolean hasMoreWin = false;
3398 int maxWin = 5;
3399 if (lastItem != null &&
3400 lastItem.getText().equals("More Windows...")) {
3401 hasMoreWin = true;
3402 maxWin++;
3403 }
3404 if (!hasMoreWin && count - 4 == 5) {
3405 windowMenu.add(item = new JMenuItem("More Windows...", 'M'));
3406 item.setActionCommand("More Windows...");
3407 item.addActionListener(this);
3408 return;
3409 } else if (count - 4 <= maxWin) {
3410 if (hasMoreWin) {
3411 count--;
3412 windowMenu.remove(lastItem);
3413 }
3414 String shortName = SwingGui.getShortName(url);
3415
3416 windowMenu.add(item = new JMenuItem((char)('0' + (count-4)) + " " + shortName, '0' + (count - 4)));
3417 if (hasMoreWin) {
3418 windowMenu.add(lastItem);
3419 }
3420 } else {
3421 return;
3422 }
3423 item.setActionCommand(url);
3424 item.addActionListener(this);
3425 }
3426
3427 /**
3428 * Updates the enabledness of menu items.
3429 */
3430 public void updateEnabled(boolean interrupted) {
3431 for (int i = 0; i != interruptOnlyItems.size(); ++i) {
3432 JMenuItem item = interruptOnlyItems.get(i);
3433 item.setEnabled(interrupted);
3434 }
3435
3436 for (int i = 0; i != runOnlyItems.size(); ++i) {
3437 JMenuItem item = runOnlyItems.get(i);
3438 item.setEnabled(!interrupted);
3439 }
3440 }
3441 }
3442
3443 /**
3444 * Class to consolidate all cases that require to implement Runnable
3445 * to avoid class generation bloat.
3446 */
3447 class RunProxy implements Runnable {
3448
3449 // Constants for 'type'.
3450 static final int OPEN_FILE = 1;
3451 static final int LOAD_FILE = 2;
3452 static final int UPDATE_SOURCE_TEXT = 3;
3453 static final int ENTER_INTERRUPT = 4;
3454
3455 /**
3456 * The debugger GUI.
3457 */
3458 private SwingGui debugGui;
3459
3460 /**
3461 * The type of Runnable this object is. Takes one of the constants
3462 * defined in this class.
3463 */
3464 private int type;
3465
3466 /**
3467 * The name of the file to open or load.
3468 */
3469 String fileName;
3470
3471 /**
3472 * The source text to update.
3473 */
3474 String text;
3475
3476 /**
3477 * The source for which to update the text.
3478 */
3479 Dim.SourceInfo sourceInfo;
3480
3481 /**
3482 * The frame to interrupt in.
3483 */
3484 Dim.StackFrame lastFrame;
3485
3486 /**
3487 * The name of the interrupted thread.
3488 */
3489 String threadTitle;
3490
3491 /**
3492 * The message of the exception thrown that caused the thread
3493 * interruption, if any.
3494 */
3495 String alertMessage;
3496
3497 /**
3498 * Creates a new RunProxy.
3499 */
3500 public RunProxy(SwingGui debugGui, int type) {
3501 this.debugGui = debugGui;
3502 this.type = type;
3503 }
3504
3505 /**
3506 * Runs this Runnable.
3507 */
3508 public void run() {
3509 switch (type) {
3510 case OPEN_FILE:
3511 try {
3512 debugGui.dim.compileScript(fileName, text);
3513 } catch (RuntimeException ex) {
3514 MessageDialogWrapper.showMessageDialog(
3515 debugGui, ex.getMessage(), "Error Compiling "+fileName,
3516 JOptionPane.ERROR_MESSAGE);
3517 }
3518 break;
3519
3520 case LOAD_FILE:
3521 try {
3522 debugGui.dim.evalScript(fileName, text);
3523 } catch (RuntimeException ex) {
3524 MessageDialogWrapper.showMessageDialog(
3525 debugGui, ex.getMessage(), "Run error for "+fileName,
3526 JOptionPane.ERROR_MESSAGE);
3527 }
3528 break;
3529
3530 case UPDATE_SOURCE_TEXT:
3531 {
3532 String fileName = sourceInfo.url();
3533 if (!debugGui.updateFileWindow(sourceInfo) &&
3534 !fileName.equals("<stdin>")) {
3535 debugGui.createFileWindow(sourceInfo, -1);
3536 }
3537 }
3538 break;
3539
3540 case ENTER_INTERRUPT:
3541 debugGui.enterInterruptImpl(lastFrame, threadTitle, alertMessage);
3542 break;
3543
3544 default:
3545 throw new IllegalArgumentException(String.valueOf(type));
3546
3547 }
3548 }
3549 }