feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.tools.example.debug.bdi.*;
public class ApplicationTool extends JPanel {
private static final long serialVersionUID = 310966063293205714L;
private ExecutionManager runtime;
private TypeScript script;
private static final String PROMPT = "Input:";
public ApplicationTool(Environment env) {
super(new BorderLayout());
this.runtime = env.getExecutionManager();
this.script = new TypeScript(PROMPT, false); // No implicit echo.
this.add(script);
script.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runtime.sendLineToApplication(script.readln());
}
});
runtime.addApplicationEchoListener(new TypeScriptOutputListener(script));
runtime.addApplicationOutputListener(new TypeScriptOutputListener(script));
runtime.addApplicationErrorListener(new TypeScriptOutputListener(script));
//### should clean up on exit!
}
/******
public void setFont(Font f) {
script.setFont(f);
}
******/
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
public class ClassManager {
// This class is provided primarily for symmetry with
// SourceManager. Currently, it does very little.
// If we add facilities in the future that require that
// class files be read outside of the VM, for example, to
// provide a disassembled view of a class for bytecode-level
// debugging, the required class file management will be done
// here.
private SearchPath classPath;
public ClassManager(Environment env) {
this.classPath = new SearchPath("");
}
public ClassManager(SearchPath classPath) {
this.classPath = classPath;
}
/*
* Set path for access to class files.
*/
public void setClassPath(SearchPath sp) {
classPath = sp;
}
/*
* Get path for access to class files.
*/
public SearchPath getClassPath() {
return classPath;
}
}

View File

