Instanciation de composants

Toutes les interactions impliquant un composant ont lieu dans ISite. Du point de vue du créateur d'un composant, ISite est le composant. ISite peut être créé à partir d'IPartFactory ou en instanciant directement la classe du site.

Pour supprimer un composant, supprimez le contrôle d'ISite.

Instanciation de composants avec IPartFactory

Les vues et les éditeurs sont normalement créés avec IPartFactory. Ce dernier peut seulement créer des composants enregistrés avec les points d'extension des vues ou des éditeurs . Les composants créés par IPartFactory dépendent d'IWorkbenchPage et ne peuvent exister sans ce dernier. IPartFactory crée des composants par identifiant. La classe d'implémentation du composant n'a pas besoin d'être API. IPartFactory peut être obtenu à partir d'IWorkbenchPage. Les composants peuvent également se servir de l'IPartFactory de leur constructeur pour créer des enfants imbriqués.

Cet exemple montre comment créer une vue avec IPartFactory.

/**
 * Used to create instances of editors and views.
 *
 * @since 3.1
 */
public interface IPartFactory {
    /**
     * Creates an instance of a view. Returns an <code>ISite</code> for the newly created view.
     * When the caller is done with the part it should dispose the part's main control. This can
     * be accomplished by calling <code>ISite.getControl().dispose()</code>, or by disposing the
     * parent composite.
     *
     * @param viewId ID of the view, as registered with the org.eclipse.ui.views extension point
     * @param parentComposite parent composite for the view. If the view is successfully created, it
     *        will create exactly one new child control in this composite.
     * @param context local context for the view. This object can override any or all of the view's dependencies.
     *        If the view has a dependency that isn't found in the local context, a default implementation will
     *        be supplied by the org.eclipse.core.component.types extension point.
     * @param savedState previously saved state of the part, or null if none
     * @return an ISite for the newly created view
     * @throws CoreException if unable to create the part
     */
    public ISite createView(String viewId, Composite parentComposite, IContainerContext context, IMemento savedState) throws CoreException;
   
    /**
     * Creates an instance of an editor. Returns an <code>ISite</code> for the newly created editor.
     * When the caller is done with the part it should dispose the part's main control. This can
     * be accomplished by calling <code>ISite.getControl().dispose()</code>, or by disposing the
     * parent composite.
     *
     * @param editorId ID of the editor, as registered with the org.eclipse.ui.editors extension point
     * @param parentComposite parent composite for the editor. If the editor is successfully created,
     *        it will create exactly one new child control in this composite.
     * @param context local context for the editor. This object can override any or all of the part's dependencies.
     *        If the part has a dependency that isn't found in the local context, a default implementation will
     *        be supplied by the org.eclipse.core.component.types extension point.
     * @param input IEditorInput for this editor
     * @param savedState previously saved state for the part, or null if none
     * @return an ISite for the newly created editor
     * @throws CoreException if unable to create the part
     */
    public ISite createEditor(String editorId, Composite parentComposite, IContainerContext context, IEditorInput input, IMemento savedState) throws CoreException;
}


Voici l'exemple d'une action qui crée une vue en utilisant IPartFactory

/**
 * Demonstrate how to open a view by its ID from an IWorkbenchPage.
 */
public class CreateViewByIdAction implements IWorkbenchWindowActionDelegate {
    private IWorkbenchWindow window;

    public void run(IAction action) {       
        IWorkbenchPage page = window.getActivePage();
       
        if (page == null) {
           
// ...uninteresting error-handling code removed...
            return;
        }
       
        final Shell tempShell = new Shell(window.getShell(), SWT.DIALOG_TRIM | SWT.RESIZE);
       
        tempShell.setLayout(new FillLayout());
        tempShell.setText("Problems");
       
        IPartFactory factory = page.getPartFactory();
        try {
            factory.createView(IPageLayout.ID_PROBLEM_VIEW, tempShell, new ContainerContext(), null);
        } catch (CoreException e) {
           
// ...uninteresting error-handling code removed...
        }
       
        // Open the dialog
        tempShell.open();
        Display d = tempShell.getDisplay();
        while (!tempShell.isDisposed()) {
            if (!d.readAndDispatch())
                d.sleep();
        }
       
    }

    public void init(IWorkbenchWindow window) {
        this.window = window;
    }

    // ...remaining (empty) methods removed...
}

Instanciation de composants avec la classe de site

Tous les composants ne sont pas des vues ou des éditeurs. Les clients peuvent également utiliser le composant API pour créer leurs propres composants réutilisables. De tels composants ne sont pas enregistrés avec les points d'extension de la vue ou de l'éditeur, mais ils peuvent utiliser la plupart de l'API dont disposent ces derniers. Bien que rien n'empêche les clients d'inventer leur propre API pour des composants réutilisables, l'utilisation de ce système permet l'imbrication des composants dans tout élément prenant en charge l'imbrication des vues ou éditeurs.

Les composants créés avec la classe de site ont les propriétés suivantes : Le constructeur du site doit connaître la classe d'implémentation du composant ainsi que l'ensemble de plug-ins associés. Le groupe de plug-ins détermine où seront consignés les messages d'erreur du journal mais aussi où le composant doit rechercher les ressources dans ses propres plug-ins.

L'exemple qui suit montre comment utiliser la classe de site pour instancier directement un composant. Dans cet exemple, le composant NameTestView est instancié dans une boîte de dialogue. Bien que TestView soit qualifié de vue et puisse utiliser la vue API, il n'est pas nécessaire de l'enregistrer avec le point d'extension org.eclipse.ui.views, à moins que le plan de travail ne soit vraiment censé l'utiliser comme une vue.


/**
 * Demonstrate how to open a part programmatically using the Site class.
 */
public class ProgrammaticViewCreationExampleAction implements IWorkbenchWindowActionDelegate {
    private IWorkbenchWindow window;

    public void run(IAction action) {       
        // Create a shell
        final Shell tempShell = new Shell(window.getShell(), SWT.DIALOG_TRIM | SWT.RESIZE);
        tempShell.setLayout(new FillLayout());
        tempShell.setText("Name test view");
       
        Bundle thisPlugin = ComponentExamplesPlugin.getDefault().getBundle();
       
        try {
            // Instantiate the NameTestView part (this line is the whole point of the example)
            // It demonstrates how the Site class can be used instead of calling NameTestView's constructor.
            Site testPart = new Site(tempShell, new ContainerContext(),
                    thisPlugin,
                    NameTestView.class);           
           
        } catch (CoreException e) {
            // ...uninteresting error-handling code removed...
        }
       
        // Open a modal dialog
        tempShell.open();
        Display d = tempShell.getDisplay();
        while (!tempShell.isDisposed()) {
            if (!d.readAndDispatch())
                d.sleep();
        }
       
    }
\
    public void init(IWorkbenchWindow window) {
        this.window = window;
    }

   
// ...remaining (empty) methods removed...
}