Example usage for org.eclipse.jface.dialogs ProgressMonitorDialog getProgressMonitor

List of usage examples for org.eclipse.jface.dialogs ProgressMonitorDialog getProgressMonitor

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs ProgressMonitorDialog getProgressMonitor.

Prototype

public IProgressMonitor getProgressMonitor() 

Source Link

Document

Returns the progress monitor to use for operations run in this progress dialog.

Usage

From source file:net.sf.freeqda.common.handler.SaveProjectHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    Shell shell = HandlerUtil.getActiveWorkbenchWindow(event).getShell();

    /*/*from   www. j a  v a2 s .co m*/
     * Load selected project file
     */
    try {
        /*
         * Save project data
         */
        JAXBUtils.saveProject(PM.getProjectFile());

        ProgressMonitorDialog progressMonitor = new ProgressMonitorDialog(shell);
        /*
         * Save dirty editors
         */
        for (IEditorPart editor : PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
                .getDirtyEditors()) {
            if (editor instanceof StyledEditor) {
                StyledEditor styledEditor = (StyledEditor) editor;
                styledEditor.doSave(progressMonitor.getProgressMonitor());
            } else if (editor instanceof TaggedPassagesEditor) {
                TaggedPassagesEditor taggedPassagesEditor = (TaggedPassagesEditor) editor;
                taggedPassagesEditor.doSave(progressMonitor.getProgressMonitor());
            } else {
                new MessageDialog(shell, SAVE_PROJECT_UNHANDLED_TITLE, null, SAVE_PROJECT_UNHANDLED_MESSAGE,
                        MessageDialog.ERROR, new String[] { SAVE_PROJECT_UNHANDLED_BUTTON_CONFIRM }, 0).open();
            }
        }
        new MessageDialog(shell, SAVE_PROJECT_SUCCESS_TITLE, null, SAVE_PROJECT_SUCCESS_MESSAGE,
                MessageDialog.INFORMATION, new String[] { SAVE_PROJECT_SUCCESS_BUTTON_CONFIRM }, 0).open();

    } catch (IOException e) {
        new MessageDialog(shell, SAVE_PROJECT_FAILED_TITLE, null,
                MessageFormat.format(Messages.SaveProjectHandler_SaveProjectFailed_Message,
                        new Object[] { PM.getProjectFile().getAbsolutePath() }),
                MessageDialog.ERROR, new String[] { SAVE_PROJECT_FAILED_BUTTON_CONFIRM }, 0).open();
        e.printStackTrace();
    }
    return null;
}

From source file:nexcore.tool.uml.ui.project.explorer.action.ClearUnusedElementAction.java

License:Open Source License

/**
 * @see nexcore.tool.uml.ui.project.explorer.action.CommonActionDelegate#run(org.eclipse.jface.action.IAction)
 *//* w w w  . j  av  a2  s.co m*/
