September 30, 2009

NetBeans Platform: Implement Perforce client - part III

Switch to P4JAPI, annotate and basic actions

All the Netbeans Plugins which tried to implement the Perforce client uses p4 command line tool. This is somehow difficult, because you have to manage the input and output of a command line. A lot of effort with no benefit. Because the perforce team put on place what is called P4Java, the Perforce Java API. You can find the release notes here (last version) http://www.perforce.com/perforce/doc.091/user/p4javanotes.txt. Download it from here. The main benefits are the fact that you work with objects, don't have to parse things, and to manage external processes. Thought, also, it is faster than its command line brother. Since this is not an NetBeans Platform thing, I will not insist on that too much.

As mentioned in a previous article, the presentation of versioning information is implemented in a class based on VCSAnnotator. In our case, this class is called PerforceAnnotator. There are some aspects which need to be explained. First is the fact that this class is a listener on some specific property change. That is done using the following code:

public class PerforceAnnotator extends VCSAnnotator {
    /**
     * Fired when textual annotations and badges have changed. 
     * The NEW value is Set<File> of files that changed or NULL
     * if all annotaions changed.
     */
    public static final String PROP_ANNOTATIONS_CHANGED = "annotationsChanged";
    private final PropertyChangeSupport support = new PropertyChangeSupport(this);
     public void addPropertyChangeListener(PropertyChangeListener listener) {
        support.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        support.removePropertyChangeListener(listener);
    } 


The PerforceAnnotator has two methods related to property change events: addPropertyChangeListener and removePropertyChangeListener. How it works? We define a logical property, named "annotationChanged". Any listener added will be notified if this property have been changed. This code works together with another piece from PerforceVS and another one from FileStatusCache. Practically, through this logical properties and wire of listeners we send messages from a component to another. They remain loosely coupled. As a sample, when the status of a file has been changed (from perforce point of view), the instance of FileStatusCache (which manages these statuses) notify PerforceVS that something on a file has been changed. PerforceVS than will notify the PerforceAnnotator about that change and the annotator will change also the status in UI (labels, colors, versioning info). The property change method is a very important concept. It is used very ofted to put UI things together, so take a closer lok on that, whenever you have some time.

PerforceAnnotator show some UI information about the status of files. The icon from explorer view is modified and the name and color of the file element is modified. These is done with the following code.

    @Override
    public Image annotateIcon(Image oldImage, VCSContext context) {
        FileStatusCache cache = PerforceSystem.getCache();
        int x = 12;
        int y = 0;
        if (cache.containsStatus(context, FileStatus.STATUS_VERSIONED_EDIT)) {
            return ImageUtilities.mergeImages(oldImage, ImageRoot.DECORATION_EDIT, x, y);
        }
        if(cache.containsStatus(context, FileStatus.STATUS_VERSIONED_ADD)) {
            return ImageUtilities.mergeImages(oldImage, ImageRoot.DECORATION_ADD, x, y);
        }
        if(cache.containsStatus(context, FileStatus.STATUS_VERSIONED_UPTODATE)) {
            return super.annotateIcon(oldImage, context);
        }
        return super.annotateIcon(oldImage, context);
    }

    @Override
    public String annotateName(String name, VCSContext ctx) {
        FileStatusCache cache = PerforceSystem.getCache();
        int version;
        List<FileInformation> files;
        files = cache.listFiles(ctx, FileStatus.STATUS_VERSIONED_EDIT);
        if (files.size() > 0) {
            version = files.get(0).getVersion();
            return markName(name, "#0B610B", "#" + version + " [edit]");
        }
        files = cache.listFiles(ctx, FileStatus.STATUS_VERSIONED_ADD);
        if (files.size() > 0) {
            version = files.get(0).getVersion();
            return markName(name, "#084B8A", "#" + version + " [add]");
        }
        files = cache.listFiles(ctx, FileStatus.STATUS_VERSIONED_UPTODATE);
        if (files.size() > 0) {
            version = files.get(0).getVersion();
            return markName(name, null, "#" + version);
        }
        files = cache.listFiles(ctx, FileStatus.STATUS_UNKNOWN);
        if (files.size() > 0) {
            return super.annotateName(name, ctx);
        }
        if (name.equalsIgnoreCase("<default package>")) {
            return "&lt;default package&gt;";
        }
        return super.annotateName(name, ctx);
    }

    private String markName(String name, String color, String label) {
        boolean extra = VersioningSupport.getPreferences().getBoolean(
                VersioningSupport.PREF_BOOLEAN_TEXT_ANNOTATIONS_VISIBLE, false);

        if (color == null) {
            return name + (extra ? label : "");
        }
        return "<font color=\"" + color + "\">" + name + "</font>" +
                (extra ? "  <font color=\"" + color + "\">" + label + "</font>" : "");
    }

How it works? Depending on the status of the file, we modify the actual icon or label of the file from explorer view. To find the status of the file we ask the FileStatusCache, this class manages the FileInformation related to every managed file. The VCSContext represents the selection of files on which we should show information. Note that is possible to have multiple files in a context. In order to keep things simple, I considered that context have only one file and if there are many, I take into consideration only the first one. In time this should be changed. The same scenario happens for labels. On labels we use HTML tags because the view allow that to modify the aspect of a label.

One small tip to know. ImageUtilities class offers some very useful methods in managing images. We can use that class to merge two images, as is the case with PerforceAnnotator (we put a small Perforce icon over the original NetBeans file icon). We can load an image giving only a location in class path and we can transform with easy from an image into an icon and viceversa.

Let's take a look on the results of our work until now.


Another thing which PerfoceAnnotator do is to wire up some actions. It does this by implementing the method getActions. This method receives two parameters as input. The first one is the VCSContext. As noted before, the context gives information about the selected files for which the user wants to show actions. I repeat that is important to be aware that the context can represent more than one file, so behave accordingly. The second parameter is ActionDestination. This is an enum which tells us if the IDE wants the actions to be inserted on the main menu or on the contextual menu. In the sample code below the complexity of building available actions is wrapped into another class, called FileStatusManager. An action is a standard swing action. My actions usually calls the perforce client and do something with that. Since this is not a NetBeans Platform I will not talk about that, as usual, I invite you to take a look on the sources and give at least a feedback (you are welcomed anytime to submit).

    @Override
    public Action[] getActions(VCSContext ctx, ActionDestination destination) {
        List<Action> actions = new ArrayList<Action>();
        FileStatusManager manager = FileStatusManager.getInstance();
        switch (destination) {
            case MainMenu:
                actions.addAll(manager.getAvailableActionsOnMainMenu(ctx));
                break;
            case PopupMenu:
                actions.addAll(manager.getAvailableActionsOnPopup(ctx));
                break;
        }
        return actions.toArray(new Action[actions.size()]);
    }

One more cookie, thought. To create a progress notification which will be displayed on status bar in a dedicated section, you can use ProgressHandle. Like in the sample below taken form FileStatusCache.reloadCacheOnThread.

        final ProgressHandle progress =


                ProgressHandleFactory.createHandle("Perforce refresh..");


        progress.start();


        .....


        progress.finish();


              
I mention this simple thing because a lot of things in NetBeans are very simple and straightforward to implement or use. That is the meaning of  strong API. The simplest form possible, intuitive and elegant. I think NetBeans Platform has a lot of those.

Untill the next time, see changes on http://kenai.com/projects/perforcenb.

September 8, 2009

NetBeans Platform: Implement Perforce client - part II

Module preferences for PerforceNB.

Usually options for NetBeans modules are handled via option panel. For that we can use a specialized wizard. You can start the wizard from the contextual menu of the project, where we fire the New - Other - Module Development - Options Panel. In this way we can create primary or secondary panels for options.

This is not our case. That is because for versioning system options, NetBeans has created a panel already. You can find that panel from the main menu by Tools - Options - Miscellaneous - Versioning. Take a look on the dialog box and see what comes next. Our job is to insert another item in the list of versioning systems, handling preferences for Perforce.

We achieve that by extending org.netbeans.spi.options.AdvancedOption. This class represents an advanced interface element for options dialog. We create a new class which extends AdvancedOption.

After that we must configure the layout.xml to inject in the interface this element. The programmatic way is to modify by hand the layout.xml file. This file will look like below:


<filesystem>
    <folder name="VersioningOptionsDialog">
        <file name="PerforceOptions.instance">
            <attr name="instanceClass" stringvalue="org.padreati.perforcenb.ui.PerforceOptions"/>
        </file>
    </folder>
</filesystem>


Another option to generate this content is to find in the IDE the layer GUI editor. Use <this layer in context> representation. Find VersioningOptionsDialog folder. There use context menu to create a new file called PerforceOptions.instance and so on.


Now we injected our UI element in NetBeans IDE. We implement the class to provide appropriate values. I implemented AdvancedOption in class PerforceOptions.


public class PerforceOptions extends AdvancedOption {
    @Override
    public String getDisplayName() {
        return NbBundle.getMessage(PerforceVS.class, "CTL_Perforce_DisplayName");
    }

    @Override
    public String getTooltip() {
        return NbBundle.getMessage(PerforceVS.class, "CTL_Perforce_OptionsTooltip");
    }

    @Override
    public OptionsPanelController create() {
        return new PerforceOptionsPanelController();
    }
}


The listing is clear, we provide a display name and a tooltip for the UI element. I used resources for that. The main method here is create() which returns an instance of PerforceOptionsPanelController.An OptionPanelController is the controller behind UI for managing options (MVC sounds familiar? that's one reason why I love NetBeans and Swing). The controller handles operations of managing data. Here is the listing:

public class PerforceOptionsPanelController extends OptionsPanelController {
    private PerforceOptionsPanel panel;

    public PerforceOptionsPanelController() {
        panel = new PerforceOptionsPanel();
    }

    @Override
    public void update() {
        PerforceModuleConfig config = PerforceModuleConfig.getInstance();
        config.reload();
        panel.setPath(config.getP4Path());
        panel.setDefaultPort(config.getP4DefaultPort());
        panel.setDefaultWorkspace(config.getP4DefaultWorkspace());
    }

    @Override
    public void applyChanges() {
        PerforceModuleConfig config = PerforceModuleConfig.getInstance();
        config.setP4Path(panel.getPath());
        config.setP4DefaultPort(panel.getDefaultPort());
        config.setP4DefaultWorkspace(panel.getDefaultWorkspace());
        config.store();
    }

    @Override
    public void cancel() {
        PerforceModuleConfig.getInstance().reload();
    }

    @Override
    public boolean isValid() {
        return true;
    }

    @Override
    public boolean isChanged() {
        return panel.isDirty();
    }

    @Override
    public JComponent getComponent(Lookup masterLookup) {
        return panel;
    }

    @Override
    public HelpCtx getHelpCtx() {
        return new HelpCtx(PerforceOptionsPanel.class);
    }

    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
    }

    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
    }

}

There are only some methods which are really relevant. The update method is called when IDE loads configuration data from storage, I update the interface at that moment. The applyChanges is called when a save action is fired from interface. Use isChanged to tell IDE if the configuration data was updated in UI. The UI is specified in getComponent method. This method returns an instance of PerforceOptionsPanel, a class which extends JPanel.

This is the interface. Here is how it looks:


For managing the preferences of the module I created a class called PerforceModuleConfig. This is a singleton which calls NbPreferences to persist it's properties. This class I will use in our module to see which are the options for PerforceNB module. Here is a listing:

public final class PerforceModuleConfig {
    private static PerforceModuleConfig instance;

    private final static String P4_PATH_KEY = "P4_PATH_KEY";
    private final static String P4_DEFAULT_PORT_KEY = "P4_DEFAULT_PORT_KEY";
    private final static String P4_DEFAULT_WORKSPACE_KEY = "P4_DEFAULT_WORKSPACE_KEY";

    private String p4Path;
    private String p4DefaultPort;
    private String p4DefaultWorkspace;

    private PerforceModuleConfig() {
    }

    public static PerforceModuleConfig getInstance() {
        if(instance==null) {
            instance = new PerforceModuleConfig();
        }
        return instance;
    }

    public String getP4Path() {
        return p4Path;
    }

    public void setP4Path(String p4Path) {
        this.p4Path = p4Path;
    }

    public String getP4DefaultPort() {
        return p4DefaultPort;
    }

    public void setP4DefaultPort(String p4DefaultPort) {
        this.p4DefaultPort = p4DefaultPort;
    }

    public String getP4DefaultWorkspace() {
        return p4DefaultWorkspace;
    }

    public void setP4DefaultWorkspace(String p4DefaultWorkspace) {
        this.p4DefaultWorkspace = p4DefaultWorkspace;
    }

    public void reload() {
        Preferences pref = NbPreferences.forModule(PerforceModuleConfig.class);
        String p4PathDefault = "p4";
        if(System.getProperty("os.name").startsWith("Windows")) {
            p4PathDefault = "p4.exe";
        }
        setP4Path(pref.get(P4_PATH_KEY, p4PathDefault));
        setP4DefaultPort(pref.get(P4_DEFAULT_PORT_KEY, ""));
        setP4DefaultWorkspace(pref.get(P4_DEFAULT_WORKSPACE_KEY, ""));
    }

    public void store() {
        Preferences pref = NbPreferences.forModule(PerforceModuleConfig.class);
        pref.put(P4_PATH_KEY, getP4Path());
        pref.put(P4_DEFAULT_PORT_KEY, getP4DefaultPort());
        pref.put(P4_DEFAULT_WORKSPACE_KEY, getP4DefaultWorkspace());
    }
}

The content is obvious. Only notice that I have used NbPreferences, a utility class from NetBeans Platform for persisting preferences. Very useful one. Here is the result of my work from this episode.


As usual, you can see the whole project and code from the kenai project page at http://kenai.com/projects/perforcenb. See you on the next episode.

September 7, 2009

NetBeans Platform: Implement Perforce client - part I

NetBeans and NetBeans Platform were always the tools for the heart. Unfortunately, my usual job duties did not included enough time spent with them. So, I tool my chanses to spent some nights on these. Since I have to use Perforce versioning system and because NetBeans has not (yet!) a client for this system, I decided to implement such a client. Hope I can give something back to the community in this way, a humble little piece compared to the things I received. You will see project details here http://kenai.com/projects/perforcenb.

So, a versioning control system. If you want to know more about Perforce, you can go to their site www.perforce.com. It should be enought to say that I know at least two very big companies which use it as a main VCS.

NetBeans Platform gives us an API which can be used to integrate a client for a versioning system into the IDE. A nice side effect of this is the fact that all the versioning control system clients will behave in a similar way. We will implement our Perforce client as a NetBeans module. In this way we can use it on our daily basis usual tasks.

First thing to create is a NetBeans module project. We can do that by using New -> Project from NetBeans IDE. (I use 6.7.1, thought you should use a recent version too). We chose then NetBeans Modules -> Module for the project type and hit Next button.


In the next dialog box we insert information about the project. Like project name, location and so. You can see the data I enetered from the image. Afer that, hit the Next button again.


In the next dialog box we insert some information useful for code generation. Base package can be configured here, title of the plugin and layer. The will be important in the next parts of this story. For the moment just be sure you select it. To generate the code for the project you should use action Finish button.

So, we have now a module project which does nothing for the moment. We want to implement a versioning system client in it, so the starting point should be extending the VersioningSystem class. But, to be able to use that class, we must do another preparation step. Importing the NetBeans modules which we will base our module on. For the beginning we will add two dependencies at the project. For that, action the contextual menu of the project. From there, action Properties -> Libraries. In the dialog box fire Add button which will gives us a search screen.


The interesting thing in this screen is that you can use it in two ways. First you know already which module you should import, so you can roll over the Module list and select modules you like to use it. The second way is to use search Filter. The nice thing here is that you can search for an exposed class. So, if you don't know which module to import in order to use a specific class or interface, you filter module by that class or interface and you will have listed all the modules which offer that name. Nice trick when you are lost somehow.

So, we need to add dependencies to the following modules: Versioning and Utiities API. The last because we use an utility class for getting the resources (look for NbBundle to see what I mean).

The next stept is to let the NetBeans IDE "know" that I just implemented a new versioning client for him.We do this by extending org.netbeans.modules.versioning.spi.VersioningSystem in a service provider interface way. So we create a derived class, PerforceVS which extends VersioningSystem. We create META-INF folder into the source root. In META-INF we create a folder called services. In META-INF/services we create an empty text file. That file will be called org.netbeans.modules.versioning.spi.VersioningSystem and will have one line only: org.padreati.perforcenb.PerforceVS. This is the name of the class which extends VersioningSystem. For a broader view of Service Provider Interface you can take a look here.

