Search in sources :

Example 1 with XJPopupMenu

use of gate.swing.XJPopupMenu in project gate-core by GateNLP.

the class MainFrame method initGuiComponents.

protected void initGuiComponents() {
    this.getContentPane().setLayout(new BorderLayout());
    Integer width = Gate.getUserConfig().getInt(GateConstants.MAIN_FRAME_WIDTH, 1024);
    Integer height = Gate.getUserConfig().getInt(GateConstants.MAIN_FRAME_HEIGHT, 768);
    Rectangle maxDimensions = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    this.setSize(new Dimension(Math.min(width, maxDimensions.width), Math.min(height, maxDimensions.height)));
    if (Gate.getUserConfig().getBoolean(GateConstants.MAIN_FRAME_MAXIMIZED))
        setExtendedState(JFrame.MAXIMIZED_BOTH);
    setIconImages(Arrays.asList(new Image[] { new GATEVersionIcon(256, 256).getImage(), new GATEVersionIcon(128, 128).getImage(), new GATEVersionIcon(64, 64).getImage(), new GATEVersionIcon(48, 48).getImage(), new GATEVersionIcon(32, 32).getImage(), new GATEIcon(22, 22).getImage(), new GATEIcon(16, 16).getImage() }));
    resourcesTree = new ResourcesTree();
    resourcesTree.setModel(resourcesTreeModel);
    resourcesTree.setRowHeight(0);
    resourcesTree.setEditable(true);
    ResourcesTreeCellRenderer treeCellRenderer = new ResourcesTreeCellRenderer();
    resourcesTree.setCellRenderer(treeCellRenderer);
    resourcesTree.setCellEditor(new ResourcesTreeCellEditor(resourcesTree, treeCellRenderer));
    resourcesTree.setInvokesStopCellEditing(true);
    resourcesTree.setRowHeight(0);
    // expand all nodes
    resourcesTree.expandRow(0);
    resourcesTree.expandRow(1);
    resourcesTree.expandRow(2);
    resourcesTree.expandRow(3);
    resourcesTree.expandRow(4);
    resourcesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    resourcesTree.setEnabled(true);
    ToolTipManager.sharedInstance().registerComponent(resourcesTree);
    resourcesTreeScroll = new JScrollPane(resourcesTree);
    resourcesTree.setDragEnabled(true);
    resourcesTree.setTransferHandler(new TransferHandler() {

        // drag and drop that export a list of the selected documents
        @Override
        public int getSourceActions(JComponent c) {
            return COPY;
        }

        @Override
        protected Transferable createTransferable(JComponent c) {
            TreePath[] paths = resourcesTree.getSelectionPaths();
            if (paths == null) {
                return new StringSelection("");
            }
            Handle handle;
            List<String> documentsNames = new ArrayList<String>();
            for (TreePath path : paths) {
                if (path != null) {
                    Object value = path.getLastPathComponent();
                    value = ((DefaultMutableTreeNode) value).getUserObject();
                    if (value instanceof Handle) {
                        handle = (Handle) value;
                        if (handle.getTarget() instanceof Document) {
                            documentsNames.add(((Document) handle.getTarget()).getName());
                        }
                    }
                }
            }
            return new StringSelection("ResourcesTree" + Arrays.toString(documentsNames.toArray()));
        }

        @Override
        protected void exportDone(JComponent c, Transferable data, int action) {
        }

        @Override
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            return false;
        }

        @Override
        public boolean importData(JComponent c, Transferable t) {
            return false;
        }
    });
    lowerScroll = new JScrollPane();
    JPanel lowerPane = new JPanel();
    lowerPane.setLayout(new OverlayLayout(lowerPane));
    JPanel animationPane = new JPanel();
    animationPane.setOpaque(false);
    animationPane.setLayout(new BoxLayout(animationPane, BoxLayout.X_AXIS));
    JPanel vBox = new JPanel();
    vBox.setLayout(new BoxLayout(vBox, BoxLayout.Y_AXIS));
    vBox.setOpaque(false);
    JPanel hBox = new JPanel();
    hBox.setLayout(new BoxLayout(hBox, BoxLayout.X_AXIS));
    hBox.setOpaque(false);
    vBox.add(Box.createVerticalGlue());
    vBox.add(animationPane);
    hBox.add(vBox);
    hBox.add(Box.createHorizontalGlue());
    lowerPane.add(hBox);
    lowerPane.add(lowerScroll);
    animator = new CartoonMinder(animationPane);
    Thread thread = new Thread(Thread.currentThread().getThreadGroup(), animator, "MainFrame animation");
    thread.setDaemon(true);
    thread.setPriority(Thread.MIN_PRIORITY);
    thread.start();
    leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, resourcesTreeScroll, lowerPane);
    leftSplit.setResizeWeight(0.7);
    leftSplit.setContinuousLayout(true);
    leftSplit.setOneTouchExpandable(true);
    // Create a new logArea and redirect the Out and Err output to it.
    logArea = new LogArea();
    // Out has been redirected to the logArea
    Out.prln("GATE " + Main.version + " build " + Main.build + " started at " + new Date().toString());
    Out.prln("and using Java " + System.getProperty("java.version") + " " + System.getProperty("java.vendor") + " on " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version") + ".");
    mainTabbedPane = new XJTabbedPane(JTabbedPane.TOP);
    mainTabbedPane.insertTab("Messages", null, logArea.getComponentToDisplay(), "GATE log", 0);
    logHighlighter = new TabHighlighter(mainTabbedPane, logArea.getComponentToDisplay(), Color.red);
    mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftSplit, mainTabbedPane);
    mainSplit.setDividerLocation(leftSplit.getPreferredSize().width + 10);
    this.getContentPane().add(mainSplit, BorderLayout.CENTER);
    mainSplit.setContinuousLayout(true);
    mainSplit.setOneTouchExpandable(true);
    // status and progress bars
    statusBar = new JLabel("Welcome to GATE!");
    statusBar.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
    UIManager.put("ProgressBar.cellSpacing", 0);
    progressBar = new JProgressBar(JProgressBar.HORIZONTAL);
    progressBar.setBorder(BorderFactory.createEmptyBorder());
    progressBar.setForeground(new Color(150, 75, 150));
    progressBar.setStringPainted(false);
    globalProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);
    globalProgressBar.setBorder(BorderFactory.createEmptyBorder());
    globalProgressBar.setForeground(new Color(150, 75, 150));
    globalProgressBar.setStringPainted(true);
    JPanel southBox = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.weightx = 1;
    southBox.add(statusBar, gbc);
    gbc.insets = new Insets(0, 3, 0, 3);
    gbc.anchor = GridBagConstraints.EAST;
    gbc.weightx = 0;
    southBox.add(progressBar, gbc);
    southBox.add(globalProgressBar, gbc);
    this.getContentPane().add(southBox, BorderLayout.SOUTH);
    progressBar.setVisible(false);
    globalProgressBar.setVisible(false);
    // extra stuff
    newResourceDialog = new NewResourceDialog(this, "Resource parameters", true);
    // build the Help->About dialog
    JPanel splashBox = new JPanel();
    splashBox.setBackground(Color.WHITE);
    splashBox.setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.weightx = 1;
    constraints.insets = new Insets(2, 2, 2, 2);
    constraints.gridy = 0;
    constraints.fill = GridBagConstraints.BOTH;
    JLabel gifLbl = new JLabel(getIcon("splash"));
    splashBox.add(gifLbl, constraints);
    constraints.gridy = 2;
    constraints.gridwidth = 2;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    String splashHtml;
    try {
        splashHtml = Files.getGateResourceAsString("splash.html");
    } catch (IOException e) {
        splashHtml = "GATE";
        log.error("Couldn't get splash.html resource.", e);
    }
    JLabel htmlLbl = new JLabel(splashHtml);
    htmlLbl.setHorizontalAlignment(SwingConstants.CENTER);
    splashBox.add(htmlLbl, constraints);
    constraints.gridy = 3;
    htmlLbl = new JLabel("<HTML><FONT color=\"blue\">Version <B>" + Main.version + "</B></FONT>" + ", <FONT color=\"red\">build <B>" + Main.build + "</B></FONT>" + "<P><B>JVM version</B>: " + System.getProperty("java.version") + " from " + System.getProperty("java.vendor") + "</HTML>");
    constraints.fill = GridBagConstraints.HORIZONTAL;
    splashBox.add(htmlLbl, constraints);
    constraints.gridy = 4;
    constraints.gridwidth = 2;
    constraints.fill = GridBagConstraints.NONE;
    final JButton okButton = new JButton("OK");
    okButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            splash.setVisible(false);
        }
    });
    okButton.setBackground(Color.white);
    splashBox.add(okButton, constraints);
    splash = new Splash(this, splashBox);
    // make Enter and Escape keys closing the splash window
    splash.getRootPane().setDefaultButton(okButton);
    InputMap inputMap = ((JComponent) splash.getContentPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actionMap = ((JComponent) splash.getContentPane()).getActionMap();
    inputMap.put(KeyStroke.getKeyStroke("ENTER"), "Apply");
    actionMap.put("Apply", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            okButton.doClick();
        }
    });
    inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), "Cancel");
    actionMap.put("Cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            okButton.doClick();
        }
    });
    // MENUS
    menuBar = new JMenuBar();
    JMenu fileMenu = new XJMenu("File", null, this);
    fileMenu.setMnemonic(KeyEvent.VK_F);
    LiveMenu newAPPMenu = new LiveMenu(LiveMenu.APP);
    newAPPMenu.setText("New Application");
    newAPPMenu.setIcon(getIcon("applications"));
    fileMenu.add(newAPPMenu);
    LiveMenu newLRMenu = new LiveMenu(LiveMenu.LR);
    newLRMenu.setText("New Language Resource");
    newLRMenu.setIcon(getIcon("lrs"));
    fileMenu.add(newLRMenu);
    LiveMenu newPRMenu = new LiveMenu(LiveMenu.PR);
    newPRMenu.setText("New Processing Resource");
    newPRMenu.setIcon(getIcon("prs"));
    fileMenu.add(newPRMenu);
    final JMenu dsMenu = new XJMenu("Datastores", "Repositories for large data", this);
    dsMenu.setIcon(getIcon("datastores"));
    dsMenu.add(new XJMenuItem(new NewDSAction(), this));
    dsMenu.add(new XJMenuItem(new OpenDSAction(), this));
    fileMenu.add(dsMenu);
    fileMenu.addSeparator();
    fileMenu.add(new ReadyMadeMenu());
    fileMenu.add(new XJMenuItem(new LoadResourceFromFileAction(), this));
    RecentAppsMenu recentAppsMenu = new RecentAppsMenu();
    fileMenu.add(recentAppsMenu);
    /*final JMenu loadANNIEMenu = new XJMenu("Load ANNIE System",
      "Application that adds morphosyntaxic and semantic annotations", this);
    loadANNIEMenu.setIcon(getIcon("annie-application"));
    loadANNIEMenu.add(new XJMenuItem(new LoadANNIEWithDefaultsAction(), this));
    loadANNIEMenu
      .add(new XJMenuItem(new LoadANNIEWithoutDefaultsAction(), this));
    fileMenu.add(loadANNIEMenu);

    // LingPipe action
    fileMenu.add(new XJMenuItem(new LoadApplicationAction(
            "Load LingPipe System", "LingPipe", "resources/lingpipe.gapp"),
            this));

    // OpenNLP action
    fileMenu.add(new XJMenuItem(new LoadApplicationAction(
            "Load OpenNLP System", "OpenNLP", "resources/opennlp.gapp"), this));
*/
    fileMenu.add(new XJMenuItem(new ManagePluginsAction(), this));
    if (!Gate.runningOnMac()) {
        fileMenu.addSeparator();
        fileMenu.add(new XJMenuItem(new ExitGateAction(), this));
    }
    menuBar.add(fileMenu);
    JMenu optionsMenu = new XJMenu("Options", null, this);
    optionsMenu.setMnemonic(KeyEvent.VK_O);
    boolean optionsMenuHasEntries = false;
    optionsDialog = new OptionsDialog(MainFrame.this);
    if (!Gate.runningOnMac()) {
        optionsMenu.add(new XJMenuItem(new AbstractAction("Configuration") {

            private static final long serialVersionUID = 1L;

            {
                putValue(SHORT_DESCRIPTION, "Edit GATE options");
            }

            @Override
            public void actionPerformed(ActionEvent evt) {
                optionsDialog.showDialog();
                optionsDialog.dispose();
            }
        }, this));
        optionsMenuHasEntries = true;
    }
    if (optionsMenuHasEntries) {
        menuBar.add(optionsMenu);
    }
    ToolsMenu toolsMenu = new ToolsMenu("Tools", null, this);
    toolsMenu.setMnemonic(KeyEvent.VK_T);
    toolsMenu.add(new XJMenuItem(new NewAnnotDiffAction(), this));
    try {
        // Check if log4j is present on the classpath, in order to avoid failures
        // in cases when running the GATE GUI in the same JVM with a system which
        // uses SLF4J and the log4j bridge.
        // The log4j-over-slf4j bridge does not include org.apache.log4j.Appender, so
        // if the class is not present we assume the lack of a log4j jar in the classpath
        // and do not populate the menu.
        Class.forName("org.apache.log4j.Appender");
        final JMenuItem reportClearMenuItem = new XJMenuItem(new AbstractAction("Clear Profiling History") {

            {
                putValue(SHORT_DESCRIPTION, "Clear profiling history otherwise the report is cumulative.");
            }

            @Override
            public void actionPerformed(ActionEvent evt) {
                // create a new log file
                File logFile = new File(System.getProperty("java.io.tmpdir"), "gate-benchmark-log.txt");
                logFile.deleteOnExit();
                if (logFile.exists() && !logFile.delete()) {
                    log.info("Error when deleting the file:\n" + logFile.getAbsolutePath());
                }
            }
        }, this);
        JMenu reportMenu = new XJMenu("Profiling Reports", "Generates profiling reports from processing resources", this);
        reportMenu.setIcon(getIcon("gazetteer"));
        reportMenu.add(new XJMenuItem(new AbstractAction("Start Profiling Applications") {

            {
                putValue(SHORT_DESCRIPTION, "Toggles the profiling of processing resources");
            }

            // stores the value held by the benchmarking switch before we started
            // this profiling run.
            boolean benchmarkWasEnabled;

            @Override
            public void actionPerformed(ActionEvent evt) {
                if (getValue(NAME).equals("Start Profiling Applications")) {
                    reportClearMenuItem.setEnabled(false);
                    // store old value of benchmark switch
                    benchmarkWasEnabled = Benchmark.isBenchmarkingEnabled();
                    Benchmark.setBenchmarkingEnabled(true);
                    Layout layout = new PatternLayout("%m%n");
                    File logFile = new File(System.getProperty("java.io.tmpdir"), "gate-benchmark-log.txt");
                    logFile.deleteOnExit();
                    Appender appender;
                    try {
                        appender = new FileAppender(layout, logFile.getAbsolutePath(), true);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    appender.setName("gate-benchmark");
                    Benchmark.logger.addAppender(appender);
                    putValue(NAME, "Stop Profiling Applications");
                } else {
                    // reset old value of benchmark switch - i.e. if benchmarking was
                    // disabled before the user selected "start profiling" then we
                    // disable it again now, but if it was already enabled before they
                    // started profiling then we assume it was turned on explicitly and
                    // leave it alone.
                    Benchmark.setBenchmarkingEnabled(benchmarkWasEnabled);
                    Benchmark.logger.removeAppender("gate-benchmark");
                    putValue(NAME, "Start Profiling Applications");
                    reportClearMenuItem.setEnabled(true);
                }
            }
        }, this));
        reportMenu.add(reportClearMenuItem);
        reportMenu.add(new XJMenuItem(new AbstractAction("Help on this tool") {

            @Override
            public void actionPerformed(ActionEvent e) {
                showHelpFrame("chap:profiling", "Profiling Processing Resources");
            }
        }, this));
        reportMenu.addSeparator();
        final JCheckBoxMenuItem reportZeroTimesCheckBox = new JCheckBoxMenuItem();
        reportZeroTimesCheckBox.setAction(new AbstractAction("Report Zero Time Entries") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Gate.getUserConfig().put(MainFrame.class.getName() + ".reportzerotime", reportZeroTimesCheckBox.isSelected());
            }
        });
        reportZeroTimesCheckBox.setSelected(Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".reportzerotimes"));
        ButtonGroup group = new ButtonGroup();
        final JRadioButtonMenuItem reportSortExecution = new JRadioButtonMenuItem();
        reportSortExecution.setAction(new AbstractAction("Sort by Execution") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Gate.getUserConfig().put(MainFrame.class.getName() + ".reportsorttime", false);
            }
        });
        reportSortExecution.setSelected(!Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".reportsorttime"));
        group.add(reportSortExecution);
        final JRadioButtonMenuItem reportSortTime = new JRadioButtonMenuItem();
        reportSortTime.setAction(new AbstractAction("Sort by Time") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Gate.getUserConfig().put(MainFrame.class.getName() + ".reportsorttime", true);
            }
        });
        reportSortTime.setSelected(Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".reportsorttime"));
        group.add(reportSortTime);
        reportMenu.add(new XJMenuItem(new AbstractAction("Report on Processing Resources") {

            {
                putValue(SHORT_DESCRIPTION, "Report time taken by each processing resource");
            }

            @Override
            public void actionPerformed(ActionEvent evt) {
                PRTimeReporter report = new PRTimeReporter();
                report.setBenchmarkFile(new File(System.getProperty("java.io.tmpdir"), "gate-benchmark-log.txt"));
                report.setSuppressZeroTimeEntries(!reportZeroTimesCheckBox.isSelected());
                report.setSortOrder(reportSortTime.isSelected() ? PRTimeReporter.SORT_TIME_TAKEN : PRTimeReporter.SORT_EXEC_ORDER);
                try {
                    report.executeReport();
                } catch (BenchmarkReportException e) {
                    e.printStackTrace();
                    return;
                }
                showHelpFrame("file://" + report.getReportFile(), "processing times report");
            }
        }, this));
        reportMenu.add(reportZeroTimesCheckBox);
        reportMenu.add(reportSortTime);
        reportMenu.add(reportSortExecution);
        reportMenu.addSeparator();
        reportMenu.add(new XJMenuItem(new AbstractAction("Report on Documents Processed") {

            {
                putValue(SHORT_DESCRIPTION, "Report most time consuming documents");
            }

            @Override
            public void actionPerformed(ActionEvent evt) {
                DocTimeReporter report = new DocTimeReporter();
                report.setBenchmarkFile(new File(System.getProperty("java.io.tmpdir"), "gate-benchmark-log.txt"));
                String maxDocs = Gate.getUserConfig().getString(MainFrame.class.getName() + ".reportmaxdocs");
                if (maxDocs != null) {
                    report.setMaxDocumentInReport((maxDocs.equals("All")) ? DocTimeReporter.ALL_DOCS : Integer.parseInt(maxDocs));
                }
                String prRegex = Gate.getUserConfig().getString(MainFrame.class.getName() + ".reportprregex");
                if (prRegex != null) {
                    report.setPRMatchingRegex((prRegex.equals("")) ? DocTimeReporter.MATCH_ALL_PR_REGEX : prRegex);
                }
                try {
                    report.executeReport();
                } catch (BenchmarkReportException e) {
                    e.printStackTrace();
                    return;
                }
                showHelpFrame("file://" + report.getReportFile(), "documents time report");
            }
        }, this));
        String maxDocs = Gate.getUserConfig().getString(MainFrame.class.getName() + ".reportmaxdocs");
        if (maxDocs == null) {
            maxDocs = "10";
        }
        reportMenu.add(new XJMenuItem(new AbstractAction("Set Max Documents (" + maxDocs + ")") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Object response = JOptionPane.showInputDialog(instance, "Set the maximum of documents to report", "Report options", JOptionPane.QUESTION_MESSAGE, null, new Object[] { "All", "10", "20", "30", "40", "50", "100" }, "10");
                if (response != null) {
                    Gate.getUserConfig().put(MainFrame.class.getName() + ".reportmaxdocs", response);
                    putValue(NAME, "Set Max Documents (" + response + ")");
                }
            }
        }, this));
        String prRegex = Gate.getUserConfig().getString(MainFrame.class.getName() + ".reportprregex");
        if (prRegex == null || prRegex.equals("")) {
            prRegex = "All";
        }
        reportMenu.add(new XJMenuItem(new AbstractAction("Set PR Matching Regex (" + prRegex + ")") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Object response = JOptionPane.showInputDialog(instance, "Set the processing resource regex filter\n" + "Leave empty to not filter", "Report options", JOptionPane.QUESTION_MESSAGE);
                if (response != null) {
                    Gate.getUserConfig().put(MainFrame.class.getName() + ".reportprregex", response);
                    if (response.equals("")) {
                        response = "All";
                    }
                    putValue(NAME, "Set PR Matching Regex (" + response + ")");
                }
            }
        }, this));
        toolsMenu.add(reportMenu);
    } catch (ClassNotFoundException e) {
        log.warn("log4j.jar not found on the classpath, disabling profiling reports.");
    }
    toolsMenu.add(new XJMenuItem(new NewBootStrapAction(), this));
    final JMenu corpusEvalMenu = new XJMenu("Corpus Benchmark", "Compares processed and human-annotated annotations", this);
    corpusEvalMenu.setIcon(getIcon("corpus-benchmark"));
    toolsMenu.add(corpusEvalMenu);
    corpusEvalMenu.add(new XJMenuItem(new NewCorpusEvalAction(), this));
    corpusEvalMenu.addSeparator();
    corpusEvalMenu.add(new XJMenuItem(new GenerateStoredCorpusEvalAction(), this));
    corpusEvalMenu.addSeparator();
    corpusEvalMenu.add(new XJMenuItem(new StoredMarkedCorpusEvalAction(), this));
    corpusEvalMenu.add(new XJMenuItem(new CleanMarkedCorpusEvalAction(), this));
    corpusEvalMenu.addSeparator();
    verboseModeItem = new JCheckBoxMenuItem(new VerboseModeCorpusEvalToolAction());
    corpusEvalMenu.add(verboseModeItem);
    toolsMenu.staticItemsAdded();
    menuBar.add(toolsMenu);
    JMenu helpMenu = new XJMenu("Help", null, MainFrame.this);
    helpMenu.setMnemonic(KeyEvent.VK_H);
    helpMenu.add(new XJMenuItem(new HelpUserGuideAction(), this));
    helpMenu.add(new XJMenuItem(new HelpUserGuideInContextAction(), this));
    helpMenu.add(new XJMenuItem(new AbstractAction("Keyboard Shortcuts") {

        @Override
        public void actionPerformed(ActionEvent e) {
            showHelpFrame("sec:developer:keyboard", "shortcuts");
        }
    }, this));
    helpMenu.addSeparator();
    helpMenu.add(new XJMenuItem(new AbstractAction("Using GATE Developer") {

        {
            this.putValue(Action.SHORT_DESCRIPTION, "To read first");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            showHelpFrame("chap:developer", "Using GATE Developer");
        }
    }, this));
    helpMenu.add(new XJMenuItem(new AbstractAction("Demo Movies") {

        {
            this.putValue(Action.SHORT_DESCRIPTION, "Movie tutorials");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            showHelpFrame("http://gate.ac.uk/demos/developer-videos/", "movies");
        }
    }, this));
    helpMenu.add(new XJMenuItem(new HelpMailingListAction(), this));
    helpMenu.addSeparator();
    JCheckBoxMenuItem toggleToolTipsCheckBoxMenuItem = new JCheckBoxMenuItem(new ToggleToolTipsAction());
    javax.swing.ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
    if (Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".hidetooltips")) {
        toolTipManager.setEnabled(false);
        toggleToolTipsCheckBoxMenuItem.setSelected(false);
    } else {
        toolTipManager.setEnabled(true);
        toggleToolTipsCheckBoxMenuItem.setSelected(true);
    }
    helpMenu.add(toggleToolTipsCheckBoxMenuItem);
    helpMenu.add(new XJMenuItem(new AbstractAction("What's New") {

        {
            this.putValue(Action.SHORT_DESCRIPTION, "List new features and important changes");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            showHelpFrame("chap:changes", "changes");
        }
    }, this));
    if (!Gate.runningOnMac()) {
        helpMenu.add(new XJMenuItem(new HelpAboutAction(), this));
    }
    menuBar.add(helpMenu);
    this.setJMenuBar(menuBar);
    // popups
    lrsPopup = new XJPopupMenu();
    LiveMenu lrsMenu = new LiveMenu(LiveMenu.LR);
    lrsMenu.setText("New");
    lrsPopup.add(lrsMenu);
    guiRoots.add(lrsPopup);
    guiRoots.add(lrsMenu);
    prsPopup = new XJPopupMenu();
    LiveMenu prsMenu = new LiveMenu(LiveMenu.PR);
    prsMenu.setText("New");
    prsPopup.add(prsMenu);
    guiRoots.add(prsPopup);
    guiRoots.add(prsMenu);
    dssPopup = new XJPopupMenu();
    dssPopup.add(new NewDSAction());
    dssPopup.add(new OpenDSAction());
    guiRoots.add(dssPopup);
    // TOOLBAR
    toolbar = new JToolBar(JToolBar.HORIZONTAL);
    toolbar.setFloatable(false);
    JButton button = new JButton(new LoadResourceFromFileAction());
    button.setToolTipText(button.getText());
    button.setText("");
    toolbar.add(button);
    toolbar.addSeparator();
    try {
        JButton annieMenu = new JButton(new LoadApplicationAction("ANNIE", "annie-application", new ResourceReference(new URI("creole://uk.ac.gate.plugins;annie;" + gate.Main.version + "/resources/" + ANNIEConstants.DEFAULT_FILE))));
        annieMenu.setText("");
        annieMenu.setToolTipText("Load ANNIE");
        toolbar.add(annieMenu);
        toolbar.addSeparator();
    } catch (URISyntaxException e) {
    // should be impossible
    }
    LiveMenu tbNewLRMenu = new LiveMenu(LiveMenu.LR);
    JMenuButton menuButton = new JMenuButton(tbNewLRMenu);
    menuButton.setToolTipText("New Language Resource");
    menuButton.setIcon(getIcon("lrs"));
    toolbar.add(menuButton);
    LiveMenu tbNewPRMenu = new LiveMenu(LiveMenu.PR);
    menuButton = new JMenuButton(tbNewPRMenu);
    menuButton.setToolTipText("New Processing Resource");
    menuButton.setIcon(getIcon("prs"));
    toolbar.add(menuButton);
    LiveMenu tbNewAppMenu = new LiveMenu(LiveMenu.APP);
    menuButton = new JMenuButton(tbNewAppMenu);
    menuButton.setToolTipText("New Application");
    menuButton.setIcon(getIcon("applications"));
    toolbar.add(menuButton);
    toolbar.addSeparator();
    JPopupMenu tbDsMenu = new JPopupMenu();
    tbDsMenu.add(new NewDSAction());
    tbDsMenu.add(new OpenDSAction());
    menuButton = new JMenuButton(tbDsMenu);
    menuButton.setToolTipText("Datastores");
    menuButton.setIcon(getIcon("datastores"));
    toolbar.add(menuButton);
    toolbar.addSeparator();
    button = new JButton(new ManagePluginsAction());
    button.setToolTipText(button.getText());
    button.setText("");
    toolbar.add(button);
    toolbar.addSeparator();
    button = new JButton(new NewAnnotDiffAction());
    button.setToolTipText(button.getText());
    button.setText("");
    toolbar.add(button);
    toolbar.add(Box.createHorizontalGlue());
    this.getContentPane().add(toolbar, BorderLayout.NORTH);
}
Also used : JPanel(javax.swing.JPanel) Rectangle(java.awt.Rectangle) Image(java.awt.Image) Document(gate.Document) XJMenu(gate.swing.XJMenu) BenchmarkReportException(gate.util.reporting.exceptions.BenchmarkReportException) FileAppender(org.apache.log4j.FileAppender) ToolTipManager(javax.swing.ToolTipManager) GATEVersionIcon(gate.resources.img.svg.GATEVersionIcon) PatternLayout(org.apache.log4j.PatternLayout) JMenuButton(gate.swing.JMenuButton) TransferHandler(javax.swing.TransferHandler) GridBagLayout(java.awt.GridBagLayout) URI(java.net.URI) DataFlavor(java.awt.datatransfer.DataFlavor) JScrollPane(javax.swing.JScrollPane) ActionMap(javax.swing.ActionMap) JLabel(javax.swing.JLabel) Dimension(java.awt.Dimension) IOException(java.io.IOException) XJTabbedPane(gate.swing.XJTabbedPane) TreePath(javax.swing.tree.TreePath) OverlayLayout(javax.swing.OverlayLayout) Layout(org.apache.log4j.Layout) GridBagLayout(java.awt.GridBagLayout) BorderLayout(java.awt.BorderLayout) BoxLayout(javax.swing.BoxLayout) PatternLayout(org.apache.log4j.PatternLayout) ButtonGroup(javax.swing.ButtonGroup) JMenuBar(javax.swing.JMenuBar) GridBagConstraints(java.awt.GridBagConstraints) ActionEvent(java.awt.event.ActionEvent) StringSelection(java.awt.datatransfer.StringSelection) BorderLayout(java.awt.BorderLayout) ArrayList(java.util.ArrayList) List(java.util.List) JList(javax.swing.JList) AbstractAction(javax.swing.AbstractAction) Appender(org.apache.log4j.Appender) FileAppender(org.apache.log4j.FileAppender) Color(java.awt.Color) JRadioButtonMenuItem(javax.swing.JRadioButtonMenuItem) JCheckBoxMenuItem(javax.swing.JCheckBoxMenuItem) ActionListener(java.awt.event.ActionListener) InputMap(javax.swing.InputMap) JSplitPane(javax.swing.JSplitPane) File(java.io.File) Insets(java.awt.Insets) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) BoxLayout(javax.swing.BoxLayout) JProgressBar(javax.swing.JProgressBar) JButton(javax.swing.JButton) GATEIcon(gate.resources.img.svg.GATEIcon) URISyntaxException(java.net.URISyntaxException) XJPopupMenu(gate.swing.XJPopupMenu) ResourceReference(gate.creole.ResourceReference) XJMenuItem(gate.swing.XJMenuItem) JMenuItem(javax.swing.JMenuItem) DocTimeReporter(gate.util.reporting.DocTimeReporter) JComponent(javax.swing.JComponent) Transferable(java.awt.datatransfer.Transferable) JToolBar(javax.swing.JToolBar) Point(java.awt.Point) Date(java.util.Date) XJPopupMenu(gate.swing.XJPopupMenu) JPopupMenu(javax.swing.JPopupMenu) OverlayLayout(javax.swing.OverlayLayout) PRTimeReporter(gate.util.reporting.PRTimeReporter) XJMenuItem(gate.swing.XJMenuItem) JMenu(javax.swing.JMenu) XJMenu(gate.swing.XJMenu)

