com.baremetalstudios.mapleide.actions.OpenFileAction.java Source code

Java tutorial

Introduction

Here is the source code for com.baremetalstudios.mapleide.actions.OpenFileAction.java

Source

/**********************************************************************
Copyright (c) 2012 baremetalstudios
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
    
Contributors:
   baremetalstudios, Ivan Bondarenko
 **********************************************************************/
package com.baremetalstudios.mapleide.actions;

import java.io.File;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;

import com.baremetalstudios.mapleide.Activator;

public class OpenFileAction extends Action implements IWorkbenchWindowActionDelegate {
    private IWorkbenchWindow fWindow;

    public OpenFileAction() {
        setId(ICommandIds.CMD_OPEN_FILE);
        setText("Open bm file");
        setEnabled(true);
        setImageDescriptor(Activator.getImageDescriptor("/icons/open.gif"));
    }

    public void dispose() {
        fWindow = null;
    }

    public void init(IWorkbenchWindow window) {
        fWindow = window;
    }

    public void run(IAction action) {
        run();
    }

    public void selectionChanged(IAction action, ISelection selection) {
    }

    private File queryFile() {
        FileDialog dialog = new FileDialog(fWindow.getShell(), SWT.OPEN);
        dialog.setText("Open File"); //$NON-NLS-1$
        String path = dialog.open();
        if (path != null && path.length() > 0)
            return new File(path);
        return null;
    }

    @Override
    public void run() {
        File file = queryFile();
        if (file != null) {
            IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(file.getPath()));
            if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
                IWorkbenchPage page = fWindow.getActivePage();
                try {
                    IDE.openEditorOnFileStore(page, fileStore);
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
        } else {
            MessageDialog.openWarning(fWindow.getShell(), "Problem", "File is 'null'");
        }
    }
}