@@ -0,0 +1,287 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
import com.sun.tools.example.debug.bdi.*;
public class ClassTreeTool extends JPanel {
private static final long serialVersionUID = 526178912591739259L;
private Environment env;
private ExecutionManager runtime;
private SourceManager sourceManager;
private ClassManager classManager;
private JTree tree;
private DefaultTreeModel treeModel;
private ClassTreeNode root;
// private SearchPath sourcePath;
private CommandInterpreter interpreter;
private static String HEADING = "CLASSES";
public ClassTreeTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env);
root = createClassTree(HEADING);
treeModel = new DefaultTreeModel(root);
// Create a tree that allows one selection at a time.
tree = new JTree(treeModel);
tree.setSelectionModel(new SingleLeafTreeSelectionModel());
/******
// Listen for when the selection changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
ClassTreeNode node = (ClassTreeNode)
(e.getPath().getLastPathComponent());
if (node != null) {
interpreter.executeCommand("view " + node.getReferenceTypeName());
}
}
});
******/
MouseListener ml = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
ClassTreeNode node =
(ClassTreeNode)selPath.getLastPathComponent();
// If user clicks on leaf, select it, and issue 'view' command.
if (node.isLeaf()) {
tree.setSelectionPath(selPath);
interpreter.executeCommand("view " + node.getReferenceTypeName());
}
}
}
}
};
tree.addMouseListener(ml);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);
// Create listener.
ClassTreeToolListener listener = new ClassTreeToolListener();
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
//### remove listeners on exit!
}
private class ClassTreeToolListener extends JDIAdapter
implements JDIListener, SessionListener {
// SessionListener
@Override
public void sessionStart(EventObject e) {
// Get system classes and any others loaded before attaching.
try {
for (ReferenceType type : runtime.allClasses()) {
root.addClass(type);
}
} catch (VMDisconnectedException ee) {
// VM terminated unexpectedly.
} catch (NoSessionException ee) {
// Ignore. Should not happen.
}
}
@Override
public void sessionInterrupt(EventObject e) {}
@Override
public void sessionContinue(EventObject e) {}
// JDIListener
@Override
public void classPrepare(ClassPrepareEventSet e) {
root.addClass(e.getReferenceType());
}
@Override
public void classUnload(ClassUnloadEventSet e) {
root.removeClass(e.getClassName());
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
// Clear contents of this view.
root = createClassTree(HEADING);
treeModel = new DefaultTreeModel(root);
tree.setModel(treeModel);
}
}
ClassTreeNode createClassTree(String label) {
return new ClassTreeNode(label, null);
}
class ClassTreeNode extends DefaultMutableTreeNode {
private String name;
private ReferenceType refTy; // null for package
ClassTreeNode(String name, ReferenceType refTy) {
this.name = name;
this.refTy = refTy;
}
@Override
public String toString() {
return name;
}
public ReferenceType getReferenceType() {
return refTy;
}
public String getReferenceTypeName() {
return refTy.name();
}
private boolean isPackage() {
return (refTy == null);
}
@Override
public boolean isLeaf() {
return !isPackage();
}
public void addClass(ReferenceType refTy) {
addClass(refTy.name(), refTy);
}
private void addClass(String className, ReferenceType refTy) {
if (className.equals("")) {
return;
}
int pos = className.indexOf('.');
if (pos < 0) {
insertNode(className, refTy);
} else {
String head = className.substring(0, pos);
String tail = className.substring(pos + 1);
ClassTreeNode child = insertNode(head, null);
child.addClass(tail, refTy);
}
}
private ClassTreeNode insertNode(String name, ReferenceType refTy) {
for (int i = 0; i < getChildCount(); i++) {
ClassTreeNode child = (ClassTreeNode)getChildAt(i);
int cmp = name.compareTo(child.toString());
if (cmp == 0) {
// like-named node already exists
return child;
} else if (cmp < 0) {
// insert new node before the child
ClassTreeNode newChild = new ClassTreeNode(name, refTy);
treeModel.insertNodeInto(newChild, this, i);
return newChild;
}
}
// insert new node after last child
ClassTreeNode newChild = new ClassTreeNode(name, refTy);
treeModel.insertNodeInto(newChild, this, getChildCount());
return newChild;
}
public void removeClass(String className) {
if (className.equals("")) {
return;
}
int pos = className.indexOf('.');
if (pos < 0) {
ClassTreeNode child = findNode(className);
if (!isPackage()) {
treeModel.removeNodeFromParent(child);
}
} else {
String head = className.substring(0, pos);
String tail = className.substring(pos + 1);
ClassTreeNode child = findNode(head);
child.removeClass(tail);
if (isPackage() && child.getChildCount() < 1) {
// Prune non-leaf nodes with no children.
treeModel.removeNodeFromParent(child);
}
}
}
private ClassTreeNode findNode(String name) {
for (int i = 0; i < getChildCount(); i++) {
ClassTreeNode child = (ClassTreeNode)getChildAt(i);
int cmp = name.compareTo(child.toString());
if (cmp == 0) {
return child;
} else if (cmp > 0) {
// not found, since children are sorted
return null;
}
}
return null;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,342 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.tools.example.debug.bdi.*;
import com.sun.tools.example.debug.event.*;
public class CommandTool extends JPanel {
private static final long serialVersionUID = 8613516856378346415L;
private Environment env;
private ContextManager context;
private ExecutionManager runtime;
private SourceManager sourceManager;
private TypeScript script;
private static final String DEFAULT_CMD_PROMPT = "Command:";
public CommandTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.context = env.getContextManager();
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
script = new TypeScript(DEFAULT_CMD_PROMPT, false); //no echo
this.add(script);
final CommandInterpreter interpreter =
new CommandInterpreter(env);
// Establish handler for incoming commands.
script.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(script.readln());
}
});
// Establish ourselves as the listener for VM diagnostics.
OutputListener diagnosticsListener =
new TypeScriptOutputListener(script, true);
runtime.addDiagnosticsListener(diagnosticsListener);
// Establish ourselves as the shared debugger typescript.
env.setTypeScript(new PrintWriter(new TypeScriptWriter(script)));
// Handle VM events.
TTYDebugListener listener = new TTYDebugListener(diagnosticsListener);
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
runtime.addSpecListener(listener);
context.addContextListener(listener);
//### remove listeners on exit!
}
private class TTYDebugListener implements
JDIListener, SessionListener, SpecListener, ContextListener {
private OutputListener diagnostics;
TTYDebugListener(OutputListener diagnostics) {
this.diagnostics = diagnostics;
}
// JDIListener
@Override
public void accessWatchpoint(AccessWatchpointEventSet e) {
setThread(e);
for (EventIterator it = e.eventIterator(); it.hasNext(); ) {
it.nextEvent();
diagnostics.putString("Watchpoint hit: " +
locationString(e));
}
}
@Override
public void classPrepare(ClassPrepareEventSet e) {
if (context.getVerboseFlag()) {
String name = e.getReferenceType().name();
diagnostics.putString("Class " + name + " loaded");
}
}
@Override
public void classUnload(ClassUnloadEventSet e) {
if (context.getVerboseFlag()) {
diagnostics.putString("Class " + e.getClassName() +
" unloaded.");
}
}
@Override
public void exception(ExceptionEventSet e) {
setThread(e);
String name = e.getException().referenceType().name();
diagnostics.putString("Exception: " + name);
}
@Override
public void locationTrigger(LocationTriggerEventSet e) {
String locString = locationString(e);
setThread(e);
for (EventIterator it = e.eventIterator(); it.hasNext(); ) {
Event evt = it.nextEvent();
if (evt instanceof BreakpointEvent) {
diagnostics.putString("Breakpoint hit: " + locString);
} else if (evt instanceof StepEvent) {
diagnostics.putString("Step completed: " + locString);
} else if (evt instanceof MethodEntryEvent) {
diagnostics.putString("Method entered: " + locString);
} else if (evt instanceof MethodExitEvent) {
diagnostics.putString("Method exited: " + locString);
} else {
diagnostics.putString("UNKNOWN event: " + e);
}
}
}
@Override
public void modificationWatchpoint(ModificationWatchpointEventSet e) {
setThread(e);
for (EventIterator it = e.eventIterator(); it.hasNext(); ) {
it.nextEvent();
diagnostics.putString("Watchpoint hit: " +
locationString(e));
}
}
@Override
public void threadDeath(ThreadDeathEventSet e) {
if (context.getVerboseFlag()) {
diagnostics.putString("Thread " + e.getThread() +
" ended.");
}
}
@Override
public void threadStart(ThreadStartEventSet e) {
if (context.getVerboseFlag()) {
diagnostics.putString("Thread " + e.getThread() +
" started.");
}
}
@Override
public void vmDeath(VMDeathEventSet e) {
script.setPrompt(DEFAULT_CMD_PROMPT);
diagnostics.putString("VM exited");
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
script.setPrompt(DEFAULT_CMD_PROMPT);
diagnostics.putString("Disconnected from VM");
}
@Override
public void vmStart(VMStartEventSet e) {
script.setPrompt(DEFAULT_CMD_PROMPT);
diagnostics.putString("VM started");
}
// SessionListener
@Override
public void sessionStart(EventObject e) {}
@Override
public void sessionInterrupt(EventObject e) {
Thread.yield(); // fetch output
diagnostics.putString("VM interrupted by user.");
script.setPrompt(DEFAULT_CMD_PROMPT);
}
@Override
public void sessionContinue(EventObject e) {
diagnostics.putString("Execution resumed.");
script.setPrompt(DEFAULT_CMD_PROMPT);
}
// SpecListener
@Override
public void breakpointSet(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint set at " + spec + ".");
}
@Override
public void breakpointDeferred(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint will be set at " +
spec + " when its class is loaded.");
}
@Override
public void breakpointDeleted(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint at " + spec.toString() + " deleted.");
}
@Override
public void breakpointResolved(SpecEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Breakpoint resolved to " + spec.toString() + ".");
}
@Override
public void breakpointError(SpecErrorEvent e) {
EventRequestSpec spec = e.getEventRequestSpec();
diagnostics.putString("Deferred breakpoint at " +
spec + " could not be resolved:" +
e.getReason());
}
//### Add info for watchpoints and exceptions
@Override
public void watchpointSet(SpecEvent e) {
}
@Override
public void watchpointDeferred(SpecEvent e) {
}
@Override
public void watchpointDeleted(SpecEvent e) {
}
@Override
public void watchpointResolved(SpecEvent e) {
}
@Override
public void watchpointError(SpecErrorEvent e) {
}
@Override
public void exceptionInterceptSet(SpecEvent e) {
}
@Override
public void exceptionInterceptDeferred(SpecEvent e) {
}
@Override
public void exceptionInterceptDeleted(SpecEvent e) {
}
@Override
public void exceptionInterceptResolved(SpecEvent e) {
}
@Override
public void exceptionInterceptError(SpecErrorEvent e) {
}
// ContextListener.
// If the user selects a new current thread or frame, update prompt.
@Override
public void currentFrameChanged(CurrentFrameChangedEvent e) {
// Update prompt only if affect thread is current.
ThreadReference thread = e.getThread();
if (thread == context.getCurrentThread()) {
script.setPrompt(promptString(thread, e.getIndex()));
}
}
}
private String locationString(LocatableEventSet e) {
Location loc = e.getLocation();
return "thread=\"" + e.getThread().name() +
"\", " + Utils.locationString(loc);
}
private void setThread(LocatableEventSet e) {
if (!e.suspendedNone()) {
Thread.yield(); // fetch output
script.setPrompt(promptString(e.getThread(), 0));
//### Current thread should be set elsewhere, e.g.,
//### in ContextManager
//### context.setCurrentThread(thread);
}
}
private String promptString(ThreadReference thread, int frameIndex) {
if (thread == null) {
return DEFAULT_CMD_PROMPT;
} else {
// Frame indices are presented to user as indexed from 1.
return (thread.name() + "[" + (frameIndex + 1) + "]:");
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
public interface ContextListener {
void currentFrameChanged(CurrentFrameChangedEvent e);
}

View File

@@ -0,0 +1,362 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
import com.sun.tools.example.debug.bdi.*;
public class ContextManager {
private ClassManager classManager;
private ExecutionManager runtime;
private String mainClassName;
private String vmArguments;
private String commandArguments;
private String remotePort;
private ThreadReference currentThread;
private boolean verbose;
private ArrayList<ContextListener> contextListeners = new ArrayList<ContextListener>();
public ContextManager(Environment env) {
classManager = env.getClassManager();
runtime = env.getExecutionManager();
mainClassName = "";
vmArguments = "";
commandArguments = "";
currentThread = null;
ContextManagerListener listener = new ContextManagerListener();
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
}
// Program execution defaults.
//### Should there be change listeners for these?
//### They would be needed if we expected a dialog to be
//### synchronized with command input while it was open.
public String getMainClassName() {
return mainClassName;
}
public void setMainClassName(String mainClassName) {
this.mainClassName = mainClassName;
}
public String getVmArguments() {
return processClasspathDefaults(vmArguments);
}
public void setVmArguments(String vmArguments) {
this.vmArguments = vmArguments;
}
public String getProgramArguments() {
return commandArguments;
}
public void setProgramArguments(String commandArguments) {
this.commandArguments = commandArguments;
}
public String getRemotePort() {
return remotePort;
}
public void setRemotePort(String remotePort) {
this.remotePort = remotePort;
}
// Miscellaneous debugger session preferences.
public boolean getVerboseFlag() {
return verbose;
}
public void setVerboseFlag(boolean verbose) {
this.verbose = verbose;
}
// Thread focus.
public ThreadReference getCurrentThread() {
return currentThread;
}
public void setCurrentThread(ThreadReference t) {
if (t != currentThread) {
currentThread = t;
notifyCurrentThreadChanged(t);
}
}
public void setCurrentThreadInvalidate(ThreadReference t) {
currentThread = t;
notifyCurrentFrameChanged(runtime.threadInfo(t),
0, true);
}
public void invalidateCurrentThread() {
notifyCurrentFrameChanged(null, 0, true);
}
// If a view is displaying the current thread, it may
// choose to indicate which frame is current in the
// sense of the command-line UI. It may also "warp" the
// selection to that frame when changed by an 'up' or 'down'
// command. Hence, a notifier is provided.
/******
public int getCurrentFrameIndex() {
return getCurrentFrameIndex(currentThreadInfo);
}
******/
public int getCurrentFrameIndex(ThreadReference t) {
return getCurrentFrameIndex(runtime.threadInfo(t));
}
//### Used in StackTraceTool.
public int getCurrentFrameIndex(ThreadInfo tinfo) {
if (tinfo == null) {
return 0;
}
Integer currentFrame = (Integer)tinfo.getUserObject();
if (currentFrame == null) {
return 0;
} else {
return currentFrame.intValue();
}
}
public int moveCurrentFrameIndex(ThreadReference t, int count) throws VMNotInterruptedException {
return setCurrentFrameIndex(t,count, true);
}
public int setCurrentFrameIndex(ThreadReference t, int newIndex) throws VMNotInterruptedException {
return setCurrentFrameIndex(t, newIndex, false);
}
public int setCurrentFrameIndex(int newIndex) throws VMNotInterruptedException {
if (currentThread == null) {
return 0;
} else {
return setCurrentFrameIndex(currentThread, newIndex, false);
}
}
private int setCurrentFrameIndex(ThreadReference t, int x, boolean relative) throws VMNotInterruptedException {
boolean sameThread = t.equals(currentThread);
ThreadInfo tinfo = runtime.threadInfo(t);
if (tinfo == null) {
return 0;
}
int maxIndex = tinfo.getFrameCount()-1;
int oldIndex = getCurrentFrameIndex(tinfo);
int newIndex = relative? oldIndex + x : x;
if (newIndex > maxIndex) {
newIndex = maxIndex;
} else if (newIndex < 0) {
newIndex = 0;
}
if (!sameThread || newIndex != oldIndex) { // don't recurse
setCurrentFrameIndex(tinfo, newIndex);
}
return newIndex - oldIndex;
}
private void setCurrentFrameIndex(ThreadInfo tinfo, int index) {
tinfo.setUserObject(new Integer(index));
//### In fact, the value may not have changed at this point.
//### We need to signal that the user attempted to change it,
//### however, so that the selection can be "warped" to the
//### current location.
notifyCurrentFrameChanged(tinfo.thread(), index);
}
public StackFrame getCurrentFrame() throws VMNotInterruptedException {
return getCurrentFrame(runtime.threadInfo(currentThread));
}
public StackFrame getCurrentFrame(ThreadReference t) throws VMNotInterruptedException {
return getCurrentFrame(runtime.threadInfo(t));
}
public StackFrame getCurrentFrame(ThreadInfo tinfo) throws VMNotInterruptedException {
int index = getCurrentFrameIndex(tinfo);
try {
// It is possible, though unlikely, that the VM was interrupted
// before the thread created its Java stack.
return tinfo.getFrame(index);
} catch (FrameIndexOutOfBoundsException e) {
return null;
}
}
public void addContextListener(ContextListener cl) {
contextListeners.add(cl);
}
public void removeContextListener(ContextListener cl) {
contextListeners.remove(cl);
}
//### These notifiers are fired only in response to USER-INITIATED changes
//### to the current thread and current frame. When the current thread is set automatically
//### after a breakpoint hit or step completion, no event is generated. Instead,
//### interested parties are expected to listen for the BreakpointHit and StepCompleted
//### events. This convention is unclean, and I believe that it reflects a defect in
//### in the current architecture. Unfortunately, however, we cannot guarantee the
//### order in which various listeners receive a given event, and the handlers for
//### the very same events that cause automatic changes to the current thread may also
//### need to know the current thread.
private void notifyCurrentThreadChanged(ThreadReference t) {
ThreadInfo tinfo = null;
int index = 0;
if (t != null) {
tinfo = runtime.threadInfo(t);
index = getCurrentFrameIndex(tinfo);
}
notifyCurrentFrameChanged(tinfo, index, false);
}
private void notifyCurrentFrameChanged(ThreadReference t, int index) {
notifyCurrentFrameChanged(runtime.threadInfo(t),
index, false);
}
private void notifyCurrentFrameChanged(ThreadInfo tinfo, int index,
boolean invalidate) {
ArrayList<ContextListener> l = new ArrayList<ContextListener>(contextListeners);
CurrentFrameChangedEvent evt =
new CurrentFrameChangedEvent(this, tinfo, index, invalidate);
for (int i = 0; i < l.size(); i++) {
l.get(i).currentFrameChanged(evt);
}
}
private class ContextManagerListener extends JDIAdapter
implements SessionListener, JDIListener {
// SessionListener
@Override
public void sessionStart(EventObject e) {
invalidateCurrentThread();
}
@Override
public void sessionInterrupt(EventObject e) {
setCurrentThreadInvalidate(currentThread);
}
@Override
public void sessionContinue(EventObject e) {
invalidateCurrentThread();
}
// JDIListener
@Override
public void locationTrigger(LocationTriggerEventSet e) {
setCurrentThreadInvalidate(e.getThread());
}
@Override
public void exception(ExceptionEventSet e) {
setCurrentThreadInvalidate(e.getThread());
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
invalidateCurrentThread();
}
}
/**
* Add a -classpath argument to the arguments passed to the exec'ed
* VM with the contents of CLASSPATH environment variable,
* if -classpath was not already specified.
*
* @param javaArgs the arguments to the VM being exec'd that
* potentially has a user specified -classpath argument.
* @return a javaArgs whose -classpath option has been added
*/
private String processClasspathDefaults(String javaArgs) {
if (javaArgs.indexOf("-classpath ") == -1) {
StringBuffer munged = new StringBuffer(javaArgs);
SearchPath classpath = classManager.getClassPath();
if (classpath.isEmpty()) {
String envcp = System.getProperty("env.class.path");
if ((envcp != null) && (envcp.length() > 0)) {
munged.append(" -classpath " + envcp);
}
} else {
munged.append(" -classpath " + classpath.asString());
}
return munged.toString();
} else {
return javaArgs;
}
}
private String appendPath(String path1, String path2) {
if (path1 == null || path1.length() == 0) {
return path2 == null ? "." : path2;
} else if (path2 == null || path2.length() == 0) {
return path1;
} else {
return path1 + File.pathSeparator + path2;
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
import java.util.EventObject;
public class CurrentFrameChangedEvent extends EventObject {
private static final long serialVersionUID = 4214479486546762179L;
private ThreadInfo tinfo;
private int index;
private boolean invalidate;
public CurrentFrameChangedEvent(Object source, ThreadInfo tinfo,
int index, boolean invalidate) {
super(source);
this.tinfo = tinfo;
this.index = index;
this.invalidate = invalidate;
}
public ThreadReference getThread() {
return tinfo == null? null : tinfo.thread();
}
public ThreadInfo getThreadInfo() {
return tinfo;
}
public int getIndex() {
return index;
}
public boolean getInvalidate() {
return invalidate;
}
}

View File

@@ -0,0 +1,165 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
public class Environment {
private SourceManager sourceManager;
private ClassManager classManager;
private ContextManager contextManager;
private MonitorListModel monitorListModel;
private ExecutionManager runtime;
private PrintWriter typeScript;
private boolean verbose;
public Environment() {
this.classManager = new ClassManager(this);
//### Order of the next three lines is important! (FIX THIS)
this.runtime = new ExecutionManager();
this.sourceManager = new SourceManager(this);
this.contextManager = new ContextManager(this);
this.monitorListModel = new MonitorListModel(this);
}
// Services used by debugging tools.
public SourceManager getSourceManager() {
return sourceManager;
}
public ClassManager getClassManager() {
return classManager;
}
public ContextManager getContextManager() {
return contextManager;
}
public MonitorListModel getMonitorListModel() {
return monitorListModel;
}
public ExecutionManager getExecutionManager() {
return runtime;
}
//### TODO:
//### Tools should attach/detach from environment
//### via a property, which should call an 'addTool'
//### method when set to maintain a registry of
//### tools for exit-time cleanup, etc. Tool
//### class constructors should be argument-free, so
//### that they may be instantiated by bean builders.
//### Will also need 'removeTool' in case property
//### value is changed.
//
// public void addTool(Tool t);
// public void removeTool(Tool t);
public void terminate() {
System.exit(0);
}
// public void refresh(); // notify all tools to refresh their views
// public void addStatusListener(StatusListener l);
// public void removeStatusListener(StatusListener l);
// public void addOutputListener(OutputListener l);
// public void removeOutputListener(OutputListener l);
public void setTypeScript(PrintWriter writer) {
typeScript = writer;
}
public void error(String message) {
if (typeScript != null) {
typeScript.println(message);
} else {
System.out.println(message);
}
}
public void failure(String message) {
if (typeScript != null) {
typeScript.println(message);
} else {
System.out.println(message);
}
}
public void notice(String message) {
if (typeScript != null) {
typeScript.println(message);
} else {
System.out.println(message);
}
}
public OutputSink getOutputSink() {
return new OutputSink(typeScript);
}
public void viewSource(String fileName) {
//### HACK ###
//### Should use listener here.
com.sun.tools.example.debug.gui.GUI.srcTool.showSourceFile(fileName);
}
public void viewLocation(Location locn) {
//### HACK ###
//### Should use listener here.
//### Should we use sourceForLocation here?
com.sun.tools.example.debug.gui.GUI.srcTool.showSourceForLocation(locn);
}
//### Also in 'ContextManager'. Do we need both?
public boolean getVerboseFlag() {
return verbose;
}
public void setVerboseFlag(boolean verbose) {
this.verbose = verbose;
}
}

View File

@@ -0,0 +1,265 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
public class GUI extends JPanel {
private static final long serialVersionUID = 3292463234530679091L;
private CommandTool cmdTool;
private ApplicationTool appTool;
//###HACK##
//### There is currently dirty code in Environment that
//### accesses this directly.
//private SourceTool srcTool;
public static SourceTool srcTool;
private SourceTreeTool sourceTreeTool;
private ClassTreeTool classTreeTool;
private ThreadTreeTool threadTreeTool;
private StackTraceTool stackTool;
private MonitorTool monitorTool;
public static final String progname = "javadt";
public static final String version = "1.0Beta"; //### FIX ME.
public static final String windowBanner = "Java(tm) platform Debug Tool";
private Font fixedFont = new Font("monospaced", Font.PLAIN, 10);
private GUI(Environment env) {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(5, 5, 5, 5));
add(new JDBToolBar(env), BorderLayout.NORTH);
srcTool = new SourceTool(env);
srcTool.setPreferredSize(new java.awt.Dimension(500, 300));
srcTool.setTextFont(fixedFont);
stackTool = new StackTraceTool(env);
stackTool.setPreferredSize(new java.awt.Dimension(500, 100));
monitorTool = new MonitorTool(env);
monitorTool.setPreferredSize(new java.awt.Dimension(500, 50));
JSplitPane right = new JSplitPane(JSplitPane.VERTICAL_SPLIT, srcTool,
new JSplitPane(JSplitPane.VERTICAL_SPLIT, stackTool, monitorTool));
sourceTreeTool = new SourceTreeTool(env);
sourceTreeTool.setPreferredSize(new java.awt.Dimension(200, 450));
classTreeTool = new ClassTreeTool(env);
classTreeTool.setPreferredSize(new java.awt.Dimension(200, 450));
threadTreeTool = new ThreadTreeTool(env);
threadTreeTool.setPreferredSize(new java.awt.Dimension(200, 450));
JTabbedPane treePane = new JTabbedPane(SwingConstants.BOTTOM);
treePane.addTab("Source", null, sourceTreeTool);
treePane.addTab("Classes", null, classTreeTool);
treePane.addTab("Threads", null, threadTreeTool);
JSplitPane centerTop = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treePane, right);
cmdTool = new CommandTool(env);
cmdTool.setPreferredSize(new java.awt.Dimension(700, 150));
appTool = new ApplicationTool(env);
appTool.setPreferredSize(new java.awt.Dimension(700, 200));
JSplitPane centerBottom = new JSplitPane(JSplitPane.VERTICAL_SPLIT, cmdTool, appTool);
// centerBottom.setPreferredSize(new java.awt.Dimension(700, 350));
JSplitPane center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, centerTop, centerBottom);
add(center, BorderLayout.CENTER);
}
private static void usage() {
String separator = File.pathSeparator;
System.out.println("Usage: " + progname + " <options> <class> <arguments>");
System.out.println();
System.out.println("where options include:");
System.out.println(" -help print out this message and exit");
System.out.println(" -sourcepath <directories separated by \"" +
separator + "\">");
System.out.println(" list directories in which to look for source files");
System.out.println(" -remote <hostname>:<port-number>");
System.out.println(" host machine and port number of interpreter to attach to");
System.out.println(" -dbgtrace [flags] print info for debugging " + progname);
System.out.println();
System.out.println("options forwarded to debuggee process:");
System.out.println(" -v -verbose[:class|gc|jni]");
System.out.println(" turn on verbose mode");
System.out.println(" -D<name>=<value> set a system property");
System.out.println(" -classpath <directories separated by \"" +
separator + "\">");
System.out.println(" list directories in which to look for classes");
System.out.println(" -X<option> non-standard debuggee VM option");
System.out.println();
System.out.println("<class> is the name of the class to begin debugging");
System.out.println("<arguments> are the arguments passed to the main() method of <class>");
System.out.println();
System.out.println("For command help type 'help' at " + progname + " prompt");
}
public static void main(String argv[]) {
String clsName = "";
String progArgs = "";
String javaArgs = "";
final Environment env = new Environment();
JPanel mainPanel = new GUI(env);
ContextManager context = env.getContextManager();
ExecutionManager runtime = env.getExecutionManager();
for (int i = 0; i < argv.length; i++) {
String token = argv[i];
if (token.equals("-dbgtrace")) {
if ((i == argv.length - 1) ||
! Character.isDigit(argv[i+1].charAt(0))) {
runtime.setTraceMode(VirtualMachine.TRACE_ALL);
} else {
String flagStr = argv[++i];
runtime.setTraceMode(Integer.decode(flagStr).intValue());
}
} else if (token.equals("-X")) {
System.out.println(
"Use 'java -X' to see the available non-standard options");
System.out.println();
usage();
System.exit(1);
} else if (
// Standard VM options passed on
token.equals("-v") || token.startsWith("-v:") || // -v[:...]
token.startsWith("-verbose") || // -verbose[:...]
token.startsWith("-D") ||
// NonStandard options passed on
token.startsWith("-X") ||
// Old-style options
// (These should remain in place as long as the standard VM accepts them)
token.equals("-noasyncgc") || token.equals("-prof") ||
token.equals("-verify") || token.equals("-noverify") ||
token.equals("-verifyremote") ||
token.equals("-verbosegc") ||
token.startsWith("-ms") || token.startsWith("-mx") ||
token.startsWith("-ss") || token.startsWith("-oss") ) {
javaArgs += token + " ";
} else if (token.equals("-sourcepath")) {
if (i == (argv.length - 1)) {
System.out.println("No sourcepath specified.");
usage();
System.exit(1);
}
env.getSourceManager().setSourcePath(new SearchPath(argv[++i]));
} else if (token.equals("-classpath")) {
if (i == (argv.length - 1)) {
System.out.println("No classpath specified.");
usage();
System.exit(1);
}
env.getClassManager().setClassPath(new SearchPath(argv[++i]));
} else if (token.equals("-remote")) {
if (i == (argv.length - 1)) {
System.out.println("No remote specified.");
usage();
System.exit(1);
}
env.getContextManager().setRemotePort(argv[++i]);
} else if (token.equals("-help")) {
usage();
System.exit(0);
} else if (token.equals("-version")) {
System.out.println(progname + " version " + version);
System.exit(0);
} else if (token.startsWith("-")) {
System.out.println("invalid option: " + token);
usage();
System.exit(1);
} else {
// Everything from here is part of the command line
clsName = token;
for (i++; i < argv.length; i++) {
progArgs += argv[i] + " ";
}
break;
}
}
context.setMainClassName(clsName);
context.setProgramArguments(progArgs);
context.setVmArguments(javaArgs);
// Force Cross Platform L&F
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
// If you want the System L&F instead, comment out the above line and
// uncomment the following:
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exc) {
System.err.println("Error loading L&F: " + exc);
}
JFrame frame = new JFrame();
frame.setBackground(Color.lightGray);
frame.setTitle(windowBanner);
frame.setJMenuBar(new JDBMenuBar(env));
frame.setContentPane(mainPanel);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
env.terminate();
}
});
frame.pack();
frame.setVisible(true);
}
}