Example 2 with XJPopupMenu

use of gate.swing.XJPopupMenu in project gate-core by GateNLP.

the class MainFrame method initListeners.

protected void initListeners() {
    Gate.getCreoleRegister().addCreoleListener(this);
    Gate.getCreoleRegister().addPluginListener(this);
    resourcesTree.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                // shows in the central tabbed pane, the selected resources
                // in the resource tree when the Enter key is pressed
                (new ShowSelectedResourcesAction()).actionPerformed(null);
            } else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                // close selected resources from GATE
                (new CloseSelectedResourcesAction()).actionPerformed(null);
            } else if (e.getKeyCode() == KeyEvent.VK_DELETE && e.getModifiers() == InputEvent.SHIFT_DOWN_MASK) {
                // close recursively selected resources from GATE
                (new CloseRecursivelySelectedResourcesAction()).actionPerformed(null);
            }
        }
    });
    resourcesTree.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            TreePath path = resourcesTree.getClosestPathForLocation(e.getX(), e.getY());
            if (e.isPopupTrigger() && !resourcesTree.isPathSelected(path)) {
                // if right click outside the selection then reset selection
                resourcesTree.getSelectionModel().setSelectionPath(path);
            }
            processMouseEvent(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            processMouseEvent(e);
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            processMouseEvent(e);
        }

        protected void processMouseEvent(MouseEvent e) {
            // where inside the tree?
            int x = e.getX();
            int y = e.getY();
            TreePath path = resourcesTree.getClosestPathForLocation(x, y);
            JPopupMenu popup = null;
            Handle handle = null;
            if (path != null) {
                Object value = path.getLastPathComponent();
                if (value == resourcesTreeRoot) {
                // no default item for this menu
                } else if (value == applicationsRoot) {
                    appsPopup = new XJPopupMenu();
                    LiveMenu appsMenu = new LiveMenu(LiveMenu.APP);
                    appsMenu.setText("Create New Application");
                    appsMenu.setIcon(MainFrame.getIcon("applications"));
                    appsPopup.add(appsMenu);
                    appsPopup.add(new ReadyMadeMenu());
                    appsPopup.add(new XJMenuItem(new LoadResourceFromFileAction(), MainFrame.this));
                    RecentAppsMenu recentApps = new RecentAppsMenu();
                    if (recentApps.getMenuComponentCount() > 0)
                        appsPopup.add(recentApps);
                    popup = appsPopup;
                } else if (value == languageResourcesRoot) {
                    popup = lrsPopup;
                } else if (value == processingResourcesRoot) {
                    popup = prsPopup;
                } else if (value == datastoresRoot) {
                    popup = dssPopup;
                } else {
                    value = ((DefaultMutableTreeNode) value).getUserObject();
                    if (value instanceof Handle) {
                        handle = (Handle) value;
                        fileChooser.setResource(handle.getTarget().getClass().getName());
                        if (e.isPopupTrigger()) {
                            popup = handle.getPopup();
                        }
                    }
                }
            }
            // popup menu
            if (e.isPopupTrigger()) {
                if (resourcesTree.getSelectionCount() > 1) {
                    // multiple selection in tree
                    popup = new XJPopupMenu();
                    // add a close all action
                    popup.add(new XJMenuItem(new CloseSelectedResourcesAction(), MainFrame.this));
                    // add a close recursively all action
                    TreePath[] selectedPaths = resourcesTree.getSelectionPaths();
                    for (TreePath selectedPath : selectedPaths) {
                        Object userObject = ((DefaultMutableTreeNode) selectedPath.getLastPathComponent()).getUserObject();
                        if (userObject instanceof NameBearerHandle && ((NameBearerHandle) userObject).getTarget() instanceof Controller) {
                            // there is at least one application
                            popup.add(new XJMenuItem(new CloseRecursivelySelectedResourcesAction(), MainFrame.this));
                            break;
                        }
                    }
                    // add a show all action
                    selectedPaths = resourcesTree.getSelectionPaths();
                    for (TreePath selectedPath : selectedPaths) {
                        Object userObject = ((DefaultMutableTreeNode) selectedPath.getLastPathComponent()).getUserObject();
                        if (userObject instanceof Handle && (!((Handle) userObject).viewsBuilt() || (mainTabbedPane.indexOfComponent(((Handle) userObject).getLargeView()) == -1))) {
                            // there is at least one resource not shown
                            popup.add(new XJMenuItem(new ShowSelectedResourcesAction(), MainFrame.this));
                            break;
                        }
                    }
                    // add a hide all action
                    selectedPaths = resourcesTree.getSelectionPaths();
                    for (TreePath selectedPath : selectedPaths) {
                        Object userObject = ((DefaultMutableTreeNode) selectedPath.getLastPathComponent()).getUserObject();
                        if (userObject instanceof Handle && ((Handle) userObject).viewsBuilt() && ((Handle) userObject).getLargeView() != null && (mainTabbedPane.indexOfComponent(((Handle) userObject).getLargeView()) != -1)) {
                            // there is at least one resource shown
                            popup.add(new XJMenuItem(new CloseViewsForSelectedResourcesAction(), MainFrame.this));
                            break;
                        }
                    }
                    popup.show(resourcesTree, e.getX(), e.getY());
                } else if (popup != null) {
                    if (handle != null) {
                        // add a close action
                        if (handle instanceof NameBearerHandle) {
                            popup.insert(new XJMenuItem(((NameBearerHandle) handle).getCloseAction(), MainFrame.this), 0);
                        }
                        // if application then add a close recursively action
                        if (handle instanceof NameBearerHandle && handle.getTarget() instanceof Controller) {
                            popup.insert(new XJMenuItem(((NameBearerHandle) handle).getCloseRecursivelyAction(), MainFrame.this), 1);
                        }
                        // add a show/hide action
                        if (handle.viewsBuilt() && handle.getLargeView() != null && (mainTabbedPane.indexOfComponent(handle.getLargeView()) != -1)) {
                            popup.insert(new XJMenuItem(new CloseViewAction(handle), MainFrame.this), 2);
                        } else {
                            popup.insert(new XJMenuItem(new ShowResourceAction(handle), MainFrame.this), 2);
                        }
                        // add a rename action
                        popup.insert(new XJMenuItem(new RenameResourceAction(path), MainFrame.this), 3);
                        // add a help action
                        if (handle instanceof NameBearerHandle) {
                            popup.insert(new XJMenuItem(new HelpOnItemTreeAction((NameBearerHandle) handle), MainFrame.this), 4);
                        }
                    }
                    popup.show(resourcesTree, e.getX(), e.getY());
                }
            } else if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() == 2 && handle != null) {
                // double click - show the resource
                select(handle);
            }
        }
    });
    resourcesTree.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            if (!Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".treeselectview")) {
                return;
            }
            // the resource tree selection
            if (resourcesTree.getSelectionPaths() != null && resourcesTree.getSelectionPaths().length == 1) {
                Object value = e.getPath().getLastPathComponent();
                Object object = ((DefaultMutableTreeNode) value).getUserObject();
                if (object instanceof Handle && ((Handle) object).viewsBuilt() && (mainTabbedPane.indexOfComponent(((Handle) object).getLargeView()) != -1)) {
                    select((Handle) object);
                }
            }
        }
    });
    // define keystrokes action bindings at the level of the main window
    InputMap inputMap = ((JComponent) this.getContentPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(KeyStroke.getKeyStroke("control F4"), "Close resource");
    inputMap.put(KeyStroke.getKeyStroke("shift F4"), "Close recursively");
    inputMap.put(KeyStroke.getKeyStroke("control H"), "Hide");
    inputMap.put(KeyStroke.getKeyStroke("control shift H"), "Hide all");
    inputMap.put(KeyStroke.getKeyStroke("control S"), "Save As XML");
    // TODO: remove when Swing will take care of the context menu key
    if (inputMap.get(KeyStroke.getKeyStroke("CONTEXT_MENU")) == null) {
        inputMap.put(KeyStroke.getKeyStroke("CONTEXT_MENU"), "Show context menu");
    }
    ActionMap actionMap = ((JComponent) instance.getContentPane()).getActionMap();
    actionMap.put("Show context menu", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            // get the current focused component
            Component focusedComponent = focusManager.getFocusOwner();
            if (focusedComponent != null) {
                Point menuLocation = null;
                Rectangle selectionRectangle = null;
                if (focusedComponent instanceof JTable && ((JTable) focusedComponent).getSelectedRowCount() > 0) {
                    // selection in a JTable
                    JTable table = (JTable) focusedComponent;
                    selectionRectangle = table.getCellRect(table.getSelectionModel().getLeadSelectionIndex(), table.convertColumnIndexToView(table.getSelectedColumn()), false);
                } else if (focusedComponent instanceof JTree && ((JTree) focusedComponent).getSelectionCount() > 0) {
                    // selection in a JTree
                    JTree tree = (JTree) focusedComponent;
                    selectionRectangle = tree.getRowBounds(tree.getSelectionModel().getLeadSelectionRow());
                } else {
                    // for other component set the menu location at the top left corner
                    menuLocation = new Point(focusedComponent.getX() - 1, focusedComponent.getY() - 1);
                }
                if (menuLocation == null) {
                    // menu location at the bottom left of the JTable or JTree
                    menuLocation = new Point(new Double(selectionRectangle.getMinX() + 1).intValue(), new Double(selectionRectangle.getMaxY() - 1).intValue());
                }
                // generate a right/button 3/popup menu mouse click
                focusedComponent.dispatchEvent(new MouseEvent(focusedComponent, MouseEvent.MOUSE_PRESSED, e.getWhen(), MouseEvent.BUTTON3_DOWN_MASK, menuLocation.x, menuLocation.y, 1, true, MouseEvent.BUTTON3));
            }
        }
    });
    mainTabbedPane.getModel().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            // find the handle in the resources tree for the main view
            JComponent largeView = (JComponent) mainTabbedPane.getSelectedComponent();
            Enumeration<?> nodesEnum = resourcesTreeRoot.preorderEnumeration();
            boolean done = false;
            DefaultMutableTreeNode node = resourcesTreeRoot;
            while (!done && nodesEnum.hasMoreElements()) {
                node = (DefaultMutableTreeNode) nodesEnum.nextElement();
                done = node.getUserObject() instanceof Handle && ((Handle) node.getUserObject()).viewsBuilt() && ((Handle) node.getUserObject()).getLargeView() == largeView;
            }
            ActionMap actionMap = ((JComponent) instance.getContentPane()).getActionMap();
            if (done) {
                Handle handle = (Handle) node.getUserObject();
                if (Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".viewselecttree")) {
                    // synchronise the selection in the tabbed pane with
                    // the one in the resources tree
                    TreePath nodePath = new TreePath(node.getPath());
                    resourcesTree.setSelectionPath(nodePath);
                    resourcesTree.scrollPathToVisible(nodePath);
                }
                lowerScroll.getViewport().setView(handle.getSmallView());
                // redefine MainFrame actionMaps for the selected tab
                JComponent resource = (JComponent) mainTabbedPane.getSelectedComponent();
                actionMap.put("Close resource", resource.getActionMap().get("Close resource"));
                actionMap.put("Close recursively", resource.getActionMap().get("Close recursively"));
                actionMap.put("Hide", new CloseViewAction(handle));
                actionMap.put("Hide all", new HideAllAction());
                actionMap.put("Save As XML", resource.getActionMap().get("Save As XML"));
            } else {
                // the selected item is not a resource (maybe the log area?)
                lowerScroll.getViewport().setView(null);
                // disabled actions on the selected tabbed pane
                actionMap.put("Close resource", null);
                actionMap.put("Close recursively", null);
                actionMap.put("Hide", null);
                actionMap.put("Hide all", null);
                actionMap.put("Save As XML", null);
            }
        }
    });
    mainTabbedPane.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            processMouseEvent(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            processMouseEvent(e);
        }

        protected void processMouseEvent(MouseEvent e) {
            if (e.isPopupTrigger()) {
                int index = mainTabbedPane.getIndexAt(e.getPoint());
                if (index != -1) {
                    JComponent view = (JComponent) mainTabbedPane.getComponentAt(index);
                    Enumeration<?> nodesEnum = resourcesTreeRoot.preorderEnumeration();
                    boolean done = false;
                    DefaultMutableTreeNode node = resourcesTreeRoot;
                    while (!done && nodesEnum.hasMoreElements()) {
                        node = (DefaultMutableTreeNode) nodesEnum.nextElement();
                        done = node.getUserObject() instanceof Handle && ((Handle) node.getUserObject()).viewsBuilt() && ((Handle) node.getUserObject()).getLargeView() == view;
                    }
                    if (done) {
                        Handle handle = (Handle) node.getUserObject();
                        JPopupMenu popup = handle.getPopup();
                        // add a hide action
                        CloseViewAction cva = new CloseViewAction(handle);
                        XJMenuItem menuItem = new XJMenuItem(cva, MainFrame.this);
                        popup.insert(menuItem, 0);
                        // add a hide all action
                        if (mainTabbedPane.getTabCount() > 2) {
                            HideAllAction haa = new HideAllAction();
                            menuItem = new XJMenuItem(haa, MainFrame.this);
                            popup.insert(menuItem, 1);
                        }
                        popup.show(mainTabbedPane, e.getX(), e.getY());
                    }
                }
            }
        }
    });
    addComponentListener(new ComponentAdapter() {

        @Override
        public void componentShown(ComponentEvent e) {
            leftSplit.setDividerLocation(0.7);
        }

        @Override
        public void componentResized(ComponentEvent e) {
            // resize proportionally the status bar elements
            int width = MainFrame.this.getWidth();
            statusBar.setPreferredSize(new Dimension(width * 65 / 100, statusBar.getPreferredSize().height));
            progressBar.setPreferredSize(new Dimension(width * 20 / 100, progressBar.getPreferredSize().height));
            progressBar.setMinimumSize(new Dimension(80, 0));
            globalProgressBar.setPreferredSize(new Dimension(width * 10 / 100, globalProgressBar.getPreferredSize().height));
            globalProgressBar.setMinimumSize(new Dimension(80, 0));
        }
    });
    // blink the messages tab when new information is displayed
    logArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

        @Override
        public void insertUpdate(javax.swing.event.DocumentEvent e) {
            changeOccured();
        }

        @Override
        public void removeUpdate(javax.swing.event.DocumentEvent e) {
            changeOccured();
        }

        @Override
        public void changedUpdate(javax.swing.event.DocumentEvent e) {
        }

        protected void changeOccured() {
            logHighlighter.highlight();
        }
    });
    logArea.addPropertyChangeListener("document", new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            // add the document listener
            logArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

                @Override
                public void insertUpdate(javax.swing.event.DocumentEvent e) {
                    changeOccured();
                }

                @Override
                public void removeUpdate(javax.swing.event.DocumentEvent e) {
                    changeOccured();
                }

                @Override
                public void changedUpdate(javax.swing.event.DocumentEvent e) {
                    changeOccured();
                }

                protected void changeOccured() {
                    logHighlighter.highlight();
                }
            });
        }
    });
    Gate.getListeners().put("gate.event.StatusListener", MainFrame.this);
    Gate.getListeners().put("gate.event.ProgressListener", MainFrame.this);
    if (Gate.runningOnMac()) {
        // mac-specific initialisation
        initMacListeners();
    }
}
Also used : ActionEvent(java.awt.event.ActionEvent) KeyAdapter(java.awt.event.KeyAdapter) Rectangle(java.awt.Rectangle) AbstractAction(javax.swing.AbstractAction) PropertyChangeEvent(java.beans.PropertyChangeEvent) JTree(javax.swing.JTree) JTable(javax.swing.JTable) InputMap(javax.swing.InputMap) ComponentEvent(java.awt.event.ComponentEvent) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) PropertyChangeListener(java.beans.PropertyChangeListener) TreeSelectionListener(javax.swing.event.TreeSelectionListener) KeyEvent(java.awt.event.KeyEvent) MenuKeyEvent(javax.swing.event.MenuKeyEvent) XJPopupMenu(gate.swing.XJPopupMenu) KeyboardFocusManager(java.awt.KeyboardFocusManager) ChangeListener(javax.swing.event.ChangeListener) PropertyChangeListener(java.beans.PropertyChangeListener) Component(java.awt.Component) JComponent(javax.swing.JComponent) ComponentAdapter(java.awt.event.ComponentAdapter) MouseEvent(java.awt.event.MouseEvent) Enumeration(java.util.Enumeration) ActionMap(javax.swing.ActionMap) MouseAdapter(java.awt.event.MouseAdapter) JComponent(javax.swing.JComponent) Point(java.awt.Point) Dimension(java.awt.Dimension) Controller(gate.Controller) ConditionalSerialAnalyserController(gate.creole.ConditionalSerialAnalyserController) PackagedController(gate.creole.PackagedController) XJPopupMenu(gate.swing.XJPopupMenu) JPopupMenu(javax.swing.JPopupMenu) TreePath(javax.swing.tree.TreePath) ChangeEvent(javax.swing.event.ChangeEvent) PropertyChangeEvent(java.beans.PropertyChangeEvent) XJMenuItem(gate.swing.XJMenuItem) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent)