package org.padreati.perforcenb;

import java.io.File;
import org.netbeans.modules.versioning.spi.VCSAnnotator;
import org.netbeans.modules.versioning.spi.VersioningSystem;
import org.openide.util.NbBundle;
import org.padreati.perforcenb.wrapper.PerforceSystem;

/**
 *
 * @author padreati
 */
public class PerforceVS extends VersioningSystem {

    public PerforceVS() {
        putProperty(PROP_DISPLAY_NAME, NbBundle.getMessage(
            PerforceVS.class, "CTL_Perforce_DisplayName")); // NOI18N
        putProperty(PROP_MENU_LABEL, NbBundle.getMessage(
            PerforceVS.class, "CTL_Perforce_MainMenu")); // NOI18N
    }

    @Override
    public File getTopmostManagedAncestor(File file) {
        // TODO for the moment all will be considered under
        // Perforce just for testing
        return new File("/");
    }

    @Override
    public VCSAnnotator getVCSAnnotator() {
        return PerforceSystem.getSystem().getAnnotator();
    }
}

This class is in the very basic form. We do the following:

  • In constructor we set values for menu labels. In order to work I have inserted entries into resource (properties) files for CTL_Perforce_DisplayName and CTL_Perforce_MainMenu.
  • I implemented getVCSAnnotator just to return the instance of annotator we will use (details a little bit latter).
  • implement getTopmostManagedAncestor. If this method returns a value, it means that the file/folder receicved as parameter is managed by our versioning system. If not, we return null.
One important aspect is the design of versioning system in NetBeans. It is considered that one resource from disk (either file or folder) can be in two states only. Either is managed by one versioning system (only one versioning system can own the resource in the same time) or is not managed at all. The versioning API consider also that if a folder is managed by a versioning system, all of the folders and files should be managed by that version control. So, to find for a folder if it is managed by a versioning control, we should tell to the versioning API that the specified files resides under a managed folder. We do that by implementing getTopmostManagedAncestor. This method should return the topmost managed folder where resides the file received as parameter. 
In my sample I simply return root folder. Why, would you ask. Just for the testing purposes. Returning the root folder of the file system (this is similar to C:\ folder on Windows) I specify that all files are managed by Perforce. Obviously this is not true. We do it for now just to see where we go.
Also, I created a singleton class to hold all the references of the Perforce versioning system. For the moment we hold only annotator instance. But what is an annotator?
package org.padreati.perforcenb.impl;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Action;
import org.netbeans.modules.versioning.spi.VCSAnnotator;
import org.netbeans.modules.versioning.spi.VCSContext;
/**
 *
 * @author padreati
 */
public class PerforceAnnotator extends VCSAnnotator {
    @Override
    public Image annotateIcon(Image arg0, VCSContext arg1) {
        return super.annotateIcon(arg0, arg1);
    }
    @Override
    public String annotateName(String name, VCSContext ctx) {
        return name + " [PERFORCE]";
    }
    @Override
    public Action[] getActions(VCSContext ctx, ActionDestination destination) {
        // TODO complete actions, for the moment only an empty
        // menu as a sample
        List actions = new ArrayList();
        if (destination == VCSAnnotator.ActionDestination.MainMenu) {
            actions.add(null);
        }
        return actions.toArray(new Action[actions.size()]);
    }
}
An VCS Annotator is the class which implements the decoration in IDE of the code elements controlled by a versioning system. In our case, all the files managed by Perforce should be specified in a way that is visible into interface. Just because we signaled that all files are managed by Perforce (we know that is not true), all the files will be decorated by this annotator.

annotateName will decorate the name of the resource, and annotateIcon will decorate the icon. These methods receives VSContext. This class encapsulates a selection of objects, so we can multiple annotate the resources. In our sample implementation we only append the [PERFORCE] string at the name of resource.
The method getActions deserves also a lot of attention. Bu on that in another next chapter. For the moment just remember that this is a way to provide actions to main or contextual menus. For the moment we give an empty menu.
Until the next episode, just give it a try. Run the module. It will open the IDE with our module enabled. Open   a project in IDE and watch for names, You will the the appended text for all the resources. Like it would be managed by Perforce.
On the next things in the following episode. Follow it! NetBeans Platform deserves it!