Sunday Nov 11, 2007

TIP: Shift text of selected lines or current line to left or right in NetBeans 6.0 editor

In any NetBeans 6.0 editor you can shift the text of selected lines or the current line to the left or right using the following key bindings:

Alt+Shift+Left (Ctrl+Shift+Left on Mac) - shift the text of selected lines or the current line to the left by one indent unit

Alt+Shift+Right (Ctrl+Shift+Right on Mac) - shift the text of selected lines or the current line to the right by one indent unit

The number of spaces used for shifting is controlled by the Tools:Options:Editor:Indetation:Number of Spaces per Indent: option.

 

Sunday Nov 04, 2007

Add Property module on NetBeans Plugin Portal

I have uploaded the Add Property module to the NetBeans Plugin Portal. It installs the action Source:Add Property. Invoking the action shows the following dialog.

Add Property Dialog

 

You can configure the property settings. The preview window shows what code will be inserted in Java editor. Select OK to insert the code at current caret position.

 

You can customize the template by editing it using the Tools:Templates action.

Template Manager Dialog

The template uses the freemarker template engine.

TODO

 

  • validation of name and type
  • validation of duplicate property name
  • browse to select type
  • nicer positioning of the field, getters and setters
  • insertion of required import statements instead of using FQNs

Sources

DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

Friday Oct 19, 2007

Java Decl Gen module

I have uploaded the Java Decl Gen module on the Plugin Portal.

This module supports several forms of parameter, variable, array parameter and array variable declarations.

These actions were formerly part of the contrib/CamelCase module. The CameCase movement and selections are now part of NetBeans 6.0 Java editor.

Assuming you have typed:

Foo|

 
in the Java editor you can invoke the following actions:

ActionKey binding
Declare Parameter e.g. Foo foo |Alt+U SPACE
Declare Parameter with comma e.g. Foo foo, |Alt+U ,
Declare Variable e.g. Foo foo;|Alt+U ;
Declare Variable with initializer e.g. Foo foo = new Foo()|;Alt+U =
Declare Variable with casted initializer e.g. Foo foo = (Foo)|;Alt+U (
Declare Array Parameter e.g. Foo[] foos|Ctrl+Alt+U SPACE
Declare Array Parameter with comma e.g. Foo[] foos, |Ctrl+Alt+U ,
Declare Array Variable e.g. Foo[] foos;|Ctrl+Alt+U ;
Declare Array Variable with initializer e.g. Foo[] foos = new Foo[]{};|Ctrl+Alt+U =
Declare Array Variable with casted initializer e.g. Foo[] foos = (Foo[]) ;|Ctrl+Alt+U (

The highlighted regions behave like editor code templates. Use ENTER to escape the code template parameter editing mode - then the cursor will be positioned at |.

 TODO

  • Use the same algorithm as the one used by Java Editor to generate proposed parameter or variable names.

Sources

DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

 

Wednesday Oct 17, 2007

TIP: Structural selection in Netbeans 6.0 Java editor

In this entry I had talked about the Structural selection in Netbeans Java editor. The keybindings for the same functionality have changed in NetBeans 6.0. The new keybindings are:

  • Alt+Shift+. - successively selects outer syntactic element. Statement -> Surrounding Block Statements -> Surrounding Block Statements -> Surrounding Method -> Surrounding Class and so on. I use this for quick selection.
  • Alt+Shift+, - successively selects inner syntactic element. This works only if you had expanded the selection using the Alt+Shift+. . This helps me fine tune the selection if I went too far.


 

NB 60 compatible LineTools on NetBeans Plugin Portal

I have updated the NetBeans 6.0 compatible LineTools module to NetBeans Plugin Portal. I have removed the Move/Copy Selection/Line Up/Down actions from this module as they are now part of NetBeans 6.0 editors. I have checked in the updated sources in here.

Monday Sep 03, 2007

Nautilus scripts to launch diff viewer and view a particular revision

I have hacked two more nautilus scripts.

  • cvs_diff_revisions - this script prompts for two revisions of a file and shows diffs them in a diff viewer.
  • cvs_view_revision - this script prompts for a revisions of a file and shows it a editor.

Just put the scripts in your

~/gnome2/nautilus-scripts

directory and

> chmod 755 cvs_diff_revisions cvs_view_revision

> nautilus -q

Here are the scripts:

cvs_diff_revisions - this uses the meld diff viewer. You can use any other diff viewer in it's place.


#!/bin/bash
#
# Distributed under the terms of GNU GPL version 2
#
# http://blogs.sun.com/scblog
#

ICONPATH="`dirname $0`/cvs.xpm"

for TARGET in ${NAUTILUS_SCRIPT_SELECTED_FILE_PATHS}
do
TARGETDIR=`dirname "${TARGET}"`
TARGET=`basename "${TARGET}"`

cd "${TARGETDIR}"
REVISIONA=`zenity --list --radiolist --title="cvs diff - Select Revision A" --text="${TARGETDIR}/${TARGET}" \\
--width=500 --height=700 --column "A" --column "Revisions" \\`cvs log "${TARGET}" | grep "\^revision" | mawk '{ print "FALSE", $2 }'\\``
if [ $? -eq 0 ] ; then
if [ ! -z "${REVISIONA}" ] ; then
REVISIONB=`zenity --list --radiolist --title="cvs diff - Select Revision B (A is ${REVISIONA})" \\
--text="${TARGETDIR}/${TARGET}" --width=500 --height=700 --column "B" --column "Revisions" \\`cvs log "${TARGET}" \\
| grep "\^revision" | grep -v ${REVISIONA}| mawk '{ print "FALSE", $2 }'\\``
if [ $? -eq 0 ] ; then
if [ ! -z "${REVISIONB}" ] ; then
cvs update -r "${REVISIONA}" -p "${TARGET}" > "${TARGETDIR}/${TARGET}.~${REVISIONA}~"
cvs update -r "${REVISIONB}" -p "${TARGET}" > "${TARGETDIR}/${TARGET}.~${REVISIONB}~"
meld "${TARGETDIR}/${TARGET}.~${REVISIONA}~" "${TARGETDIR}/${TARGET}.~${REVISIONB}~"
fi
fi
fi
fi
done 

cvs_view_revision


#!/bin/bash
#
# Distributed under the terms of GNU GPL version 2
#
# http://blogs.sun.com/scblog
#

ICONPATH="`dirname $0`/cvs.xpm"

for TARGET in ${NAUTILUS_SCRIPT_SELECTED_FILE_PATHS}
do
TARGETDIR=`dirname "${TARGET}"`
TARGET=`basename "${TARGET}"`

cd "${TARGETDIR}"
REVISION=`zenity --list --radiolist --title="cvs view revision" --text="${TARGETDIR}/${TARGET}" \\
--width=500 --height=700 --column "" --column "Revisions" \\`cvs log "${TARGET}" | grep "\^revision" | mawk '{ print "FALSE", $2 }'\\``
if [ $? -eq 0 -a ! -z "${REVISION}" ] ; then
cvs update -r "${REVISION}" -p "${TARGET}" > "${TARGETDIR}/${TARGET}.~${REVISION}~"
gedit "${TARGETDIR}/${TARGET}.~${REVISION}~"
fi
done

Also save this cvs icon as ~/gnome2/nautilus-scripts/cvs.xpm.

I think it should be possible to build a set of scripts which more or less emulate TortoiseCVS integration with Windows Explorer. 

Saturday Aug 25, 2007

Copy Path in Nautilus

I recently switched to Ubuntu. Starting to like it.

Here is my first Ubuntu/Nautilus hack. Put the following python script:

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk
import os

# get the clipboard
clipboard = gtk.clipboard_get()

# set the clipboard text data
clipboard.set_text(os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'])

# make our data available to other applications
clipboard.store()

in the file:

~/.gnome2/nautilus-scripts/Copy Path

Now launch Nautilus, select any file(s) or folder(s) and invoke pop up menu  and select Scripts:Copy Path. The fully qualified path(s) of the file(s) or folder(s) will be copied to the clipboard.

Does anyone know a better way?

Tuesday Aug 07, 2007

BorderLayout implemented in terms of GroupLayout

Just for fun. Here is a java.awt.BorderLayout implemented in terms of javax.swing.GroupLayout:

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BorderLayoutGroupLayout {
    public static void main(String[] args) {
        JButton west = new JButton("West");
        JButton north = new JButton("North");
        JButton east = new JButton("East");
        JButton south = new JButton("South");
        JButton center = new JButton("Center");
       
        JPanel panel = new JPanel();
        GroupLayout groupLayout = new GroupLayout(panel);
        panel.setLayout(groupLayout);
       
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(north, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(groupLayout.createSequentialGroup()
                    .addComponent(west)
                    .addComponent(center, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(east))
                .addComponent(south, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        groupLayout.setVerticalGroup(
            groupLayout.createSequentialGroup()
                .addComponent(north)
                .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(west, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(center, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(east, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addComponent(south)               
        );
        JDialog dialog = new JDialog((JFrame)null, "", true);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setContentPane(panel);
        dialog.pack();
        dialog.setVisible(true);
    }
}

Monday Jun 04, 2007

TIP: Declaration and initialization of an unmodifiable static final Set

    static final Set<String> stringSet =
            Collections.unmodifiableSet(
                new HashSet<String>(Arrays.asList(
                    "foo",
                    "bar",
                    "baz"
                    )));

Modified based on a tip by Rafael de F. Ferreira. I cannot use a trailing comma on each line though for easy addition/removal of entries.

Saturday Jun 02, 2007

Navigating layer files

If you develop NetBeans modules you must be aware of layer files. The layer files are the NetBeans module system's mechanism for declarative registration of almost all aspects of module's functionality. The overall functionality of a NetBeans Platform based application is derived by merging the layer files contributed by all the modules in the application.

The NetBeans modules can be developed using the NetBeans IDE itself, using the NetBeans module projects. The NetBeans module project's logical view has the following nodes related to the layer file(s) (see the first screen shot below).

  • Important Files/XML Layer/<this layer> - This node's children display the structure of the current modules layer file content.
  • Important Files/XML Layer/<this layer in context> - This node's children display the structure of the merged layer file that will be effective when the module runs inside the NetBeans Platform based application. The layer files of the other modules in the module's suite or the NetBeans platform against which it is being deverloped are used to build this structure.

Sometimes it is desirable to quickly find out which layer file(s) a particular node comes from. Starting with today's (6/2/2007) build there is a context menu action called Open Layer File(s) just for such a pupose (see the screenshot below).

Open Layer File(s) Action

When the Open Layer File(s) action is invoked on a particular node, the layer file(s) which declares that node is opened in the editor window. Please note that a particular node (such as Actions folder) may be declared in more than one file, in which case all the layer files will be opened in the editor window. The layer file may be read-only if it comes from a module's jar file in the NetBeans platform against which this module is being built.

Layer File

In the above screen shot the layer file of the debuggercore module project was opened because the Actions/Debug/New Breakpoint... action is declared by it.

The layer file may be owned by other module's in this modules suite. For modules in the NetBeans workspace the layer file may be owned by other NetBeans modules. In those cases you can use the Select in > Projects action in the layer file editors context menu to quickly open the owner project and select the layer file in it's local view. If that module project is not already open you will be prompted to open it as shown in the screen shot below.

Open Project dialog

I hope this helps you with your NetBeans module development. Enjoy!

Monday May 21, 2007

Answer for Netbeans Teaser

In this blog entry I showed the following screenshot:

Debugger HeapWalker

Note: This functionality is available in recent (last weeks) NetBeans IDE build with JDK 6.

Here is the explaination of what is going on:

The screenshot shows the debugger stopped at a line in the contructor of class Foo. Foo has a member variable bar of type Bar which is an inner class of Foo. The Local Variables window show the this instance of type Foo and bar field of type Bar. Nothing new or interesting so far. Right clicking on the bar field's row in the Local Variables window reveals the Show References action in the popup menu. Invoking the Show references action shows the Instances window. The Instances window is the interesting bit. The Instances window shows three panes - Instances pane, Fields pane and References pane. The Instances pane shows all instances of type Bar. The Fields pane is analogous to the Local Variables window and shows the structure of the instance of Bar. The References pane shows the references to the selected instance of Bar. In this example the only reference to the instance pointed to by the bar field is the instance of Foo. I think this is huge! What this means is that I can look at the references to the objects while I am debugging my program. The ability to look at the references has been traditionally available in the Profiler tools such as HeapWalker. The differences is that the HeapWalker tool shows the static information from a heap dump file. The Instances window above shows the information from a live VM that is being debugged. This brings the power of Profiler like tools to the NetBeans debugger. I think this is very synergistic. For example, normally one can only look at the objects visible from the current stack frame in the Local Variables window. Using the Instances pane in the Instances window now it is possible to look at other instances of any reference type that may not be directly visible from the current stack frame. Similarly by using the fix&continue feature of the debugger it will be possible to debug memory leaks in certain scenarios.

There is also a Classes window which can be invoked using Windows:Debugger:Classes action. This is analogous to Classes window of the HeapWalker.

Small nit:

  • The #nnn numbers shown in the Instances pane of Instances window are not the same ad Unique Id# shown in the Local Variables window. I have already filed an RFE to display the debuger assigned Unique ids in the Instances window so that it will be easy to corelate the information those two windows.
  • The Fields pane shows information very similar to the Local Variables window. The two GUIs could be better unified.

Going forward I hope to see more and more integration of NetBeans debugger and profiler which will help integrate the profiling in the regular edit-compile-debug cycle.

Sunday May 20, 2007

NetBeans Teaser

What is going on in the following screenshot?

Hint: Study the areas marked by red rectangles.

Debugger Heapwalker

Answer in the next blog entry.

Saturday May 19, 2007

KeyBinding Explorer module on Plugin Portal

I have started to move my modules to NetBeans Plugin Portal. There you will find the Key Binding Explorer module which let's you explore the active key bindings in NetBeans IDE. Here are the screenshots:

Search based on key bindings sequence

Type the key sequence in the textfield on top of the first column to see what it is bound to.

key binding sequence search

Search based on raw keys (no modifiers)

Type the keys (without modifiers) in the textfield on top of the second column to see what the they are bound to.

raw key search

Search based on action name

Type the name of the action in the textfield on top of the third column to see what key sequence is bound to it. You can use regexps in the action name.

 action search

You can sort the columns. You can do primary, secondary and tertiary sort by control clicking on the column headings. You can generate the html or xml file. You could use an xml+XSLT to generate nice PDF reference card. If anyone develops such a tool please send me the information.

You can download the plugin from here.

Sources

DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

Friday May 11, 2007

How is it implemented? Java Editor Hint: Change variable type fix

In the previous entry I talked about the Change Variable Type fix. In this entry I will talk about how it is implemented.

Registration of the factory

Like many other features in NetBeans the hints/fixes/suggestions are implemented using a factory mechanism. The factory is registered in the module's layer file like this:

<filesystem>
  <folder name="org-netbeans-modules-java-hints">
    <folder name="rules">\\
      <folder name="errors">
        <file name="org-netbeans-modules-javahints-ChangeTypeCreator.instance"/>
      </folder>
    </folder>
  </folder>
</filesystem>

The factory is registered under the org-netbeans-modules-java-hints/rules/errors folder because it creates a fix for certain compilation errors such as type mismatch of the left and right side of a vatriable declaration statement.

Implementation of the factory

As the user edits the source code, the Java editor incrementally runs the javac in the background. As the javac emits compilation errors the editor shows the red squiggly lines. Aside from that it also invokes the factories registered to handle the particular compilation errors. In this case org.netbeans.modules.javahints.ChangeTypeCreator is one such factory. The ChangeTypeCreator implements the interface org.netbeans.modules.java.hints.spi.ErrorRule. This intreface essentially has two important method:

    /\*\* Get the diagnostic codes this rule should run on
     \*/
    public Set<String> getCodes();
    /\*\* Return possible fixes for a given diagnostic report.
     \*/
    public List<Fix> run(CompilationInfo compilationInfo,
                         String diagnosticKey,
                         int offset,
                         TreePath treePath,
                         Data<T> data);

The getCodes() method essentially indicates the set of compilatioin error codes that are handled by the factory. The ChangeTypeCreator handles:

compiler.err.prob.found.req
compiler.err.incomparable.types

These codes are part of standard error codes emitted by the javac.

In the run(...) method of ChangeTypeCreator,enough information about the context in the editor is passed in. The ChangeTypeCreator uses the APIs to determine the types of expressions on the left and right side of a variable assignmenets and returns an instance of org.netbeans.modules.javahints.ChangeTypeHint. This instance is used to populate the list of fixes that appear as actions in the light bulb pop up menu in the left margin of the editor.

Implementation of the Change variable type fix

The ChangeTypeHint which implements org.netbeans.spi.editor.hints.Fix . It provides the text of menu item which is returned from:

    public String getText()

The actual fix is implemented in the method:

 public ChangeInfo implement()

using the Java Source APIs.

Friday May 04, 2007

Java Editor Hint: Change variable type fix

In NetBeans 6.0 Java editor supports writing custom, so called, fixes, hints and suggestions. These appear as a light bulb icon in the left margin of the Java editor. For example, in the code below:

100        List list = ...;
101        :
:
110        String s = list.get(0);

the type of the variable s does not match the type of the expression list.get(0). In such cases a light bulb icon appears in the left margin of the Java editor on the line 110 of the code. Clicking or invoking the fix action reveals a menu item saying Cast ...get(...) to String. Selecting the menu item changes the code on line 110 to:

110        String s = (String) list.get(0);

This is all well and good. However what if you wanted to adjust the type of the variable s to Object. It is very easy to write such a fix and that is what I have implemented.

With this fix, I always write my variable like this:

110        int i = .....; // some expression that return a type I don't know - assume it is RefactoringPluginFactory

Select the hint to change the type of i to the correct type.

110        RefactoringPluginFactory i = ....; 

(I know, I know some may say why I am doing this...because I am an extremely poor typist :( )
Then I quickly delete i and use the smart variable name proposal code completion to get:

110        RefactoringPluginFactory refactoringPluginFactory = ....;

I have added the fix to the Experimental Java Hints (contrib/editorhints/java) module. You can get the module from Development Update center.

Sources

DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

About

sandipchitale

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today