@Override
public void run(IAction action) {

    if (!(selectedEObject instanceof Namespace)) {
        return;
    }

    Namespace selectedElement = (Namespace) selectedEObject;
    if (!MessageDialog.openConfirm(UiCorePlugin.getShell(),
            UMLMessage.getMessage(UMLMessage.LABEL_DELETE_UNUSED_ELEMENT), UMLMessage.getMessage(
                    UMLMessage.MESSAGE_DELETE_UNUSED_ELEMENT, selectedElement.getQualifiedName()))) {
        return;
    }

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(targetPart.getSite().getShell());
    dialog.create();
    dialog.getProgressMonitor().beginTask(UMLMessage.LABEL_DELETE_UNUSED_ELEMENT, IProgressMonitor.UNKNOWN);
    dialog.open();

    /*********   . *********/
    EList<Lifeline> lifelineList = null; // ????? .
    EList<Message> messageList = null; // ? .
    EList<AbstractConnection> connectionList = null; // ??   .
    EList<AbstractNode> nodeList = null; // ??   .

    // ??  ? ???? .
    List<Lifeline> lifelineNodeList = new ArrayList<Lifeline>();
    // ??  ?  .
    List<Message> messageConnectionList = new ArrayList<Message>();

    // EObject  ?  ..
    List<Element> deleteList = new ArrayList<Element>(); //  ? ?.

    //        List<Diagram> sequencediagramList = ModelManager.getAllDiagramList(selectedElement,
    //            DiagramType.SEQUENCE_DIAGRAM);
    //        for (Diagram diagram : sequencediagramList) {
    //            if (diagram.getParent() instanceof Interaction) {
    //                Interaction interaction = (Interaction) diagram.getParent();
    //
    //                /*********  MessageOccurenceSpecification, BehaviorExecutionSpecification ?. *********/
    //                // ???? ? ? MessageOccurenceSpecification BehaviorExecutionSpecification, Event.
    //                EList<InteractionFragment> fragments = interaction.getFragments();
    //                for (InteractionFragment interactionFragment : fragments) {
    //                    if (interactionFragment instanceof MessageOccurrenceSpecification) {
    //                        MessageOccurrenceSpecification mos = (MessageOccurrenceSpecification) interactionFragment;
    //                        if (null == mos.getMessage()) {
    //                            deleteList.add(interactionFragment);
    //                            if (null != mos.getEvent()) {
    //                                deleteList.add(mos.getEvent());
    //                            }
    //                        }
    //                    } else if (interactionFragment instanceof BehaviorExecutionSpecification) {
    //                        BehaviorExecutionSpecification bes = (BehaviorExecutionSpecification) interactionFragment;
    //                        if (null == bes.getStart() || null == bes.getFinish()) {
    //                            deleteList.add(interactionFragment);
    //                        }
    //                    }
    //                }
    //                
    //                /*********  ???? ?. *********/
    //                // ??  ????  ?.
    //                nodeList = diagram.getNodeList();
    //                lifelineNodeList = new ArrayList<Lifeline>();
    //                for (AbstractNode abstractNode : nodeList) {
    //                    Element element = abstractNode.getUmlModel();
    //                    if (element instanceof Lifeline) {
    //                        lifelineNodeList.add((Lifeline) element);
    //                    }
    //                }
    //
    //                // ????? ??    ?.
    //                lifelineList = interaction.getLifelines();
    //                for (Lifeline lifeline : lifelineList) {
    //                    if (!lifelineNodeList.contains(lifeline)) {
    //                        deleteList.add(lifeline);
    //                    }
    //                }
    //
    //                /*********   ?. *********/
    //                // ??    ?
    //                connectionList = diagram.getConnectionList();
    //                messageConnectionList = new ArrayList<Message>();
    //                for (AbstractConnection abstractConnection : connectionList) {
    //                    Element element = abstractConnection.getUmlModel();
    //                    if (element instanceof Message) {
    //                        messageConnectionList.add((Message) element);
    //                    }
    //                }
    //
    //                //  ??    ?.
    //                messageList = interaction.getMessages();
    //                for (Message message : messageList) {
    //                    if (!messageConnectionList.contains(message)) {
    //                        deleteList.add(message);
    //                    }
    //                }
    //            }
    //        }

    /*********   . *********/
    // TODO deleteList      .
    Command deleteCommand;
    CompoundCommand deleteCommandList = new CompoundCommand();
    List<IMarker> deleteMarkerList = new ArrayList<IMarker>();
    // deleteCommandList.add(diagramDelete);
    for (EObject eobject : deleteList) {
        // UMLManager.clearStereotype((Element) eobject);
        // EcoreUtil.remove(eobject);
        NamedElement obj = (NamedElement) eobject;

        deleteCommand = DeleteUMLElementCommandFactory.getCommand(obj);
        if (null == deleteCommand) {
            continue;
        } else {
            deleteCommandList.add(deleteCommand);
            ProjectRegistry.UMLTreeNodeRegistry.removeTreeNode(obj);

            //  
            IPath path = new Path(obj.eResource().getURI().toFileString());
            IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
            try {
                IMarker[] markers = file.findMarkers(UICoreConstant.VALIDATION_MARKER_TYPE, true,
                        IResource.DEPTH_INFINITE);
                for (IMarker marker : markers) {
                    String location = (String) marker.getAttribute(IMarker.LOCATION);
                    if (obj.getQualifiedName().equals(location) && !deleteMarkerList.contains(marker)) {
                        deleteMarkerList.add(marker);
                    }
                }

            } catch (CoreException e) {
            }

        }
    }
    if (0 != deleteCommandList.getCommands().size()) {
        for (int i = 0; i < deleteMarkerList.size(); i++) {
            try {
                if (deleteMarkerList.get(i).exists()) {
                    deleteMarkerList.get(i).delete();
                }
            } catch (CoreException e) {
                Log.error(e);
            }
        }
        ((UMLDiagramCommandStack) DomainRegistry.getUMLDomain().getCommandStackListener())
                .execute(deleteCommandList);
        // deleteResource();
    }
    dialog.getProgressMonitor().done();
    dialog.close();

    MessageDialog.openInformation(ProjectExplorerPlugin.getShell(),
            UMLMessage.LABEL_DELETE_UNUSED_ELEMENT_COMPLETED,
            UMLMessage.getMessage(UMLMessage.MESSAGE_DELETE_UNUSED_ELEMENT_COMPLETED,
                    String.valueOf(deleteCommandList.size())));
}

From source file:nexcore.tool.uml.ui.project.explorer.action.MergeFragmentAction.java

License:Open Source License

/**
 * @see nexcore.tool.uml.ui.project.explorer.action.CommonActionDelegate#run(org.eclipse.jface.action.IAction)
 *///  w  w w .  j  ava  2  s .co  m