Example 3 with XJPopupMenu

use of gate.swing.XJPopupMenu in project gate-core by GateNLP.

the class CorpusEditor method initListeners.

protected void initListeners() {
    // mouse double-click to open the document
    // context menu to get the actions for the selection
    docTable.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            processMouseEvent(e);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        private void processMouseEvent(MouseEvent e) {
            int row = docTable.rowAtPoint(e.getPoint());
            if (row == -1) {
                return;
            }
            if (e.isPopupTrigger()) {
                // context menu
                if (!docTable.isRowSelected(row)) {
                    // if right click outside the selection then reset selection
                    docTable.getSelectionModel().setSelectionInterval(row, row);
                }
                JPopupMenu popup = new XJPopupMenu();
                popup.add(openDocumentsAction);
                popup.add(removeDocumentsAction);
                popup.show(docTable, e.getPoint().x, e.getPoint().y);
            } else if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() == 2) {
                // open document on double-click
                openDocumentsAction.actionPerformed(null);
            }
        }
    });
    // Enter key opens the selected documents
    docTable.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                openDocumentsAction.actionPerformed(null);
            }
        }
    });
    docTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // enable/disable buttons according to the selection
            removeDocumentsAction.setEnabled(docTable.getSelectedRowCount() > 0);
            openDocumentsAction.setEnabled(docTable.getSelectedRowCount() > 0);
            moveUpAction.setEnabled(docTable.getSelectedRowCount() > 0 && !docTable.isRowSelected(0));
            moveDownAction.setEnabled(docTable.getSelectedRowCount() > 0 && !docTable.isRowSelected(docTable.getRowCount() - 1));
        }
    });
    Gate.getCreoleRegister().addCreoleListener(new CreoleListener() {

        @Override
        public void resourceLoaded(CreoleEvent e) {
            if (e.getResource() instanceof Document) {
                documentsLoadedCount++;
                changeMessage();
            }
        }

        @Override
        public void resourceUnloaded(CreoleEvent e) {
            if (e.getResource() instanceof Document) {
                documentsLoadedCount--;
                changeMessage();
            }
        }

        @Override
        public void datastoreOpened(CreoleEvent e) {
        /* do nothing */
        }

        @Override
        public void datastoreCreated(CreoleEvent e) {
        /* do nothing */
        }

        @Override
        public void datastoreClosed(CreoleEvent e) {
        /* do nothing */
        }

        @Override
        public void resourceRenamed(Resource resource, String oldName, String newName) {
        /* do nothing */
        }
    });
}
Also used : CreoleEvent(gate.event.CreoleEvent) ListSelectionEvent(javax.swing.event.ListSelectionEvent) CreoleResource(gate.creole.metadata.CreoleResource) AbstractVisualResource(gate.creole.AbstractVisualResource) XJPopupMenu(gate.swing.XJPopupMenu) ListSelectionListener(javax.swing.event.ListSelectionListener) CreoleListener(gate.event.CreoleListener) XJPopupMenu(gate.swing.XJPopupMenu)

