Search in sources :

Example 1 with TaskListener

use of org.openide.util.TaskListener in project netbeans-rcp-lite by outersky.

the class RequestProcessorTest method testCancel.

/**
 * Make sure that successfully canceled task is not performed.
 */
public void testCancel() throws Exception {
    class X implements Runnable {

        public boolean performed = false;

        public void run() {
            performed = true;
        }
    }
    X x = new X();
    final boolean[] finished = new boolean[1];
    finished[0] = false;
    // post task with some delay
    RequestProcessor.Task task = RequestProcessor.postRequest(x, 1000);
    task.addTaskListener(new TaskListener() {

        @Override
        public void taskFinished(Task t) {
            finished[0] = true;
        }
    });
    boolean canceled = task.cancel();
    assertTrue("Task is canceled now", canceled);
    assertTrue("Cancelling actually means finished", finished[0]);
    // wait longer than task delay
    Thread.sleep(1500);
    assertFalse("Task should not be performed", x.performed);
}
Also used : Task(org.openide.util.Task) TaskListener(org.openide.util.TaskListener) RequestProcessor(org.openide.util.RequestProcessor)

Example 2 with TaskListener

use of org.openide.util.TaskListener in project netbeans-rcp-lite by outersky.

the class RequestProcessorTest method testWaitFinishedFromNotification.

/**
 * Make sure it is safe to call waitFinished() on a task from within
 * a task listener.
 */
public void testWaitFinishedFromNotification() throws Exception {
    class X implements Runnable {

        private Task task;

        private int cnt;

        public synchronized Task start() {
            if (task == null) {
                task = RequestProcessor.postRequest(this);
            }
            return task;
        }

        public void run() {
            cnt++;
        }

        public int getCount() {
            return cnt;
        }

        public void block() {
            start().waitFinished();
        }
    }
    final X x = new X();
    final Object lock = "wait for task to finish";
    final boolean[] finished = new boolean[1];
    x.start().addTaskListener(new TaskListener() {

        public void taskFinished(Task t) {
            x.block();
            finished[0] = true;
            synchronized (lock) {
                lock.notify();
            }
        }
    });
    synchronized (lock) {
        lock.wait(5000);
    }
    assertTrue(finished[0]);
    assertEquals(1, x.getCount());
}
Also used : Task(org.openide.util.Task) TaskListener(org.openide.util.TaskListener)

Example 3 with TaskListener

use of org.openide.util.TaskListener in project netbeans-rcp-lite by outersky.

the class AutoupdateCheckScheduler method scheduleRefreshProviders.

private static void scheduleRefreshProviders() {
    refreshUpdateCenters(null);
    final int delay = 500;
    final long startTime = System.currentTimeMillis();
    RequestProcessor.Task t = Installer.RP.post(doCheckAvailableUpdates, delay);
    t.addTaskListener(new TaskListener() {

        @Override
        public void taskFinished(Task task) {
            task.removeTaskListener(this);
            long time = (System.currentTimeMillis() - startTime - delay) / 1000;
            if (time > 0) {
                Utilities.putTimeOfInitialization(time);
            }
        }
    });
}
Also used : Task(org.openide.util.Task) TaskListener(org.openide.util.TaskListener) RequestProcessor(org.openide.util.RequestProcessor)

Example 4 with TaskListener

use of org.openide.util.TaskListener in project netbeans-rcp-lite by outersky.

the class OptionsChooserPanel method showExportDialog.

/**
 * Shows panel for export of options.
 */
@NbBundle.Messages({ "ProgressHandle_Export_DisplayName=Exporting Options", "# {0} - path where the exported options are saved", "Export_Notification_DetailsText=File saved at {0}" })
public static void showExportDialog() {
    if (exportTask != null && !exportTask.isFinished()) {
        return;
    }
    // NOI18N
    LOGGER.fine("showExportDialog");
    File sourceUserdir = Places.getUserDirectory();
    final OptionsChooserPanel optionsChooserPanel = new OptionsChooserPanel();
    optionsChooserPanel.panelType = PanelType.EXPORT;
    optionsChooserPanel.setOptionsExportModel(new OptionsExportModel(sourceUserdir));
    optionsChooserPanel.loadOptions();
    optionsChooserPanel.txtFile.setText(getDefaultUserdirRoot().concat(File.separator));
    optionsChooserPanel.txtFile.getDocument().addDocumentListener(new DocumentListener() {

        public void insertUpdate(DocumentEvent e) {
            optionsChooserPanel.dialogDescriptor.setValid(optionsChooserPanel.isPanelValid());
        }

        public void removeUpdate(DocumentEvent e) {
            optionsChooserPanel.dialogDescriptor.setValid(optionsChooserPanel.isPanelValid());
        }

        public void changedUpdate(DocumentEvent e) {
            optionsChooserPanel.dialogDescriptor.setValid(optionsChooserPanel.isPanelValid());
        }
    });
    DialogDescriptor dd = new DialogDescriptor(optionsChooserPanel, NbBundle.getMessage(OptionsChooserPanel.class, "OptionsChooserPanel.export.title"), true, new Object[] { DialogDescriptor.OK_OPTION, DialogDescriptor.CANCEL_OPTION }, DialogDescriptor.OK_OPTION, DialogDescriptor.DEFAULT_ALIGN, null, null);
    // add bottom user notification area
    dd.createNotificationLineSupport();
    dd.setValid(false);
    ExportConfirmationPanel exportConfirmationPanel = null;
    if (!ExportConfirmationPanel.getSkipOption()) {
        exportConfirmationPanel = new ExportConfirmationPanel();
        final ExportConfirmationPanel finalExportConfirmationPanel = exportConfirmationPanel;
        dd.setButtonListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == DialogDescriptor.OK_OPTION) {
                    String passwords = NbBundle.getMessage(OptionsChooserPanel.class, "OptionsChooserPanel.export.passwords.displayName");
                    Enumeration dfs = ((DefaultMutableTreeNode) treeModel.getRoot()).depthFirstEnumeration();
                    while (dfs.hasMoreElements()) {
                        Object nodeObj = dfs.nextElement();
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeObj;
                        Object userObject = node.getUserObject();
                        if (userObject instanceof OptionsExportModel.Item) {
                            if (((OptionsExportModel.Item) userObject).getDisplayName().equals(passwords)) {
                                if (treeDataProvider.isSelected(nodeObj)) {
                                    // show confirmation dialog when user click OK and All/Passwords/Passwords item is selected
                                    finalExportConfirmationPanel.showConfirmation();
                                }
                            }
                        }
                    }
                }
            }
        });
    }
    optionsChooserPanel.setDialogDescriptor(dd);
    DialogDisplayer.getDefault().createDialog(dd).setVisible(true);
    if (DialogDescriptor.OK_OPTION.equals(dd.getValue())) {
        if (exportConfirmationPanel != null && !exportConfirmationPanel.confirmed()) {
            // NOI18N
            LOGGER.fine("Export canceled.");
            return;
        }
        // NOI18N
        Action save = Actions.forID("Window", "org.netbeans.core.windows.actions.SaveWindowsAction");
        if (save != null) {
            save.actionPerformed(new ActionEvent(optionsChooserPanel, 0, ""));
        }
        String selectedFilePath = optionsChooserPanel.getSelectedFilePath();
        if (selectedFilePath.endsWith("/")) {
            // NOI18N
            // name zip file after last folder
            // NOI18N
            selectedFilePath = selectedFilePath.substring(0, selectedFilePath.lastIndexOf("/"));
            // NOI18N
            String zipName = selectedFilePath.substring(selectedFilePath.lastIndexOf("/") + 1);
            // NOI18N
            selectedFilePath = selectedFilePath.concat("/").concat(zipName).concat(".zip");
        }
        if (!selectedFilePath.endsWith(".zip")) {
            // NOI18N
            // NOI18N
            selectedFilePath = selectedFilePath.concat(".zip");
        }
        final String targetPath = selectedFilePath;
        // NOI18N
        RequestProcessor RP = new RequestProcessor("OptionsChooserPanel Export", 1);
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // to avoid false possitives during import, find the items that are explicitly selected by the user for export
                Enumeration dfs = ((DefaultMutableTreeNode) treeModel.getRoot()).depthFirstEnumeration();
                ArrayList<String> enabledItems = new ArrayList<String>();
                while (dfs.hasMoreElements()) {
                    Object userObject = ((DefaultMutableTreeNode) dfs.nextElement()).getUserObject();
                    if (userObject instanceof OptionsExportModel.Category) {
                        OptionsExportModel.Category category = (OptionsExportModel.Category) userObject;
                        if (!category.getState().equals(OptionsExportModel.State.DISABLED)) {
                            List<OptionsExportModel.Item> items = ((OptionsExportModel.Category) userObject).getItems();
                            for (OptionsExportModel.Item item : items) {
                                if (item.isEnabled()) {
                                    enabledItems.add(category.getDisplayName().concat(item.getDisplayName()));
                                }
                            }
                        }
                    }
                }
                optionsChooserPanel.getOptionsExportModel().doExport(new File(targetPath), enabledItems);
                NotificationDisplayer.getDefault().notify(// NOI18N
                NbBundle.getMessage(OptionsChooserPanel.class, "OptionsChooserPanel.export.status.text"), OPTIONS_ICON, Bundle.Export_Notification_DetailsText(targetPath), null);
                // NOI18N
                LOGGER.fine("Export finished.");
            }
        };
        exportTask = RP.create(runnable);
        final ProgressHandle ph = ProgressHandleFactory.createHandle(Bundle.ProgressHandle_Export_DisplayName(), exportTask);
        exportTask.addTaskListener(new TaskListener() {

            @Override
            public void taskFinished(org.openide.util.Task task) {
                ph.finish();
            }
        });
        ph.start();
        exportTask.schedule(0);
    }
}
Also used : DocumentListener(javax.swing.event.DocumentListener) Action(javax.swing.Action) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) TaskListener(org.openide.util.TaskListener) Enumeration(java.util.Enumeration) DocumentEvent(javax.swing.event.DocumentEvent) ActionListener(java.awt.event.ActionListener) ProgressHandle(org.netbeans.api.progress.ProgressHandle) DialogDescriptor(org.openide.DialogDescriptor) File(java.io.File) RequestProcessor(org.openide.util.RequestProcessor)