@Override
public void run(IAction action) {
    if (selectedEObject == null) {
        return;
    }
    if (!(AdapterFactoryEditingDomain.isControlled(selectedEObject))) {
        MessageDialog.openInformation(ProjectExplorerPlugin.getShell(), UMLMessage.LABEL_FILE_DEFRAGMENTATION,
                UMLMessage.MESSAGE_FRAGMENT_NOT_FRAGMENTED);
        return;
    }

    if (!MessageDialog.openConfirm(UiCorePlugin.getShell(),
            UMLMessage.getMessage(UMLMessage.LABEL_FILE_DEFRAGMENTATION),
            UMLMessage.getMessage(UMLMessage.MESSAGE_CONFIRM_MERGE))) {
        return;
    }

    final ChangeRecorder recorder = new ChangeRecorder(DomainRegistry.getUMLDomain().getResourceSet());

    // TODO : close the opened windows of the fragment file.
    // CommandUtil.closeEditor(eobject, false);
    DomainRegistry.getEditingDomain().getCommandStack()
            .execute(new RecordingCommand(DomainRegistry.getEditingDomain()) {
                /**
                 * @see org.eclipse.emf.transaction.RecordingCommand#doExecute()
                 */
                @Override
                public void doExecute() {
                    ProgressMonitorDialog dialog = new ProgressMonitorDialog(ProjectExplorerPlugin.getShell());
                    dialog.create();
                    EList<Resource> resources = DomainRegistry.getUMLDomain().getResourceSet().getResources();
                    dialog.getProgressMonitor().beginTask(UMLMessage.LABEL_FILE_DEFRAGMENTATION,
                            resources.size());
                    dialog.open();

                    IResourceSetListener rsListener = ContentProviderRegistry.getContentProvider();
                    try {
                        if (rsListener != null) {
                            rsListener.stopResourceListening();
                        }

                        Resource sourceResource = selectedEObject.eResource();
                        org.eclipse.uml2.uml.Package source = (org.eclipse.uml2.uml.Package) selectedEObject;

                        // ? ?? ?  Reference  .
                        EAnnotation sourceFragmentContainerAnnotation = ProjectUtil
                                .getFragmentContainerAnnotation(source);
                        if (sourceFragmentContainerAnnotation.getReferences() != null) {
                            sourceFragmentContainerAnnotation.getReferences()
                                    .remove(selectedEObject.eContainer());
                        }

                        // ? ?? FragmentContainer  
                        if (sourceFragmentContainerAnnotation != null) {
                            source.getEAnnotations().remove(sourceFragmentContainerAnnotation);
                        }
                        // ? ?? ProjectInfo  
                        EAnnotation sourceProjectInfoAnnotation = ProjectUtil.getProjectInfoAnnotation(source);
                        if (sourceProjectInfoAnnotation != null) {
                            source.getEAnnotations().remove(sourceProjectInfoAnnotation);
                        }

                        //  ?? Fragment Reference  
                        org.eclipse.uml2.uml.Package target = (org.eclipse.uml2.uml.Package) selectedEObject
                                .eContainer();
                        EAnnotation targetAnn = ProjectUtil.getFragmentAnnotation(target);
                        if (targetAnn.getReferences() != null) {
                            targetAnn.getReferences().remove(selectedEObject);
                        }

                        //  ?? ? ?    ?
                        URI srcUri = sourceResource.getURI();
                        URI parentUri = selectedEObject.eContainer().eResource().getURI();
                        List<Resource> saveResourceList = new ArrayList<Resource>();

                        for (Resource rs : resources) {
                            if (rs != null && ProjectUtil.isModelFile(rs)) {
                                final IFile file = WorkspaceSynchronizer.getFile(rs);
                                if (file != null && file.exists()) {
                                    if (!rs.isLoaded()) {
                                        rs.load(DomainModelHandlerUtil.getLoadOptions());
                                    }

                                    dialog.getProgressMonitor().worked(1);

                                    if (ResourceManager.getInstance().isRelated(rs, srcUri)) {
                                        dialog.getProgressMonitor().subTask(rs.getURI().toString());

                                        saveResourceList.add(rs);
                                        continue;
                                    }

                                    if (ResourceManager.getInstance().isRelated(rs, parentUri)) {
                                        dialog.getProgressMonitor().subTask(rs.getURI().toString());

                                        saveResourceList.add(rs);
                                        continue;
                                    }

                                    if (rs == selectedEObject.eResource()) {
                                        dialog.getProgressMonitor().subTask(rs.getURI().toString());

                                        saveResourceList.add(rs);
                                        continue;
                                    }

                                    if (rs == selectedEObject.eContainer().eResource()) {
                                        dialog.getProgressMonitor().subTask(rs.getURI().toString());

                                        saveResourceList.add(rs);
                                    }

                                    dialog.getProgressMonitor().subTask("");
                                }
                            }
                        }

                        //  ?? Fragment  
                        if (targetAnn != null) {
                            if (targetAnn.getReferences() != null && targetAnn.getReferences().size() == 0) {
                                target.getEAnnotations().remove(targetAnn);
                            }
                        }

                        ResourceManager.getInstance().removeContentsOfResource(sourceResource, selectedEObject);

                        selectedEObject.eResource().getContents().addAll(
                                ProjectUtil.getStereotypesForFragment(sourceResource, selectedEObject, true));

                        for (Resource saveResource : saveResourceList) {
                            DomainModelHandlerUtil.save(saveResource, true);
                        }
                        // have to remove source file.
                        final EObject parentObject = selectedEObject.eContainer();

                        final IFile file = WorkspaceSynchronizer.getFile(sourceResource);

                        TreeIterator<EObject> allContents = source.eAllContents();
                        while (allContents.hasNext()) {
                            EObject content = allContents.next();
                            UMLTreeNodeRegistry.removeTreeNode(content);
                        }

                        UMLTreeNodeRegistry.removeTreeNode(source);
                        //                        ResourceManager.getInstance().removeResource(sourceResource);
                        ResourceUnloader.getInstance().put(sourceResource);

                        ProjectExplorerPlugin.getDisplay().asyncExec(new Runnable() {
                            public void run() {
                                try { // 2011-08-11 ?
                                      // ?? ?? .fragment?  ?? 
                                    boolean isPackageStructuredFragment = true;
                                    IFolder folder = ((IFolder) ResourcesPlugin.getWorkspace().getRoot()
                                            .getFolder(file.getFullPath()).getParent());
                                    while (!folder.getName()
                                            .equals(UICoreConstant.PROJECT_CONSTANTS__FRAGMENT_FOLDER_NAME)) {
                                        Object parent = folder.getParent();
                                        if (!(parent instanceof IFolder)) {
                                            isPackageStructuredFragment = false;
                                            break;
                                        }
                                        folder = ((IFolder) parent);
                                    }

                                    if (isPackageStructuredFragment) {
                                        folder = ((IFolder) ResourcesPlugin.getWorkspace().getRoot()
                                                .getFolder(file.getFullPath()).getParent());
                                        List<IFolder> removeList = new ArrayList<IFolder>();
                                        while ((folder.members().length == 1) && (!folder.getName().equals(
                                                UICoreConstant.PROJECT_CONSTANTS__FRAGMENT_FOLDER_NAME))) {
                                            removeList.add(folder);
                                            folder = ((IFolder) folder.getParent());
                                        }
                                        file.delete(false, new NullProgressMonitor());
                                        for (Iterator<IFolder> it = removeList.iterator(); it.hasNext();) {
                                            folder = (IFolder) it.next();
                                            folder.delete(false, new NullProgressMonitor());
                                        }
                                    } else {
                                        file.delete(false, new NullProgressMonitor());
                                    }

                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                    Log.error(ex);
                                } finally {
                                    try {
                                        if (parentObject != null) {
                                            ProjectUtil.refreshNodeInExplorer(parentObject);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        // ignore
                                    }
                                }
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();

                        // ResourceSet rollback 
                        ProjectUtil.rollbackResourceSet(recorder);

                        dialog.getProgressMonitor().done();
                        dialog.close();
                        MessageDialog.openError(ProjectExplorerPlugin.getShell(),
                                UMLMessage.LABEL_FILE_DEFRAGMENTATION, UMLMessage.MESSAGE_SAVE_FAIL);
                    } finally {
                        if (rsListener != null) {
                            rsListener.startResourceListening();
                        }
                        try {
                            dialog.getProgressMonitor().done();
                            dialog.close();
                        } catch (Exception e) {
                            //ignore
                        }
                    }
                }
            });
    System.gc();
}

From source file:org.apache.openjpa.eclipse.PluginLibrary.java

License:Apache License

/**
 * Gets the runtime libraries required for this bundle to the given project.
 * //from   w  w  w.j a  v  a2  s. c  o m
 * @param list of patterns that matches an actual library. null implies all runtime libraries.
 * @param copy if true then the libraries are copied to the given project directory.
 */
public IClasspathEntry[] getLibraryClasspaths(IProject project, List<String> libs, boolean copy)
        throws CoreException {
    if (libs != null && libs.isEmpty())
        return new IClasspathEntry[0];
    Bundle bundle = Platform.getBundle(BUNDLE_ID);
    List<String> libraries = getRuntimeLibraries(bundle);
    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    ProgressMonitorDialog progress = null;
    for (String lib : libraries) {
        try {
            if (".".equals(lib))
                continue;
            URL url = bundle.getEntry(lib);
            url = FileLocator.resolve(url);
            String urlString = url.getFile();
            if (!urlString.endsWith(".jar") || !matchesPattern(urlString, libs))
                continue;
            String libName = urlString.substring(urlString.indexOf('!') + 1);
            IFile iFile = project.getFile(libName);
            if (iFile == null) {
                continue;
            }
            IPath outPath = iFile.getRawLocation();
            File outFile = outPath.toFile();
            if (!outFile.getParentFile().exists() && copy) {
                outFile.getParentFile().mkdirs();
            }
            if (!outFile.exists() && copy) {
                outFile.createNewFile();
            }
            if (copy) {
                boolean firstTask = progress == null;
                if (progress == null) {
                    progress = new ProgressMonitorDialog(Activator.getShell());
                }
                if (firstTask) {
                    int nTask = libs == null ? libraries.size() : libs.size();
                    progress.run(true, false, new JarCopier(url.openStream(), outFile, true, nTask));
                } else {
                    progress.run(true, false, new JarCopier(url.openStream(), outFile));
                }
            }
            IClasspathEntry classpath = JavaCore.newLibraryEntry(outPath, null, null);
            entries.add(classpath);
        } catch (Exception e) {
            Activator.log(e);
        } finally {
            if (progress != null) {
                progress.getProgressMonitor().done();
            }
        }
    }
    return entries.toArray(new IClasspathEntry[entries.size()]);
}

From source file:org.dbeclipse.ui.internal.browser.WebBrowserPreferencePage.java

License:Open Source License

/**
 * Create the preference options.// ww w.j av  a  2s  . c  om
 * 
 * @param parent
 *            org.eclipse.swt.widgets.Composite
 * @return org.eclipse.swt.widgets.Control
 */
protected Control createContents(Composite parent) {
    initializeDialogUnits(parent);
    PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, ContextIds.PREF_BROWSER);

    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 2;
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(4);
    layout.verticalSpacing = convertVerticalDLUsToPixels(3);
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    composite.setLayout(layout);
    GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
    composite.setLayoutData(data);

    Label label = new Label(composite, SWT.WRAP);
    label.setText(Messages.preferenceWebBrowserDescription);
    data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
    data.horizontalSpan = 2;
    label.setLayoutData(data);

    label = new Label(composite, SWT.WRAP);
    data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
    data.horizontalSpan = 2;
    label.setLayoutData(data);

    internal = new Button(composite, SWT.RADIO);
    internal.setText(Messages.prefInternalBrowser);
    data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
    data.horizontalSpan = 2;
    internal.setLayoutData(data);

    if (!WebBrowserUtil.canUseInternalWebBrowser())
        internal.setEnabled(false);

    external = new Button(composite, SWT.RADIO);
    external.setText(Messages.prefExternalBrowser);
    data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
    data.horizontalSpan = 2;
    external.setLayoutData(data);

    label = new Label(composite, SWT.NONE);
    label.setText(Messages.browserList);
    data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER);
    data.horizontalSpan = 2;
    label.setLayoutData(data);

    table = new Table(composite,
            SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE | SWT.FULL_SELECTION);
    data = new GridData(GridData.FILL_BOTH);
    table.setLayoutData(data);
    table.setHeaderVisible(false);
    table.setLinesVisible(false);

    TableLayout tableLayout = new TableLayout();
    new TableColumn(table, SWT.NONE);
    tableLayout.addColumnData(new ColumnWeightData(100));
    table.setLayout(tableLayout);

    tableViewer = new CheckboxTableViewer(table);
    tableViewer.setContentProvider(new BrowserContentProvider());
    tableViewer.setLabelProvider(new BrowserTableLabelProvider());
    tableViewer.setInput("root"); //$NON-NLS-1$

    // uncheck any other elements that might be checked and leave only the
    // element checked to remain checked since one can only chose one
    // brower at a time to be current.
    tableViewer.addCheckStateListener(new ICheckStateListener() {
        public void checkStateChanged(CheckStateChangedEvent e) {
            checkNewDefaultBrowser(e.getElement());
            checkedBrowser = (IBrowserDescriptor) e.getElement();

            // if no other browsers are checked, don't allow the single one
            // currently checked to become unchecked, and lose a current
            // browser. That is, don't permit unchecking if no other item
            // is checked which is supposed to be the case.
            Object[] obj = tableViewer.getCheckedElements();
            if (obj.length == 0)
                tableViewer.setChecked(e.getElement(), true);
        }
    });

    // set a default, checked browser based on the current browser. If there
    // is not a current browser, but the first item exists, use that instead.
    // This will work currently until workbench shutdown, because current
    // browser is not yet persisted.
    checkedBrowser = BrowserManager.getInstance().getCurrentWebBrowser();
    if (checkedBrowser != null)
        tableViewer.setChecked(checkedBrowser, true);
    else {
        Object obj = tableViewer.getElementAt(0);
        if (obj != null)
            tableViewer.setChecked(obj, true);
    }

    tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sele = ((IStructuredSelection) tableViewer.getSelection());
            boolean sel = sele.getFirstElement() != null
                    && !(sele.getFirstElement() instanceof SystemBrowserDescriptor);
            remove.setEnabled(sel);
            edit.setEnabled(sel);
        }
    });

    tableViewer.addDoubleClickListener(new IDoubleClickListener() {
        public void doubleClick(DoubleClickEvent event) {
            IStructuredSelection sel = ((IStructuredSelection) tableViewer.getSelection());
            Object firstElem = sel.getFirstElement();
            if (firstElem != null && !(firstElem instanceof SystemBrowserDescriptor)) {
                IBrowserDescriptor browser2 = (IBrowserDescriptor) sel.getFirstElement();
                IBrowserDescriptorWorkingCopy wc = browser2.getWorkingCopy();
                BrowserDescriptorDialog dialog = new BrowserDescriptorDialog(getShell(), wc);
                if (dialog.open() != Window.CANCEL) {
                    try {
                        tableViewer.refresh(wc.save());
                    } catch (Exception ex) {
                        // ignore
                    }
                }
            }
        }
    });

    table.addKeyListener(new KeyListener() {
        public void keyPressed(KeyEvent e) {
            if (e.character == SWT.DEL) {
                IStructuredSelection sel = ((IStructuredSelection) tableViewer.getSelection());
                if (sel.getFirstElement() != null) {
                    IBrowserDescriptor browser2 = (IBrowserDescriptor) sel.getFirstElement();
                    try {
                        browser2.delete();
                        tableViewer.remove(browser2);

                        // need here to ensure that if the item deleted was
                        // checked, ie. was
                        // the current browser, that the new current browser
                        // will be the first in the
                        // list, typically, the internal browser, which
                        // cannot be
                        // deleted, and be current
                        BrowserManager manager = BrowserManager.getInstance();
                        if (browser2 == checkedBrowser) {
                            if (manager.browsers.size() > 0) {
                                checkedBrowser = (IBrowserDescriptor) manager.browsers.get(0);
                                tableViewer.setChecked(checkedBrowser, true);
                            }
                        }
                    } catch (Exception ex) {
                        // ignore
                    }
                }
            }
        }

        public void keyReleased(KeyEvent e) {
            // ignore
        }
    });

    Composite buttonComp = new Composite(composite, SWT.NONE);
    layout = new GridLayout();
    layout.horizontalSpacing = 0;
    layout.verticalSpacing = convertVerticalDLUsToPixels(3);
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    layout.numColumns = 1;
    buttonComp.setLayout(layout);
    data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
    buttonComp.setLayoutData(data);

    final Button add = SWTUtil.createButton(buttonComp, Messages.add);
    add.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            BrowserDescriptorDialog dialog = new BrowserDescriptorDialog(getShell());
            if (dialog.open() == Window.CANCEL)
                return;
            tableViewer.refresh();
            if (checkedBrowser != null)
                tableViewer.setChecked(checkedBrowser, true);
        }
    });

    edit = SWTUtil.createButton(buttonComp, Messages.edit);
    edit.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection sel = ((IStructuredSelection) tableViewer.getSelection());
            IBrowserDescriptor browser2 = (IBrowserDescriptor) sel.getFirstElement();
            IBrowserDescriptorWorkingCopy wc = browser2.getWorkingCopy();
            BrowserDescriptorDialog dialog = new BrowserDescriptorDialog(getShell(), wc);
            if (dialog.open() != Window.CANCEL) {
                try {
                    tableViewer.refresh(wc.save());
                } catch (Exception ex) {
                    // ignore
                }
            }
        }
    });

    remove = SWTUtil.createButton(buttonComp, Messages.remove);
    remove.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection sel = ((IStructuredSelection) tableViewer.getSelection());
            IBrowserDescriptor browser2 = (IBrowserDescriptor) sel.getFirstElement();
            try {
                browser2.delete();
                tableViewer.remove(browser2);

                // need here to ensure that if the item deleted was checked,
                // ie. was
                // the current browser, that the new current browser will be
                // the first in the
                // list, typically, the internal browser, which cannot be
                // deleted, and be current
                BrowserManager manager = BrowserManager.getInstance();
                if (browser2 == checkedBrowser) {
                    if (manager.browsers.size() > 0) {
                        checkedBrowser = (IBrowserDescriptor) manager.browsers.get(0);
                        tableViewer.setChecked(checkedBrowser, true);
                    }
                }
            } catch (Exception ex) {
                // ignore
            }
        }
    });

    search = SWTUtil.createButton(buttonComp, Messages.search);
    data = (GridData) search.getLayoutData();
    data.verticalIndent = 9;
    search.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            final List foundBrowsers = new ArrayList();
            final List existingPaths = WebBrowserUtil.getExternalBrowserPaths();

            // select a target directory for the search
            DirectoryDialog dialog = new DirectoryDialog(getShell());
            dialog.setMessage(Messages.selectDirectory);
            dialog.setText(Messages.directoryDialogTitle);

            String path = dialog.open();
            if (path == null)
                return;

            final File rootDir = new File(path);
            ProgressMonitorDialog pm = new ProgressMonitorDialog(getShell());

            IRunnableWithProgress r = new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor) {
                    monitor.beginTask(Messages.searchingTaskName, IProgressMonitor.UNKNOWN);
                    search(rootDir, existingPaths, foundBrowsers, monitor);
                    monitor.done();
                }
            };

            try {
                pm.run(true, true, r);
            } catch (InvocationTargetException ex) {
                Trace.trace(Trace.SEVERE, "Invocation Exception occured running monitor: " //$NON-NLS-1$
                        + ex);
            } catch (InterruptedException ex) {
                Trace.trace(Trace.SEVERE, "Interrupted exception occured running monitor: " //$NON-NLS-1$
                        + ex);
                return;
            }

            if (pm.getProgressMonitor().isCanceled())
                return;

            List browsersToCreate = foundBrowsers;

            if (browsersToCreate == null) // cancelled
                return;

            if (browsersToCreate.isEmpty()) { // no browsers found
                WebBrowserUtil.openMessage(Messages.searchingNoneFound);
                return;
            }

            Iterator iterator = browsersToCreate.iterator();
            while (iterator.hasNext()) {
                IBrowserDescriptorWorkingCopy browser2 = (IBrowserDescriptorWorkingCopy) iterator.next();
                browser2.save();
            }
            tableViewer.refresh();

            if (checkedBrowser != null)
                tableViewer.setChecked(checkedBrowser, true);
        }
    });

    tableViewer.addCheckStateListener(new ICheckStateListener() {
        public void checkStateChanged(CheckStateChangedEvent e) {
            checkNewDefaultBrowser(e.getElement());
            checkedBrowser = (IBrowserDescriptor) e.getElement();
        }
    });

    /*external.addSelectionListener(new SelectionListener() {
       public void widgetSelected(SelectionEvent e) {
    boolean sel = !tableViewer.getSelection().isEmpty();
    edit.setEnabled(sel);
    remove.setEnabled(sel);
       }
            
       public void widgetDefaultSelected(SelectionEvent e) {
    // ignore
       }
    });*/
    internal.setSelection(WebBrowserPreference.getBrowserChoice() == WebBrowserPreference.INTERNAL);
    external.setSelection(WebBrowserPreference.getBrowserChoice() == WebBrowserPreference.EXTERNAL);

    //boolean sel = !tableViewer.getSelection().isEmpty();
    IStructuredSelection sele = ((IStructuredSelection) tableViewer.getSelection());
    boolean sel = sele.getFirstElement() != null
            && !(sele.getFirstElement() instanceof SystemBrowserDescriptor);
    edit.setEnabled(sel);
    remove.setEnabled(sel);

    Dialog.applyDialogFont(composite);

    return composite;
}