Example 4 with XJPopupMenu

use of gate.swing.XJPopupMenu in project gate-core by GateNLP.

the class SerialControllerEditor method initListeners.

// initGuiComponents()
protected void initListeners() {
    Gate.getCreoleRegister().addCreoleListener(this);
    this.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            processMouseEvent(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            processMouseEvent(e);
        }

        protected void processMouseEvent(MouseEvent e) {
            if (e.isPopupTrigger()) {
                // context menu
                if (handle != null && handle.getPopup() != null) {
                    handle.getPopup().show(SerialControllerEditor.this, e.getX(), e.getY());
                }
            }
        }
    });
    moveUpButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = memberPRsTable.getSelectedRows();
            if (rows == null || rows.length == 0) {
                JOptionPane.showMessageDialog(SerialControllerEditor.this, "Please select some components to be moved " + "from the list of used components!\n", "GATE", JOptionPane.ERROR_MESSAGE);
            } else {
                // we need to make sure the rows are sorted
                Arrays.sort(rows);
                // get the list of PRs
                for (int row : rows) {
                    if (row > 0) {
                        // move it up
                        List<RunningStrategy> strategies = null;
                        if (conditionalMode) {
                            strategies = new ArrayList<RunningStrategy>(((ConditionalController) controller).getRunningStrategies());
                            RunningStrategy straegy = strategies.remove(row);
                            strategies.add(row - 1, straegy);
                        }
                        ProcessingResource value = controller.remove(row);
                        controller.add(row - 1, value);
                        if (conditionalMode) {
                            ((ConditionalController) controller).setRunningStrategies(strategies);
                            ;
                        }
                    }
                }
                // restore selection
                for (int row : rows) {
                    int newRow;
                    if (row > 0)
                        newRow = row - 1;
                    else
                        newRow = row;
                    memberPRsTable.addRowSelectionInterval(newRow, newRow);
                }
                memberPRsTable.requestFocusInWindow();
            }
        }
    });
    moveDownButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = memberPRsTable.getSelectedRows();
            if (rows == null || rows.length == 0) {
                JOptionPane.showMessageDialog(SerialControllerEditor.this, "Please select some components to be moved " + "from the list of used components!\n", "GATE", JOptionPane.ERROR_MESSAGE);
            } else {
                // we need to make sure the rows are sorted
                Arrays.sort(rows);
                // get the list of PRs
                for (int i = rows.length - 1; i >= 0; i--) {
                    int row = rows[i];
                    if (row < controller.getPRs().size() - 1) {
                        List<RunningStrategy> strategies = null;
                        if (conditionalMode) {
                            strategies = new ArrayList<RunningStrategy>(((ConditionalController) controller).getRunningStrategies());
                            RunningStrategy straegy = strategies.remove(row);
                            strategies.add(row + 1, straegy);
                        }
                        // move it down
                        ProcessingResource value = controller.remove(row);
                        controller.add(row + 1, value);
                        if (conditionalMode) {
                            ((ConditionalController) controller).setRunningStrategies(strategies);
                            ;
                        }
                    }
                }
                // restore selection
                for (int row : rows) {
                    int newRow;
                    if (row < controller.getPRs().size() - 1)
                        newRow = row + 1;
                    else
                        newRow = row;
                    memberPRsTable.addRowSelectionInterval(newRow, newRow);
                }
                memberPRsTable.requestFocusInWindow();
            }
        }
    });
    // mouse click edit the resource
    // mouse double click or context menu add the resource to the application
    loadedPRsTable.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            processMouseEvent(e);
        }

        protected void processMouseEvent(MouseEvent e) {
            int row = loadedPRsTable.rowAtPoint(e.getPoint());
            if (row == -1) {
                return;
            }
            if (e.isPopupTrigger()) {
                // context menu
                if (!loadedPRsTable.isRowSelected(row)) {
                    // if right click outside the selection then reset selection
                    loadedPRsTable.getSelectionModel().setSelectionInterval(row, row);
                }
                JPopupMenu popup = new XJPopupMenu();
                popup.add(addPRAction);
                popup.show(loadedPRsTable, e.getPoint().x, e.getPoint().y);
            } else if (e.getID() == MouseEvent.MOUSE_CLICKED) {
                if (e.getClickCount() == 2) {
                    // add selected modules on double click
                    addPRAction.actionPerformed(null);
                }
            }
        }
    });
    // drag and drop support
    loadedPRsTable.setTransferHandler(new TransferHandler() {

        // minimal drag and drop that only call the removePRAction when importing
        String source = "";

        @Override
        public int getSourceActions(JComponent c) {
            return MOVE;
        }

        @Override
        protected Transferable createTransferable(JComponent c) {
            return new StringSelection("loadedPRsTable");
        }

        @Override
        protected void exportDone(JComponent c, Transferable data, int action) {
        }

        @Override
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (DataFlavor flavor : flavors) {
                if (DataFlavor.stringFlavor.equals(flavor)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean importData(JComponent c, Transferable t) {
            if (canImport(c, t.getTransferDataFlavors())) {
                try {
                    source = (String) t.getTransferData(DataFlavor.stringFlavor);
                    if (source.startsWith("memberPRsTable")) {
                        removePRAction.actionPerformed(null);
                        return true;
                    } else {
                        return false;
                    }
                } catch (UnsupportedFlavorException ufe) {
                // just return false later
                } catch (IOException ioe) {
                // just return false later
                }
            }
            return false;
        }
    });
    // mouse click edit the resource
    // mouse double click or context menu remove the resource from the
    // application
    memberPRsTable.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            processMouseEvent(e);
        }

        protected void processMouseEvent(MouseEvent e) {
            int row = memberPRsTable.rowAtPoint(e.getPoint());
            if (row == -1) {
                return;
            }
            if (e.isPopupTrigger()) {
                // context menu
                if (!memberPRsTable.isRowSelected(row)) {
                    // if right click outside the selection then reset selection
                    memberPRsTable.getSelectionModel().setSelectionInterval(row, row);
                }
                JPopupMenu popup = new XJPopupMenu();
                popup.add(removePRAction);
                popup.show(memberPRsTable, e.getPoint().x, e.getPoint().y);
            } else if (e.getID() == MouseEvent.MOUSE_CLICKED) {
                if (e.getClickCount() == 2) {
                    // open the double-clicked PR in the main view.
                    Component root = SwingUtilities.getRoot(SerialControllerEditor.this);
                    if (!(root instanceof MainFrame)) {
                        return;
                    }
                    final MainFrame mainFrame = (MainFrame) root;
                    if (controller != null) {
                        ProcessingResource res = controller.getPRs().get(row);
                        if (res != null)
                            mainFrame.select(res);
                    }
                }
            }
        }
    });
    // Drag and drop support
    memberPRsTable.setTransferHandler(new TransferHandler() {

        // minimal drag and drop that only call the addPRAction when importing
        String source = "";

        @Override
        public int getSourceActions(JComponent c) {
            return MOVE;
        }

        @Override
        protected Transferable createTransferable(JComponent c) {
            int[] selectedRows = memberPRsTable.getSelectedRows();
            Arrays.sort(selectedRows);
            return new StringSelection("memberPRsTable" + Arrays.toString(selectedRows));
        }

        @Override
        protected void exportDone(JComponent c, Transferable data, int action) {
        }

        @Override
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (DataFlavor flavor : flavors) {
                if (DataFlavor.stringFlavor.equals(flavor)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean importData(JComponent c, Transferable t) {
            if (!canImport(c, t.getTransferDataFlavors())) {
                return false;
            }
            try {
                source = (String) t.getTransferData(DataFlavor.stringFlavor);
                if (source.startsWith("memberPRsTable")) {
                    int insertion = memberPRsTable.getSelectedRow();
                    int initialInsertion = insertion;
                    List<ProcessingResource> prs = new ArrayList<ProcessingResource>();
                    source = source.replaceFirst("^memberPRsTable\\[", "");
                    source = source.replaceFirst("\\]$", "");
                    String[] selectedRows = source.split(", ");
                    if (Integer.parseInt(selectedRows[0]) < insertion) {
                        insertion++;
                    }
                    // get the list of PRs selected when dragging started
                    for (String row : selectedRows) {
                        if (Integer.parseInt(row) == initialInsertion) {
                            // the user draged the selected rows on themselves, do nothing
                            return false;
                        }
                        prs.add((ProcessingResource) memberPRsTable.getValueAt(Integer.parseInt(row), memberPRsTable.convertColumnIndexToView(1)));
                        if (Integer.parseInt(row) < initialInsertion) {
                            insertion--;
                        }
                    }
                    // remove the PRs selected when dragging started
                    for (ProcessingResource pr : prs) {
                        controller.remove(pr);
                    }
                    // add the PRs at the insertion point
                    for (ProcessingResource pr : prs) {
                        controller.add(insertion, pr);
                        insertion++;
                    }
                    // select the moved PRs
                    memberPRsTable.addRowSelectionInterval(insertion - selectedRows.length, insertion - 1);
                    return true;
                } else if (source.equals("loadedPRsTable")) {
                    addPRAction.actionPerformed(null);
                    return true;
                } else {
                    return false;
                }
            } catch (UnsupportedFlavorException ufe) {
                return false;
            } catch (IOException ioe) {
                return false;
            }
        }
    });
    loadedPRsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // disable Add button if no selection
            addButton.setEnabled(loadedPRsTable.getSelectedRowCount() > 0);
        }
    });
    memberPRsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // disable Remove and Move buttons if no selection
            removeButton.setEnabled(memberPRsTable.getSelectedRowCount() > 0);
            moveUpButton.setEnabled(memberPRsTable.getSelectedRowCount() > 0 && !memberPRsTable.isRowSelected(0));
            moveDownButton.setEnabled(memberPRsTable.getSelectedRowCount() > 0 && !memberPRsTable.isRowSelected(memberPRsTable.getRowCount() - 1));
            // update the parameters & strategy editors
            if (memberPRsTable.getSelectedRowCount() == 1) {
                // only one selection
                selectPR(memberPRsTable.getSelectedRow());
            } else {
                // clean up UI
                selectPR(-1);
            }
        }
    });
    if (conditionalMode) {
        /**
         * A listener called when the selection state changes for any of the
         * execution mode radio buttons. We use selection changes rather than
         * action listeners, as the change of state may not be as results of an
         * action (e.g. editing one of the text fields, changes the selection).
         */
        ItemListener strategyModeListener = new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if (selectedPRRunStrategy != null) {
                    if (selectedPRRunStrategy instanceof AnalyserRunningStrategy) {
                        AnalyserRunningStrategy strategy = (AnalyserRunningStrategy) selectedPRRunStrategy;
                        if (yes_RunRBtn.isSelected()) {
                            strategy.setRunMode(RunningStrategy.RUN_ALWAYS);
                        } else if (no_RunRBtn.isSelected()) {
                            strategy.setRunMode(RunningStrategy.RUN_NEVER);
                        } else if (conditional_RunRBtn.isSelected()) {
                            strategy.setRunMode(RunningStrategy.RUN_CONDITIONAL);
                        }
                    } else if (selectedPRRunStrategy instanceof UnconditionalRunningStrategy) {
                        UnconditionalRunningStrategy strategy = (UnconditionalRunningStrategy) selectedPRRunStrategy;
                        if (yes_RunRBtn.isSelected()) {
                            strategy.shouldRun(true);
                        } else if (no_RunRBtn.isSelected()) {
                            strategy.shouldRun(false);
                        }
                    }
                }
                // some icons may have changed!
                memberPRsTable.repaint();
            }
        };
        yes_RunRBtn.addItemListener(strategyModeListener);
        no_RunRBtn.addItemListener(strategyModeListener);
        conditional_RunRBtn.addItemListener(strategyModeListener);
        featureNameTextField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                changeOccured(e);
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                changeOccured(e);
            }

            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                changeOccured(e);
            }

            protected void changeOccured(javax.swing.event.DocumentEvent e) {
                if (selectedPRRunStrategy != null && selectedPRRunStrategy instanceof AnalyserRunningStrategy) {
                    AnalyserRunningStrategy strategy = (AnalyserRunningStrategy) selectedPRRunStrategy;
                    strategy.setFeatureName(featureNameTextField.getText());
                }
                // editing the textfield changes the running strategy to conditional
                conditional_RunRBtn.setSelected(true);
            }
        });
        featureValueTextField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                changeOccured(e);
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                changeOccured(e);
            }

            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                changeOccured(e);
            }

            protected void changeOccured(javax.swing.event.DocumentEvent e) {
                if (selectedPRRunStrategy != null && selectedPRRunStrategy instanceof AnalyserRunningStrategy) {
                    AnalyserRunningStrategy strategy = (AnalyserRunningStrategy) selectedPRRunStrategy;
                    strategy.setFeatureValue(featureValueTextField.getText());
                }
                // editing the textfield changes the running strategy to conditional
                conditional_RunRBtn.setSelected(true);
            }
        });
    }
    if (corpusControllerMode) {
        corpusCombo.addPopupMenuListener(new PopupMenuListener() {

            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                corpusComboModel.fireDataChanged();
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
            }
        });
    }
    addAncestorListener(new AncestorListener() {

        @Override
        public void ancestorAdded(AncestorEvent event) {
            // every time the user switches back to this view, we check
            // whether another controller has just included this one
            loadedPRsTableModel.fireTableDataChanged();
            memberPRsTableModel.fireTableDataChanged();
        }

        @Override
        public void ancestorRemoved(AncestorEvent event) {
        /* do nothing */
        }

        @Override
        public void ancestorMoved(AncestorEvent event) {
        /* do nothing */
        }
    });
    // binds F3 key to the run action
    getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("F3"), "Run");
    getActionMap().put("Run", runAction);
}
Also used : ItemEvent(java.awt.event.ItemEvent) ActionEvent(java.awt.event.ActionEvent) PopupMenuListener(javax.swing.event.PopupMenuListener) ArrayList(java.util.ArrayList) ProcessingResource(gate.ProcessingResource) ListSelectionEvent(javax.swing.event.ListSelectionEvent) PopupMenuEvent(javax.swing.event.PopupMenuEvent) AncestorEvent(javax.swing.event.AncestorEvent) StringSelection(java.awt.datatransfer.StringSelection) DataFlavor(java.awt.datatransfer.DataFlavor) XJPopupMenu(gate.swing.XJPopupMenu) AncestorListener(javax.swing.event.AncestorListener) List(java.util.List) ArrayList(java.util.ArrayList) Component(java.awt.Component) JComponent(javax.swing.JComponent) MouseEvent(java.awt.event.MouseEvent) RunningStrategy(gate.creole.RunningStrategy) AnalyserRunningStrategy(gate.creole.AnalyserRunningStrategy) UnconditionalRunningStrategy(gate.creole.RunningStrategy.UnconditionalRunningStrategy) MouseAdapter(java.awt.event.MouseAdapter) JComponent(javax.swing.JComponent) Transferable(java.awt.datatransfer.Transferable) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) XJPopupMenu(gate.swing.XJPopupMenu) JPopupMenu(javax.swing.JPopupMenu) ListSelectionListener(javax.swing.event.ListSelectionListener) ActionListener(java.awt.event.ActionListener) TransferHandler(javax.swing.TransferHandler) ItemListener(java.awt.event.ItemListener) AnalyserRunningStrategy(gate.creole.AnalyserRunningStrategy) UnconditionalRunningStrategy(gate.creole.RunningStrategy.UnconditionalRunningStrategy)

