Package net.cakenet.jsaton.ui

Source Code of net.cakenet.jsaton.ui.MainWindow$LoadRecentAction

/*
* Created by JFormDesigner on Mon Feb 11 10:52:03 GMT 2013
*/

package net.cakenet.jsaton.ui;

import com.sun.awt.AWTUtilities;
import net.cakenet.jsaton.Main;
import net.cakenet.jsaton.config.Configuration;
import net.cakenet.jsaton.nativedef.WindowManager;
import net.cakenet.jsaton.nativedef.WindowReference;
import net.cakenet.jsaton.script.Script;
import net.cakenet.jsaton.script.ScriptLanguage;
import net.cakenet.jsaton.script.ScriptState;
import net.cakenet.jsaton.script.ruby.RubyScript;
import net.cakenet.jsaton.ui.tools.LogWindow;
import net.cakenet.jsaton.ui.tools.MemoryUsageWindow;
import net.cakenet.jsaton.ui.tools.ScreenSelectionOverlay;
import net.cakenet.jsaton.ui.tools.ToolWindow;
import net.cakenet.jsaton.ui.tools.script.DebugWindow;
import net.cakenet.jsaton.ui.tools.script.ScriptEditor;
import net.cakenet.jsaton.ui.tools.snippet.SnippetManager;
import net.cakenet.jsaton.util.FileManager;
import net.cakenet.jsaton.util.ImageUtil;
import org.flexdock.docking.Dockable;
import org.flexdock.docking.DockingConstants;
import org.flexdock.docking.DockingManager;
import org.flexdock.docking.activation.ActiveDockableTracker;
import org.flexdock.docking.defaults.DefaultDockingPort;
import org.flexdock.docking.props.DockingPortPropertySet;
import org.flexdock.view.Viewport;
import org.jruby.embed.EvalFailedException;

import javax.imageio.ImageIO;
import javax.script.ScriptException;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
* @author unknown
*/
public class MainWindow extends JFrame {
    private boolean picking;
    private DefaultDockingPort scriptContainer;
    private ScriptEditor currentEditor;
    private LogWindow log;
    private DebugWindow debug;
    private LinkedList<String> recentFiles = new LinkedList<>();