View File

@@ -0,0 +1,218 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.Icon;
import javax.swing.ImageIcon;
class Icons {
private static int[] exec = {
0xffd8ffe0, 0x00104a46, 0x49460001, 0x01020000
, 0x00000000, 0xffdb0043, 0x00020101, 0x01010102
, 0x01010102, 0x02020202, 0x04030202, 0x02020504
, 0x04030406, 0x05060606, 0x05060606, 0x07090806
, 0x07090706, 0x06080b08, 0x090a0a0a, 0x0a0a0608
, 0x0b0c0b0a, 0x0c090a0a, 0x0affdb00, 0x43010202
, 0x02020202, 0x05030305, 0x0a070607, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0affc0
, 0x00110800, 0x0c000c03, 0x01220002, 0x11010311
, 0x01ffc400, 0x1f000001, 0x05010101, 0x01010100
, 0x00000000, 0x00000001, 0x02030405, 0x06070809
, 0x0a0bffc4, 0x00b51000, 0x02010303, 0x02040305
, 0x05040400, 0x00017d01, 0x02030004, 0x11051221
, 0x31410613, 0x51610722, 0x71143281, 0x91a10823
, 0x42b1c115, 0x52d1f024, 0x33627282, 0x090a1617
, 0x18191a25, 0x26272829, 0x2a343536, 0x3738393a
, 0x43444546, 0x4748494a, 0x53545556, 0x5758595a
, 0x63646566, 0x6768696a, 0x73747576, 0x7778797a
, 0x83848586, 0x8788898a, 0x92939495, 0x96979899
, 0x9aa2a3a4, 0xa5a6a7a8, 0xa9aab2b3, 0xb4b5b6b7
, 0xb8b9bac2, 0xc3c4c5c6, 0xc7c8c9ca, 0xd2d3d4d5
, 0xd6d7d8d9, 0xdae1e2e3, 0xe4e5e6e7, 0xe8e9eaf1
, 0xf2f3f4f5, 0xf6f7f8f9, 0xfaffc400, 0x1f010003
, 0x01010101, 0x01010101, 0x01000000, 0x00000001
, 0x02030405, 0x06070809, 0x0a0bffc4, 0x00b51100
, 0x02010204, 0x04030407, 0x05040400, 0x01027700
, 0x01020311, 0x04052131, 0x06124151, 0x07617113
, 0x22328108, 0x144291a1, 0xb1c10923, 0x3352f015
, 0x6272d10a, 0x162434e1, 0x25f11718, 0x191a2627
, 0x28292a35, 0x36373839, 0x3a434445, 0x46474849
, 0x4a535455, 0x56575859, 0x5a636465, 0x66676869
, 0x6a737475, 0x76777879, 0x7a828384, 0x85868788
, 0x898a9293, 0x94959697, 0x98999aa2, 0xa3a4a5a6
, 0xa7a8a9aa, 0xb2b3b4b5, 0xb6b7b8b9, 0xbac2c3c4
, 0xc5c6c7c8, 0xc9cad2d3, 0xd4d5d6d7, 0xd8d9dae2
, 0xe3e4e5e6, 0xe7e8e9ea, 0xf2f3f4f5, 0xf6f7f8f9
, 0xfaffda00, 0x0c030100, 0x02110311, 0x003f00fd
, 0xbafda27e, 0x35ea1f03, 0x346f0ef8, 0x86cfc2d3
, 0x6b31ea9e, 0x2ab7d2ee, 0xf4fb38cb, 0x5cc91cb0
, 0xce4790a0, 0xfcd2ef44, 0xc29e1f95, 0xf94b065f
, 0x42a86eb4, 0xed3ef67b, 0x7b9bcb18, 0x6692ce63
, 0x35a492c4, 0x19a090a3, 0x465d09fb, 0xadb1dd72
, 0x39daec3a, 0x13535706, 0x1f0f8ca7, 0x8dad56a5
, 0x5e6a72e5, 0xe485be0b, 0x2b49df77, 0xcceda6ca
, 0xda6ece3a, 0x147150c5, 0xd5a93a97, 0x84b97963
, 0x6f86cbde, 0x77ddf33b, 0x69b2b69b, 0xb3ffd900
};
private static int[] blank = {
0xffd8ffe0, 0x00104a46, 0x49460001, 0x01020000
, 0x00000000, 0xffdb0043, 0x00020101, 0x01010102
, 0x01010102, 0x02020202, 0x04030202, 0x02020504
, 0x04030406, 0x05060606, 0x05060606, 0x07090806
, 0x07090706, 0x06080b08, 0x090a0a0a, 0x0a0a0608
, 0x0b0c0b0a, 0x0c090a0a, 0x0affdb00, 0x43010202
, 0x02020202, 0x05030305, 0x0a070607, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0affc0
, 0x00110800, 0x0c000c03, 0x01220002, 0x11010311
, 0x01ffc400, 0x1f000001, 0x05010101, 0x01010100
, 0x00000000, 0x00000001, 0x02030405, 0x06070809
, 0x0a0bffc4, 0x00b51000, 0x02010303, 0x02040305
, 0x05040400, 0x00017d01, 0x02030004, 0x11051221
, 0x31410613, 0x51610722, 0x71143281, 0x91a10823
, 0x42b1c115, 0x52d1f024, 0x33627282, 0x090a1617
, 0x18191a25, 0x26272829, 0x2a343536, 0x3738393a
, 0x43444546, 0x4748494a, 0x53545556, 0x5758595a
, 0x63646566, 0x6768696a, 0x73747576, 0x7778797a
, 0x83848586, 0x8788898a, 0x92939495, 0x96979899
, 0x9aa2a3a4, 0xa5a6a7a8, 0xa9aab2b3, 0xb4b5b6b7
, 0xb8b9bac2, 0xc3c4c5c6, 0xc7c8c9ca, 0xd2d3d4d5
, 0xd6d7d8d9, 0xdae1e2e3, 0xe4e5e6e7, 0xe8e9eaf1
, 0xf2f3f4f5, 0xf6f7f8f9, 0xfaffc400, 0x1f010003
, 0x01010101, 0x01010101, 0x01000000, 0x00000001
, 0x02030405, 0x06070809, 0x0a0bffc4, 0x00b51100
, 0x02010204, 0x04030407, 0x05040400, 0x01027700
, 0x01020311, 0x04052131, 0x06124151, 0x07617113
, 0x22328108, 0x144291a1, 0xb1c10923, 0x3352f015
, 0x6272d10a, 0x162434e1, 0x25f11718, 0x191a2627
, 0x28292a35, 0x36373839, 0x3a434445, 0x46474849
, 0x4a535455, 0x56575859, 0x5a636465, 0x66676869
, 0x6a737475, 0x76777879, 0x7a828384, 0x85868788
, 0x898a9293, 0x94959697, 0x98999aa2, 0xa3a4a5a6
, 0xa7a8a9aa, 0xb2b3b4b5, 0xb6b7b8b9, 0xbac2c3c4
, 0xc5c6c7c8, 0xc9cad2d3, 0xd4d5d6d7, 0xd8d9dae2
, 0xe3e4e5e6, 0xe7e8e9ea, 0xf2f3f4f5, 0xf6f7f8f9
, 0xfaffda00, 0x0c030100, 0x02110311, 0x003f00fd
, 0xfca28a28, 0x03ffd900
};
private static int[] stopSignWords = {
0xffd8ffe0, 0x00104a46, 0x49460001, 0x01020000
, 0x00000000, 0xffdb0043, 0x00020101, 0x01010102
, 0x01010102, 0x02020202, 0x04030202, 0x02020504
, 0x04030406, 0x05060606, 0x05060606, 0x07090806
, 0x07090706, 0x06080b08, 0x090a0a0a, 0x0a0a0608
, 0x0b0c0b0a, 0x0c090a0a, 0x0affdb00, 0x43010202
, 0x02020202, 0x05030305, 0x0a070607, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a
, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0a0a0a, 0x0a0affc0
, 0x00110800, 0x0c000c03, 0x01220002, 0x11010311
, 0x01ffc400, 0x1f000001, 0x05010101, 0x01010100
, 0x00000000, 0x00000001, 0x02030405, 0x06070809
, 0x0a0bffc4, 0x00b51000, 0x02010303, 0x02040305
, 0x05040400, 0x00017d01, 0x02030004, 0x11051221
, 0x31410613, 0x51610722, 0x71143281, 0x91a10823
, 0x42b1c115, 0x52d1f024, 0x33627282, 0x090a1617
, 0x18191a25, 0x26272829, 0x2a343536, 0x3738393a
, 0x43444546, 0x4748494a, 0x53545556, 0x5758595a
, 0x63646566, 0x6768696a, 0x73747576, 0x7778797a
, 0x83848586, 0x8788898a, 0x92939495, 0x96979899
, 0x9aa2a3a4, 0xa5a6a7a8, 0xa9aab2b3, 0xb4b5b6b7
, 0xb8b9bac2, 0xc3c4c5c6, 0xc7c8c9ca, 0xd2d3d4d5
, 0xd6d7d8d9, 0xdae1e2e3, 0xe4e5e6e7, 0xe8e9eaf1
, 0xf2f3f4f5, 0xf6f7f8f9, 0xfaffc400, 0x1f010003
, 0x01010101, 0x01010101, 0x01000000, 0x00000001
, 0x02030405, 0x06070809, 0x0a0bffc4, 0x00b51100
, 0x02010204, 0x04030407, 0x05040400, 0x01027700
, 0x01020311, 0x04052131, 0x06124151, 0x07617113
, 0x22328108, 0x144291a1, 0xb1c10923, 0x3352f015
, 0x6272d10a, 0x162434e1, 0x25f11718, 0x191a2627
, 0x28292a35, 0x36373839, 0x3a434445, 0x46474849
, 0x4a535455, 0x56575859, 0x5a636465, 0x66676869
, 0x6a737475, 0x76777879, 0x7a828384, 0x85868788
, 0x898a9293, 0x94959697, 0x98999aa2, 0xa3a4a5a6
, 0xa7a8a9aa, 0xb2b3b4b5, 0xb6b7b8b9, 0xbac2c3c4
, 0xc5c6c7c8, 0xc9cad2d3, 0xd4d5d6d7, 0xd8d9dae2
, 0xe3e4e5e6, 0xe7e8e9ea, 0xf2f3f4f5, 0xf6f7f8f9
, 0xfaffda00, 0x0c030100, 0x02110311, 0x003f00f8
, 0xe7e37fc6, 0xff00197f, 0xc142fc65, 0x17ed5bfb
, 0x56db699e, 0x27f14f89, 0xf4cb7b85, 0x5bcd3924
, 0xb5d1ed5d, 0x3cc8b4db, 0x08a4ddf6, 0x6b387cc6
, 0x09182599, 0x99e595e5, 0x9e69a693, 0xbaf0dffc
, 0x1c9dff00, 0x050aff00, 0x82637837, 0x44fd94be
, 0x11e89f0f, 0xfc61e16d, 0x334c5b8f, 0x0f37c45d
, 0x26fef2eb, 0x46b56778, 0xd34db796, 0xd6fadbfd
, 0x0e2f2898, 0xa3903b42, 0xb21891d6, 0x08e08623
, 0xfe0e4ef0, 0xdf837fe0, 0x98dff050, 0xbb2f847f
, 0xb2978274, 0xcd33c2de, 0x30f87f69, 0xe2e6f0f5
, 0xe44ef6ba, 0x35d5c5fe, 0xa16b2dad, 0x8246d1f9
, 0x167fe84b, 0x2a40772c, 0x2d33c717, 0x9702c304
, 0x5fb0dff0, 0x4abff825, 0x5ffc13d7, 0xc55ff04f
, 0x5f845f17, 0x3e2e7ec8, 0xbf0ffe21, 0xf8a7e21f
, 0xc3fd1fc5, 0xde21f10f, 0xc45f0758, 0x6b774b75
, 0xa9584174, 0xf6b6ef75, 0x0b7d9ace, 0x1f304514
, 0x11ed50a8, 0x647f3279, 0x679e5fcf, 0x720cbb37
, 0xc3f1257a, 0x95eb7343, 0xdebabc9d, 0xeef4d1ab
, 0x2b7e1b2d, 0x0fec0f16, 0xb8c7c3cc, 0xdbc15caf
, 0x0795e59e, 0xc710fd97, 0x2cfd9d38, 0xf2f241aa
, 0x9efc64e5, 0x2e67dd7b, 0xdf14acd1, 0xffd90000
};
static private byte[] wordsToBytes(int[] wordArray) {
byte[] bytes = new byte[wordArray.length * 4];
int inx = bytes.length;
for (int i = wordArray.length-1; i >= 0; --i) {
int word = wordArray[i];
for (int j = 0; j < 4; ++j) {
bytes[--inx] = (byte)(word & 0xff);
word = word >>> 8;
}
}
return bytes;
}
static Icon stopSignIcon = new ImageIcon(wordsToBytes(stopSignWords));
static Icon blankIcon = new ImageIcon(wordsToBytes(blank));
static Icon execIcon = new ImageIcon(wordsToBytes(exec));
}