Example 5 with XJPopupMenu

use of gate.swing.XJPopupMenu in project gate-core by GateNLP.

the class NameBearerHandle method getPopup.

@Override
public JPopupMenu getPopup() {
    JPopupMenu popup = new XJPopupMenu();
    // first add the static items
    Iterator<JComponent> itemIter = staticPopupItems.iterator();
    while (itemIter.hasNext()) {
        JComponent anItem = itemIter.next();
        if (anItem == null)
            popup.addSeparator();
        else
            popup.add(anItem);
    }
    // next add the dynamic list from the target and its editors
    Iterator<ActionsPublisher> publishersIter = actionPublishers.iterator();
    while (publishersIter.hasNext()) {
        ActionsPublisher aPublisher = publishersIter.next();
        if (aPublisher.getActions() != null) {
            Iterator<Action> actionIter = aPublisher.getActions().iterator();
            while (actionIter.hasNext()) {
                Action anAction = actionIter.next();
                if (anAction == null)
                    popup.addSeparator();
                else {
                    popup.add(new XJMenuItem(anAction, sListenerProxy));
                }
            }
        }
    }
    if (target instanceof Resource) {
        Set<String> toolTypes = Gate.getCreoleRegister().getToolTypes();
        for (String type : toolTypes) {
            List<Resource> instances = Gate.getCreoleRegister().get(type).getInstantiations();
            for (Resource res : instances) {
                if (res instanceof ResourceHelper) {
                    Iterator<Action> actionIter = ((ResourceHelper) res).getActions(NameBearerHandle.this).iterator();
                    while (actionIter.hasNext()) {
                        Action anAction = actionIter.next();
                        if (anAction == null)
                            popup.addSeparator();
                        else {
                            popup.add(new XJMenuItem(anAction, sListenerProxy));
                        }
                    }
                }
            }
        }
    }
    return popup;
}
Also used : AbstractAction(javax.swing.AbstractAction) Action(javax.swing.Action) JComponent(javax.swing.JComponent) VisualResource(gate.VisualResource) Resource(gate.Resource) ProcessingResource(gate.ProcessingResource) AbstractResource(gate.creole.AbstractResource) LanguageResource(gate.LanguageResource) XJPopupMenu(gate.swing.XJPopupMenu) JPopupMenu(javax.swing.JPopupMenu) XJPopupMenu(gate.swing.XJPopupMenu) XJMenuItem(gate.swing.XJMenuItem)

Aggregations

XJPopupMenu (gate.swing.XJPopupMenu)5 JComponent (javax.swing.JComponent)4 JPopupMenu (javax.swing.JPopupMenu)4 XJMenuItem (gate.swing.XJMenuItem)3 ActionEvent (java.awt.event.ActionEvent)3 AbstractAction (javax.swing.AbstractAction)3 ProcessingResource (gate.ProcessingResource)2 Component (java.awt.Component)2 Dimension (java.awt.Dimension)2 Point (java.awt.Point)2 Rectangle (java.awt.Rectangle)2 DataFlavor (java.awt.datatransfer.DataFlavor)2 StringSelection (java.awt.datatransfer.StringSelection)2 Transferable (java.awt.datatransfer.Transferable)2 ActionListener (java.awt.event.ActionListener)2 MouseAdapter (java.awt.event.MouseAdapter)2 MouseEvent (java.awt.event.MouseEvent)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2