From source file:org.eclipse.birt.chart.integration.wtp.ui.internal.actions.ImportChartRuntimeAction.java

License:Open Source License

/**
 * action to import birt runtime component
 * //from  w  w w . j a  v  a 2 s .c o m
 * @param window
 * @param isClear
 * @throws Exception
 */
protected void doImport(IWorkbenchWindow window, boolean isClear) throws Exception {
    ProgressMonitorDialog monitor = null;
    try {
        // web content folder
        IPath webContentPath = BirtWizardUtil.getWebContentPath(project);

        // do import birt runtime
        monitor = new ProgressMonitorDialog(window.getShell());
        monitor.open();

        // check whether clears the old birt runtime files
        if (isClear)
            doClearAction(webContentPath, monitor.getProgressMonitor());

        // import birt runtime component
        BirtWizardUtil.doImports(project, null, webContentPath, monitor.getProgressMonitor(),
                new ImportOverwriteQuery(monitor.getShell()));

        // process defined folders
        BirtWizardUtil.processCheckFolder(properties, project, webContentPath.toFile().getName(),
                monitor.getProgressMonitor());

        // configurate web.xml
        processConfiguration(monitor.getProgressMonitor(), monitor.getShell());
    } finally {
        // closs dialog
        if (monitor != null) {
            monitor.close();
        }
    }
}

From source file:org.eclipse.cdt.cpp.ui.internal.actions.ReplicateFromAction.java

License:Open Source License

public void run() {
    ModelInterface api = ModelInterface.getInstance();
    ChooseProjectDialog dlg = new ChooseProjectDialog("Choose a Project To Replicate From",
            api.findWorkspaceElement());

    dlg.open();//from w ww.ja va  2 s . c  om

    if (dlg.getReturnCode() == dlg.OK) {
        List projects = dlg.getSelected();

        ReplicateFromOperation op = new ReplicateFromOperation(_subject, projects, api);
        ProgressMonitorDialog progressDlg = new ProgressMonitorDialog(api.getDummyShell());
        try {
            progressDlg.run(true, true, op);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        IProgressMonitor monitor = progressDlg.getProgressMonitor();
        if (monitor.isCanceled()) {
            System.out.println("cancelled");
        }

    }
}

From source file:org.eclipse.compare.internal.AddFromHistoryAction.java

License:Open Source License

protected void run(ISelection selection) {

    ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME);
    String title = Utilities.getString(bundle, "title"); //$NON-NLS-1$

    Shell parentShell = CompareUIPlugin.getShell();
    AddFromHistoryDialog dialog = null;/*  www.ja  v a2  s  .c om*/

    Object[] s = Utilities.getResources(selection);

    for (int i = 0; i < s.length; i++) {
        Object o = s[i];
        if (o instanceof IContainer) {
            IContainer container = (IContainer) o;

            ProgressMonitorDialog pmdialog = new ProgressMonitorDialog(parentShell);
            IProgressMonitor pm = pmdialog.getProgressMonitor();
            IFile[] states = null;
            try {
                states = container.findDeletedMembersWithHistory(IResource.DEPTH_INFINITE, pm);
            } catch (CoreException ex) {
                pm.done();
            }

            // There could be a recently deleted file at the same path as
            // the container. If such a file is the only one to restore, we
            // should not suggest to restore it, so set states to null.
            if (states.length == 1 && states[0].getFullPath().equals(container.getFullPath()))
                states = null;

            if (states == null || states.length <= 0) {
                String msg = Utilities.getString(bundle, "noLocalHistoryError"); //$NON-NLS-1$
                MessageDialog.openInformation(parentShell, title, msg);
                return;
            }

            if (dialog == null) {
                dialog = new AddFromHistoryDialog(parentShell, bundle);
                dialog.setHelpContextId(ICompareContextIds.ADD_FROM_HISTORY_DIALOG);
            }

            if (dialog.select(container, states)) {
                AddFromHistoryDialog.HistoryInput[] selected = dialog.getSelected();
                if (selected != null && selected.length > 0) {
                    try {
                        updateWorkspace(bundle, parentShell, selected);
                    } catch (InterruptedException x) {
                        // Do nothing. Operation has been canceled by user.
                    } catch (InvocationTargetException x) {
                        String reason = x.getTargetException().getMessage();
                        MessageDialog.openError(parentShell, title,
                                Utilities.getFormattedString(bundle, "replaceError", reason)); //$NON-NLS-1$
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.debug.examples.ui.pda.adapters.PDAVirtualFindAction.java

License:Open Source License

public void run() {
    final VirtualViewerListener listener = new VirtualViewerListener();
    VirtualTreeModelViewer virtualViewer = initVirtualViewer(fClientViewer, listener);

    ProgressMonitorDialog dialog = new TimeTriggeredProgressMonitorDialog(fClientViewer.getControl().getShell(),
            500);// ww  w . j a v a2 s  .  c o m
    final IProgressMonitor monitor = dialog.getProgressMonitor();
    dialog.setCancelable(true);

    try {
        dialog.run(true, true, new IRunnableWithProgress() {
            public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException {
                synchronized (listener) {
                    listener.fProgressMonitor = m;
                    listener.fProgressMonitor.beginTask(DebugUIPlugin.removeAccelerators(getText()),
                            listener.fRemainingUpdatesCount);
                }

                while ((!listener.fLabelUpdatesComplete || !listener.fViewerUpdatesComplete)
                        && !listener.fProgressMonitor.isCanceled()) {
                    Thread.sleep(1);
                }
                synchronized (listener) {
                    listener.fProgressMonitor = null;
                }
            }
        });
    } catch (InvocationTargetException e) {
        DebugUIPlugin.log(e);
        return;
    } catch (InterruptedException e) {
        return;
    }

    VirtualItem root = virtualViewer.getTree();
    if (!monitor.isCanceled()) {
        List list = new ArrayList();
        collectAllChildren(root, list);
        FindLabelProvider labelProvider = new FindLabelProvider(virtualViewer, list);
        VirtualItem result = performFind(list, labelProvider);
        if (result != null) {
            setSelectionToClient(virtualViewer, labelProvider, result);
        }
    }

    virtualViewer.removeLabelUpdateListener(listener);
    virtualViewer.removeViewerUpdateListener(listener);
    virtualViewer.dispose();
}

From source file:org.eclipse.debug.internal.ui.viewers.model.VirtualCopyToClipboardActionDelegate.java

License:Open Source License

/**
 * Do the specific action using the current selection.
 * @param action Action that is running.
 *//*from  ww  w  .ja v  a 2  s .c  om*/
public void run(final IAction action) {
    if (fClientViewer.getSelection().isEmpty()) {
        writeBufferToClipboard(new StringBuffer(""));
        return;
    }

    final VirtualViewerListener listener = new VirtualViewerListener();
    ItemsToCopyVirtualItemValidator validator = new ItemsToCopyVirtualItemValidator();
    VirtualTreeModelViewer virtualViewer = initVirtualViewer(fClientViewer, listener, validator);

    ProgressMonitorDialog dialog = new TimeTriggeredProgressMonitorDialog(fClientViewer.getControl().getShell(),
            500);
    final IProgressMonitor monitor = dialog.getProgressMonitor();
    dialog.setCancelable(true);

    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException {
            synchronized (listener) {
                listener.fProgressMonitor = m;
                listener.fProgressMonitor.beginTask(DebugUIPlugin.removeAccelerators(getAction().getText()),
                        listener.fRemainingUpdatesCount);
            }

            while ((!listener.fLabelUpdatesComplete || !listener.fViewerUpdatesComplete)
                    && !listener.fProgressMonitor.isCanceled()) {
                Thread.sleep(1);
            }
            synchronized (listener) {
                listener.fProgressMonitor = null;
            }
        }
    };
    try {
        dialog.run(true, true, runnable);
    } catch (InvocationTargetException e) {
        DebugUIPlugin.log(e);
        return;
    } catch (InterruptedException e) {
        return;
    }

    if (!monitor.isCanceled()) {
        copySelectionToClipboard(virtualViewer, validator.fItemsToCopy, listener.fSelectionRootDepth);
    }

    virtualViewer.removeLabelUpdateListener(listener);
    virtualViewer.removeViewerUpdateListener(listener);
    virtualViewer.dispose();
}