View File

@@ -0,0 +1,278 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.File;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.filechooser.*;
//### Renamed from 'ExampleFileFilter.java' provided with Swing demos.
/**
* A convenience implementation of FileFilter that filters out
* all files except for those type extensions that it knows about.
*
* Extensions are of the type ".foo", which is typically found on
* Windows and Unix boxes, but not on Macinthosh. Case is ignored.
*
* Example - create a new filter that filerts out all files
* but gif and jpg image files:
*
* JFileChooser chooser = new JFileChooser();
* ExampleFileFilter filter = new ExampleFileFilter(
* new String{"gif", "jpg"}, "JPEG & GIF Images")
* chooser.addChoosableFileFilter(filter);
* chooser.showOpenDialog(this);
*
* @author Jeff Dinkins
*/
public class JDBFileFilter extends FileFilter {
private static String TYPE_UNKNOWN = "Type Unknown";
private static String HIDDEN_FILE = "Hidden File";
private Hashtable<String, JDBFileFilter> filters = null;
private String description = null;
private String fullDescription = null;
private boolean useExtensionsInDescription = true;
/**
* Creates a file filter. If no filters are added, then all
* files are accepted.
*
* @see #addExtension
*/
public JDBFileFilter() {
this.filters = new Hashtable<String, JDBFileFilter>();
}
/**
* Creates a file filter that accepts files with the given extension.
* Example: new JDBFileFilter("jpg");
*
* @see #addExtension
*/
public JDBFileFilter(String extension) {
this(extension,null);
}
/**
* Creates a file filter that accepts the given file type.
* Example: new JDBFileFilter("jpg", "JPEG Image Images");
*
* Note that the "." before the extension is not needed. If
* provided, it will be ignored.
*
* @see #addExtension
*/
public JDBFileFilter(String extension, String description) {
this();
if(extension!=null) {
addExtension(extension);
}
if(description!=null) {
setDescription(description);
}
}
/**
* Creates a file filter from the given string array.
* Example: new JDBFileFilter(String {"gif", "jpg"});
*
* Note that the "." before the extension is not needed adn
* will be ignored.
*
* @see #addExtension
*/
public JDBFileFilter(String[] filters) {
this(filters, null);
}
/**
* Creates a file filter from the given string array and description.
* Example: new JDBFileFilter(String {"gif", "jpg"}, "Gif and JPG Images");
*
* Note that the "." before the extension is not needed and will be ignored.
*
* @see #addExtension
*/
public JDBFileFilter(String[] filters, String description) {
this();
for (String filter : filters) {
// add filters one by one
addExtension(filter);
}
if(description!=null) {
setDescription(description);
}
}
/**
* Return true if this file should be shown in the directory pane,
* false if it shouldn't.
*
* Files that begin with "." are ignored.
*
* @see #getExtension
* @see FileFilter#accepts
*/
@Override
public boolean accept(File f) {
if(f != null) {
if(f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if(extension != null && filters.get(getExtension(f)) != null) {
return true;
};
}
return false;
}
/**
* Return the extension portion of the file's name .
*
* @see #getExtension
* @see FileFilter#accept
*/
public String getExtension(File f) {
if(f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if(i>0 && i<filename.length()-1) {
return filename.substring(i+1).toLowerCase();
};
}
return null;
}
/**
* Adds a filetype "dot" extension to filter against.
*
* For example: the following code will create a filter that filters
* out all files except those that end in ".jpg" and ".tif":
*
* JDBFileFilter filter = new JDBFileFilter();
* filter.addExtension("jpg");
* filter.addExtension("tif");
*
* Note that the "." before the extension is not needed and will be ignored.
*/
public void addExtension(String extension) {
if(filters == null) {
filters = new Hashtable<String, JDBFileFilter>(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
/**
* Returns the human readable description of this filter. For
* example: "JPEG and GIF Image Files (*.jpg, *.gif)"
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
* @see FileFilter#getDescription
*/
@Override
public String getDescription() {
if(fullDescription == null) {
if(description == null || isExtensionListInDescription()) {
fullDescription = description==null ? "(" : description + " (";
// build the description from the extension list
Enumeration<String> extensions = filters.keys();
if(extensions != null) {
fullDescription += "." + extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", " + extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
}
/**
* Sets the human readable description of this filter. For
* example: filter.setDescription("Gif and JPG Images");
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
*/
public void setDescription(String description) {
this.description = description;
fullDescription = null;
}
/**
* Determines whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see isExtensionListInDescription
*/
public void setExtensionListInDescription(boolean b) {
useExtensionsInDescription = b;
fullDescription = null;
}
/**
* Returns whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see setExtensionListInDescription
*/
public boolean isExtensionListInDescription() {
return useExtensionsInDescription;
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import java.util.List;
import com.sun.tools.example.debug.bdi.*;
//### This is currently just a placeholder!
class JDBMenuBar extends JMenuBar {
Environment env;
ExecutionManager runtime;
ClassManager classManager;
SourceManager sourceManager;
CommandInterpreter interpreter;
JDBMenuBar(Environment env) {
this.env = env;
this.runtime = env.getExecutionManager();
this.classManager = env.getClassManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env, true);
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open...", 'O');
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openCommand();
}
});
fileMenu.add(openItem);
addTool(fileMenu, "Exit debugger", "Exit", "exit");
JMenu cmdMenu = new JMenu("Commands");
addTool(cmdMenu, "Step into next line", "Step", "step");
addTool(cmdMenu, "Step over next line", "Next", "next");
cmdMenu.addSeparator();
addTool(cmdMenu, "Step into next instruction",
"Step Instruction", "stepi");
addTool(cmdMenu, "Step over next instruction",
"Next Instruction", "nexti");
cmdMenu.addSeparator();
addTool(cmdMenu, "Step out of current method call",
"Step Up", "step up");
cmdMenu.addSeparator();
addTool(cmdMenu, "Suspend execution", "Interrupt", "interrupt");
addTool(cmdMenu, "Continue execution", "Continue", "cont");
cmdMenu.addSeparator();
addTool(cmdMenu, "Display current stack", "Where", "where");
cmdMenu.addSeparator();
addTool(cmdMenu, "Move up one stack frame", "Up", "up");
addTool(cmdMenu, "Move down one stack frame", "Down", "down");
cmdMenu.addSeparator();
JMenuItem monitorItem = new JMenuItem("Monitor Expression...", 'M');
monitorItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
monitorCommand();
}
});
cmdMenu.add(monitorItem);
JMenuItem unmonitorItem = new JMenuItem("Unmonitor Expression...");
unmonitorItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
unmonitorCommand();
}
});
cmdMenu.add(unmonitorItem);
JMenu breakpointMenu = new JMenu("Breakpoint");
JMenuItem stopItem = new JMenuItem("Stop in...", 'S');
stopItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buildBreakpoint();
}
});
breakpointMenu.add(stopItem);
JMenu helpMenu = new JMenu("Help");
addTool(helpMenu, "Display command list", "Help", "help");
this.add(fileMenu);
this.add(cmdMenu);
// this.add(breakpointMenu);
this.add(helpMenu);
}
private void buildBreakpoint() {
Frame frame = JOptionPane.getRootFrame();
JDialog dialog = new JDialog(frame, "Specify Breakpoint");
Container contents = dialog.getContentPane();
Vector<String> classes = new Vector<String>();
classes.add("Foo");
classes.add("Bar");
JList list = new JList(classes);
JScrollPane scrollPane = new JScrollPane(list);
contents.add(scrollPane);
dialog.show();
}
private void monitorCommand() {
String expr = (String)JOptionPane.showInputDialog(null,
"Expression to monitor:", "Add Monitor",
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (expr != null) {
interpreter.executeCommand("monitor " + expr);
}
}
private void unmonitorCommand() {
List monitors = env.getMonitorListModel().monitors();
String expr = (String)JOptionPane.showInputDialog(null,
"Expression to unmonitor:", "Remove Monitor",
JOptionPane.QUESTION_MESSAGE, null,
monitors.toArray(),
monitors.get(monitors.size()-1));
if (expr != null) {
interpreter.executeCommand("unmonitor " + expr);
}
}
private void openCommand() {
JFileChooser chooser = new JFileChooser();
JDBFileFilter filter = new JDBFileFilter("java", "Java source code");
chooser.setFileFilter(filter);
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Chose file: " + chooser.getSelectedFile().getName());
}
}
private void addTool(JMenu menu, String toolTip, String labelText,
String command) {
JMenuItem mi = new JMenuItem(labelText);
mi.setToolTipText(toolTip);
final String cmd = command;
mi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(cmd);
}
});
menu.add(mi);
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import java.awt.event.*;
import com.sun.tools.example.debug.bdi.*;
class JDBToolBar extends JToolBar {
Environment env;
ExecutionManager runtime;
ClassManager classManager;
SourceManager sourceManager;
CommandInterpreter interpreter;
JDBToolBar(Environment env) {
this.env = env;
this.runtime = env.getExecutionManager();
this.classManager = env.getClassManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env, true);
//===== Configure toolbar here =====
addTool("Run application", "run", "run");
addTool("Connect to application", "connect", "connect");
addSeparator();
addTool("Step into next line", "step", "step");
addTool("Step over next line", "next", "next");
// addSeparator();
// addTool("Step into next instruction", "stepi", "stepi");
// addTool("Step over next instruction", "nexti", "nexti");
// addSeparator();
addTool("Step out of current method call", "step up", "step up");
addSeparator();
addTool("Suspend execution", "interrupt", "interrupt");
addTool("Continue execution", "cont", "cont");
addSeparator();
// addTool("Display current stack", "where", "where");
// addSeparator();
addTool("Move up one stack frame", "up", "up");
addTool("Move down one stack frame", "down", "down");
// addSeparator();
// addTool("Display command list", "help", "help");
// addSeparator();
// addTool("Exit debugger", "exit", "exit");
//==================================
}
private void addTool(String toolTip, String labelText, String command) {
JButton button = new JButton(labelText);
button.setToolTipText(toolTip);
final String cmd = command;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(cmd);
}
});
this.add(button);
}
}

View File

@@ -0,0 +1,272 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import com.sun.jdi.*;
import com.sun.jdi.connect.*;
import com.sun.tools.example.debug.bdi.*;
class LaunchTool {
private final ExecutionManager runtime;
private abstract class ArgRep {
final Connector.Argument arg;
final JPanel panel;
ArgRep(Connector.Argument arg) {
this.arg = arg;
panel = new JPanel();
Border etched = BorderFactory.createEtchedBorder();
Border titled = BorderFactory.createTitledBorder(etched,
arg.description(),
TitledBorder.LEFT, TitledBorder.TOP);
panel.setBorder(titled);
}
abstract String getText();
boolean isValid() {
return arg.isValid(getText());
}
boolean isSpecified() {
String value = getText();
return (value != null && value.length() > 0) ||
!arg.mustSpecify();
}
void install() {
arg.setValue(getText());
}
}
private class StringArgRep extends ArgRep {
final JTextField textField;
StringArgRep(Connector.Argument arg, JPanel comp) {
super(arg);
textField = new JTextField(arg.value(), 50 );
textField.setBorder(BorderFactory.createLoweredBevelBorder());
panel.add(new JLabel(arg.label(), SwingConstants.RIGHT));
panel.add(textField); // , BorderLayout.CENTER);
comp.add(panel);
}
@Override
String getText() {
return textField.getText();
}
}
private class BooleanArgRep extends ArgRep {
final JCheckBox check;
BooleanArgRep(Connector.BooleanArgument barg, JPanel comp) {
super(barg);
check = new JCheckBox(barg.label());
check.setSelected(barg.booleanValue());
panel.add(check);
comp.add(panel);
}
@Override
String getText() {
return ((Connector.BooleanArgument)arg)
.stringValueOf(check.getModel().isSelected());
}
}
private LaunchTool(ExecutionManager runtime) {
this.runtime = runtime;
}
private Connector selectConnector() {
final JDialog dialog = new JDialog();
Container content = dialog.getContentPane();
final JPanel radioPanel = new JPanel();
final ButtonGroup radioGroup = new ButtonGroup();
VirtualMachineManager manager = Bootstrap.virtualMachineManager();
List<Connector> all = manager.allConnectors();
Map<ButtonModel, Connector> modelToConnector = new HashMap<ButtonModel, Connector>(all.size(), 0.5f);
dialog.setModal(true);
dialog.setTitle("Select Connector Type");
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
for (Connector connector : all) {
JRadioButton radio = new JRadioButton(connector.description());
modelToConnector.put(radio.getModel(), connector);
radioPanel.add(radio);
radioGroup.add(radio);
}
content.add(radioPanel);
final boolean[] oked = {false};
JPanel buttonPanel = okCancel( dialog, new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (radioGroup.getSelection() == null) {
JOptionPane.showMessageDialog(dialog,
"Please select a connector type",
"No Selection",
JOptionPane.ERROR_MESSAGE);
} else {
oked[0] = true;
dialog.setVisible(false);
dialog.dispose();
}
}
} );
content.add(BorderLayout.SOUTH, buttonPanel);
dialog.pack();
dialog.setVisible(true);
return oked[0] ?
modelToConnector.get(radioGroup.getSelection()) :
null;
}
private void configureAndConnect(final Connector connector) {
final JDialog dialog = new JDialog();
final Map<String, Connector.Argument> args = connector.defaultArguments();
dialog.setModal(true);
dialog.setTitle("Connector Arguments");
Container content = dialog.getContentPane();
JPanel guts = new JPanel();
Border etched = BorderFactory.createEtchedBorder();
BorderFactory.createTitledBorder(etched,
connector.description(),
TitledBorder.LEFT, TitledBorder.TOP);
guts.setBorder(etched);
guts.setLayout(new BoxLayout(guts, BoxLayout.Y_AXIS));
// guts.add(new JLabel(connector.description()));
final List<ArgRep> argReps = new ArrayList<ArgRep>(args.size());
for (Connector.Argument arg : args.values()) {
ArgRep ar;
if (arg instanceof Connector.BooleanArgument) {
ar = new BooleanArgRep((Connector.BooleanArgument)arg, guts);
} else {
ar = new StringArgRep(arg, guts);
}
argReps.add(ar);
}
content.add(guts);
JPanel buttonPanel = okCancel( dialog, new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
for (ArgRep ar : argReps) {
if (!ar.isSpecified()) {
JOptionPane.showMessageDialog(dialog,
ar.arg.label() +
": Argument must be specified",
"No argument", JOptionPane.ERROR_MESSAGE);
return;
}
if (!ar.isValid()) {
JOptionPane.showMessageDialog(dialog,
ar.arg.label() +
": Bad argument value: " +
ar.getText(),
"Bad argument", JOptionPane.ERROR_MESSAGE);
return;
}
ar.install();
}
try {
if (runtime.explictStart(connector, args)) {
dialog.setVisible(false);
dialog.dispose();
} else {
JOptionPane.showMessageDialog(dialog,
"Bad arguments values: See diagnostics window.",
"Bad arguments", JOptionPane.ERROR_MESSAGE);
}
} catch (VMLaunchFailureException exc) {
JOptionPane.showMessageDialog(dialog,
"Launch Failure: " + exc,
"Launch Failed",JOptionPane.ERROR_MESSAGE);
}
}
} );
content.add(BorderLayout.SOUTH, buttonPanel);
dialog.pack();
dialog.setVisible(true);
}
private JPanel okCancel(final JDialog dialog, ActionListener okListener) {
JPanel buttonPanel = new JPanel();
JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
buttonPanel.add(ok);
buttonPanel.add(cancel);
ok.addActionListener(okListener);
cancel.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
dialog.setVisible(false);
dialog.dispose();
}
} );
return buttonPanel;
}
static void queryAndLaunchVM(ExecutionManager runtime)
throws VMLaunchFailureException {
LaunchTool lt = new LaunchTool(runtime);
Connector connector = lt.selectConnector();
if (connector != null) {
lt.configureAndConnect(connector);
}
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.*;
import javax.swing.AbstractListModel;
public class MonitorListModel extends AbstractListModel {
private final List<String> monitors = new ArrayList<String>();
MonitorListModel(Environment env) {
// Create listener.
MonitorListListener listener = new MonitorListListener();
env.getContextManager().addContextListener(listener);
//### remove listeners on exit!
}
@Override
public Object getElementAt(int index) {
return monitors.get(index);
}
@Override
public int getSize() {
return monitors.size();
}
public void add(String expr) {
monitors.add(expr);
int newIndex = monitors.size()-1; // order important
fireIntervalAdded(this, newIndex, newIndex);
}
public void remove(String expr) {
int index = monitors.indexOf(expr);
remove(index);
}
public void remove(int index) {
monitors.remove(index);
fireIntervalRemoved(this, index, index);
}
public List<String> monitors() {
return Collections.unmodifiableList(monitors);
}
public Iterator<?> iterator() {
return monitors().iterator();
}
private void invalidate() {
fireContentsChanged(this, 0, monitors.size()-1);
}
private class MonitorListListener implements ContextListener {
@Override
public void currentFrameChanged(final CurrentFrameChangedEvent e) {
invalidate();
}
}
}

View File

@@ -0,0 +1,134 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
import com.sun.tools.example.debug.expr.ExpressionParser;
import com.sun.tools.example.debug.expr.ParseException;
public class MonitorTool extends JPanel {
private static final long serialVersionUID = -645235951031726647L;
private ExecutionManager runtime;
private ContextManager context;
private JList list;
public MonitorTool(Environment env) {
super(new BorderLayout());
this.runtime = env.getExecutionManager();
this.context = env.getContextManager();
list = new JList(env.getMonitorListModel());
list.setCellRenderer(new MonitorRenderer());
JScrollPane listView = new JScrollPane(list);
add(listView);
// Create listener.
MonitorToolListener listener = new MonitorToolListener();
list.addListSelectionListener(listener);
//### remove listeners on exit!
}
private class MonitorToolListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
int index = list.getSelectedIndex();
if (index != -1) {
}
}
}
private Value evaluate(String expr) throws ParseException,
InvocationException,
InvalidTypeException,
ClassNotLoadedException,
IncompatibleThreadStateException {
ExpressionParser.GetFrame frameGetter =
new ExpressionParser.GetFrame() {
@Override
public StackFrame get()
throws IncompatibleThreadStateException
{
try {
return context.getCurrentFrame();
} catch (VMNotInterruptedException exc) {
throw new IncompatibleThreadStateException();
}
}
};
return ExpressionParser.evaluate(expr, runtime.vm(), frameGetter);
}
private class MonitorRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//### We should indicate the current thread independently of the
//### selection, e.g., with an icon, because the user may change
//### the selection graphically without affecting the current
//### thread.
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value == null) {
this.setText("<unavailable>");
} else {
String expr = (String)value;
try {
Value result = evaluate(expr);
this.setText(expr + " = " + result);
} catch (ParseException exc) {
this.setText(expr + " ? " + exc.getMessage());
} catch (IncompatibleThreadStateException exc) {
this.setText(expr + " ...");
} catch (Exception exc) {
this.setText(expr + " ? " + exc);
}
}
return this;
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
// This class is used in 'CommandInterpreter' as a hook to
// allow messagebox style command output as an alternative
// to a typescript. It should be an interface, not a class.
public class OutputSink extends PrintWriter {
// Currently, we do no buffering,
// so 'show' is a no-op.
OutputSink(Writer writer) {
super(writer);
}
public void show() {
// ignore
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
public class SearchPath {
private String pathString;
private String[] pathArray;
public SearchPath(String searchPath) {
//### Should check searchpath for well-formedness.
StringTokenizer st = new StringTokenizer(searchPath, File.pathSeparator);
List<String> dlist = new ArrayList<String>();
while (st.hasMoreTokens()) {
dlist.add(st.nextToken());
}
pathString = searchPath;
pathArray = dlist.toArray(new String[dlist.size()]);
}
public boolean isEmpty() {
return (pathArray.length == 0);
}
public String asString() {
return pathString;
}
public String[] asArray() {
return pathArray.clone();
}
public File resolve(String relativeFileName) {
for (String element : pathArray) {
File path = new File(element, relativeFileName);
if (path.exists()) {
return path;
}
}
return null;
}
//### return List?
public String[] children(String relativeDirName, FilenameFilter filter) {
// If a file appears at the same relative path
// with respect to multiple entries on the classpath,
// the one corresponding to the earliest entry on the
// classpath is retained. This is the one that will be
// found if we later do a 'resolve'.
SortedSet<String> s = new TreeSet<String>(); // sorted, no duplicates
for (String element : pathArray) {
File path = new File(element, relativeDirName);
if (path.exists()) {
String[] childArray = path.list(filter);
if (childArray != null) {
for (int j = 0; j < childArray.length; j++) {
if (!s.contains(childArray[j])) {
s.add(childArray[j]);
}
}
}
}
}
return s.toArray(new String[s.size()]);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.tree.*;
public class SingleLeafTreeSelectionModel extends DefaultTreeSelectionModel {
private static final long serialVersionUID = -7849105107888117679L;
SingleLeafTreeSelectionModel() {
super();
selectionMode = SINGLE_TREE_SELECTION;
}
@Override
public void setSelectionPath(TreePath path) {
if(((TreeNode)(path.getLastPathComponent())).isLeaf()) {
super.setSelectionPath(path);
}
}
@Override
public void setSelectionPaths(TreePath[] paths) {
// Only look at first path, as all others will be
// ignored anyway in single tree selection mode.
if(((TreeNode)(paths[0].getLastPathComponent())).isLeaf()) {
super.setSelectionPaths(paths);
}
}
@Override
public void addSelectionPath(TreePath path) {
if(((TreeNode)(path.getLastPathComponent())).isLeaf()) {
super.setSelectionPath(path);
}
}
@Override
public void addSelectionPaths(TreePath[] paths) {
// Only look at first path, as all others will be
// ignored anyway in single tree selection mode.
if(((TreeNode)(paths[0].getLastPathComponent())).isLeaf()) {
super.addSelectionPaths(paths);
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
public interface SourceListener {
void sourcepathChanged(SourcepathChangedEvent e);
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
/**
* Manage the list of source files.
* Origin of SourceListener events.
*/
public class SourceManager {
//### TODO: The source cache should be aged, and some cap
//### put on memory consumption by source files loaded into core.
private List<SourceModel> sourceList;
private SearchPath sourcePath;
private ArrayList<SourceListener> sourceListeners = new ArrayList<SourceListener>();
private Map<ReferenceType, SourceModel> classToSource = new HashMap<ReferenceType, SourceModel>();
private Environment env;
/**
* Hold on to it so it can be removed.
*/
private SMClassListener classListener = new SMClassListener();
public SourceManager(Environment env) {
this(env, new SearchPath(""));
}
public SourceManager(Environment env, SearchPath sourcePath) {
this.env = env;
this.sourceList = new LinkedList<SourceModel>();
this.sourcePath = sourcePath;
env.getExecutionManager().addJDIListener(classListener);
}
/**
* Set path for access to source code.
*/
public void setSourcePath(SearchPath sp) {
sourcePath = sp;
// Old cached sources are now invalid.
sourceList = new LinkedList<SourceModel>();
notifySourcepathChanged();
classToSource = new HashMap<ReferenceType, SourceModel>();
}
public void addSourceListener(SourceListener l) {
sourceListeners.add(l);
}
public void removeSourceListener(SourceListener l) {
sourceListeners.remove(l);
}
private void notifySourcepathChanged() {
ArrayList<SourceListener> l = new ArrayList<SourceListener>(sourceListeners);
SourcepathChangedEvent evt = new SourcepathChangedEvent(this);
for (int i = 0; i < l.size(); i++) {
l.get(i).sourcepathChanged(evt);
}
}
/**
* Get path for access to source code.
*/
public SearchPath getSourcePath() {
return sourcePath;
}
/**
* Get source object associated with a Location.
*/
public SourceModel sourceForLocation(Location loc) {
return sourceForClass(loc.declaringType());
}
/**
* Get source object associated with a class or interface.
* Returns null if not available.
*/
public SourceModel sourceForClass(ReferenceType refType) {
SourceModel sm = classToSource.get(refType);
if (sm != null) {
return sm;
}
try {
String filename = refType.sourceName();
String refName = refType.name();
int iDot = refName.lastIndexOf('.');
String pkgName = (iDot >= 0)? refName.substring(0, iDot+1) : "";
String full = pkgName.replace('.', File.separatorChar) + filename;
File path = sourcePath.resolve(full);
if (path != null) {
sm = sourceForFile(path);
classToSource.put(refType, sm);
return sm;
}
return null;
} catch (AbsentInformationException e) {
return null;
}
}
/**
* Get source object associated with an absolute file path.
*/
//### Use hash table for this?
public SourceModel sourceForFile(File path) {
Iterator<SourceModel> iter = sourceList.iterator();
SourceModel sm = null;
while (iter.hasNext()) {
SourceModel candidate = iter.next();
if (candidate.fileName().equals(path)) {
sm = candidate;
iter.remove(); // Will move to start of list.
break;
}
}
if (sm == null && path.exists()) {
sm = new SourceModel(env, path);
}
if (sm != null) {
// At start of list for faster access
sourceList.add(0, sm);
}
return sm;
}
private class SMClassListener extends JDIAdapter
implements JDIListener {
@Override
public void classPrepare(ClassPrepareEventSet e) {
ReferenceType refType = e.getReferenceType();
SourceModel sm = sourceForClass(refType);
if (sm != null) {
sm.addClass(refType);
}
}
@Override
public void classUnload(ClassUnloadEventSet e) {
//### iterate through looking for (e.getTypeName()).
//### then remove it.
}
}
}

View File

@@ -0,0 +1,256 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
import javax.swing.*;
/**
* Represents and manages one source file.
* Caches source lines. Holds other source file info.
*/
public class SourceModel extends AbstractListModel {
private File path;
boolean isActuallySource = true;
private List<ReferenceType> classes = new ArrayList<ReferenceType>();
private Environment env;
// Cached line-by-line access.
//### Unify this with source model used in source view?
//### What is our cache-management policy for these?
//### Even with weak refs, we won't discard any part of the
//### source if the SourceModel object is reachable.
/**
* List of Line.
*/
private List<Line> sourceLines = null;
public static class Line {
public String text;
public boolean hasBreakpoint = false;
public ReferenceType refType = null;
Line(String text) {
this.text = text;
}
public boolean isExecutable() {
return refType != null;
}
public boolean hasBreakpoint() {
return hasBreakpoint;
}
};
// 132 characters long, all printable characters.
public static final Line prototypeCellValue = new Line(
"abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"1234567890~!@#$%^&*()_+{}|" +
":<>?`-=[];',.XXXXXXXXXXXX/\\\"");
SourceModel(Environment env, File path) {
this.env = env;
this.path = path;
}
public SourceModel(String message) {
this.path = null;
setMessage(message);
}
private void setMessage(String message) {
isActuallySource = false;
sourceLines = new ArrayList<Line>();
sourceLines.add(new Line(message));
}
// **** Implement ListModel *****
@Override
public Object getElementAt(int index) {
if (sourceLines == null) {
initialize();
}
return sourceLines.get(index);
}
@Override
public int getSize() {
if (sourceLines == null) {
initialize();
}
return sourceLines.size();
}
// ***** Other functionality *****
public File fileName() {
return path;
}
public BufferedReader sourceReader() throws IOException {
return new BufferedReader(new FileReader(path));
}
public Line line(int lineNo) {
if (sourceLines == null) {
initialize();
}
int index = lineNo - 1; // list is 0-indexed
if (index >= sourceLines.size() || index < 0) {
return null;
} else {
return sourceLines.get(index);
}
}
public String sourceLine(int lineNo) {
Line line = line(lineNo);
if (line == null) {
return null;
} else {
return line.text;
}
}
void addClass(ReferenceType refType) {
// Logically is Set
if (classes.indexOf(refType) == -1) {
classes.add(refType);
if (sourceLines != null) {
markClassLines(refType);
}
}
}
/**
* @return List of currently known {@link com.sun.jdi.ReferenceType}
* in this source file.
*/
public List<ReferenceType> referenceTypes() {
return Collections.unmodifiableList(classes);
}
private void initialize() {
try {
rawInit();
} catch (IOException exc) {
setMessage("[Error reading source code]");
}
}
public void showBreakpoint(int ln, boolean hasBreakpoint) {
line(ln).hasBreakpoint = hasBreakpoint;
fireContentsChanged(this, ln, ln);
}
public void showExecutable(int ln, ReferenceType refType) {
line(ln).refType = refType;
fireContentsChanged(this, ln, ln);
}
/**
* Mark executable lines and breakpoints, but only
* when sourceLines is set.
*/
private void markClassLines(ReferenceType refType) {
for (Method meth : refType.methods()) {
try {
for (Location loc : meth.allLineLocations()) {
showExecutable(loc.lineNumber(), refType);
}
} catch (AbsentInformationException exc) {
// do nothing
}
}
for (BreakpointRequest bp :
env.getExecutionManager().eventRequestManager().breakpointRequests()) {
if (bp.location() != null) {
Location loc = bp.location();
if (loc.declaringType().equals(refType)) {
showBreakpoint(loc.lineNumber(),true);
}
}
}
}
private void rawInit() throws IOException {
sourceLines = new ArrayList<Line>();
BufferedReader reader = sourceReader();
try {
String line = reader.readLine();
while (line != null) {
sourceLines.add(new Line(expandTabs(line)));
line = reader.readLine();
}
} finally {
reader.close();
}
for (ReferenceType refType : classes) {
markClassLines(refType);
}
}
private String expandTabs(String s) {
int col = 0;
int len = s.length();
StringBuffer sb = new StringBuffer(132);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
sb.append(c);
if (c == '\t') {
int pad = (8 - (col % 8));
for (int j = 0; j < pad; j++) {
sb.append(' ');
}
col += pad;
} else {
col++;
}
}
return sb.toString();
}
}

View File

@@ -0,0 +1,392 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.sun.jdi.*;
import com.sun.jdi.request.*;
import com.sun.tools.example.debug.bdi.*;
public class SourceTool extends JPanel {
private static final long serialVersionUID = -5461299294186395257L;
private Environment env;
private ExecutionManager runtime;
private ContextManager context;
private SourceManager sourceManager;
private JList list;
private ListModel sourceModel;
// Information on source file that is on display, or failed to be
// displayed due to inaccessible source. Used to update display
// when sourcepath is changed.
private String sourceName; // relative path name, if showSourceFile
private Location sourceLocn; // location, if showSourceForLocation
private CommandInterpreter interpreter;
public SourceTool(Environment env) {
super(new BorderLayout());
this.env = env;
runtime = env.getExecutionManager();
sourceManager = env.getSourceManager();
this.context = env.getContextManager();
this.interpreter = new CommandInterpreter(env, true);
sourceModel = new DefaultListModel(); // empty
list = new JList(sourceModel);
list.setCellRenderer(new SourceLineRenderer());
list.setPrototypeCellValue(SourceModel.prototypeCellValue);
SourceToolListener listener = new SourceToolListener();
context.addContextListener(listener);
runtime.addSpecListener(listener);
sourceManager.addSourceListener(listener);
MouseListener squeek = new STMouseListener();
list.addMouseListener(squeek);
add(new JScrollPane(list));
}
public void setTextFont(Font f) {
list.setFont(f);
list.setPrototypeCellValue(SourceModel.prototypeCellValue);
}
private class SourceToolListener
implements ContextListener, SourceListener, SpecListener
{
// ContextListener
@Override
public void currentFrameChanged(CurrentFrameChangedEvent e) {
showSourceContext(e.getThread(), e.getIndex());
}
// Clear source view.
// sourceModel = new DefaultListModel(); // empty
// SourceListener
@Override
public void sourcepathChanged(SourcepathChangedEvent e) {
// Reload source view if its contents depend
// on the source path.
if (sourceName != null) {
showSourceFile(sourceName);
} else if (sourceLocn != null) {
showSourceForLocation(sourceLocn);
}
}
// SpecListener
@Override
public void breakpointSet(SpecEvent e) {
breakpointResolved(e);
}
@Override
public void breakpointDeferred(SpecEvent e) { }
@Override
public void breakpointDeleted(SpecEvent e) {
BreakpointRequest req = (BreakpointRequest)e.getEventRequest();
Location loc = req.location();
if (loc != null) {
try {
SourceModel sm = sourceManager.sourceForLocation(loc);
sm.showBreakpoint(loc.lineNumber(), false);
showSourceForLocation(loc);
} catch (Exception exc) {
}
}
}
@Override
public void breakpointResolved(SpecEvent e) {
BreakpointRequest req = (BreakpointRequest)e.getEventRequest();
Location loc = req.location();
try {
SourceModel sm = sourceManager.sourceForLocation(loc);
sm.showBreakpoint(loc.lineNumber(), true);
showSourceForLocation(loc);
} catch (Exception exc) {
}
}
@Override
public void breakpointError(SpecErrorEvent e) {
breakpointDeleted(e);
}
@Override
public void watchpointSet(SpecEvent e) {
}
@Override
public void watchpointDeferred(SpecEvent e) {
}
@Override
public void watchpointDeleted(SpecEvent e) {
}
@Override
public void watchpointResolved(SpecEvent e) {
}
@Override
public void watchpointError(SpecErrorEvent e) {
}
@Override
public void exceptionInterceptSet(SpecEvent e) {
}
@Override
public void exceptionInterceptDeferred(SpecEvent e) {
}
@Override
public void exceptionInterceptDeleted(SpecEvent e) {
}
@Override
public void exceptionInterceptResolved(SpecEvent e) {
}
@Override
public void exceptionInterceptError(SpecErrorEvent e) {
}
}
private void showSourceContext(ThreadReference thread, int index) {
//### Should use ThreadInfo here.
StackFrame frame = null;
if (thread != null) {
try {
frame = thread.frame(index);
} catch (IncompatibleThreadStateException e) {}
}
if (frame == null) {
return;
}
Location locn = frame.location();
/*****
if (!showSourceForLocation(locn)) {
env.notice("Could not display source for "
+ Utils.locationString(locn));
}
*****/
showSourceForLocation(locn);
}
public boolean showSourceForLocation(Location locn) {
sourceName = null;
sourceLocn = locn;
int lineNo = locn.lineNumber();
if (lineNo != -1) {
SourceModel source = sourceManager.sourceForLocation(locn);
if (source != null) {
showSourceAtLine(source, lineNo-1);
return true;
}
}
// Here if we could not display source.
showSourceUnavailable();
return false;
}
public boolean showSourceFile(String fileName) {
sourceLocn = null;
File file;
if (!fileName.startsWith(File.separator)) {
sourceName = fileName;
SearchPath sourcePath = sourceManager.getSourcePath();
file = sourcePath.resolve(fileName);
if (file == null) {
//env.failure("Source not found on current source path.");
showSourceUnavailable();
return false;
}
} else {
sourceName = null; // Absolute pathname does not depend on sourcepath.
file = new File(fileName);
}
SourceModel source = sourceManager.sourceForFile(file);
if (source != null) {
showSource(source);
return true;
}
showSourceUnavailable();
return false;
}
private void showSource(SourceModel model) {
setViewModel(model);
}
private void showSourceAtLine(SourceModel model, int lineNo) {
setViewModel(model);
if (model.isActuallySource && (lineNo < model.getSize())) {
list.setSelectedIndex(lineNo);
if (lineNo+4 < model.getSize()) {
list.ensureIndexIsVisible(lineNo+4); // give some context
}
list.ensureIndexIsVisible(lineNo);
}
}
private void showSourceUnavailable() {
SourceModel model = new SourceModel("[Source code is not available]");
setViewModel(model);
}
private void setViewModel(SourceModel model) {
if (model != sourceModel) {
// install new model
list.setModel(model);
sourceModel = model;
}
}
private class SourceLineRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//### Should set background highlight and/or icon if breakpoint on this line.
// Configures "this"
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
SourceModel.Line line = (SourceModel.Line)value;
//### Tab expansion is now done when source file is read in,
//### to speed up display. This costs a lot of space, slows
//### down source file loading, and has not been demonstrated
//### to yield an observable improvement in display performance.
//### Measurements may be appropriate here.
//String sourceLine = expandTabs((String)value);
setText(line.text);
if (line.hasBreakpoint) {
setIcon(Icons.stopSignIcon);
} else if (line.isExecutable()) {
setIcon(Icons.execIcon);
} else {
setIcon(Icons.blankIcon);
}
return this;
}
@Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
return new Dimension(dim.width, dim.height-5);
}
}
private class STMouseListener extends MouseAdapter implements MouseListener {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu((Component)e.getSource(),
e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu((Component)e.getSource(),
e.getX(), e.getY());
}
}
private void showPopupMenu(Component invoker, int x, int y) {
JList list = (JList)invoker;
int ln = list.getSelectedIndex() + 1;
SourceModel.Line line =
(SourceModel.Line)list.getSelectedValue();
JPopupMenu popup = new JPopupMenu();
if (line == null) {
popup.add(new JMenuItem("please select a line"));
} else if (line.isExecutable()) {
String className = line.refType.name();
if (line.hasBreakpoint()) {
popup.add(commandItem("Clear Breakpoint",
"clear " + className +
":" + ln));
} else {
popup.add(commandItem("Set Breakpoint",
"stop at " + className +
":" + ln));
}
} else {
popup.add(new JMenuItem("not an executable line"));
}
popup.show(invoker,
x + popup.getWidth()/2, y + popup.getHeight()/2);
}
private JMenuItem commandItem(String label, final String cmd) {
JMenuItem item = new JMenuItem(label);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpreter.executeCommand(cmd);
}
});
return item;
}
}
}

View File

@@ -0,0 +1,292 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.tools.example.debug.bdi.*;
public class SourceTreeTool extends JPanel {
private static final long serialVersionUID = 3336680912107956419L;
private Environment env;
private ExecutionManager runtime;
private SourceManager sourceManager;
private ClassManager classManager;
private JTree tree;
private SourceTreeNode root;
private SearchPath sourcePath;
private CommandInterpreter interpreter;
private static String HEADING = "SOURCES";
public SourceTreeTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env);
sourcePath = sourceManager.getSourcePath();
root = createDirectoryTree(HEADING);
// Create a tree that allows one selection at a time.
tree = new JTree(new DefaultTreeModel(root));
tree.setSelectionModel(new SingleLeafTreeSelectionModel());
/******
// Listen for when the selection changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
SourceTreeNode node = (SourceTreeNode)
(e.getPath().getLastPathComponent());
interpreter.executeCommand("view " + node.getRelativePath());
}
});
******/
MouseListener ml = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
SourceTreeNode node =
(SourceTreeNode)selPath.getLastPathComponent();
// If user clicks on leaf, select it, and issue 'view' command.
if (node.isLeaf()) {
tree.setSelectionPath(selPath);
interpreter.executeCommand("view " + node.getRelativePath());
}
}
}
}
};
tree.addMouseListener(ml);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);
// Create listener for source path changes.
SourceTreeToolListener listener = new SourceTreeToolListener();
sourceManager.addSourceListener(listener);
//### remove listeners on exit!
}
private class SourceTreeToolListener implements SourceListener {
@Override
public void sourcepathChanged(SourcepathChangedEvent e) {
sourcePath = sourceManager.getSourcePath();
root = createDirectoryTree(HEADING);
tree.setModel(new DefaultTreeModel(root));
}
}
private static class SourceOrDirectoryFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return (name.endsWith(".java") ||
new File(dir, name).isDirectory());
}
}
private static FilenameFilter filter = new SourceOrDirectoryFilter();
SourceTreeNode createDirectoryTree(String label) {
try {
return new SourceTreeNode(label, null, "", true);
} catch (SecurityException e) {
env.failure("Cannot access source file or directory");
return null;
}
}
class SourceTreeNode implements TreeNode {
private String name;
private boolean isDirectory;
private SourceTreeNode parent;
private SourceTreeNode[] children;
private String relativePath;
private boolean isExpanded;
private SourceTreeNode(String label,
SourceTreeNode parent,
String relativePath,
boolean isDirectory) {
this.name = label;
this.relativePath = relativePath;
this.parent = parent;
this.isDirectory = isDirectory;
}
@Override
public String toString() {
return name;
}
public String getRelativePath() {
return relativePath;
}
private void expandIfNeeded() {
try {
if (!isExpanded && isDirectory) {
String[] files = sourcePath.children(relativePath, filter);
children = new SourceTreeNode[files.length];
for (int i = 0; i < files.length; i++) {
String childName =
(relativePath.equals(""))
? files[i]
: relativePath + File.separator + files[i];
File file = sourcePath.resolve(childName);
boolean isDir = (file != null && file.isDirectory());
children[i] =
new SourceTreeNode(files[i], this, childName, isDir);
}
}
isExpanded = true;
} catch (SecurityException e) {
children = null;
env.failure("Cannot access source file or directory");
}
}
// -- interface TreeNode --
/*
* Returns the child <code>TreeNode</code> at index
* <code>childIndex</code>.
*/
@Override
public TreeNode getChildAt(int childIndex) {
expandIfNeeded();
return children[childIndex];
}
/**
* Returns the number of children <code>TreeNode</code>s the receiver
* contains.
*/
@Override
public int getChildCount() {
expandIfNeeded();
return children.length;
}
/**
* Returns the parent <code>TreeNode</code> of the receiver.
*/
@Override
public TreeNode getParent() {
return parent;
}
/**
* Returns the index of <code>node</code> in the receivers children.
* If the receiver does not contain <code>node</code>, -1 will be
* returned.
*/
@Override
public int getIndex(TreeNode node) {
expandIfNeeded();
for (int i = 0; i < children.length; i++) {
if (children[i] == node) {
return i;
}
}
return -1;
}
/**
* Returns true if the receiver allows children.
*/
@Override
public boolean getAllowsChildren() {
return isDirectory;
}
/**
* Returns true if the receiver is a leaf.
*/
@Override
public boolean isLeaf() {
expandIfNeeded();
return !isDirectory;
}
/**
* Returns the children of the receiver as an Enumeration.
*/
@Override
public Enumeration children() {
expandIfNeeded();
return new Enumeration() {
int i = 0;
@Override
public boolean hasMoreElements() {
return (i < children.length);
}
@Override
public Object nextElement() throws NoSuchElementException {
if (i >= children.length) {
throw new NoSuchElementException();
}
return children[i++];
}
};
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.EventObject;
public class SourcepathChangedEvent extends EventObject {
private static final long serialVersionUID = 8762169481005804121L;
public SourcepathChangedEvent(Object source) {
super(source);
}
}

View File

@@ -0,0 +1,207 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.bdi.*;
public class StackTraceTool extends JPanel {
private static final long serialVersionUID = 9140041989427965718L;
private Environment env;
private ExecutionManager runtime;
private ContextManager context;
private ThreadInfo tinfo;
private JList list;
private ListModel stackModel;
public StackTraceTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.context = env.getContextManager();
stackModel = new DefaultListModel(); // empty
list = new JList(stackModel);
list.setCellRenderer(new StackFrameRenderer());
JScrollPane listView = new JScrollPane(list);
add(listView);
// Create listener.
StackTraceToolListener listener = new StackTraceToolListener();
context.addContextListener(listener);
list.addListSelectionListener(listener);
//### remove listeners on exit!
}
private class StackTraceToolListener
implements ContextListener, ListSelectionListener
{
// ContextListener
// If the user selects a new current frame, display it in
// this view.
//### I suspect we handle the case badly that the VM is not interrupted.
@Override
public void currentFrameChanged(CurrentFrameChangedEvent e) {
// If the current frame of the thread appearing in this
// view is changed, move the selection to track it.
int frameIndex = e.getIndex();
ThreadInfo ti = e.getThreadInfo();
if (e.getInvalidate() || tinfo != ti) {
tinfo = ti;
showStack(ti, frameIndex);
} else {
if (frameIndex < stackModel.getSize()) {
list.setSelectedIndex(frameIndex);
list.ensureIndexIsVisible(frameIndex);
}
}
}
// ListSelectionListener
@Override
public void valueChanged(ListSelectionEvent e) {
int index = list.getSelectedIndex();
if (index != -1) {
//### should use listener?
try {
context.setCurrentFrameIndex(index);
} catch (VMNotInterruptedException exc) {
}
}
}
}
private class StackFrameRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//### We should indicate the current thread independently of the
//### selection, e.g., with an icon, because the user may change
//### the selection graphically without affecting the current
//### thread.
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value == null) {
this.setText("<unavailable>");
} else {
StackFrame frame = (StackFrame)value;
Location loc = frame.location();
Method meth = loc.method();
String methName =
meth.declaringType().name() + '.' + meth.name();
String position = "";
if (meth.isNative()) {
position = " (native method)";
} else if (loc.lineNumber() != -1) {
position = ":" + loc.lineNumber();
} else {
long pc = loc.codeIndex();
if (pc != -1) {
position = ", pc = " + pc;
}
}
// Indices are presented to the user starting from 1, not 0.
this.setText("[" + (index+1) +"] " + methName + position);
}
return this;
}
}
// Point this view at the given thread and frame.
private void showStack(ThreadInfo tinfo, int selectFrame) {
StackTraceListModel model = new StackTraceListModel(tinfo);
stackModel = model;
list.setModel(stackModel);
list.setSelectedIndex(selectFrame);
list.ensureIndexIsVisible(selectFrame);
}
private static class StackTraceListModel extends AbstractListModel {
private final ThreadInfo tinfo;
public StackTraceListModel(ThreadInfo tinfo) {
this.tinfo = tinfo;
}
@Override
public Object getElementAt(int index) {
try {
return tinfo == null? null : tinfo.getFrame(index);
} catch (VMNotInterruptedException e) {
//### Is this the right way to handle this?
//### Would happen if user scrolled stack trace
//### while not interrupted -- should probably
//### block user interaction in this case.
return null;
}
}
@Override
public int getSize() {
try {
return tinfo == null? 1 : tinfo.getFrameCount();
} catch (VMNotInterruptedException e) {
//### Is this the right way to handle this?
return 0;
}
}
}
}

View File

@@ -0,0 +1,355 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.util.*;
import java.util.List; // Must import explicitly due to conflict with javax.awt.List
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.jdi.*;
import com.sun.tools.example.debug.event.*;
import com.sun.tools.example.debug.bdi.*;
//### Bug: If the name of a thread is changed via Thread.setName(), the
//### thread tree view does not reflect this. The name of the thread at
//### the time it is created is used throughout its lifetime.
public class ThreadTreeTool extends JPanel {
private static final long serialVersionUID = 4168599992853038878L;
private Environment env;
private ExecutionManager runtime;
private SourceManager sourceManager;
private ClassManager classManager;
private JTree tree;
private DefaultTreeModel treeModel;
private ThreadTreeNode root;
private SearchPath sourcePath;
private CommandInterpreter interpreter;
private static String HEADING = "THREADS";
public ThreadTreeTool(Environment env) {
super(new BorderLayout());
this.env = env;
this.runtime = env.getExecutionManager();
this.sourceManager = env.getSourceManager();
this.interpreter = new CommandInterpreter(env);
root = createThreadTree(HEADING);
treeModel = new DefaultTreeModel(root);
// Create a tree that allows one selection at a time.
tree = new JTree(treeModel);
tree.setSelectionModel(new SingleLeafTreeSelectionModel());
MouseListener ml = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
ThreadTreeNode node =
(ThreadTreeNode)selPath.getLastPathComponent();
// If user clicks on leaf, select it, and issue 'thread' command.
if (node.isLeaf()) {
tree.setSelectionPath(selPath);
interpreter.executeCommand("thread " +
node.getThreadId() +
" (\"" +
node.getName() + "\")");
}
}
}
}
};
tree.addMouseListener(ml);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);
// Create listener.
ThreadTreeToolListener listener = new ThreadTreeToolListener();
runtime.addJDIListener(listener);
runtime.addSessionListener(listener);
//### remove listeners on exit!
}
HashMap<ThreadReference, List<String>> threadTable = new HashMap<ThreadReference, List<String>>();
private List<String> threadPath(ThreadReference thread) {
// May exit abnormally if VM disconnects.
List<String> l = new ArrayList<String>();
l.add(0, thread.name());
ThreadGroupReference group = thread.threadGroup();
while (group != null) {
l.add(0, group.name());
group = group.parent();
}
return l;
}
private class ThreadTreeToolListener extends JDIAdapter
implements JDIListener, SessionListener {
// SessionListener
@Override
public void sessionStart(EventObject e) {
try {
for (ThreadReference thread : runtime.allThreads()) {
root.addThread(thread);
}
} catch (VMDisconnectedException ee) {
// VM went away unexpectedly.
} catch (NoSessionException ee) {
// Ignore. Should not happen.
}
}
@Override
public void sessionInterrupt(EventObject e) {}
@Override
public void sessionContinue(EventObject e) {}
// JDIListener
@Override
public void threadStart(ThreadStartEventSet e) {
root.addThread(e.getThread());
}
@Override
public void threadDeath(ThreadDeathEventSet e) {
root.removeThread(e.getThread());
}
@Override
public void vmDisconnect(VMDisconnectEventSet e) {
// Clear the contents of this view.
root = createThreadTree(HEADING);
treeModel = new DefaultTreeModel(root);
tree.setModel(treeModel);
threadTable = new HashMap<ThreadReference, List<String>>();
}
}
ThreadTreeNode createThreadTree(String label) {
return new ThreadTreeNode(label, null);
}
class ThreadTreeNode extends DefaultMutableTreeNode {
String name;
ThreadReference thread; // null if thread group
long uid;
String description;
ThreadTreeNode(String name, ThreadReference thread) {
if (name == null) {
name = "<unnamed>";
}
this.name = name;
this.thread = thread;
if (thread == null) {
this.uid = -1;
this.description = name;
} else {
this.uid = thread.uniqueID();
this.description = name + " (t@" + Long.toHexString(uid) + ")";
}
}
@Override
public String toString() {
return description;
}
public String getName() {
return name;
}
public ThreadReference getThread() {
return thread;
}
public String getThreadId() {
return "t@" + Long.toHexString(uid);
}
private boolean isThreadGroup() {
return (thread == null);
}
@Override
public boolean isLeaf() {
return !isThreadGroup();
}
public void addThread(ThreadReference thread) {
// This can fail if the VM disconnects.
// It is important to do all necessary JDI calls
// before modifying the tree, so we don't abort
// midway through!
if (threadTable.get(thread) == null) {
// Add thread only if not already present.
try {
List<String> path = threadPath(thread);
// May not get here due to exception.
// If we get here, we are committed.
// We must not leave the tree partially updated.
try {
threadTable.put(thread, path);
addThread(path, thread);
} catch (Throwable tt) {
//### Assertion failure.
throw new RuntimeException("ThreadTree corrupted");
}
} catch (VMDisconnectedException ee) {
// Ignore. Thread will not be added.
}
}
}
private void addThread(List<String> threadPath, ThreadReference thread) {
int size = threadPath.size();
if (size == 0) {
return;
} else if (size == 1) {
String name = threadPath.get(0);
insertNode(name, thread);
} else {
String head = threadPath.get(0);
List<String> tail = threadPath.subList(1, size);
ThreadTreeNode child = insertNode(head, null);
child.addThread(tail, thread);
}
}
private ThreadTreeNode insertNode(String name, ThreadReference thread) {
for (int i = 0; i < getChildCount(); i++) {
ThreadTreeNode child = (ThreadTreeNode)getChildAt(i);
int cmp = name.compareTo(child.getName());
if (cmp == 0 && thread == null) {
// A like-named interior node already exists.
return child;
} else if (cmp < 0) {
// Insert new node before the child.
ThreadTreeNode newChild = new ThreadTreeNode(name, thread);
treeModel.insertNodeInto(newChild, this, i);
return newChild;
}
}
// Insert new node after last child.
ThreadTreeNode newChild = new ThreadTreeNode(name, thread);
treeModel.insertNodeInto(newChild, this, getChildCount());
return newChild;
}
public void removeThread(ThreadReference thread) {
List<String> threadPath = threadTable.get(thread);
// Only remove thread if we recorded it in table.
// Original add may have failed due to VM disconnect.
if (threadPath != null) {
removeThread(threadPath, thread);
}
}
private void removeThread(List<String> threadPath, ThreadReference thread) {
int size = threadPath.size();
if (size == 0) {
return;
} else if (size == 1) {
String name = threadPath.get(0);
ThreadTreeNode child = findLeafNode(thread, name);
treeModel.removeNodeFromParent(child);
} else {
String head = threadPath.get(0);
List<String> tail = threadPath.subList(1, size);
ThreadTreeNode child = findInternalNode(head);
child.removeThread(tail, thread);
if (child.isThreadGroup() && child.getChildCount() < 1) {
// Prune non-leaf nodes with no children.
treeModel.removeNodeFromParent(child);
}
}
}
private ThreadTreeNode findLeafNode(ThreadReference thread, String name) {
for (int i = 0; i < getChildCount(); i++) {
ThreadTreeNode child = (ThreadTreeNode)getChildAt(i);
if (child.getThread() == thread) {
if (!name.equals(child.getName())) {
//### Assertion failure.
throw new RuntimeException("name mismatch");
}
return child;
}
}
//### Assertion failure.
throw new RuntimeException("not found");
}
private ThreadTreeNode findInternalNode(String name) {
for (int i = 0; i < getChildCount(); i++) {
ThreadTreeNode child = (ThreadTreeNode)getChildAt(i);
if (name.equals(child.getName())) {
return child;
}
}
//### Assertion failure.
throw new RuntimeException("not found");
}
}
}

View File

@@ -0,0 +1,132 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TypeScript extends JPanel {
private static final long serialVersionUID = -983704841363534885L;
private JTextArea history;
private JTextField entry;
private JLabel promptLabel;
private JScrollBar historyVScrollBar;
private JScrollBar historyHScrollBar;
private boolean echoInput = false;
private static String newline = System.getProperty("line.separator");
public TypeScript(String prompt) {
this(prompt, true);
}
public TypeScript(String prompt, boolean echoInput) {
this.echoInput = echoInput;
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
//setBorder(new EmptyBorder(5, 5, 5, 5));
history = new JTextArea(0, 0);
history.setEditable(false);
JScrollPane scroller = new JScrollPane(history);
historyVScrollBar = scroller.getVerticalScrollBar();
historyHScrollBar = scroller.getHorizontalScrollBar();
add(scroller);
JPanel cmdLine = new JPanel();
cmdLine.setLayout(new BoxLayout(cmdLine, BoxLayout.X_AXIS));
//cmdLine.setBorder(new EmptyBorder(5, 5, 0, 0));
promptLabel = new JLabel(prompt + " ");
cmdLine.add(promptLabel);
entry = new JTextField();
//### Swing bug workaround.
entry.setMaximumSize(new Dimension(1000, 20));
cmdLine.add(entry);
add(cmdLine);
}
/******
public void setFont(Font f) {
entry.setFont(f);
history.setFont(f);
}
******/
public void setPrompt(String prompt) {
promptLabel.setText(prompt + " ");
}
public void append(String text) {
history.append(text);
historyVScrollBar.setValue(historyVScrollBar.getMaximum());
historyHScrollBar.setValue(historyHScrollBar.getMinimum());
}
public void newline() {
history.append(newline);
historyVScrollBar.setValue(historyVScrollBar.getMaximum());
historyHScrollBar.setValue(historyHScrollBar.getMinimum());
}
public void flush() {}
public void addActionListener(ActionListener a) {
entry.addActionListener(a);
}
public void removeActionListener(ActionListener a) {
entry.removeActionListener(a);
}
public String readln() {
String text = entry.getText();
entry.setText("");
if (echoInput) {
history.append(">>>");
history.append(text);
history.append(newline);
historyVScrollBar.setValue(historyVScrollBar.getMaximum());
historyHScrollBar.setValue(historyHScrollBar.getMinimum());
}
return text;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import com.sun.tools.example.debug.bdi.OutputListener;
public class TypeScriptOutputListener implements OutputListener {
private TypeScript script;
private boolean appendNewline;
public TypeScriptOutputListener(TypeScript script) {
this(script, false);
}
public TypeScriptOutputListener(TypeScript script, boolean appendNewline) {
this.script = script;
this.appendNewline = appendNewline;
}
@Override
public void putString(String s) {
script.append(s);
if (appendNewline) {
script.newline();
}
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.tools.example.debug.gui;
import java.io.*;
public class TypeScriptWriter extends Writer {
TypeScript script;
public TypeScriptWriter(TypeScript script) {
this.script = script;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
script.append(String.valueOf(cbuf, off, len));
}
@Override
public void flush() {
script.flush();
}
@Override
public void close() {
script.flush();
}
}