Showing posts with label eclipse. Show all posts
Showing posts with label eclipse. Show all posts

Monday, October 1, 2012

How to open a Java file in read-only mode?

In one of my eclipse plugin based application I wanted to open Java files in read only mode. One option was to use org.eclipse.jface.text.source.SourceViewer , where I could have used JavaSourceViewerConfiguration
for providing Java highlighting and all. But there were two problems:
  1. Source viewer won't inherit the Java editor settings (and if you have modified eclipse Java editor theme), which means your background and foreground in the SourceViewer gets completely messed up.
  2. Secondly you would lose all the markup and bookmarking facilities available with editors
So, I decided to extend the existing Java editor. The steps are extremely simple,
  1. Create an editor extension
  2. Extend the extension class with org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor
  3. Override some of the methods
  4. Open your file with this editor

Code

Editor Code

import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;

@SuppressWarnings("restriction")
public class ReadonlyEd extends CompilationUnitEditor 
{
 public static final String ID = "read.only";
 public ReadonlyEd() {
 }
 @Override
 public boolean isEditable() {
     return false;
 }
 @Override
 public boolean isEditorInputModifiable() {
     return false;
 }
 @Override
 public boolean isEditorInputReadOnly() {
     return true;
 }
 @Override
 public boolean isDirty() {
     return false;
 }
}

Code for Invoking the Editor

IFile file = ...; // Get the Java file instance
IWorkbenchPage page = ...; // Get the workbench page
  
FileEditorInput input = new FileEditorInput(file);
try {
 IDE.openEditor(window.getActivePage(), input, ReadonlyEd.ID);
} catch (PartInitException e) {
 e.printStackTrace();
}

Thursday, August 23, 2012

Firebug Lite for SWT Browser on Windows

Recently I came across this question on stackoverflow 'Eclipse swt browser and firebug lite'. The solution seemed very obvious. I answered the question there also, you can always upvote it ;).

The output:


The code for the same is as follows:

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class FirebugLite 
{
 public static void main(String[] args) {
  new FirebugLite().start();
 }
 
 public void start()
 {
  Display display = new Display();
  Shell shell = new Shell(display);
  shell.setLayout(new GridLayout(1, false));
  GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
  gridData.widthHint = SWT.DEFAULT;
  gridData.heightHint = SWT.DEFAULT;
  shell.setLayoutData(gridData);
  shell.setText("Firebug Lite for SWT ;)");
  
  final Browser browser = new Browser(shell, SWT.NONE);
  GridData gridData2 = new GridData(SWT.FILL, SWT.FILL, true, true);
  gridData2.widthHint = SWT.DEFAULT;
  gridData2.heightHint = SWT.DEFAULT;
  browser.setLayoutData(gridData2);
  
  Button button = new Button(shell, SWT.PUSH);
  button.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
  button.setText("Install");
  button.addSelectionListener(new SelectionAdapter() {
   public void widgetSelected(SelectionEvent e) {
    browser.setUrl("javascript:(function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+'NS']&&F.documentElement.namespaceURI;E=E?F[i+'NS'](E,'script'):F[i]('script');E[r]('id',b);E[r]('src',I+g+T);E[r](b,u);(F[e]('head')[0]||F[e]('body')[0]).appendChild(E);E=new%20Image;E[r]('src',I+L);})(document,'createElement','setAttribute','getElementsByTagName','FirebugLite','4','firebug-lite.js','releases/lite/latest/skin/xp/sprite.png','https://getfirebug.com/','#startOpened');");
   }
  });
  
  browser.setUrl("http://stackoverflow.com/questions/12003602/eclipse-swt-browser-and-firebug-lite");

  shell.open();
  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }
  display.dispose();
 }
}

Tuesday, May 1, 2012

SWT - Capturing Control Screen-Shot

SWT code for capturing control screen-shot.

public class ScreenCaptureTest 
{
 public static void main(String[] args) 
 {
  String[] names  = {"Harry", "Sally", "Jhon", "Tim", "Scott"};
  String[] msg = {"Hello World!", "Today is a nice day to walk", "I am bored", "This is how you take widget capture", "Ha Ha Ha!! That's funny !"}; 
  
  final Display display = new Display();
  final Shell shell = new Shell(display);
  shell.setText("Screen Capture");
  shell.setLayout(new GridLayout(1, true));
  
  final Composite composite = new Composite(shell, SWT.BORDER);
  composite.setLayout(new GridLayout(2, true));
  composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
  
  Table table = new Table(composite, SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL|SWT.FULL_SELECTION);
  
  table.setLinesVisible(true);
  table.setHeaderVisible(true);
  
  table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
  
  TableColumn columnName = new TableColumn(table, SWT.LEFT);
  columnName.setText("Name");
  columnName.setWidth(100);
  
  TableColumn columnMsg = new TableColumn(table, SWT.LEFT);
  columnMsg.setText("Message");
  columnMsg.setWidth(200);
  
  for (int i = 0; i < 5; i++) 
  {
   TableItem item = new TableItem(table, SWT.NONE, 0);
   item.setText(0, names[i]);
   item.setText(1, msg[i]);   
  }
  
  StyledText text = new StyledText (composite, SWT.BORDER);
  text.setText("0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ");
  text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
  
  StyleRange style1 = new StyleRange();
  style1.start = 0;
  style1.length = 10;
  style1.fontStyle = SWT.BOLD;
  text.setStyleRange(style1);
  
  StyleRange style2 = new StyleRange();
  style2.start = 11;
  style2.length = 13;
  style2.foreground = display.getSystemColor(SWT.COLOR_RED);
  text.setStyleRange(style2);
  
  StyleRange style3 = new StyleRange();
  style3.start = 25;
  style3.length = 13;
  style3.background = display.getSystemColor(SWT.COLOR_BLUE);
  text.setStyleRange(style3);
  
  Button button = new Button(shell, SWT.PUSH);
  button.setText("Capture");
  button.pack();

  button.addListener(SWT.Selection, new Listener()
  {
   public void handleEvent(Event event) 
   {
    GC gc = new GC(display);
    final Image image = new Image(display, shell.getBounds());
    gc.copyArea(image, shell.getBounds().x, shell.getBounds().y);
    gc.dispose();

    Shell popup = new Shell(shell);
    popup.setText("Captured Image");
    popup.addListener(SWT.Close, new Listener() {
     public void handleEvent(Event e) {
      image.dispose();
     }
    });

    Canvas canvas = new Canvas(popup, SWT.NONE);
    canvas.setBounds(0,0,image.getImageData().width, image.getImageData().height);
    canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
      e.gc.drawImage(image, 0, 0);
     }
    });
    popup.pack();
    popup.open();
   }
  });
  
  shell.pack();
  shell.open();
  
  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }
  
  display.dispose();
 }
}

Original Composite:


Captured Image:

Wednesday, April 18, 2012

Programmatically create eclipse Java project

Following is a brief code snippet for creating an eclipse Java project using core JDT API.

private IJavaProject createProject() throws Exception
{
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    String projName = getProjectName();

    if(projName == null || projName.trim().length() == 0)
        return null;

    //create eclipse project
    IProject project = root.getProject(projName);
    if(project.exists())
        project.delete(true, null);

    project.create(null);
    project.open(null);

    //set the java project nature
    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID});
    project.setDescription(description, null);

    //create java project
    IJavaProject javaProject = JavaCore.create(project);

    //add bin/ouput folder
    IFolder binFolder = project.getFolder("bin");
    binFolder.create(false, true, null);
    javaProject.setOutputLocation(binFolder.getFullPath(), null);

    //add libs to project class path
    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
    LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
    for (LibraryLocation element : locations) {
        entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
    }
    
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

    //create source folder
    IFolder sourceFolder = project.getFolder("src");
    sourceFolder.create(false, true, null);

    IPackageFragmentRoot srcRoot = project.getPackageFragmentRoot(sourceFolder);
    IClasspathEntry[] oldEntries = project.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(srcRoot.getPath());
    project.setRawClasspath(newEntries, null);

    return javaProject;
}

private String getProjectName()
{
    String init_value = "project_" + System.currentTimeMillis();
    InputDialog dialog = new InputDialog(getShell(), "Java Project", "Provide project name ..", init_value, new IInputValidator() {
        public String isValid(String newText)
        {
            char[] array = newText.toCharArray();
            for (int i = 0; i < array.length; i++)
            {
                if(!Character.isJavaIdentifierPart(array[i]))
                    return "Cannot contain special characters !!";
            }

            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            IProject[] projs = root.getProjects();
            for (int i = 0; i < projs.length; i++) {
                if(projs[i].getName().equalsIgnoreCase(newText))
                    return "Project already exist !!";
            }

            /*
                Not checking for special Win32 names like con etc.
            */
            return null;
        }
    });

    if(dialog.open() == Dialog.CANCEL)
        return null;

    return dialog.getValue();
}