    public MainWindow() {
        super(Main.APP_NAME);
        initComponents();
        ActiveDockableTracker.getTracker(this).addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                Dockable current = ActiveDockableTracker.getActiveDockable();
                if (current instanceof ScriptEditor)
                    editorFocused((ScriptEditor) current);
            }
        });
        SimpleAttributeSet out = new SimpleAttributeSet();
        SimpleAttributeSet err = new SimpleAttributeSet();
        StyleConstants.setForeground(err, Color.RED);

        scriptContainer = new DefaultDockingPort("scripts");
        DockingPortPropertySet props = scriptContainer.getDockingProperties();
        props.setSingleTabsAllowed(true);
        props.setTabPlacement(JTabbedPane.TOP);
        dock.dock(scriptContainer, DockingConstants.CENTER_REGION);
        DockingManager.setMainDockingPort(this, "scripts");
        initToolWindows();
        initRecent();
        System.setIn(log.log.getInputStream());
        System.setErr(new PrintStream(log.log.createOutputStream(System.err, err)));
        System.setOut(new PrintStream(log.log.createOutputStream(System.out, out)));
        ScriptEditor se = newScriptWindow(new RubyScript());
        selectWindow.setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, null);
        selectWindow.setInputMap(JComponent.WHEN_FOCUSED, null);
        selectWindow.setInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
        MouseAdapter mad = new MouseAdapter() {
            private Cursor prevCursor;
            private JWindow preview = new JWindow();
            private WindowReference selected = WindowManager.getDesktop();

            {
                preview.setAlwaysOnTop(true);
                preview.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
                AWTUtilities.setWindowOpaque(preview, false);
                ((JComponent) preview.getContentPane()).setBorder(BorderFactory.createLineBorder(Color.RED, 2));
            }

            public void mousePressed(MouseEvent e) {
                if (e.getButton() != 1)
                    return;
                if (currentEditor == null) {
                    JOptionPane.showMessageDialog(MainWindow.this, "You must have a script open before you can select a window", "No script", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                picking = true;
                selectWindow(e.getXOnScreen(), e.getYOnScreen());
                prevCursor = getCursor();
                setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
            }

            public void mouseReleased(MouseEvent e) {
                if (!picking)
                    return;
                try {
                    picking = false;
                    currentEditor.script.setTarget(selected);
                    preview.setVisible(false);
                    setCursor(prevCursor);
                    preview.setVisible(false);
                    preview.setVisible(false);
                    System.out.println("Selected window: " + selected.toString());
                    selected = null;
                    preview.setVisible(false);
                } catch (Throwable t) {
                    t.printStackTrace(); // wtf is going on!
                }
            }

            public void mouseDragged(MouseEvent e) {
                selectWindow(e.getXOnScreen(), e.getYOnScreen());
            }

            private void selectWindow(final int x, final int y) {
                boolean abort = getBounds().contains(x, y);
                preview.setVisible(false);
                // Don't target us! (mouse release isn't called so we can't target ourselves even if we wanted to)
                if (abort) {
                    selected = currentEditor.script.getTarget(); // revert...
                    return;
                }

                selected = WindowManager.findWindowByPoint(new Point(x, y));
                // set visible as soon as possible to avoid flicker
                preview.setVisible(true);
                Rectangle bounds = selected.getBounds();
                preview.setSize(bounds.width, bounds.height);
                preview.setLocation(bounds.x, bounds.y);
            }
        };
        selectWindow.addMouseListener(mad);
        selectWindow.addMouseMotionListener(mad);

        status(Main.APP_NAME + " version " + Main.APP_VER + " loaded.");

        ActiveDockableTracker.getTracker(this).setActive(se);
        editorFocused(se); // Cheat for startup...
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        menuBar1 = new JMenuBar();
        menu1 = new JMenu();
        menuItem12 = new JMenuItem();
        menuItem2 = new JMenuItem();
        recent = new JMenu();
        menuItem3 = new JMenuItem();
        menuItem4 = new JMenuItem();
        menuItem11 = new JMenuItem();
        menuItem13 = new JMenuItem();
        menuItem1 = new JMenuItem();
        menu4 = new JMenu();
        toolWindowMenu = new JMenu();
        menu3 = new JMenu();
        menuItem6 = new JMenuItem();
        menuItem7 = new JMenuItem();
        menuItem8 = new JMenuItem();
        menuItem9 = new JMenuItem();
        menuItem10 = new JMenuItem();
        menu2 = new JMenu();
        menuItem5 = new JMenuItem();
        toolBars = new JPanel();
        scripToolbar = new JToolBar();
        start = new JButton();
        pause = new JButton();
        stop = new JButton();
        separator2 = new JSeparator();
        stepInto = new JButton();
        stepOver = new JButton();
        utilToolbar = new JToolBar();
        pickColor = new JButton();
        screenshot = new JButton();
        capturePicture = new JButton();
        selectWindow = new JLabel();
        panel2 = new JPanel();
        status = new JLabel();
        progress = new JProgressBar();
        dock = new Viewport();
        save = new SaveAction();
        open = new OpenAction();
        saveas = new SaveAsAction();
        startAction = new StartAction();
        pauseAction = new PauseAction();
        stopAction = new StopAction();
        stepIntoAction = new StepIntoAction();
        stepOverAction = new StepOverAction();
        pickColorAction = new PickColorAction();
        screenshotAction = new ScreenshotAction();
        bitmapSelectAction = new BitmapSelectAction();
        closeAction = new CloseAction();
        newAction = new NewAction();
        scriptPropertiesAction = new ShowScriptPropertiesAction();
        aboutAction = new AboutAction();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setIconImage(new ImageIcon(getClass().getResource("/icons/hammer_screwdriver.png")).getImage());
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        //======== menuBar1 ========
        {

            //======== menu1 ========
            {
                menu1.setText("File");
                menu1.setMnemonic('F');

                //---- menuItem12 ----
                menuItem12.setAction(newAction);
                menuItem12.setMnemonic('N');
                menu1.add(menuItem12);

                //---- menuItem2 ----
                menuItem2.setAction(open);
                menuItem2.setMnemonic('O');
                menu1.add(menuItem2);

                //======== recent ========
                {
                    recent.setText("Reopen");
                    recent.setMnemonic('R');
                }
                menu1.add(recent);

                //---- menuItem3 ----
                menuItem3.setAction(save);
                menuItem3.setMnemonic('S');
                menu1.add(menuItem3);

                //---- menuItem4 ----
                menuItem4.setAction(saveas);
                menuItem4.setMnemonic('A');
                menu1.add(menuItem4);

                //---- menuItem11 ----
                menuItem11.setAction(closeAction);
                menuItem11.setMnemonic('C');
                menu1.add(menuItem11);

                //---- menuItem13 ----
                menuItem13.setAction(scriptPropertiesAction);
                menuItem13.setMnemonic('P');
                menu1.add(menuItem13);
                menu1.addSeparator();

                //---- menuItem1 ----
                menuItem1.setText("Exit");
                menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.ALT_MASK));
                menuItem1.setMnemonic('X');
                menuItem1.setIcon(new ImageIcon(getClass().getResource("/icons/door_in.png")));
                menu1.add(menuItem1);
            }
            menuBar1.add(menu1);

            //======== menu4 ========
            {
                menu4.setText("View");
                menu4.setMnemonic('V');

                //======== toolWindowMenu ========
                {
                    toolWindowMenu.setText("Tool windows");
                    toolWindowMenu.setMnemonic('T');
                }
                menu4.add(toolWindowMenu);
            }
            menuBar1.add(menu4);

            //======== menu3 ========
            {
                menu3.setText("Run");
                menu3.setMnemonic('U');

                //---- menuItem6 ----
                menuItem6.setText("Start");
                menuItem6.setAction(startAction);
                menuItem6.setMnemonic('S');
                menu3.add(menuItem6);

                //---- menuItem7 ----
                menuItem7.setText("text");
                menuItem7.setAction(pauseAction);
                menuItem7.setMnemonic('P');
                menu3.add(menuItem7);

                //---- menuItem8 ----
                menuItem8.setText("text");
                menuItem8.setAction(stopAction);
                menuItem8.setMnemonic('T');
                menu3.add(menuItem8);
                menu3.addSeparator();

                //---- menuItem9 ----
                menuItem9.setText("text");
                menuItem9.setAction(stepIntoAction);
                menuItem9.setMnemonic('I');
                menu3.add(menuItem9);

                //---- menuItem10 ----
                menuItem10.setText("text");
                menuItem10.setAction(stepOverAction);
                menuItem10.setMnemonic('O');
                menu3.add(menuItem10);
            }
            menuBar1.add(menu3);

            //======== menu2 ========
            {
                menu2.setText("Help");
                menu2.setMnemonic('H');

                //---- menuItem5 ----
                menuItem5.setMnemonic('A');
                menuItem5.setAction(aboutAction);
                menu2.add(menuItem5);
            }
            menuBar1.add(menu2);
        }
        setJMenuBar(menuBar1);

        //======== toolBars ========
        {
            toolBars.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
            ((FlowLayout)toolBars.getLayout()).setAlignOnBaseline(true);

            //======== scripToolbar ========
            {

                //---- start ----
                start.setVerticalTextPosition(SwingConstants.BOTTOM);
                start.setHorizontalTextPosition(SwingConstants.CENTER);
                start.setMnemonic('S');
                start.setAction(startAction);
                start.setHideActionText(true);
                scripToolbar.add(start);

                //---- pause ----
                pause.setVerticalTextPosition(SwingConstants.BOTTOM);
                pause.setHorizontalTextPosition(SwingConstants.CENTER);
                pause.setMnemonic('P');
                pause.setAction(pauseAction);
                pause.setHideActionText(true);
                scripToolbar.add(pause);

                //---- stop ----
                stop.setHorizontalTextPosition(SwingConstants.CENTER);
                stop.setVerticalTextPosition(SwingConstants.BOTTOM);
                stop.setMnemonic('T');
                stop.setAction(stopAction);
                stop.setHideActionText(true);
                scripToolbar.add(stop);

                //---- separator2 ----
                separator2.setOrientation(SwingConstants.VERTICAL);
                scripToolbar.add(separator2);

                //---- stepInto ----
                stepInto.setHorizontalTextPosition(SwingConstants.CENTER);
                stepInto.setVerticalTextPosition(SwingConstants.BOTTOM);
                stepInto.setMnemonic('I');
                stepInto.setAction(stepIntoAction);
                stepInto.setHideActionText(true);
                scripToolbar.add(stepInto);

                //---- stepOver ----
                stepOver.setHorizontalTextPosition(SwingConstants.CENTER);
                stepOver.setVerticalTextPosition(SwingConstants.BOTTOM);
                stepOver.setMnemonic('O');
                stepOver.setAction(stepOverAction);
                stepOver.setHideActionText(true);
                scripToolbar.add(stepOver);
            }
            toolBars.add(scripToolbar);

            //======== utilToolbar ========
            {

                //---- pickColor ----
                pickColor.setHorizontalTextPosition(SwingConstants.CENTER);
                pickColor.setVerticalTextPosition(SwingConstants.BOTTOM);
                pickColor.setMnemonic('C');
                pickColor.setAction(pickColorAction);
                pickColor.setHideActionText(true);
                utilToolbar.add(pickColor);

                //---- screenshot ----
                screenshot.setMnemonic('R');
                screenshot.setHorizontalTextPosition(SwingConstants.CENTER);
                screenshot.setVerticalTextPosition(SwingConstants.BOTTOM);
                screenshot.setAction(screenshotAction);
                screenshot.setHideActionText(true);
                utilToolbar.add(screenshot);

                //---- capturePicture ----
                capturePicture.setMnemonic('B');
                capturePicture.setVerticalTextPosition(SwingConstants.BOTTOM);
                capturePicture.setHorizontalTextPosition(SwingConstants.CENTER);
                capturePicture.setAction(bitmapSelectAction);
                capturePicture.setHideActionText(true);
                utilToolbar.add(capturePicture);

                //---- selectWindow ----
                selectWindow.setIcon(new ImageIcon(getClass().getResource("/crosshair.png")));
                selectWindow.setVerticalTextPosition(SwingConstants.BOTTOM);
                selectWindow.setHorizontalTextPosition(SwingConstants.CENTER);
                utilToolbar.add(selectWindow);
            }
            toolBars.add(utilToolbar);
        }
        contentPane.add(toolBars, BorderLayout.NORTH);

        //======== panel2 ========
        {
            panel2.setLayout(new BorderLayout());
            panel2.add(status, BorderLayout.CENTER);

            //---- progress ----
            progress.setEnabled(false);
            panel2.add(progress, BorderLayout.EAST);
        }
        contentPane.add(panel2, BorderLayout.SOUTH);
        contentPane.add(dock, BorderLayout.CENTER);
        pack();
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    private void addRecent(String path) {
        if(recentFiles.contains(path)) // remove before re-adding to the top...
            recentFiles.remove(path);

        while(recentFiles.size() >= 10)
            recentFiles.poll();

        recent.removeAll();

        recentFiles.offer(path);

        // Re-add all...
        for (int i = recentFiles.size() - 1; i >= 0; i--) {
            String s = recentFiles.get(i);
            try {
                recent.add(new LoadRecentAction(Script.open(s)));
            } catch (IOException e) {
                // Ignore it, no longer existing...
                recentFiles.remove(i);
                i--;
            }
        }
        Configuration.APP_CONFIG.set("recent", recentFiles);
    }

    private void initRecent() {
        List<String> r = Configuration.APP_CONFIG.get("recent", new LinkedList<String>());
        for(String s: r)
            addRecent(s);
    }

    private void initToolWindows() {
        Dockable snippets;
        dock.dock(snippets = finaliseToolWindow(new SnippetManager()), DockingConstants.WEST_REGION);
        dock.dock((Dockable) (log = finaliseToolWindow(new LogWindow())), DockingConstants.SOUTH_REGION);
        DockingManager.setSplitProportion(snippets, 0.2f);
        DockingManager.setSplitProportion((Dockable) log, 0.7f);
        finaliseToolWindow(new MemoryUsageWindow());
        log.dock(debug = finaliseToolWindow(new DebugWindow()), DockingConstants.EAST_REGION);
    }


    //<editor-fold desc="Script change listener">
    private PropertyChangeListener scriptPropertyListener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent pce) {
            Script script = (Script) pce.getSource();
            if (pce.getPropertyName().equals("state")) {
                ScriptState oldState = (ScriptState) pce.getOldValue();
                boolean sta, sto, pau, stin, stov;
                switch (script.getState()) {
                    case INITIALISING:
                        setProgressUnknown();
                        setProgressEnabled(true);
                        status.setText("Preparing script for execution...");
                        sta = sto = pau = stin = stov = false;
                        break;
                    case SUSPENDED:
                        sta = sto = true;
                        stin = stov = script.isDebug();
                        pau = false;
                        break;
                    case STOPPED:
                        sta = true;
                        sto = pau = stin = stov = false;
                        status.setText(script.getName() + " finished.");
                        break;
                    case RUNNING:
                        if (oldState == ScriptState.INITIALISING) {
                            status.setText("Executing " + script.getName() + "...");
                            setProgressEnabled(false);
                        }
                        sta = stin = stov = false;
                        pau = sto = true;
                        break;
                    default:
                        throw new RuntimeException("Unexpected script state");
                }
                startAction.setEnabled(sta);
                pauseAction.setEnabled(pau);
                stopAction.setEnabled(sto);
                stepIntoAction.setEnabled(stin);
                stepOverAction.setEnabled(stov);
            }
        }
    };
    //</editor-fold>

    private void editorUnfocused(ScriptEditor editor) {
        if (editor != null)
            editor.script.removePropertyChangeListener(scriptPropertyListener);
        if (currentEditor == editor) {
            currentEditor = null;
            debug.setEditor(null);
            save.setEnabled(false);
            saveas.setEnabled(false);
            closeAction.setEnabled(false);
            scriptPropertiesAction.setEnabled(false);
        }
    }

    private void editorFocused(ScriptEditor editor) {
        if(editor == currentEditor)
            return; // blah...
        if (currentEditor != null)
            editorUnfocused(currentEditor);
        debug.setEditor(editor);
        save.setEnabled(true);
        saveas.setEnabled(true);
        closeAction.setEnabled(true);
        scriptPropertiesAction.setEnabled(true);
        Script script = editor.script;
        currentEditor = editor;
        script.removePropertyChangeListener(scriptPropertyListener);
        script.addPropertyChangeListener(scriptPropertyListener);
        script.fireStateChange();
    }

    private ScriptEditor newScriptWindow(Script s) {
        s.setTarget(WindowManager.getDesktop());
        final ScriptEditor se = new ScriptEditor(s);
        finaliseToolWindow(se);
        if(currentEditor != null)
            currentEditor.dock(se);
        else
            scriptContainer.dock((Dockable) se, DockingConstants.CENTER_REGION);
        return se;
    }

    private <T extends ToolWindow> T finaliseToolWindow(final T t) {
        t.add(t.getContents());
        DockingManager.registerDockable((Dockable) t);
        if(!(t instanceof ScriptEditor)) {
            JMenuItem item = new JCheckBoxMenuItem(t.getName());
            item.setIcon(t.getIcon());
            item.setModel( new JToggleButton.ToggleButtonModel() {
                public boolean isSelected() {
                    return DockingManager.isDocked((Dockable) t);
                }

                public void setSelected(boolean b) {
                    if(!b) {
                        DockingManager.close(t);
                    } else {
                        dock.dock((Dockable) t, DockingConstants.SOUTH_REGION);
                    }
                }
            });
            toolWindowMenu.add(item);
        }
        return t;
    }

    public void status(String message) {
        status.setText(message);
    }

    public void setProgressEnabled(boolean val) {
        progress.setValue(0);
        progress.setVisible(val);
    }

    public void setProgressUnknown() {
        progress.setIndeterminate(true);
    }

    public void updateProgress(int perc) {
        if (progress.isIndeterminate())
            progress.setIndeterminate(false);
        progress.setValue(perc);
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JMenuBar menuBar1;
    private JMenu menu1;
    private JMenuItem menuItem12;
    private JMenuItem menuItem2;
    private JMenu recent;
    private JMenuItem menuItem3;
    private JMenuItem menuItem4;
    private JMenuItem menuItem11;
    private JMenuItem menuItem13;
    private JMenuItem menuItem1;
    private JMenu menu4;
    private JMenu toolWindowMenu;
    private JMenu menu3;
    private JMenuItem menuItem6;
    private JMenuItem menuItem7;
    private JMenuItem menuItem8;
    private JMenuItem menuItem9;
    private JMenuItem menuItem10;
    private JMenu menu2;
    private JMenuItem menuItem5;
    private JPanel toolBars;
    private JToolBar scripToolbar;
    private JButton start;
    private JButton pause;
    private JButton stop;
    private JSeparator separator2;
    private JButton stepInto;
    private JButton stepOver;
    private JToolBar utilToolbar;
    private JButton pickColor;
    private JButton screenshot;
    private JButton capturePicture;
    private JLabel selectWindow;
    private JPanel panel2;
    private JLabel status;
    private JProgressBar progress;
    private Viewport dock;
    private SaveAction save;
    private OpenAction open;
    private SaveAsAction saveas;
    private StartAction startAction;
    private PauseAction pauseAction;
    private StopAction stopAction;
    private StepIntoAction stepIntoAction;
    private StepOverAction stepOverAction;
    private PickColorAction pickColorAction;
    private ScreenshotAction screenshotAction;
    private BitmapSelectAction bitmapSelectAction;
    private CloseAction closeAction;
    private NewAction newAction;
    private ShowScriptPropertiesAction scriptPropertiesAction;
    private AboutAction aboutAction;
    // JFormDesigner - End of variables declaration  //GEN-END:variables

    private JFileChooser fileChooser;
    private void initFileChooser() {
        if(fileChooser == null) {
            File scriptPath = FileManager.getUserDirectory("scripts").toFile();
            fileChooser = new JFileChooser(scriptPath);
            fileChooser.setFileHidingEnabled(true);
            final LinkedList<String> exts = new LinkedList<>();
            for(ScriptLanguage lang: ScriptLanguage.values()) {
                exts.add(lang.extension);
            }
            final FileFilter filter = new FileFilter() {
                public boolean accept(File f) {
                    String s = f.getName();
                    String ext = s.substring(s.lastIndexOf('.') + 1);
                    return exts.contains(ext);
                }

                public String getDescription() {
                    return Main.APP_NAME + " scripts";
                }
            };
            final ImageIcon icon = ImageUtil.loadIcon("icons/script.png");
            fileChooser.setFileView(new FileView() {
                private Script load(File f) {
                    if(!filter.accept(f))
                        return null;
                    try {
                        return Script.open(f.getAbsolutePath());
                    } catch(Exception e) {
                        /**/
                    }
                    return null;
                }

                public String getDescription(File f) {
                    Script s = load(f);
                    if(s == null)
                        return super.getDescription(f);
                    return s.getName() + "\n" + s.getDescription();
                }

                public String getTypeDescription(File f) {
                    Script s = load(f);
                    if(s == null)
                        return super.getTypeDescription(f);
                    return Main.APP_NAME + " " + s.language.name + " script";
                }

                public Icon getIcon(File f) {
                    Script s = load(f);
                    if(s == null)
                        return super.getIcon(f);
                    return icon;
                }
            });
            fileChooser.setFileFilter(filter);
        }
    }

    private boolean saveAs() {
        initFileChooser();
        if(fileChooser.showSaveDialog(MainWindow.this) != JFileChooser.APPROVE_OPTION)
            return false;
        File f = fileChooser.getSelectedFile();
        return save(f.getAbsolutePath());
    }

    private boolean save(String path) {
        setProgressUnknown();
        setProgressEnabled(true);
        boolean result = true;
        Script script = currentEditor.script;
        String ext = "." + script.language.extension;
        if(!path.toLowerCase().endsWith(ext.toLowerCase()))
            path += ext;
        try {
            currentEditor.updateScript();
            currentEditor.script.save(path);
            currentEditor.scriptPane.setDirty(false);
            addRecent(path);
            status("Script saved successfully");
        } catch (IOException e) {
            status("Unable to save script");
            e.printStackTrace();
            result = false;
        }
        setProgressEnabled(false);
        return result;
    }

    private void open(String path) {
        setProgressUnknown();
        setProgressEnabled(true);
        status("Opening script...");
        try {
            Script s = Script.open(path);
            newScriptWindow(s);
            addRecent(path);
        } catch (IOException e1) {
            e1.printStackTrace();
            status("Unable to open script");
        }
        setProgressEnabled(false);
    }

    private class SaveAction extends AbstractAction {
        private SaveAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Save");
            putValue(SHORT_DESCRIPTION, "Save");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/disk.png")));
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK));
            putValue(ACTION_COMMAND_KEY, "save");
            setEnabled(false);
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            if(currentEditor == null)
                return;
            Script s = currentEditor.script;
            if(s.getPath() == null)
                saveAs();
            else
                save(s.getPath());
        }
    }

    private class SaveAsAction extends AbstractAction {
        private SaveAsAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Save as...");
            putValue(SHORT_DESCRIPTION, "Save as...");
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK|KeyEvent.SHIFT_MASK));
            putValue(ACTION_COMMAND_KEY, "save as");
            setEnabled(false);
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            saveAs();
        }
    }

    private class OpenAction extends AbstractAction {
        private OpenAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Open");
            putValue(SHORT_DESCRIPTION, "Open script");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/folder.png")));
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_MASK));
            putValue(ACTION_COMMAND_KEY, "open");
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            initFileChooser();
            if(fileChooser.showOpenDialog(MainWindow.this) != JFileChooser.APPROVE_OPTION)
                return;
            File f = fileChooser.getSelectedFile();
            open(f.getAbsolutePath());
        }
    }

    private class StartAction extends AbstractAction {
        private StartAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Start");
            putValue(SHORT_DESCRIPTION, "Start the script");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/start.png")));
            putValue(ACTION_COMMAND_KEY, "startScript");
            setEnabled(false);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0));
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            if (currentEditor == null)
                return;
            Script script = currentEditor.script;
            if (script.getState() != ScriptState.STOPPED) {
                if (script.getState() != ScriptState.SUSPENDED)
                    return;
                script.resume();
                return;
            }

            // start...
            currentEditor.updateScript();
            try {
                script.start(true);
            } catch (ScriptException e1) {
                e1.printStackTrace();
            }
        }
    }

    private class PauseAction extends AbstractAction {
        private PauseAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Pause");
            putValue(SHORT_DESCRIPTION, "pause the script");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/pause.png")));
            putValue(ACTION_COMMAND_KEY, "pause");
            setEnabled(false);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F9, KeyEvent.SHIFT_MASK));
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            if (currentEditor == null)
                return;
            Script script = currentEditor.script;
            script.suspend();
        }
    }

    private class StopAction extends AbstractAction {
        private StopAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Stop");
            putValue(SHORT_DESCRIPTION, "Stop the script");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/stop.png")));
            setEnabled(false);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F2, KeyEvent.CTRL_MASK));
            putValue(ACTION_COMMAND_KEY, "stopScript");
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            if (currentEditor == null)
                return;
            Script script = currentEditor.script;
            try {
                script.stop();
            } catch (EvalFailedException | ThreadDeath td) {
                /**/
            }
        }
    }

    private class StepIntoAction extends AbstractAction {
        private StepIntoAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Step into");
            putValue(SHORT_DESCRIPTION, "Step to the next line executed");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/step-into.png")));
            putValue(ACTION_COMMAND_KEY, "stepInto");
            setEnabled(false);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            if (currentEditor == null)
                return;
            Script script = currentEditor.script;
            script.stepInto();
        }
    }

    private class StepOverAction extends AbstractAction {
        private StepOverAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Step over");
            putValue(SHORT_DESCRIPTION, "Step to the next line in this file");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/step-over.png")));
            putValue(ACTION_COMMAND_KEY, "stepOver");
            setEnabled(false);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0));
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            if (currentEditor == null)
                return;
            Script script = currentEditor.script;
            script.stepOver();
        }
    }

    private class PickColorAction extends AbstractAction {
        private PickColorAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Pick color");
            putValue(SHORT_DESCRIPTION, "Pick a color from the screen");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/pipette.png")));
            putValue(ACTION_COMMAND_KEY, "pickColo");
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            ScreenSelectionOverlay overlay = new ScreenSelectionOverlay(MainWindow.this, true, ScreenSelectionOverlay.CloseMethod.CloseOnClick);
            overlay.addMouseListener(new MouseAdapter() {
                public void mouseClicked(final MouseEvent e) {
                    new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(100); // Delay so the window can hide in time...
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            int col = WindowManager.getDesktop().getPixel(e.getXOnScreen(), e.getYOnScreen()) & 0xffffff; // Only care about rgb...
                            Color c = new Color(col, false);
                            System.out.println(String.format("Selected color: #%06x", col));
                            SnippetManager.instance.addSnippet(c);
                        }
                    }.start();
                }
            });
            overlay.setVisible(true);
        }
    }

    private class ScreenshotAction extends AbstractAction {
        private ScreenshotAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Screenshot");
            putValue(SHORT_DESCRIPTION, "Take a screenshot of the currently selected window");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/camera.png")));
            putValue(ACTION_COMMAND_KEY, "screenshot");
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            String date = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
            File f = FileManager.getUserFile("screenshots", date + ".png");
            try {
                WindowReference ref = currentEditor == null ? WindowManager.getDesktop() :
                        currentEditor.script.getTarget();
                BufferedImage img = ref.captureImage().toImage();
                ImageIO.write(img, "PNG", f);
                System.out.println("Screenshot saved as file://" + f.getAbsolutePath());
            } catch (Exception e1) {
                System.out.println("Failed to capture screenshot: " + e1.getLocalizedMessage());
            }
        }
    }

    private class BitmapSelectAction extends AbstractAction {
        private BitmapSelectAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Select bitmap");
            putValue(SHORT_DESCRIPTION, "Select a bitmap from your screen");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/photo.png")));
            putValue(ACTION_COMMAND_KEY, "bitmapSelect");
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            ScreenSelectionOverlay overlay = new ScreenSelectionOverlay(MainWindow.this, false, ScreenSelectionOverlay.CloseMethod.CloseOnRelease);
            overlay.addMouseListener(new MouseAdapter() {
                private Point start
                        ,
                        end;

                public void mousePressed(MouseEvent e) {
                    start = e.getLocationOnScreen();
                    end = start; // in case they release straightway...
                }

                public void mouseReleased(MouseEvent e) {
                    end = e.getLocationOnScreen();
                    final int sX = Math.min(start.x, end.x);
                    final int sY = Math.min(start.y, end.y);
                    int eX = Math.max(start.x, end.x);
                    int eY = Math.max(start.y, end.y);
                    final int w = eX - sX;
                    final int h = eY - sY;

                    new Thread(new Runnable() {
                        public void run() {
                            setProgressEnabled(true);
                            setProgressUnknown();
                            try {
                                Thread.sleep(100); // Delay until the windows are hidden...
                            } catch (InterruptedException e1) {
                                    /**/
                            }
                            Object img = WindowManager.getDesktop().captureImage(sX, sY, w + 1, h + 1).toImage();
                            SnippetManager.instance.addSnippet(img);
                            setProgressEnabled(false);
                        }
                    }).start();
                }
            });
            overlay.setVisible(true);
        }
    }

    private class CloseAction extends AbstractAction {
        private CloseAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Close");
            putValue(SHORT_DESCRIPTION, "Close the current script");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/cross.png")));
            setEnabled(false);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.CTRL_MASK));
            putValue(ACTION_COMMAND_KEY, "close");
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(MainWindow.this, "Are you sure you want to close this script?", "Close confirmation",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                DockingManager.close(currentEditor);
                DockingManager.unregisterDockable((Dockable) currentEditor);
                editorUnfocused(currentEditor);
            }
        }
    }

    private class NewAction extends AbstractAction {
        private NewAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "New");
            putValue(SHORT_DESCRIPTION, "Create a new script");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/script.png")));
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_MASK));
            putValue(ACTION_COMMAND_KEY, "new");
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            ScriptPropertiesDialog n = new ScriptPropertiesDialog(MainWindow.this);
            n.setVisible(true);
            Script s = n.getResult();
            if(s != null)
                newScriptWindow(s);
        }
    }

    private class ShowScriptPropertiesAction extends AbstractAction {
        private ShowScriptPropertiesAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "Script properties");
            putValue(SHORT_DESCRIPTION, "View and edit the properties for this script");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/report.png")));
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK|KeyEvent.ALT_MASK));
            setEnabled(false);
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            ScriptPropertiesDialog spd = new ScriptPropertiesDialog(MainWindow.this, currentEditor.script);
            spd.setVisible(true);
            spd.getResult();
        }
    }

    private class AboutAction extends AbstractAction {
        private AboutAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            putValue(NAME, "About");
            putValue(SHORT_DESCRIPTION, "About");
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/help.png")));
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            new AboutDialog(MainWindow.this).setVisible(true);
        }
    }

    private class LoadRecentAction extends AbstractAction {
        private String path;

        public LoadRecentAction(Script script) {
            this.path = script.getPath();
            putValue(NAME, script.getName());
            putValue(SHORT_DESCRIPTION, path);
            putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/icons/script.png")));
        }

        public void actionPerformed(ActionEvent e) {
            open(path);
        }
    }
}
TOP

Related Classes of net.cakenet.jsaton.ui.MainWindow$LoadRecentAction

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.
div>