Example 5 with TaskListener

use of org.openide.util.TaskListener in project netbeans-rcp-lite by outersky.

the class CloneableEditorSupport method openAtImpl.

/**
 * Forcibly create one editor component. Then set the caret
 * to the given position.
 * @param pos where to place the caret
 * @param column where to place the caret
 * @param reuse if true, the infrastructure tries to reuse other, already opened editor
 * for the purpose of opening this file/line.
 * @return always non-<code>null</code> editor
 */
private final Pane openAtImpl(final PositionRef pos, final int column, boolean reuse) {
    CloneableEditorSupport redirect = CloneableEditorSupportRedirector.findRedirect(this);
    if (redirect != null) {
        return redirect.openAtImpl(pos, column, reuse);
    }
    final Pane e = openPane(reuse);
    final Task t = prepareDocument();
    e.ensureVisible();
    class Selector implements TaskListener, Runnable {

        private boolean documentLocked = false;

        public void taskFinished(org.openide.util.Task t2) {
            javax.swing.SwingUtilities.invokeLater(this);
            t2.removeTaskListener(this);
        }

        public void run() {
            // #25435. Pane can be null.
            JEditorPane ePane = e.getEditorPane();
            if (ePane == null) {
                return;
            }
            StyledDocument doc = getDocument();
            if (doc == null) {
                // already closed or error loading
                return;
            }
            if (!documentLocked) {
                documentLocked = true;
                doc.render(this);
            } else {
                Caret caret = ePane.getCaret();
                if (caret == null) {
                    return;
                }
                int offset;
                // Pane's document may differ - see #204980
                Document paneDoc = ePane.getDocument();
                if (paneDoc instanceof StyledDocument && paneDoc != doc) {
                    if (ERR.isLoggable(Level.FINE)) {
                        // NOI18N
                        ERR.fine("paneDoc=" + paneDoc + "\n !=\ndoc=" + doc);
                    }
                    doc = (StyledDocument) paneDoc;
                }
                javax.swing.text.Element el = NbDocument.findLineRootElement(doc);
                el = el.getElement(el.getElementIndex(pos.getOffset()));
                offset = el.getStartOffset() + Math.max(0, column);
                if (offset > el.getEndOffset()) {
                    offset = Math.max(el.getStartOffset(), el.getEndOffset() - 1);
                }
                caret.setDot(offset);
                try {
                    // scroll to show reasonable part of the document
                    Rectangle r = ePane.modelToView(offset);
                    if (r != null) {
                        r.height *= 5;
                        ePane.scrollRectToVisible(r);
                    }
                } catch (BadLocationException ex) {
                    ERR.log(Level.WARNING, // NOI18N
                    "Can't scroll to text: pos.getOffset=" + pos.getOffset() + ", column=" + column + ", offset=" + // NOI18N
                    offset + ", doc.getLength=" + doc.getLength(), // NOI18N
                    ex);
                }
            }
        }
    }
    t.addTaskListener(new Selector());
    return e;
}
Also used : Task(org.openide.util.Task) Rectangle(java.awt.Rectangle) JEditorPane(javax.swing.JEditorPane) JEditorPane(javax.swing.JEditorPane) TaskListener(org.openide.util.TaskListener) javax.swing.text(javax.swing.text)

Aggregations

TaskListener (org.openide.util.TaskListener)12 Task (org.openide.util.Task)10 RequestProcessor (org.openide.util.RequestProcessor)6 ArrayList (java.util.ArrayList)2 CardLayout (java.awt.CardLayout)1 Rectangle (java.awt.Rectangle)1 ActionEvent (java.awt.event.ActionEvent)1 ActionListener (java.awt.event.ActionListener)1 FocusEvent (java.awt.event.FocusEvent)1 FocusListener (java.awt.event.FocusListener)1 File (java.io.File)1 Enumeration (java.util.Enumeration)1 HashSet (java.util.HashSet)1 Action (javax.swing.Action)1 JEditorPane (javax.swing.JEditorPane)1 JPanel (javax.swing.JPanel)1 DocumentEvent (javax.swing.event.DocumentEvent)1 DocumentListener (javax.swing.event.DocumentListener)1 javax.swing.text (javax.swing.text)1 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)1