Reader small image

You're reading from  Eclipse Plug-in Development Beginner's Guide - Second Edition

Product typeBook
Published inAug 2016
Reading LevelExpert
Publisher
ISBN-139781783980697
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Alex Blewitt
Alex Blewitt
author image
Alex Blewitt

contacted on 30 aug 16 _____________ Dr Alex Blewitt has over 20 years of experience in Objective-C and has been using Apple frameworks since NeXTstep 3.0. He upgraded his NeXTstation for a TiBook when Apple released Mac OS X in 2001 and has been developing on it ever since. Alex currently works for an investment bank in London, writes for the on-line technology news site InfoQ and has published two other books for Packt publishing. He also has a number of apps on the Apple AppStore through Bandlem Limited. When he's not working on technology, and if the weather is nice, he likes to go flying from the nearby Cranfield airport. Alex writes regularly at his blog, http://alblue.bandlem.com, as well tweeting regularly from Twitter as @alblue. Acknowledgements This book would not have been possible without the ongoing love and support of my wife Amy, who has helped me through both the highs and lows of life. She gave me the freedom to work during the many late nights and weekends that it takes to produce a book and its associated code repository. She truly is the Lem of my life. I'd also like to thank my parents, Ann and Derek, for their encouragement and support during my formative years. It was this work ethic that allowed me to start my technology career as a teenager and to incorporate my first company before I was 25. I'd also like to congratulate them on their 50th wedding anniversary in 2015, and I look forward to reaching that goal with Amy. Thanks are due especially to the reviewer of this version of the book: Antonio Bello, as well as the previous version of this book: Nate Cook, James Robert and Arvid Gerstmann, who provided excellent feedback on the contents of this book during development and caught many errors in both the text and code. Any remaining errors are my own. I'd also like to thank my children Sam and Holly for inspiring me and hope that they too can achieve anything that they set their minds to. Finally, I'd like to thank Ben Moseley and Eren Kotan, both of whom introduced me to NeXT in the first place and set my career going on a twenty year journey to this book.
Read more about Alex Blewitt

Right arrow

Appendix B. Pop Quiz Answers

Chapter 1 – Creating Your First Plug-in


Eclipse workspaces and plug-ins

1. An Eclipse workspace is the location where all the projects are stored.

2. The naming convention for Eclipse plug-in projects is to use a reverse domain name prefix, such as com.packtpub. Additionally UI projects typically have a .ui. in their name.

3. The three key files in an Eclipse plug-in are META-INF/MANIFEST.MF, plugin.xml, and build.properties.

Launching Eclipse

1a. Quit the application with File | Exit.

1b. Use the stop button from the Debug or Console views.

2. Launch configurations are similar to pre-canned scripts which can start up an application, set its working directory and environment, and run a class.

3. Launch configurations are modified with the Run | Run Configurations… or Debug | Debug Configurations… menus.

Debugging

1. Use the Debug | Debug configurations or Debug | Debug As… menus.

2. Set step filters via the preferences menu to avoid certain package names.

3. Breakpoints can be: conditional, method entry/exit, enabled/disabled, or number of iterations.

4. Set a breakpoint and set it after a hit count of 256.

5. Use a conditional breakpoint and set argument==null as the condition.

6. Inspecting an object means opening it up in the viewer so that the values of the object can be interrogated and expanded.

7. The expression watches window allows arbitrary expressions to be set.

8. Multiple statements can be set in the breakpoint conditions provided that there is a return statement at the end.

Chapter 2 – Creating Views with SWT


Understanding views

1. In the Eclipse 3.x model, views must be subclasses of ViewPart. In the Eclipse 4.x model, parts do not need to have an explicit superclass.

2. In the Eclipse 3.x model, views are registered via an org.eclipse.ui.views extension point in the plugin.xml.

3. The two arguments that most SWT objects have are a Composite parent and an integer flags field.

4. When a widget is disposed, it will have its native resources released to the operating system. Any subsequent actions will throw an SWTException with a Widget is disposed message.

5. The Canvas has many drawing operations; to draw a circle, use drawArc(), and specify a full orbit.

6. To receive drawing events, a PaintListener must be created and associated with the control by using the addPaintListener method.

7. UI updates not on the UI thread will generate an SWTException with an Invalid thread access error.

8. To perform an update on a widget from a non-UI thread, use the asyncExec or syncExec methods from Display (3.x) or UISynchronize (4.x) to wrap a Runnable or lambda that will run on the UI thread.

9. SWT.DEFAULT is used to indicate default options in the flags parameter that is passed to the construction of an SWT widget.

10. Create a RowData object with the given size, and associate it with each widget.

Understanding resources

1. Resource leaks occur when an SWT Resource is acquired from the OS but then not returned to it via a dispose method prior to the object being garbage collected.

2. The different types of resources are Color, Cursor, Font, GC, Image, Path, Pattern, Region, TextLayout, and Transform.

3. Run the Eclipse instance in tracing mode, with org.eclipse.ui/debug and org.eclipse.ui/trace/graphics set, specified in a debug file, and launched with -debug.

4. Use the Display.getDeviceData() to get the objects arrays, and iterate through them.

5. The right way is to register a DisposeListener with the view, and the wrong way is to override the dispose method.

Understanding widgets

1. Using the setFocus method to set the focus on a particular widget.

2. Invoking redraw will allow the widget to redraw itself.

3. The combo can have a SelectionListener associated with it.

4. The widgetDefaultSelected is what is called when the default value is used, typically an empty value.

Using SWT

1. Use the Tray and TrayItem widgets.

2. The NO_TRIM means don't draw the edges of the window, or the close/maximize/minimize buttons.

3. Use setAlpha to control a widget's transparency, including shells.

4. setRegion with a path describing the shape.

5. A Group allows you to group things together with a standard item.

6. Most composites use a null layout manager by default; it's only shells and dialogs that have a non-default value.

7. Use a ScrolledComposite.

Chapter 3 – Creating JFace Viewers


Understanding JFace

1. getImage() is called to determine what image to show for an entry, while getText() is used to determine the text value of an entry.

2. The hasChildren() method is used to determine whether or not an element is shown with an expandable element, and getChildren() is used to calculate a list of children.

3. An ImageRegistry is used to share images between plug-ins or different views in plug-ins, with a means of clearing up the resources when the view is disposed.

4. Entries can be styled with an IStyledLabelProvider.

Understanding sorting and filters

1. Specifying a ViewerComparator can allow elements to be sorted in a different order other than the default one.

2. The select() method is used to filter elements, which is originally derived from the Smalltalk terminology.

3. Multiple filters can be combined by setting an array of filters, or by writing a filter to combine two or more filters together.

Understanding interaction

1. Add a DoubleClickListener to the view.

2. Dialog subclasses are used to create a Dialog with custom content.

Understanding tables

1. To show the headers, get the Table from the viewer, and use it to call the setHeaderVisible(true).

2. TableViewerColumn instances are used to set properties on individual columns and to bind the label provider for the columns.

3. An ArrayContentProvider can be used to store items as an array.

4. The TableViewerColumn is a class in the JFace package which defines where the data comes from; the TableColumn is the underlying SWT widget that the width of the column.

Understanding selection

1. Viewers have the getSelection and setSelection methods to get and set the selection, using the ISelection interface (or more commonly the IStructuredSelection interface).

2. The ISelectionChangedListener interface is used to receive notifications for selection changes from a viewer.

3. E4 uses the ESelectionService to maintain the selected object in the workspace, which can be injected into a part.

4. Although the currently selected object can be injected as a field into a part, it is more common to use an optional method with a @Named argument of IServiceConstants.ACTIVE_SELECTION.

Chapter 4 – Interacting with the User


Understanding menus

1. A command can be associated with a handler to provide a menu item. Handlers are indirection mechanisms that allow the same menu (example Copy) to take on different commands based on which context they are in. It is also possible to have a default command id associated with a menu to avoid this indirection.

2. The M1 key is an alias for Cmd on macOS, and for Ctrl on other platforms. When defining standard commands like copy (M1+C) it has the expected behaviour on both platforms (Cmd + C for macOS and Ctrl + C for others).

3. Keystrokes are bound to commands via a binding, which lists the key(s) necessary to invoke and the associated command/handler.

4. A menu's locationURI is where it will contribute the entry to the UI. These are specified either as relative to an existing menu's contribution, or to its generic additions entry. It is also possible to specify custom ones which are associated with custom code.

5. A pop-up menu is created by adding a menu to the part descriptor, and then enabling contributions by registering with the EMenuService.

Understanding jobs

1. The syncExec() will block and wait for the job to complete before continuing code. The asyncExec() will continue to run after posting the job but before it completes.

2. The UISynchronize instance can be used to run jobs on UI and non-SWT UI threads.

3. The UIJob will always run on the UI thread of the runtime, and direct access of widgets will not run into a thread error. Care should be taken to minimize the amount of time spent in the UI thread so as not to block Eclipse. The Job will run on a non-UI thread, and so does not have access to acquire or modify UI-threaded objects.

4. The Status.OK_STATUS singleton is used to indicate success in general. Although it is possible to instantiate a Status object with an OK code, doing so only increases the garbage collection as the Status result is typically discarded after execution.

5. The CommandService can be injected using DI by using @Inject ICommandService into the E4 view.

6. An icon can be displayed by setting a property on the Job with the name IProgressConstants2.ICON_NAME.

7. SubMonitors are generally easier to use at the start of a method, to ensure that the monitor being passed in is correctly partitioned as appropriate for the task in hand. The SubProgressMonitor should generally not be used.

8. The cancellation should be checked as frequently as possible, so that as soon as the user clicks on cancel, the job is aborted.

Understanding errors

1. An informational dialog is shown with MessageDialog.openInformation() (and .openWarning() and .openError() as well). There is also a MessageDialog.openConfirmation(), which returns the value of a yes/no answer to the user.

2. The StatusReporter provides a means to report statuses such that they can be handled appropriately, but without a UI association.

3. Status reporting is asynchronous by default, although a BLOCK option exists to make it synchronous.

4. To combine the results of many things into one report, use a MultiStatus object.

Chapter 5 – Storing Preferences and Settings


Understanding preferences

1. The default style is FLAT but this can be overridden to provide GRID, which provides a better layout for preference pages.

2. There are many subclasses of FieldEditor, which include editors for Boolean, Color, Combo, Font, List, RadioGroup, Scale, String, Integer, Directory, and File.

3. To provide searching in a preference page, keywords must be registered via the keyword extension point.

4. The @Preference annotation, in conjunction with an @Inject annotation, allows a preference store to be injected or a single preference value.

5. If a method is annotated/marked with @Inject and the method parameter is marked with @Parameter, then the method will be called whenever the value changes.

Chapter 6 – Working with Resources


Understanding resources, builders, and markers

1. If an editor complains of a missing document provider, install an instance of TextFileDocumentProvider with the setDocumentProvider() method on the editor.

2. An IResourceProxy is used by a builder to provide a wrapper around an IResource, but which doesn't require the construction of an IResource image.

3. An IPath is a generic file component that is used to navigate files in folders and projects.

4. A nature is a flavor of a project that enables certain behaviors. It is installed with an update to the project descriptor for the given project.

5. Markers are generally created by a builder—though they can be created by any plug-in on a resource. There is a specific function on the resource that can be used to create a marker of a specific type.

Chapter 7 – Creating Eclipse 4 Applications


Understanding E4

1. The application model is stored in the e4xmi file, and provides a way of representing the entire state of the application's UI. It is also persisted on save and then reloaded at startup, so positions of parts and their visibility are persisted. The model is also accessible at runtime via the various M* classes such as MApplication and MPart, and can be queried and mutated at runtime.

2. Parts are a more generic form of views and editors. Unlike Eclipse 3.x, not everything needs to fit into a View or Editor category; they are all just parts that contain UI components underneath, and can be organized appropriately.

3. Although extension points aren't used for things like commands, keybindings or views, they are still used to define other extensions to Eclipse such as builders, marker types, and language parsers. The only thing that the Eclipse 4 model moves out of the extension points are the UI-related concepts. Even then, in the Eclipse 4 IDE the backward compatibility mode ensures that all the UI-related extension points are still rendered. For developing IDE plug-ins, the Eclipse 3.x APIs will likely be around for the next couple of Eclipse releases.

4. The Eclipse 4 contexts are essentially a series of HashMap objects that contain values (objects) associated with keys. Parts can dynamically obtain content from their context, which includes all the injectable services as well as dynamically changing content such as the current selection. A context is implicit in every part, and inherits up the containment chain, terminating with the OSGi runtime.

5. There are several annotations used by Eclipse 4, including @Inject (used to provide a general 'insert value here' instruction to Eclipse), @Optional (meaning it can be null), @Named (to pull out a specific named value from the context), @PostConstruct (called just after the object is created), @PreDestroy (called just before the object is destroyed), @Preference (to pull out a specific preference value or the preference store), @EventTopic and @UIEventTopic (for receiving events via the event admin service and on the UI thread respectively), @Persist and @PersistState (for saving data and view data), @Execute and @CanExecute (for showing what method to execute, and a Boolean conditional which has a Boolean return to indicate if it can run), @Creatable (to indicate that the object can be instantiated), and @GroupUpdate (to indicate that updates can be deferred).

6. Messages are sent via the EventBroker, which is accessible from the injection context. This can use sendEvent or postEvent to send data. On the receiving side, using the @UIEventTopic or @EventTopic annotations is the easiest way to receive values. As with preferences, if it's set up as a method parameter then the changes will be notified.

7. Selection can be accessed using the value from the context with a method injection or value injection using @Named(IServiceConstants.ACTIVE_SELECTION).

Chapter 8 – Migrating to Eclipse 4.x


1. Actions are replaced with handler classes, and annotated with the @Execute annotation.

2. A DoubleClickEvent provides selection through the getSelection method.

3. A view menu will only be shown if the supplementary tab has a tag with ViewMenu.

4. Classes are connected to a handler by specifying a contributor URI with a bundleclass: URI.

5. A platform: URI allows references to resources in other plug-ins, such as graphics or property files; a bundleclass: URI allows a reference to a class in a plug-in. The class reference will be automatically converted to a Java Class.

6. A part represents a rendered part that is shown on the window; a part descriptor represents the definition of the part such that it can be instantiated on demand.

7. Once the pop-up menu has been created, it is necessary to use the EMenuService to register the control handler to the ID specified of the pop-up menu.

8. The selection can be obtained from the viewer using getSelection, but this will not trigger when it changes—to receive events when it does change, the viewer will need to have a selection listener added, which can then forward it to the Eclipse 4.x ESelectionService.

Chapter 9 – Styling Eclipse 4 Applications


Styling Eclipse 4

1. Eclipse 4 parts can be styled with CSS, and the underlying renderer applies the styles on the fly, including if the CSS styles change. This allows theme managers to apply different color combinations in Eclipse 4 in ways not possible in Eclipse 3.

2. An Eclipse 4 Theme is a pre-configured set of colors and styles that can be applied to a user environment, as well as dynamically switched at runtime.

3. Elements can be referenced by a CSS class name (such as .MPart), by an ID (with # as a prefix and substitutingfor example . in identifier names), or by a Java class name directly.

4. To change all labels in Eclipse to italics, the CSS would look like:

Label { font-style: italic }

5. The CSS Spy is opened by pressing Alt + Shift + F5.

6. The IThemeEngine can be used to acquire a list of themes and change them dynamically in the application.

Chapter 10 – Creating Features, Update Sites, Applications, and Products


Understanding features, applications, and products

1. The keyword qualifier is replaced with a timestamp when plug-ins or features are built.

2. The files are artifacts.jar and content.jar as well as one file per feature/plug-in built.

3. The older site.xml can be used, or a category.xml file which is essentially equivalent.

4. If a feature requires another, then it must be present in the Eclipse instance in order to install. If a feature includes another, then a copy of that included feature is included in the update site when built.

5. An application is a standalone application that can be run in any Eclipse instance when it is installed. A product affects the Eclipse instance as a whole, replacing the launcher, icons, and default application launched.

6. An application is a class that implements IApplication and has a start() method. It is referenced in the plugin.xml file and can be invoked by ID with -application on the command line.

7. A target definition is used to define set of plug-ins to compile against, when set as a target platform.

Chapter 11 – Automated Testing of Plug-ins


Understanding swtbot

1. The unit runner that is required is SWTBotJunit4ClassRunner, which is set up with an annotation @RunWith(SWTBotJunit4ClassRunner.class).

2. Views are set up by driving the menu to perform the equivalent of Window | Show View | Other… and driving the value of the dialog.

3. To get the text value of a dialog, use textWithLabel to find the text field next to the associated label, and then get or set the text from that.

4. A Matcher is used to encode a specific condition, such as a view or window with a particular title. It can be handed over to the SWTBot runner to execute in the UI thread and return a value when it is done.

5. To get values from the UI, use a StringResult (or other equivalent types) and pass that into the syncExec method of UIThreadRunnable. It will execute the code, return the value, and then pass that to the calling thread.

6. Use the bot's waitUntil or waitWhile methods, which block execution of the test until a certain condition occurs.

Chapter 12 – Automated Builds with Tycho


Understanding automated builds and update sites

1. The GroupId, ArtifactId, and Version make a set of co-ordinates known as a GAV, which Maven uses to identify dependencies and plugins. The group is a means of associating multiple artifacts together, and the artifact is the individual component name. In OSGi and Eclipse builds, the group is typically the first few segments of the bundle name, and the artifact is the bundle name. The version follows the same syntax as the bundle's version, except that .qualifier is replaced with -SNAPSHOT.

2. The six types are pom (used for the parent), eclipse-plugin (for plug-ins), eclipse-test-plugin (for running plug-in tests and UI tests), eclipse-feature (for features), eclipse-repository (for update sites and products), and eclipse-target-definition (for defining target platforms).

3. Version numbers can be updated with mvn org.eclipse.tycho:tycho-versions-plugin:set-version -DnewVersion=version.number. Note that although mvn version:set exists, it will not update the plug-in versions if chosen.

4. Jars are signed to ensure that the contents of the Jar have not been modified after creation. Eclipse looks at these Jars at runtime to ensure that they are not modified, and warns if they are unsigned or if the signatures are invalid. The standard JDK tool jarsigner is used to sign and verify Jars; the JDK tool keytool is used to manipulate keys.

5. A simple HTTP server can be launched with python -m SimpleHTTPServer. In Python 3, the command is python3 -m http.server.

6. Eclipse features are typically published in the Eclipse Marketplace at http://marketplace.eclipse.org. This includes both open-source and commercial plug-ins.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Eclipse Plug-in Development Beginner's Guide - Second Edition
Published in: Aug 2016Publisher: ISBN-13: 9781783980697
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Alex Blewitt

contacted on 30 aug 16 _____________ Dr Alex Blewitt has over 20 years of experience in Objective-C and has been using Apple frameworks since NeXTstep 3.0. He upgraded his NeXTstation for a TiBook when Apple released Mac OS X in 2001 and has been developing on it ever since. Alex currently works for an investment bank in London, writes for the on-line technology news site InfoQ and has published two other books for Packt publishing. He also has a number of apps on the Apple AppStore through Bandlem Limited. When he's not working on technology, and if the weather is nice, he likes to go flying from the nearby Cranfield airport. Alex writes regularly at his blog, http://alblue.bandlem.com, as well tweeting regularly from Twitter as @alblue. Acknowledgements This book would not have been possible without the ongoing love and support of my wife Amy, who has helped me through both the highs and lows of life. She gave me the freedom to work during the many late nights and weekends that it takes to produce a book and its associated code repository. She truly is the Lem of my life. I'd also like to thank my parents, Ann and Derek, for their encouragement and support during my formative years. It was this work ethic that allowed me to start my technology career as a teenager and to incorporate my first company before I was 25. I'd also like to congratulate them on their 50th wedding anniversary in 2015, and I look forward to reaching that goal with Amy. Thanks are due especially to the reviewer of this version of the book: Antonio Bello, as well as the previous version of this book: Nate Cook, James Robert and Arvid Gerstmann, who provided excellent feedback on the contents of this book during development and caught many errors in both the text and code. Any remaining errors are my own. I'd also like to thank my children Sam and Holly for inspiring me and hope that they too can achieve anything that they set their minds to. Finally, I'd like to thank Ben Moseley and Eren Kotan, both of whom introduced me to NeXT in the first place and set my career going on a twenty year journey to this book.
Read more about Alex Blewitt