the eclipse rcp - Ты знаешь, что...
TRANSCRIPT
© 2005 IBM
102 – Developing Applications With the Eclipse Rich Client Platform (RCP)
John Arthorne & Chris LaffraIBM Rationalhttp://eclipsefaq.org/john,chris
Tuesday, Aug. 30, 9:15 a.m. – 10:45 a.m.
© 2005 IBM
Session Abstract When many people think of Eclipse, they see a Java-
centric development environment. But there's more to Eclipse than Java—you now have several languages and protocols from which to choose.
The Eclipse versioned plug-in architecture lets developers easily add new components, including language support for C++, PHP, Fortran, Web services and others.
In this session, we will show how easy it is to write your own rich client applications based on the Eclipse Rich Client Platform (RCP).
We will guide you through the various parts of the Eclipse RCP infrastructure that are available as building blocks for your own applications
© 2005 IBM
Roadmap Introduction Rich Client Programming The Eclipse RCP Project
Examples of RCP applicationsQuick tour of RCP APIsBuilding your own Eclipse RCP application
Conclusions
© 2005 IBM
Source of Materials Material sources:
My headRCP tutorials at eclipse.orgRCP samples from eclipse.orgFeedback from Eclipse committersThe Official Eclipse 3.0 FAQs
© 2005 IBM
Format Question and answer format We will introduce
Some background; what is a Rich Client? The Eclipse project and RCPQuick tour of Eclipse RCP plugins with sample
code
After this presentation, you should be able to develop your own Eclipse RCP application.
© 2005 IBM
What is a Rich Client? Google dictionary:
“A computer program that can download files for manipulation, run applications, or request application-based services from a file server.”
Need some form of ‘installation’. Not a Thin Client (like a Web site). A ‘client’ with rich UI and interaction
© 2005 IBM
Rich Client Examples Java Applets in a browser JavaScript applications (e.g., Bindows) J2ME MIDP Midlets on a phone/PDA Macromedia Flash MX Microsoft Foundation Class (MFC) apps Eclipse Rich Clients
© 2005 IBM
Rich Client Criterias Support for various platforms Ease of installation Look-and-Feel The ‘Richness’ of the solution Interoperability with other solutions Tooling support Performance Mind-share (following the current trend)
© 2005 IBM
The Eclipse RCP in a nutshell The Eclipse Rich Client Platform is a subset
of the Eclipse platform designed for developing Rich Clients written in Java, using the Eclipse plug-in model for defining individual components using XML manifests.
Open Source, free. Uses SWT for close-to-native feeling
© 2005 IBM
Eclipse RCP sample 2IBM Workplace Client Technology, Client Administrator
Shown atEclipseCon2005
© 2005 IBM
Eclipse RCP Motivation Modular approach, using plug-ins written in XML and Java.
Connections between plug-ins are loose. Lots of open source plug-ins easily added to your
application Eclipse behaves like a native application (due to SWT). Eclipse is a framework. Lots of lessons learned and
decisions have been made for you, leaving you more time to focus on your value add. The learning curve will pay off.
Upgradeability. Use plug-ins to upload content handlers, and provide users with a given set of abilities and plugins based on their credentials.
Versioning. Plug-ins are versioned, platform manages them.
© 2005 IBM
What is Eclipse?
An open IDE platform for anything, and for nothing in particular. Open: allows for easy extension by third parties. IDE: tooling to manage workspaces; to build,
launch and debug applications; team sharing; easy customization of the programming experience.
Platform: not a finished application Anything: Java, Web-services, games, etc. Nothing in particular: Java focus is historical.
© 2005 IBM
Where did Eclipse RCP come from? Core of OTI/IBM products since late 90’s VisualAge Micro Edition (written in Java, first
use of SWT) VAME framework generalized into Eclipse Eclipse open source project, Fall 2001 Community began tearing it apart to build
things other than language tools Eclipse RCP released in June 2004 (part of
Eclipse 3.0)
© 2005 IBM
What articles are there? More than 60 at http://eclipse.org/articles Printable format is over 500 pages Covers wide range of Eclipse topics; from
SWT to preferences to RCP to Wizards to style guides to internationalization to editor support to using CVS branching.
IBM DeveloperWorks also hosts a few dozen articles on Eclipse and products
© 2005 IBM
What books are available? More than 28 were
counted in July 2005 Many are introductory
with wide coverage Others focus on vertical
domain (SWT, EMF) Eclipse RCP Book:
October 2005, Jeff McAffer and Jean-Michel Lemieux
© 2005 IBM
Where to download Eclipse? Eclipse.org/downloads:
Latest Release tested, may be 6 months old Stable/milestone build, 6 weeks apart Integration build, each week Nightly build, mileage varies directly from CVS, not for the faint of heart
Builds are tested and results are posted
© 2005 IBM
Eclipse Supported Platforms Microsoft Windows 2000/XP Red Hat Enterprise Linux SuSE Linux 8.2 Sun Solaris 8 SPARC Motif HP HP−UX 11i hp9000 IBM AIX 5L PowerPC Motif Apple Mac OS X 10.3 SWT also on QNX Photon and Win CE
© 2005 IBM
How to upgrade Eclipse? Use the included Update Manager
works for Eclipse IDE and RCP upgrade existing plug-ins to later versions install new plug-ins from third party locations
Allows you to build a rich client and have extensions added later (like content handlers or additional business logic)
© 2005 IBM
Where to get Help? Included in your plug-ins/application:
Help > Help Contents…F1, context-sensitive helpCan be added to an RCP application
During development:http://eclipse.org (articles, newsgroups, etc)Books, tutorials, portals“Use the source, Luke!”
© 2005 IBM
What is a plug-in? An encapsulation of behavior that
cooperates with other plug-ins to construct a program
Plug-ins typically consists of:Manifest, described in plugin.xmlIcons and resource bundles Java code in one or more jars
In Eclipse, everything is a plug-in
© 2005 IBM
What is the plugin.xml file? Here is an example:
<?xml version="1.0" encoding="UTF−8"?> <?eclipse version="3.0"?> <plugin id="com.xyz.myplugin" name="My Plugin“ class="com.xyz.MyPlugin" version="1.0"> <runtime> <library name="MyPlugin.jar"/> </runtime> <requires> <import plugin="org.eclipse.core.runtime"/> </requires> </plugin>
© 2005 IBM
How do I connect plug-ins? To access classes from other plug-ins,
add those to your plugin.xml:<requires> <import plugin="org.eclipse.jface"/> <import plugin="org.eclipse.swt"/></requires>
To publish certain classes from your plug-in, use a library and a wild-card:
<runtime> <library name="sample.jar"> <export name="com.xyz.*"/> </library></runtime>
© 2005 IBM
How do I connect plug-ins? Use extension points published by
other plug-ins to add your behavior to Eclipse
Define (publish) new extension points to allow others to customize your implementation
© 2005 IBM
What are extension points? Extension points (e.p.) are all about
loose coupling of complex system Interface is described in XML Implementation is usually in Java Allow for extending/customizing
existing systems
© 2005 IBM
Extension point activationArrayList contributors = new ArrayList();IExtensionPoint point = Platform. getExtensionRegistry().getExtensionPoint(ID);IExtension[] extensions = point.getExtensions();for (int i = 0; i < extensions.length; i++)
IExtension ext = extensions[i];IConfigurationElement[] elements =
ext.getConfigurationElements();for (int j = 0; j < elements.length; j++)
contributors.add( elements[j].createExecutableExtension("class"));
© 2005 IBM
What is an e.p. schema? Each e.p. has a schema Defines the e.p. elements/grammar Also contains documentation Used only during development Not used for runtime validation See PDE Schema Editor to edit
© 2005 IBM
When is a plug-in started? Plug-in has declarative and code parts Declarative part is analyzed to show UI Code part is started lazily, as late as
possible, only when really needed:When executable extension is generatedWhen published classes are used by othersWhen explicitly created (e.g. early startup)
Plug-in class is loaded before any other
© 2005 IBM
What’s the plug-in’s classpath? This is a question often asked by
‘traditional’ Java programmers A plug-in’s classpath lookup order is:
1. OSGi parent classloader (bootloader, rt.jar)2. Plug-in’s own libraries3. Exported libraries from required plug-ins
You could declare your own custom classloader (e.g., done by Ant and Help)
Buddy-loading system in Eclipse 3.1
© 2005 IBM
What is a plug-in fragment? Plug-ins can have optional parts, each
declared in a fragment, using fragment.xml Example: SWT + 1 fragment per platform Behaves similarly to regular plug-in Main mechanism for plug-in customization Fragments are added to plug-in classpath Commonly used for translation packs
© 2005 IBM
What is a dynamic plug-in? Dynamic plug-ins avoid a platform restart Four classes of dynamicity:
Nondynamic, lots of hard links to other plug-ins Dynamic-aware, expects other plug-ins to be
unloaded at any given time Dynamic-enabled, can be unloaded without
needing to restart the platform Fully Dynamic, uses OSGi to the fullest power
to unload or reload itself
© 2005 IBM
Runtime Support The Eclipse Runtime has support for
Progress monitors Logging and debug tracing Preferences storage Management of background jobs
Plug-in: org.eclipse.core.runtime
© 2005 IBM
What is a ProgressMonitor? Here is an example:
ProgressMonitor monitor = ...;try
monitor.beginTask("Performing decathlon: ", 10);monitor.subTask("hammer throw");//perform the hammer throwmonitor.worked(1);//... repeat for remaining nine events
finally monitor.done();
© 2005 IBM
What is a Job? Runs in background and not in UI thread Used for long-running activities, such as
building, server connections, etc. Here is an example:
Job myJob = new Job("Sample Job") public IStatus run(IProgressMonitor monitor)
System.out.println("This runs in a job");Return Status.OK_STATUS;
;myJob.schedule();
© 2005 IBM
Job advantages? Runs in background and not in UI thread Less overhead, uses thread pooling Support for progress and cancellation Priorities and mutual exclusion Advanced scheduling features Centralized UI
© 2005 IBM
What is SWT? SWT = Standard Widget Toolkit Goal: “efficient, portable access to the user
interface features of the operating systems on which it is implemented.”
Thin native mapping layers. For instance, Tree widget is Java API that maps directly to a native widget on Windows.
Runs on Win32, Linux, AIX, HPUX, MacOS, Photon, and Pocket PC
© 2005 IBM
Why does Eclipse use SWT? Historical: VisualAge for Java, writing in
Smalltalk, used the Common Widget toolkit Early experiments used the brand new
Swing toolkit in 1998. For IDEs, the design team wanted native look & feel. Hence CW was ported to Java, and adopted in Eclipse
Eclipse is an integration platform, integrating closely with the OS makes a lot of sense
SWT and Swing are interoperable
© 2005 IBM
Is SWT better than Swing? Is a hammer better than a screwdriver? Different tools, with different goals SWT goals: native look and feel, high
performance, deep platform integration Swing goals: high customization, same look
and feel across platforms Answer depends on your tradeoffs and
customer preference
© 2005 IBM
The JFace Framework UI Framework on
top of SWT, adding commonly usedcomponents
Like SWT, looselybased on Eclipse;can be used in isolation easily
JFace
SWT
button menutable
layout
treeshell
…
viewers wizardsactions
preferencesdialogs
© 2005 IBM
What is a Viewer? Model-view-controller on top of SWT Adds lower-level management to a widget:
add/remove items, sort, filter, refresh, etc. Example of a TableViewer:
int style = SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL;Table table = new Table(parent, style);TableViewer viewer = new TableViewer(table);viewer.setContentProvider(new BookshelfContentProvider());viewer.setLabelProvider(new BookshelfLabelProvider());viewer.setInput(createBookshelf());
© 2005 IBM
What is a Viewer? Various kinds of viewers:
TreeViewer TableViewer ListViewer TableTreeViewer TextViewer CheckBoxTreeViewer CheckBoxTableViewer
Example of a TreeViewer
© 2005 IBM
What is a Wizard? A wizard contains:
Series of Pages Back/Next buttons Finish/Cancel buttons A title A message area A progress monitor
May be in a Dialog but not necessarily API controls page order
A sample wizard
© 2005 IBM
How do I show a Wizard? Implement IWizardContainer (such as the
JFace WizardDialog does)
Here is an example:
Shell shell = window.getShell();MyWizard wizard = new MyWizard();WizardDialog dialog = new WizardDialog(shell, wizard);int result = dialog.open();
© 2005 IBM
How do I ask a question? Two kinds of questions:
MessageDialog.openQuestion(…) Yes/No MessageDialog.openConfirm(…) OK/Cancel
Here is an example:IStatus warning = new Status(IStatus.WARNING,
ExamplesPlugin.ID, 1, “Final warning.", null);ErrorDialog.openError(window.getShell(),
"This is your final warning", null, warning); Custom message dialogs are also possible
© 2005 IBM
The generic Workbench The generic elements in the workbench Naming history for “workbench”:
Used to be called “Desktop” in older Eclipses With IDE focus, renamed to “Workbench” With RCP focus, “Workbench” split from “IDE”
Generic workbench contains: The Workbench itself, with its parts, pages,
windows, progress view, status bar, menu, etc.
© 2005 IBM
Parts, Pages, Sites, Windows, eh? The entire UI is called “Workbench” Displayed in one or more “Windows”:
Title bar, Menu bar, and Cool bar Fast view bar Status line + Progress view Workbench pages contents:
• One or more workbench parts: Editors + Views• Layout is controlled by a “Perspective”
© 2005 IBM
Parts, Pages, Sites, Windows, eh? Example: ContentOutline knows its site, which
provides API to its page, which is hosted by a window, which belongs to the workbench:
© 2005 IBM
Creating Preference Pages Extension point in
org.eclipse.ui.workbench Implement either
IPreferencePage orIFieldEditorPreferencePage
Preference pages can also be used stand-alone, without using extension points
See: Programmer’s Guide > Preference pagesand three Eclipse articles on Preference pages
© 2005 IBM
Using an ImageRegistry Images are OS resources that need to be
managed carefully to avoid waste & leaks Here is an example:public class ExamplesPlugin extends AbstractUIPlugin
public static final String PLUGIN_ID ="org.eclipse.faq.examples";
public static final String IMAGE_ID = "sample.image";...protected void initializeImageRegistry(ImageRegistry registry)
Bundle bundle = Platform.getBundle(PLUGIN_ID);IPath path = new Path("icons/sample.gif");URL url = Platform.find(bundle, path);ImageDescriptor desc = ImageDescriptor.createFromURL(url);registry.put(IMAGE_ID, desc);
© 2005 IBM
Creating new Perspectives Extension point: org.eclipse.ui.perspectives Defines initial layout relative to editor area
and contents of menus and toolbar API allows for whatever you can do in
Window > Customize Perspective See Help for a good explanation in the PDE
section to create new perspectives
© 2005 IBM
Views and Editors Workbench contains Views and Editors. Create one
using the PDE plug-in template wizard.
© 2005 IBM
Views and Editors Compared
Use global toolbarHave a local toolbar
Can be “dirty”Nothing to save
At fixed page locationAnywhere on page
E.g., Java Editor/PDEE.g., Outline/Navigator
Multiple per pageOne per page
Arbitrary layoutArbitrary layout
Arbitrary contentsArbitrary contents
EditorsViews
© 2005 IBM
A Minimal Editor
<editor name="Minimal Editor" extensions="min" icon="icons/sample.gif" class=“acme.editor.MinimalEditor" id=“acme.editor.MinimalEditor"></editor>
Step one: declare extension point, specify what file extensions to handle, and class name of editor.
© 2005 IBM
A Minimal Editor
public class MinimalEditor extends EditorPart private Label contents; public void createPartControl(Composite parent) contents = new Label(parent, SWT.NONE); contents.setText("Minimal Editor"); public void init(IEditorSite site, IEditorInput input) setSite(site); setInput(input); public void setFocus() contents.setFocus();
Step two: Implementation.
© 2005 IBM
More Elaborate Editors
For form-based editors, such as the PDE plugin.xml editor, use the org.eclipse.ui.forms extension point
For graphical editors, see the Eclipse Graphical Editor Framework (GEF) project at http://eclipse.org/gef
For nested editors, see the PDE wizard that creates a multi-page editor, using the MultiPageEditorPart.
For text editors, see Chapter 15 and 19 of the Eclipse FAQ book
© 2005 IBM
Buttons and Menus
Menus and toolbars use ‘Actions’ to define content:<action
class=“acme.actions.ToolBarAction"toolbarPath="Normal/exampleGroup"menubarPath=“Acme/acmeGroup"icon="icons/sample.gif"tooltip="Sample ACME action">
</action> See the PDE wizard for the ‘Hello World’ plug-in
© 2005 IBM
Commands
An abstraction of Actions Do not physically appear in the UI, and they have
no code associated with them Must be associated with an action that performs
the work Key bindings are associated with commands Example: The ‘Cut’ command is mapped to Ctrl+C.
When an editor gets focus, it associates a particular text cut action with that command
© 2005 IBM
What is an Eclipse Application?
Could be “headless” with no UI Could use just runtime (extension registry) Just SWT and JFace
But Eclipse has a particular technical use of the word “application”. Only one per Eclipse instance; the equivalent of ‘main’
© 2005 IBM
What is an Eclipse Application?
Sample of plugin.xml for a simple headless application:
<plugin id=“acme” ...> <extension id="hello"
point="org.eclipse.core.runtime.applications"><application>
<run class="org.eclipse.faq.HelloWorld"/></application>
</extension>
© 2005 IBM
What is an Eclipse Application?
Here is the Java part for this sample:
public class HelloWorld implements IPlatformRunnable
public Object run(Object args) System.out.println("Hello");return EXIT_OK;
© 2005 IBM
What is an Eclipse Application?
Here is how the sample is executed:eclipse −application acme.hello
The fully qualified ID is the plugin ID + application ID (i.e., “acme” + “.” + “hello”).
Application get to fully control contents of menu, toolbar, views, etc. Much more control than plug-ins hosted by the Eclipse IDE.
Eclipse Application can have UI or be headless See also IDEApplication in org.eclipse.ui.ide.
© 2005 IBM
What is an RCP app?
RCP apps have more control over UI Workbench is still in charge, but takes “advice”
from the RCP application WorkbenchAdvisor: main advisor; responsible for
event loop, application lifecycle, creating other advisors
WorkbenchWindowAdvisor: responsible for lifecycle of a window
ActionBarAdvisor: responsible for filling the menus, tool bars, and status bar
© 2005 IBM
Minimal Eclipse RCP App?
Simple workbench advisor that is also the application:
public class MinimalRCPApp extends WorkbenchAdvisorimplements IPlatformRunnable
createWorkbenchWindowAdvisor(...) ...getInitialWindowPerspectiveId() ...run(...) ...
© 2005 IBM
Minimal Eclipse RCP App?
First, tell the configurer what perspective to use:
public String getInitialWindowPerspectiveId() return "org.eclipse.faq.minimalperspective";
© 2005 IBM
Minimal Eclipse RCP App?
Define a workbench window advisor:
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
IWorkbenchWindowConfigurer configurer) return new MinimalWindowAdvisor(configurer);class MinimalWindowAdvisor extends
WorkbenchWindowAdvisor public void preWindowOpen() …
© 2005 IBM
Minimal Eclipse RCP App?
Then, window advisor defines what to show: public void preWindowOpen() IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); configurer.setShowCoolBar(false); configurer.setShowFastViewBars(false); configurer.setShowMenuBar(false); configurer.setShowPerspectiveBar(false); configurer.setShowProgressIndicator(false); configurer.setShowStatusLine(false);
© 2005 IBM
Minimal Eclipse RCP App?
Finally, get an SWT display, and launch the platform on it, using your workbench advisor:
public Object run(Object args) throws Exception
Display d = PlatformUI.createDisplay();int ret = PlatformUI.createAndRunWorkbench(d, this);if (ret == PlatformUI.RETURN_RESTART)
return EXIT_RESTART;return EXIT_OK;
© 2005 IBM
Minimal Eclipse RCP App?
The result: no menu bar, no toolbar, no status bar, no views, no editors:
© 2005 IBM
Customizing the RCP menus
Method implemented by ActionBarAdvisor: public void fillMenuBar(IMenuManager mainMenu)
MenuManager windowMenu = new MenuManager("&Window",IWorkbenchActionConstants.M_WINDOW);
mainMenu.add(windowMenu);windowMenu.add(ActionFactory.MAXIMIZE.create(window));MenuManager helpMenu = new MenuManager("&Help",
IWorkbenchActionConstants.M_HELP);mainMenu.add(helpMenu);helpMenu.add(new AboutAction());
© 2005 IBM
Enabling action key bindings
Key bindings are made for free when you use the actionSet extension point in your plugin.xml
When you create actions on the fly, make sure your action has a command ID, and then use:
ActionBarAdvisor advisor = ...;IAction action = ...;advisor.register(action);
© 2005 IBM
Just use SWT and JFace?
FAQ 247 discusses how simple that is Complete source is offered at http://eclipsefaq.org
© 2005 IBM
Storing Application Data
Data is stored in the ‘workspace’ Simplest way is to rely on the –data argument See Platform.getInstanceLocation(); Make sure to lock the workspace location You can choose your own location See IDEApplication for all the subtleties
© 2005 IBM
Application vs. Product
Application has program logic written in Java Product is entirely declarative and specifies:
Icons, text, splash screen, etc
One product, can have multiple applications Example: Eclipse IDE is one product, but has
multiple applications, such as the workbench and custom Ant runners
© 2005 IBM
Product Distribution
Zip it up, add a JRE, use an installer Use features and an Update for upgrades Add multiple languages (lots of support here) Use install handlers to do post-installation fixes Add your own splash screen and workbench icon Write your own platform launcher (eclipse.exe) Use art from http://eclipse.org/artwork/main.html
© 2005 IBM
Customizing RCP Apps See the plugin_customization.ini file Example to use curved view header tabs:
org.eclipse.ui/SHOW_TRADITIONAL_STYLE_TABS=false
See Help > Help Contents > Platform Plug-in Developers Guide > Programmer’s Guide > Packaging and Delivering Eclipse-based Products > What is a Product? > Customizing a Product
© 2005 IBM
How do I create a plug-in? Plug-in Development Environment (PDE) has
special wizards to get you going quickly Use code templates to create a plug-in with:
A toolbar button and a menu optionAn editorA view (with a tree or a table)A property pageA new perspective
Help > Cheat Sheet…
© 2005 IBM
Running an RCP Application1. Launch from the project’s context menu:
2. Or simply from the PDE editor:
© 2005 IBM
Branding an RCP Application Creating an Eclipse Product is also easy See File > New > Other... > Product
Configuration
© 2005 IBM
How do I edit a plug-in?
Plug-in Manifest editor providesa graphical viewon the plug-inXML file.
F1 can be usedto get Help.
© 2005 IBM
Extension point creation Plug-ins can publish extension points Create them ala “Monkey see, Monkey do” Alternatively, use PDE manifest editor:
Extension Points > Add…Choose an ID and a nameChoose a name for your schemaAdd one or more elements and save
Generated code ends up in plugin.xml file Click F1 to get Help
© 2005 IBM
How do I create a feature? A special PDE wizard can create a feature:
File > New > Other... > Plug−in Development > Feature Project
Just add the plug-ins you want to add Features are the next step up from plug-ins A product is shipped as a collection of
features, each containing one/more plug-ins
© 2005 IBM
What is the update manager? Help > Software Updates… Allows you to find new features on your
workstation, network, or the Internet Manages configurations, allowing installation
and deactivation of features Needs “update sites” to download features
© 2005 IBM
How to create an update site? A special PDE wizard:
File > New > Other... > Plug−in Development > Update Site Project
Just add the features you want to add
Generates site.xml Editor has a special
“Build All” button
© 2005 IBM
Plug-in, Feature, Update Site Update site has one or
more features Features have one or
more plug-ins Plug-ins provide icons,
plugin.xml and Java implementation
Supports versioning
© 2005 IBM
References http://eclipse.org http://dev.eclipse.org/viewcvs/index.cgi/ ~checkout~/platform-
ui-home/rcp http://eclipsefaq.org http://eclipse.techforge.com