Kaydet (Commit) e8fa7bbf authored tarafından Lei De Bin's avatar Lei De Bin

#119998# the VCLAuto code re-factor

Patch by: Liu Zhe(aliuzhe at gmail dot com) 
Review by: Lei Debin
üst 212ba19f
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.vclauto.assistant.feature</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.pde.FeatureBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.FeatureNature</nature>
</natures>
</projectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<!--************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************ -->
<feature
id="org.vclauto.assistant.feature"
label="VclExplorer"
version="1.0.3.qualifier"
provider-name="Apache">
<description url="http://wiki.services.openoffice.org/wiki/QA/vclauto">
This plugin is tool to assist vclauto developers to write test
cases.
1. Inspect VCL control in OpenOffice.
2. Define VCL control in UIMap.
3. Insert testing code.
</description>
<copyright url="http://www.apache.org/licenses/LICENSE-2.0">
Apache License, Version 2.0
</copyright>
<license url="http://www.apache.org/licenses/LICENSE-2.0">
Apache License, Version 2.0
</license>
<plugin
id="org.vclauto.assistant"
download-size="120"
install-size="120"
version="0.0.0"
unpack="false"/>
</feature>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry exported="true" kind="lib" path="lib/vclauto.jar" sourcepath="/home/test/workspace/vclauto/src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.vclauto.assistant</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Vclauto Assistant
Bundle-SymbolicName: org.vclauto.assistant; singleton:=true
Bundle-Version: 1.0.3.qualifier
Bundle-Activator: org.vclauto.assistant.Activator
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.ui.editors;bundle-version="3.6.0",
org.eclipse.jface.text;bundle-version="3.6.0",
org.eclipse.core.resources;bundle-version="3.6.0",
org.eclipse.jdt.core;bundle-version="3.6.0"
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-ClassPath: .,
lib/vclauto.jar
Bundle-Vendor: Apache
source.. = src/
output.. = bin/
bin.includes = plugin.xml,\
META-INF/,\
.,\
icons/,\
contexts.xml,\
lib/vclauto.jar
<!--************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************ -->
<contexts>
<context id="viewer" title="Sample View">
<description>This is the context help for the sample view with a table viewer. It was generated by a PDE template.</description>
<topic href="/PLUGINS_ROOT/org.eclipse.platform.doc.isv/guide/ua_help_context.htm" label="Context-sensitive help">
<enablement>
<with variable="platform">
<test property="org.eclipse.core.runtime.isBundleInstalled" args="org.eclipse.platform.doc.isv"/>
</with>
</enablement>
</topic>
</context>
</contexts>
<?xml version="1.0" encoding="UTF-8"?>
<!--************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************ -->
<?eclipse version="3.4"?>
<plugin>
<extension
point="org.eclipse.ui.views">
<category
name="Vclauto"
id="org.vclauto.assistant">
</category>
<view
name="Vcl Explorer"
icon="icons/sample.gif"
category="org.vclauto.assistant"
class="org.vclauto.assistant.views.VclExplorer"
id="org.vclauto.assistant.views.VclExplorer">
</view>
</extension>
<extension
point="org.eclipse.ui.perspectiveExtensions">
<perspectiveExtension
targetID="org.eclipse.jdt.ui.JavaPerspective">
<view
ratio="0.5"
relative="org.eclipse.ui.views.TaskList"
relationship="right"
id="org.vclauto.assistant.views.VclExplorer">
</view>
</perspectiveExtension>
</extension>
<extension
point="org.eclipse.help.contexts">
<contexts
file="contexts.xml">
</contexts>
</extension>
<extension
point="org.eclipse.ui.preferencePages">
<page
class="org.vclauto.assistant.preferences.PreferencePage"
id="org.vclauto.assistant.preferences.PreferencePage"
name="Vclauto Assistant">
</page>
</extension>
<extension
point="org.eclipse.core.runtime.preferences">
<initializer
class="org.vclauto.assistant.preferences.PreferenceInitializer">
</initializer>
</extension>
</plugin>
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.vclauto.assistant"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.preferences;
/**
* Constant definitions for plug-in preferences
*/
public class PreferenceConstants {
public static final String P_OPENOFFICE_HOME = "openoffice.home";
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import org.vclauto.assistant.Activator;
/**
* Class used to initialize default preference values.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
public void initializeDefaultPreferences() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.P_OPENOFFICE_HOME, "");
}
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.preferences;
import org.eclipse.jface.preference.*;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.vclauto.assistant.Activator;
/**
* This class represents a preference page that
* is contributed to the Preferences dialog. By
* subclassing <samp>FieldEditorPreferencePage</samp>, we
* can use the field support built into JFace that allows
* us to create a page that is small and knows how to
* save, restore and apply itself.
* <p>
* This page is used to modify preferences only. They
* are stored in the preference store that belongs to
* the main plug-in class. That way, preferences can
* be accessed directly via the preference store.
*/
public class PreferencePage
extends FieldEditorPreferencePage
implements IWorkbenchPreferencePage {
public PreferencePage() {
super(GRID);
setPreferenceStore(Activator.getDefault().getPreferenceStore());
setDescription("Vclauto Assistant Setting");
}
/**
* Creates the field editors. Field editors are abstractions of
* the common GUI blocks needed to manipulate various types
* of preferences. Each field editor knows how to save and
* restore itself.
*/
public void createFieldEditors() {
addField(new DirectoryFieldEditor(PreferenceConstants.P_OPENOFFICE_HOME,
"&OpenOffice Home (the directory containing soffice.bin):", getFieldEditorParent()));
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
}
\ No newline at end of file
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.views;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.vclauto.client.SmartId;
import org.vclauto.widgets.VclControl;
public class ControlInfo {
private static final HashMap<Long, String> vcltypes = new HashMap<Long, String>();
static {
Field[] fields = VclControl.class.getDeclaredFields();
for (Field field : fields) {
int modifiers = field.getModifiers();
if (modifiers == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL) && field.getType() == Integer.TYPE) {
try {
int v = (Integer) field.get(null);
vcltypes.put((long)v, field.getName());
} catch (Exception e) {
//ignore
}
}
}
}
public SmartId id;
public long type;
public String tip;
public Image appearance;
public Rectangle rectangle;
public String name;
public ControlInfo(SmartId id, long type, String tip) {
super();
this.id = id;
this.type = type;
this.tip = tip;
}
public String getVclType() {
return vcltypes.get(type);
}
public void shot() {
if (id.getId() != 0 || id.getSid() != null) {
VclControl vclControl = new VclControl(id);
try {
if (!vclControl.exists())
return;
java.awt.Rectangle rect = vclControl.getScreenRectangle();
// Display display = Display.getDefault();
// GC gc = new GC(display);
rectangle = new Rectangle(rect.x, rect.y, rect.width, rect.height);
// appearance = new Image(display, rectangle);
// gc.copyArea(appearance, 0, 0);
// gc.dispose();
} catch (Throwable t) {
}
}
}
public void dispose() {
if (appearance != null)
appearance.dispose();
}
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.views;
import static org.vclauto.widgets.VclControl.*;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.WorkingCopyOwner;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.TextEdit;
import org.vclauto.client.SmartId;
import org.vclauto.utils.IDList;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class UIMapOp {
private ICompilationUnit uiMap = null;
private IDList idList = null;
public ArrayList<String> names = new ArrayList<String>();
public ArrayList<String> ids = new ArrayList<String>();
public UIMapOp() {
}
private boolean locateUIMap() {
uiMap = null;
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject[] projects = root.getProjects();
for (IProject project : projects) {
try {
if (project.isNatureEnabled("org.eclipse.jdt.core.javanature")) {
IJavaProject javaProject = JavaCore.create(project);
uiMap = findUIMap(javaProject);
if (uiMap != null) {
return true;
}
}
} catch (Exception e) {
}
}
return false;
}
private ICompilationUnit findUIMap(IJavaProject javaProject) throws JavaModelException {
IPackageFragment[] packages = javaProject.getPackageFragments();
for (IPackageFragment mypackage : packages) {
if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
ICompilationUnit ret = findUIMap(mypackage);
if (ret != null) {
return ret;
}
}
}
return null;
}
private ICompilationUnit findUIMap(IPackageFragment mypackage) throws JavaModelException {
for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
if ("UIMap.java".equals(unit.getElementName())) {
return unit;
}
}
return null;
}
private static CompilationUnit parse(ICompilationUnit unit) {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
return (CompilationUnit) parser.createAST(null); // parse
}
public boolean scan() {
if (!locateUIMap())
return false;
IProject project = uiMap.getResource().getProject();
try {
uiMap.getResource().refreshLocal(1, null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IFile file = project.getFile("ids");
idList = new IDList(file.getLocation().toFile());
names.clear();
ids.clear();
CompilationUnit compilationUnit = parse(uiMap);
TypeDeclaration typeDeclaration = (TypeDeclaration) compilationUnit.types().get(0);
FieldDeclaration[] fields = typeDeclaration.getFields();
for (FieldDeclaration field : fields) {
List fragments = field.fragments();
for (Object o : fragments) {
VariableDeclarationFragment fragment = (VariableDeclarationFragment) o;
System.out.println(fragment);
names.add(fragment.getName().toString());
String code = fragment.toString();
int left = code.indexOf('(');
if (left >= 0) {
int right = code.indexOf(')', left);
if (right >= 0) {
String idInDeclaration = code.substring(left + 1, right);
if (idInDeclaration.startsWith("\"")) {
// It's string....
idInDeclaration = idInDeclaration.substring(1, idInDeclaration.length() - 1);
ids.add(idInDeclaration);
continue;
}
}
}
ids.add(null);
}
}
return true;
}
/**
* Return the control name defined in UIMap with the given id
*
* @param id
* @return
*/
public void populateName(ArrayList<ControlInfo> controlInfos) {
for (int i = names.size() - 1; i >= 0; i--) {
String name = names.get(i);
String id = ids.get(i);
if (id == null)
continue;
SmartId smartId = idList.getId(id);
for (ControlInfo ci : controlInfos) {
if (ci.id.equals(smartId)) {
ci.name = name;
break;
}
}
}
}
/**
*
*/
private String[] codeParts(ControlInfo info) {
String method = null;
String type = null;
switch ((int) info.type) {
case WINDOW_BUTTON:
case WINDOW_PUSHBUTTON:
case WINDOW_IMAGEBUTTON:
case WINDOW_MENUBUTTON:
case WINDOW_MOREBUTTON:
case WINDOW_RADIOBUTTON:
case WINDOW_IMAGERADIOBUTTON:
case WINDOW_CHECKBOX:
case WINDOW_TRISTATEBOX:
method = "button";
type = "VclButton";
break;
case WINDOW_EDIT:
case WINDOW_MULTILINEEDIT:
case WINDOW_PATTERNBOX:
case WINDOW_NUMERICBOX:
case WINDOW_METRICBOX:
case WINDOW_CURRENCYBOX:
case WINDOW_DATEBOX:
case WINDOW_TIMEBOX:
case WINDOW_LONGCURRENCYBOX:
method = "editbox";
type = "VclEditBox";
break;
case WINDOW_COMBOBOX:
method = "combobox";
type = "VclComboBox";
break;
case WINDOW_LISTBOX:
case WINDOW_MULTILISTBOX:
case WINDOW_VALUESETLISTBOX:
method = "listbox";
type = "VclListBox";
break;
case WINDOW_TABPAGE:
method = "tabpage";
type = "VclTabPage";
break;
case WINDOW_TOOLBOX:
method = "toolbox";
type = "VclToolBox";
break;
case WINDOW_TABCONTROL:
method = "tabcontrol";
type = "VclTabControl";
break;
case WINDOW_WINDOW:
case WINDOW_BORDERWINDOW:
case WINDOW_SYSTEMCHILDWINDOW:
method = "window";
type = "VclWindow";
break;
case WINDOW_DIALOG:
case WINDOW_MODELESSDIALOG:
case WINDOW_MODALDIALOG:
case WINDOW_SYSTEMDIALOG :
case WINDOW_PATHDIALOG :
case WINDOW_FILEDIALOG :
case WINDOW_PRINTERSETUPDIALOG :
case WINDOW_PRINTDIALOG :
case WINDOW_COLORDIALOG :
case WINDOW_FONTDIALOG:
method = "dialog";
type = "VclDialog";
break;
case WINDOW_DOCKINGWINDOW:
method = "dockingwin";
type = "VclDocingWin";
break;
case WINDOW_SPINFIELD:
case WINDOW_PATTERNFIELD:
case WINDOW_NUMERICFIELD:
case WINDOW_METRICFIELD:
case WINDOW_CURRENCYFIELD:
case WINDOW_DATEFIELD:
case WINDOW_TIMEFIELD:
case WINDOW_LONGCURRENCYFIELD:
method = "field";
type = "VclField";
break;
default:
method = "control";
type = "VclControl";
}
return new String[] { type, method };
}
public void define(ControlInfo info) throws Exception {
String[] codeParts = codeParts(info);
String type = codeParts[0];
String method = codeParts[1];
String source = uiMap.getSource();
Document document = new Document(source);
// creation of DOM/AST from a ICompilationUnit
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(uiMap);
CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
AST ast = astRoot.getAST();
astRoot.recordModifications();
VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
StringLiteral literal = ast.newStringLiteral();
literal.setLiteralValue(info.id.toString());
MethodInvocation methodInvocation = ast.newMethodInvocation();
methodInvocation.setName(ast.newSimpleName(method));
methodInvocation.arguments().add(literal);
vdf.setInitializer(methodInvocation);
vdf.setName(ast.newSimpleName(info.name));
FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(vdf);
fieldDeclaration.setType(ast.newSimpleType(ast.newSimpleName(type)));
fieldDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
fieldDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
fieldDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
TypeDeclaration typeDeclaration = (TypeDeclaration) astRoot.types().get(0);
typeDeclaration.bodyDeclarations().add(fieldDeclaration);
TextEdit edits = astRoot.rewrite(document, uiMap.getJavaProject().getOptions(true));
edits.apply(document);
String newSource = document.get();
WorkingCopyOwner owner = new WorkingCopyOwner() {};
// Create working copy
ICompilationUnit workingCopy = uiMap.getWorkingCopy(owner, null);
workingCopy.getBuffer().setContents(newSource);
workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
// Commit changes
workingCopy.commitWorkingCopy(true, null);
// Destroy working copy
workingCopy.discardWorkingCopy();
// return "public static final " + type + " " + info.name + " = " +
// method + "(\"" + info.id + "\")";
}
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.views;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnViewerEditor;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerEditor;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.vclauto.assistant.Activator;
import org.vclauto.assistant.preferences.PreferenceConstants;
import org.vclauto.client.CommandCaller.WinInfoReceiver;
import org.vclauto.client.Constant;
import org.vclauto.client.SmartId;
import org.vclauto.client.VclHook;
import org.vclauto.widgets.VclApp;
public class VclExplorer extends ViewPart implements WinInfoReceiver {
public static final String ID = "org.vclauto.assistant.views.VclExplorer";
private TableViewer viewer;
private Label messageLabel;
private Action inspectAction;
private Action launchAction;
private Action insertCodeAction;
private UIMapOp uiMapOp = new UIMapOp();
private ArrayList<ControlInfo> controlInfos = new ArrayList<ControlInfo>();
private Display display;
private Color duplicatedNameColor;
/**
* The constructor.
*/
public VclExplorer() {
VclHook.getCommandCaller().setWinInfoReceiver(this);
}
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginTop = 0;
layout.marginBottom = 0;
layout.marginHeight = 0;
layout.marginWidth = 0;
parent.setLayout(layout);
messageLabel = new Label(parent, SWT.NONE);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.minimumHeight = 14;
gridData.heightHint = 14;
messageLabel.setLayoutData(gridData);
viewer = new TableViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
gridData = new GridData(GridData.FILL_BOTH);
viewer.getTable().setLayoutData(gridData);
viewer.setContentProvider(new VclExplorerContentProvider());
viewer.setLabelProvider(new VclExplorerLabelProvider());
viewer.setInput(controlInfos);
display = parent.getDisplay();
duplicatedNameColor = new Color(display, 255, 160, 160);
final Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText("ID");
column.setResizable(true);
column.setMoveable(false);
column.setWidth(100);
column = new TableColumn(table, SWT.NONE);
column.setText("Name");
column.setResizable(true);
column.setMoveable(false);
column.setWidth(150);
column = new TableColumn(table, SWT.NONE);
column.setText("Type");
column.setResizable(true);
column.setMoveable(false);
column.setWidth(100);
column = new TableColumn(table, SWT.NONE);
column.setText("Tips");
column.setResizable(true);
column.setMoveable(false);
column.setWidth(200);
viewer.setColumnProperties(new String[] { "ID", "Name", "Type", "Tips" });
TextCellEditor nameCellEditor = new TextCellEditor(viewer.getTable());
final Text nameText = ((Text) nameCellEditor.getControl());
nameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
String message = validateName(nameText.getText());
if (message != null) {
messageLabel.setText(message);
nameText.setBackground(duplicatedNameColor);
} else {
messageLabel.setText("");
nameText.setBackground(null);
}
}
});
viewer.setCellEditors(new CellEditor[] { null, nameCellEditor, null, null});
viewer.setCellModifier(new ICellModifier() {
public boolean canModify(Object element, String property) {
if (!"Name".equals(property))
return false;
ControlInfo controlInfo = (ControlInfo) element;
if (controlInfo.name != null)
return false;
return uiMapOp.scan();
}
public Object getValue(Object element, String property) {
// if (!"Name".equals(property))
// return false;
ControlInfo controlInfo = (ControlInfo) element;
return controlInfo.name == null ? "" : controlInfo.name;
}
public void modify(Object element, String property, Object value) {
// if (!"Name".equals(property))
// return;
TableItem item = (TableItem) element;
ControlInfo controlInfo = (ControlInfo) item.getData();
String newName = (String) value;
String msg = validateName(newName);
if (msg == null) {
controlInfo.name = newName;
if (doDefineName(controlInfo)) {
item.setText(1, newName);
messageLabel.setText("");
} else {
controlInfo.name = null;
messageLabel.setText("Can't define the control in UIMap. UIMap maybe is broken!");
}
} else {
messageLabel.setText(msg);
}
}
});
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(
viewer) {
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
TableViewerEditor.create(viewer, actSupport,
ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL
| ColumnViewerEditor.KEYBOARD_ACTIVATION);
// Create the help context id for the viewer's control
PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "org.vclauto.assistant.viewer");
makeActions();
hookContextMenu();
hookDoubleClickAction();
contributeToActionBars();
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
VclExplorer.this.fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, viewer);
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(inspectAction);
manager.add(new Separator());
manager.add(launchAction);
}
private void fillContextMenu(IMenuManager manager) {
manager.add(inspectAction);
manager.add(launchAction);
// Other plug-ins can contribute there actions here
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(inspectAction);
manager.add(launchAction);
}
private void makeActions() {
inspectAction = new Action() {
public void run() {
if (!VclHook.available()) {
showMessage("OpenOffice is not launched or initializing. Click \"Launch\" to start OpenOffice or wait it to finish initializing.");
return;
}
try {
VclHook.invokeCommand(Constant.RC_DisplayHid, new Object[]{Boolean.TRUE});
} catch (Exception e) {
showMessage("OpenOffice disappeared! It maybe crashed or freezed. Please re-launch it.");
}
}
};
inspectAction.setText("Inspect");
inspectAction.setToolTipText("Inspect VCL controls.");
// action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
// getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
launchAction = new Action() {
public void run() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
final String ooHome = store.getString(PreferenceConstants.P_OPENOFFICE_HOME);
if (ooHome == null || ooHome.length() == 0) {
showMessage("Please set OpenOffice home in the Vclauto assistant preference page.");
return;
}
File ooHomeFile = new File(ooHome, "soffice.bin");
if (!ooHomeFile.exists()) {
showMessage("OpenOffice home is not set correctly in the Vclauto assistant preference page.");
return;
}
IRunnableWithProgress op = new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor arg0) throws InvocationTargetException, InterruptedException {
VclApp app = new VclApp(ooHome);
if (!app.exists()) {
app.kill();
app.start();
}
}
};
IWorkbench wb = PlatformUI.getWorkbench();
try {
wb.getProgressService().run(true, false, op);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
launchAction.setText("Launch");
launchAction.setToolTipText("Launch OpenOffice");
// action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
// getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
insertCodeAction = new Action() {
public void run() {
ISelection selection = viewer.getSelection();
if (selection == null)
return;
final ControlInfo controlInfo = (ControlInfo)((IStructuredSelection) selection).getFirstElement();
if (controlInfo.name != null) {
doInsertCode(controlInfo.name);
}
}
};
}
private String validateName(String name) {
if (uiMapOp.names.contains(name))
return "Duplicated name.";
IStatus status = JavaConventions.validateFieldName(name, "1.5", "1.5");
return status.isOK() ? null : "It's an invalidate java field name.";
}
private boolean doDefineName(ControlInfo controlInfo) {
try {
uiMapOp.define(controlInfo);
} catch (Exception e) {
controlInfo.name = null;
e.printStackTrace();
}
return true;
}
private void doInsertCode(String code) {
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchWindow window = wb.getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
IEditorPart editorPart = page.getActiveEditor();
if (!(editorPart instanceof AbstractTextEditor))
return;
AbstractTextEditor editor = (AbstractTextEditor) editorPart;
IDocumentProvider dp = editor.getDocumentProvider();
IDocument doc = dp.getDocument(editor.getEditorInput());
try {
ITextSelection textSelection = (ITextSelection) editorPart.getSite().getSelectionProvider().getSelection();
int offset = textSelection.getOffset();
doc.replace(offset, textSelection.getLength(), code);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void hookDoubleClickAction() {
viewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
insertCodeAction.run();
}
});
}
private void showMessage(String message) {
MessageDialog.openInformation(
viewer.getControl().getShell(),
"Vcl Explorer",
message);
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
viewer.getControl().setFocus();
}
@Override
public void addWinInfo(final SmartId id, final long type, final String t) {
final String tooltip = t.replaceAll("%.*%.*:", "");
ControlInfo info = new ControlInfo(id, type, tooltip);
//info.shot();
controlInfos.add(info);
}
@Override
public void onFinishReceiving() {
// for (ControlInfo info : controlInfos) {
// info.shot();
// }
//
display.asyncExec(new Runnable() {
public void run() {
if (uiMapOp.scan()) {
uiMapOp.populateName(controlInfos);
} else {
messageLabel.setText("Can not find UIMap and code generating will not work.");
}
viewer.setInput(controlInfos);
}
});
}
@Override
public void onStartReceiving() {
controlInfos = new ArrayList<ControlInfo>();
}
}
\ No newline at end of file
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.views;
import java.util.ArrayList;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
public class VclExplorerContentProvider implements IStructuredContentProvider {
public VclExplorerContentProvider() {
}
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
ArrayList<ControlInfo> oldControlInfos = (ArrayList<ControlInfo>) oldInput;
if (oldControlInfos != null) {
for (ControlInfo info : oldControlInfos) {
info.dispose();
}
}
}
public void dispose() {
}
public Object[] getElements(Object parent) {
ArrayList<ControlInfo> controlInfos = (ArrayList<ControlInfo>) parent;
if (controlInfos != null)
return controlInfos.toArray();
return new Object[0];
}
}
\ No newline at end of file
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.vclauto.assistant.views;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
public class VclExplorerLabelProvider extends LabelProvider implements ITableLabelProvider {
public VclExplorerLabelProvider() {
}
public String getColumnText(Object obj, int index) {
ControlInfo info = (ControlInfo) obj;
switch (index) {
case 0:
return info.id.toString();
case 1:
return info.name;
case 2:
return Long.toString(info.type) + " " + info.getVclType();
case 3:
return info.tip;
}
return "";
}
public Image getColumnImage(Object obj, int index) {
return null;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment