Sunday, January 3, 2010

Eclipse : Tips - Common Utility API in Eclipse

Eclipse API users very often reinvent some common utilities which are already provided by some Eclipse core plugins.
org.eclipse.gmf.runtime.common.ui.util.FileUtil provides methods like createFile(..) and deleteFile(.)..
org.eclipse.gmf.runtime.common.core.util.FileCopyUtil help copyFile(..) and copyFolder(..)
copyFolder(String sourceFolder, String targetFolder) performs a deep copy of all internal folders.

While creating any swt control with Grid data we can reuse org.eclipse.debug.internal.ui.SWTFactory

Unfortunately same SWTFactory exists also in org.eclipse.pde.internal.ui
Instead of duplicating or internalizing or privatizing in a specific tool - such utility classes FileUtil, FileCopyUtil and SWTFactory etc. should be part of a common core public API.

Similarly org.eclipse.jface.layout.GridDataFactory provides a convienient shorthand for creating and initializing GridData.

Example : Typical grid data for a button

// GridDataFactory version
Point preferredSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, false);
* Point hint = Geometry.max(LayoutConstants.getMinButtonSize(), preferredSize);
* GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).hint(hint).applyTo(button);
The same factory can be used many times to create several GridData instances.

In order to create LightWeight Dialog we should extend PopupDialog and for a Multi-selection Search Dialog we have to extend FilteredMultiSelectionDialog which provides a nice ‘search filter text box’.

And there is a well-known - org.eclipse.core.resources.IFile.ResourceUtil – which provides convenience methods findEditor(IWorkbenchPage page, IFile file) to return the editor in the given page whose input represents the given file and vice versa i.e. getFile(IEditorInput editorInput) to find file from editorInput.

org.eclipse.gmf.runtime.common.ui.action.util.SelectionUtil – selects and reveals the object in all the corresponding parts.
It also has got an useful refactoring method startRename(IWorkbenchPart part, Object newElement).
org.eclipse.ui.dialogs.PreferencesUtil provides convenience methods createPreferenceDialogOn() to create a workbench preference dialog and also createPropertyDialogOn().

In the modeling world, in order to copy, remove, replace and resolve semantic model elements EcoreUtil provides all the necessary methods. Similarly
org.eclipse.gmf.runtime.diagram.core.util.ViewUtil provides methods to resolve, delete, insert view model elements.

No comments: