Example usage for org.eclipse.jface.dialogs MessageDialog WARNING

List of usage examples for org.eclipse.jface.dialogs MessageDialog WARNING

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs MessageDialog WARNING.

Prototype

int WARNING

To view the source code for org.eclipse.jface.dialogs MessageDialog WARNING.

Click Source Link

Document

Constant for the warning image, or a simple dialog with the warning image and a single OK button (value 4).

Usage

From source file:org.cfeclipse.cfml.editors.CFMLEditor.java

License:Open Source License

public void createPartControl(Composite parent) {

    /* TODO: hook this up to a button
     * Check the preferences, and add a toolbar */
    if (getPreferenceStore().getBoolean(EditorPreferenceConstants.P_SHOW_EDITOR_TOOLBAR)) {
        CFMLEditorToolbar editorWithToolbar = new CFMLEditorToolbar();
        parent = editorWithToolbar.getTabs(parent);
    }//from www .j a v  a  2  s .c  o  m

    super.createPartControl(parent);
    IKeyBindingService service = this.getSite().getKeyBindingService();
    service.setScopes(new String[] { EDITOR_CONTEXT });
    this.setBackgroundColor();
    //      this.fSourceViewerDecorationSupport.install(getPreferenceStore());

    ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();

    this.fProjectionSupport = new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
    this.fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error");
    this.fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.task");
    this.fProjectionSupport.addSummarizableAnnotationType("org.cfeclipse.cfml.parserProblemAnnotation");
    this.fProjectionSupport.addSummarizableAnnotationType("org.cfeclipse.cfml.parserWarningAnnotation");
    this.fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning");
    this.fProjectionSupport.addSummarizableAnnotationType("org.cfeclipse.cfml.occurrenceAnnotation");

    this.fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
        public IInformationControl createInformationControl(Shell shell) {

            IInformationControl returnIInformationControl = new DefaultInformationControl(shell);
            return returnIInformationControl;
        }
    });
    this.fProjectionSupport.install();
    // ensure decoration support has been created and configured.
    getSourceViewerDecorationSupport(getSourceViewer());
    //Object lay = parent.getLayoutData();

    //System.out.println(lay.getClass());

    //one.setToolTipText("This is tab one");
    //  one.setControl(getTabOneControl(tabFolder));

    //two.setToolTipText("This is tab two");
    //  two.setControl(getTabTwoControl(tabFolder));

    //three.setToolTipText("This is tab three");
    //  three.setControl(getTabThreeControl(tabFolder));

    //four.setToolTipText("This is tab four");

    projectionViewer.doOperation(ProjectionViewer.TOGGLE);

    this.foldingSetter = new CodeFoldingSetter(this);
    this.foldingSetter.docChanged(true);

    // TODO: If we set this directly the projection fViewer loses track of the
    // line numbers.
    // Need to create a class that extends projectionViewer so we can implement
    // wrapped
    // line tracking.
    //projectionViewer.getTextWidget().setWordWrap(true);

    try {
        if (isEditorInputReadOnly()) {

            if (getPreferenceStore().getBoolean(EditorPreferenceConstants.P_WARN_READ_ONLY_FILES)
                    && !getPreferenceStore().getBoolean("MAKE_WRITABLE")) {

                String[] labels = new String[2];
                labels[0] = "OK";
                labels[1] = "Make writable";
                MessageDialogWithToggle msg = new MessageDialogWithToggle(this.getEditorSite().getShell(),
                        "Warning!", null,
                        "You are opening a read only file. You will not be able to make or save any changes.",
                        MessageDialog.WARNING, labels, 0, "Don't show this warning in future.", false);
                //MessageBox msg = new MessageBox(this.getEditorSite().getShell());
                //msg.setText("Warning!");
                //msg.setMessage("You are opening a read only file. You will not be
                // able to make or save any changes.");
                if (msg.open() == 0) {
                    if (msg.getToggleState()) {
                        // Don't show warning in future.
                        getPreferenceStore().setValue(EditorPreferenceConstants.P_WARN_READ_ONLY_FILES, false);
                    }
                } else {
                    if (msg.getToggleState()) {
                        // Don't show warning in future.
                        getPreferenceStore().setValue("MAKE_WRITABLE", true);
                    }
                    setReadOnly(false);
                }
            } else if (getPreferenceStore().getBoolean("MAKE_WRITABLE")) {
                setReadOnly(false);
            }
        }

        //if (this.DEBUG) {
        //IWorkbenchPage p = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        //System.out.println(p);
        //}

    } catch (Exception e) {

        e.printStackTrace();

    }

    setStatusLine();
    setupSelectionListeners(projectionViewer);

}

From source file:org.cfeclipse.cfml.editors.CFMLEditor.java

License:Open Source License

/**
 * Add menu items based on the tag that was right clicked on... doesnt work as
 * I have no idea how to find out what tag was just clicked on :) seems like
 * perhaps the CFDocument could know...//from   w  w w  .j a  va2s . c o  m
 * 
 * @param menu
 */
protected void addTagSpecificMenuItems(IMenuManager menu) {

    //Find out which version of Eclipse we are running in:
    boolean inEclipse32 = false;
    final String version = System.getProperty("osgi.framework.version"); //$NON-NLS-1$
    if (version != null && version.startsWith("3.2")) //$NON-NLS-1$
    {
        inEclipse32 = true;
    }

    //all this mess is really just to get the offset and a handle to the
    //CFDocument object attached to the Document...
    try {
        final IEditorPart iep = getSite().getPage().getActiveEditor();
        final ITextEditor editor = (ITextEditor) iep;
        final IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());

        final ICFDocument cfd = (ICFDocument) doc;
        final ITextSelection sel = (ITextSelection) editor.getSelectionProvider().getSelection();

        Action act = new Action("Refresh syntax highlighting", null) {
            public void run() {
                try {
                    new CFDocumentSetupParticipant().setup(doc);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        menu.add(act);

        //Add programatically the locate in File Explorer and navigator for Eclipse 3.1 users

        if (!inEclipse32) {

            act = new Action("Show in File Explorer", null) {
                public void run() {
                    LocateInFileSystemAction action = new LocateInFileSystemAction();
                    action.run(null);
                }
            };
            menu.add(act);

            act = new Action("Show in Navigator", null) {
                public void run() {
                    LocateInTreeAction action = new LocateInTreeAction();
                    action.run(null);
                }
            };
            menu.add(act);

        }

        act = new Action("Show partition info", null) {
            public void run() {
                /*
                IEditorPart iep = getSite().getPage().getActiveEditor();
                ITextEditor editor = (ITextEditor) iep;
                IDocument doc = editor.getDocumentProvider().getDocument(
                     editor.getEditorInput());
                        
                ICFDocument cfd = (ICFDocument) doc;
                ITextSelection sel = (ITextSelection) editor.getSelectionProvider()
                     .getSelection();
                     */
                int startpos = sel.getOffset();
                int len = Math.max(sel.getLength(), 1);
                CFEPartitioner partitioner = (CFEPartitioner) cfd.getDocumentPartitioner();
                CFEPartition[] partitioning = partitioner.getCFEPartitions(startpos, startpos + len);
                String info = "Partitioning info from offset " + startpos + " to "
                        + Integer.toString(startpos + len) + "\n\n";
                CFEPartition part = partitioner.findClosestPartition(startpos);
                info += "(Closest partition: " + part.getType() + " = " + part.getTagName() + ")\n";
                for (int i = 0; i < partitioning.length; i++) {
                    info += partitioning[i].getType();
                    info += " starting at ";
                    info += partitioning[i].getOffset();
                    info += " ending at ";
                    info += Integer.toString(partitioning[i].getOffset() + partitioning[i].getLength());
                    if (partitioning[i].getTagName() != null) {
                        info += " (";
                        info += partitioning[i].getTagName();
                        info += ") ";
                    }
                    info += "\n";
                }

                String[] labels = new String[1];
                labels[0] = "OK";
                MessageDialog msg = new MessageDialog(Display.getCurrent().getActiveShell(), "Partition info",
                        null, info, MessageDialog.WARNING, labels, 0);
                msg.open();
            }
        };
        menu.add(act);

        /*
         * TODO: re-write this so the edit this tag action can be called from different places
         * Edit this tag action start
         */
        act = new Action("Edit this tag", null) {
            public void run() {

                EditTagAction eta = new EditTagAction();
                eta.run();

            }
        };

        //Only display if you are at the start tag
        int startpos = sel.getOffset();
        CFEPartitioner partitioner = (CFEPartitioner) cfd.getDocumentPartitioner();
        CFEPartition part = partitioner.findClosestPartition(startpos);
        //         ITypedRegion part = cfd.getDocumentPartitioner(CFDocumentSetupParticipant.CFML_PARTITIONING).getPartition(startpos);

        if (part != null && EditableTags.isEditable(part.getType())) {
            menu.add(act);
        }

        //This is not only for
        act = new Action("Genrate Getters and Setters", null) {
            public void run() {
                InsertGetAndSetAction insertGetSet = new InsertGetAndSetAction();
                insertGetSet.setActiveEditor(null, getSite().getPage().getActiveEditor());
                insertGetSet.run(null);
            }
        };

        /*   TODO: Setup the Generate Getters and Setters, 
         *    This might actually go into the suggest stuff
         *   Add More checks:
         *      1) If we are in a CFC
         *      2) If the cursor is in a cfproperty tag
         *      3) or if we are in a cfset tag who's parent tag is a cfcomponent tag  
         */

        if (getSelectionCursorListener().getSelectedTag() != null
                && getSelectionCursorListener().getSelectedTag().getName().equalsIgnoreCase("cfproperty")) {
            menu.add(act);
        }

        act = new Action("Jump to matching tag", null) {
            public void run() {
                JumpToMatchingTagAction matchTagAction = new JumpToMatchingTagAction();
                matchTagAction.setActiveEditor(null, getSite().getPage().getActiveEditor());
                matchTagAction.run(null);
            }
        };
        menu.add(act);

        /*
         * Start the logic to see if we are in a cfinclude or a cfmodule. get the tag.
         * Added the lines below to check the partition type and thus get the cfincluded file
         */

        DocItem cti = null;
        try {
            cti = cfd.getTagAt(startpos, startpos);
        } catch (Exception e) {
            // do nothing.
        }

        if (cti != null) {

            if (cti instanceof CfmlTagItem && ((CfmlTagItem) cti).matchingItem != null) {

                this.jumpAction.setDocPos(((CfmlTagItem) cti).matchingItem.getEndPosition());
                this.jumpAction.setActiveEditor(null, getSite().getPage().getActiveEditor());
                Action jumpNow = new Action("Jump to end tag",
                        CFPluginImages.getImageRegistry().getDescriptor(CFPluginImages.ICON_FORWARD)) {
                    public void run() {
                        CFMLEditor.this.jumpAction.run(null);
                    }
                };
                menu.add(jumpNow);
            }

            System.out.println(part);
            // this is a bit hokey - there has to be a way to load the
            // action in the xml file then just call it here...
            if (getSelectionCursorListener().getSelectedTag() != null && (getSelectionCursorListener()
                    .getSelectedTag().getName().equalsIgnoreCase("cfinclude")
                    || getSelectionCursorListener().getSelectedTag().getName().equalsIgnoreCase("cfmodule"))) {
                this.gfa.setActiveEditor(null, getSite().getPage().getActiveEditor());

                Action ack = new Action("Open/Create File",
                        CFPluginImages.getImageRegistry().getDescriptor(CFPluginImages.ICON_IMPORT)) {
                    public void run() {

                        CFMLEditor.this.gfa.run(null);
                    }
                };
                menu.add(ack);
            }

        }

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

From source file:org.csstudio.utility.adlconverter.ui.ADLDisplayImporter.java

License:Open Source License

private IFile handelPathAndFile(IPath targetProject, String targetFileName) throws CoreException {
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IPath filePath = targetProject.append(targetFileName.trim());
    if (!workspaceRoot.exists(targetProject)) {
        if (_createFolderAllways) {
            IFolder folder = workspaceRoot.getFolder(targetProject);
            createFolder(folder);//  w w  w  .ja  va2  s .  c o  m
        } else if (_createFolderNever) {
            return null;
        } else {
            String[] dialogButtonsText = new String[] { Messages.ADLDisplayImporter_Dialog_Yes_Button,
                    Messages.ADLDisplayImporter_Dialog_Yes2All_Button,
                    Messages.ADLDisplayImporter_Dialog_No_Button,
                    Messages.ADLDisplayImporter_Dialog_No2All_Button, "cancel" };
            Formatter f = new Formatter();
            f.format("Dir \"%s\" not exist!\r\nCreat this Folder?", targetProject);

            MessageDialog md = new MessageDialog(Display.getCurrent().getActiveShell(),
                    Messages.ADLDisplayImporter_Dialog_Header_Directory_not_exist, null, f.toString(),
                    MessageDialog.WARNING, dialogButtonsText, 0);

            switch (md.open()) {
            case 1:
                _createFolderAllways = true;
                //$FALL-THROUGH$
            case 0:
                IFolder folder = workspaceRoot.getFolder(targetProject);
                createFolder(folder);
                break;
            case 3:
                _createFolderNever = true;
                //$FALL-THROUGH$
            case 2:
                _status = 2;
                return null;
            default:
                _status = 5;
                return null;
            }
        }
    }
    return workspaceRoot.getFile(filePath);
}

From source file:org.dawb.passerelle.actors.ui.MessageSink.java

License:Open Source License

public MessageSink(CompositeEntity container, String name)
        throws NameDuplicationException, IllegalActionException {
    super(container, name);

    visibleChoices.put(MessageDialog.ERROR + "", "ERROR");
    visibleChoices.put(MessageDialog.WARNING + "", "WARNING");
    visibleChoices.put(MessageDialog.INFORMATION + "", "INFORMATION");

    messageType = new StringChoiceParameter(this, "Message Type", new IAvailableChoices() {

        @Override/*from w  w  w.  j  a va 2 s  . com*/
        public Map<String, String> getVisibleChoices() {
            return visibleChoices;
        }

        @Override
        public String[] getChoices() {
            return visibleChoices.keySet().toArray(new String[0]);
        }

    }, SWT.SINGLE);
    messageType.setExpression(MessageDialog.INFORMATION + "");
    registerConfigurableParameter(messageType);

    messageParam = new StringParameter(this, "Message");
    messageParam.setExpression("${message_text}");
    registerConfigurableParameter(messageParam);

    messageTitle = new StringParameter(this, "Message Title");
    messageTitle.setExpression("Error Message");
    registerConfigurableParameter(messageTitle);

    memoryManagementParam.setVisibility(Settable.NONE);
    passModeParameter.setExpression(EXPRESSION_MODE.get(1));
    passModeParameter.setVisibility(Settable.NONE);

    shownMessagePort = PortFactory.getInstance().createOutputPort(this, "shownMessage");

}

From source file:org.dawb.passerelle.common.remote.RemoteWorkbenchImpl.java

License:Open Source License

@Override
public boolean showMessage(final String title, final String message, final int type) {

    if (!PlatformUI.isWorkbenchRunning()) {
        if (type == MessageDialog.ERROR)
            logger.error(title + "> " + message);
        if (type == MessageDialog.WARNING)
            logger.warn(title + "> " + message);
        if (type == MessageDialog.INFORMATION)
            logger.info(title + "> " + message);
        return true;
    }//w  w  w. j  a  v a2 s. co m

    PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

        @Override
        public void run() {
            MessageDialog.open(type, PlatformUI.getWorkbench().getDisplay().getActiveShell(), title, message,
                    SWT.NONE);
        }
    });
    return true;
}

From source file:org.dawnsci.conversion.ui.pages.AlignImagesConversionPage.java

License:Open Source License

@Override
protected void createContentAfterFileChoose(Composite container) {
    Composite controlComp = new Composite(container, SWT.NONE);
    controlComp.setLayout(new GridLayout(2, false));
    controlComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 4, 1));

    // Check type of data and load first image
    if (getSelectedPaths() == null)
        return;/*w  w w  .  j a v a  2 s.  c  o m*/
    String filePath = getSelectedPaths()[0];
    try {
        IDataHolder holder = LoaderServiceHolder.getLoaderService().getData(filePath, new IMonitor.Stub());
        ILazyDataset lazy = holder.getLazyDataset(0);
        int[] shape = lazy.getShape();
        if (lazy.getRank() == 2)
            firstImage = lazy.getSlice(new Slice());
        else
            firstImage = lazy.getSlice(new Slice(0, shape[0], shape[1])).squeeze();
    } catch (Exception e) {
        logger.error("Error loading file:" + e.getMessage());
    }
    Label methodLabel = new Label(controlComp, SWT.NONE);
    methodLabel.setText("Align method:");
    alignMethodCombo = new Combo(controlComp, SWT.READ_ONLY);
    alignMethodCombo.setItems(new String[] { "With ROI", "Affine transform" });
    alignMethodCombo.setToolTipText(
            "Choose the method of alignement: with a region of interest or without using an affine transformation");
    alignMethodCombo.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            alignState = AlignMethod.getAlignMethod(alignMethodCombo.getSelectionIndex());
            IRegion region = getRegion(ROI_NAME);
            if (region != null) {
                boolean withROI = alignState == AlignMethod.WITH_ROI;
                region.setVisible(withROI);
                radioButtons.get(0).setEnabled(withROI);
                radioButtons.get(1).setEnabled(withROI);
            }
        }
    });
    // set default selection
    alignMethodCombo.select(AlignMethod.WITH_ROI.getIdx());

    Label modeLabel = new Label(controlComp, SWT.NONE);
    modeLabel.setText("Mode:");
    final Composite modeComp = new Composite(controlComp, SWT.NONE);
    modeComp.setLayout(new RowLayout());
    modeComp.setToolTipText("Number of columns used for image alignment with ROI");
    Button b;
    radioButtons = new ArrayList<Button>();
    b = new Button(modeComp, SWT.RADIO);
    b.setText("2");
    b.setToolTipText("Use 2 columns to implement image alignment with ROI");
    b.addSelectionListener(radioListener);
    radioButtons.add(b);
    b = new Button(modeComp, SWT.RADIO);
    b.setText("4");
    b.setToolTipText("Use 4 columns to implement image alignment with ROI");
    b.addSelectionListener(radioListener);
    radioButtons.add(b);
    b.setSelection(true);

    align = new Button(controlComp, SWT.NONE);
    align.setText("Align");
    align.setToolTipText("Run the alignment calculation with the corresponding alignment type chosen");
    GridData gd = new GridData(SWT.CENTER, SWT.CENTER, true, false, 2, 1);
    align.setLayoutData(gd);
    align.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (alignState == AlignMethod.WITH_ROI) {
                // if there is a ROI on the plotting system we can perform an align calculation
                IRegion region = getRegion(ROI_NAME);
                if (region != null && region.getROI() instanceof RectangularROI) {
                    align((RectangularROI) region.getROI());
                } else {
                    String[] dialogButtonLabel = { "OK" };
                    Image warning = new Image(Display.getCurrent(),
                            getClass().getResourceAsStream("/icons/warning_small.gif"));
                    MessageDialog messageDialog = new MessageDialog(Display.getCurrent().getActiveShell(),
                            "Error running image alignment", warning, "", MessageDialog.WARNING,
                            dialogButtonLabel, 0);
                    messageDialog.open();
                }
            } else if (alignState == AlignMethod.AFFINE_TRANSFORM) {
                align(null);
            }
            setPageComplete(true);
            getWizard().getContainer().updateButtons();
        }
    });

    Group sliderGroup = new Group(container, SWT.NONE);
    sliderGroup.setText("Image stack slicing");
    sliderGroup.setToolTipText(
            "Use the slider to browse through the original " + "loaded images or through the corrected images");
    sliderGroup.setLayout(new GridLayout(1, false));
    sliderGroup.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 4, 1));

    sliderButtons = new ArrayList<Button>();
    b = new Button(sliderGroup, SWT.RADIO);
    b.setText("Original Data");
    b.setToolTipText("Show original stack of images");
    b.addSelectionListener(sliderListener);
    sliderButtons.add(b);
    b.setSelection(true);
    b = new Button(sliderGroup, SWT.RADIO);
    b.setText("Aligned Data");
    b.setToolTipText("Show aligned stack of images");
    b.addSelectionListener(sliderListener);
    sliderButtons.add(b);
    sliderButtons.get(1).setEnabled(false);

    scaleProgress = new Scale(sliderGroup, SWT.HORIZONTAL);
    scaleProgress.setPageIncrement(1);
    scaleProgress.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            int p = scaleProgress.getSelection();
            if (p != currentPosition) {
                currentPosition = p;
                if (showCorrected) {
                    if (aligned != null && aligned.size() > 0 && p < aligned.size()) {
                        plotSystem.updatePlot2D(aligned.get(p), null, null);
                    }
                } else {
                    if (data != null && data.size() > 0 && p < data.size())
                        plotSystem.updatePlot2D(data.get(p), null, null);
                }
            }
        }
    });
    scaleProgress.setLayoutData(new GridData(SWT.FILL, SWT.LEFT, true, false));
    if (data != null) {
        scaleProgress.setMaximum(data.size());
        scaleProgress.redraw();
    }

    Composite plotComp = new Composite(container, SWT.NONE);
    plotComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1));
    plotComp.setLayout(new GridLayout(1, false));

    Composite subComp = new Composite(plotComp, SWT.NONE);
    subComp.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
    subComp.setLayout(new GridLayout(2, false));

    Label description = new Label(subComp, SWT.WRAP);
    description.setText("Press 'Align' to register the stack of images loaded then "
            + "press 'Finish' to save all aligned images in the output folder of your choice.");
    description.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    try {
        plotSystem = PlottingFactory.createPlottingSystem();
        plotSystem.createPlotPart(plotComp, "Preprocess", null, PlotType.IMAGE, null);
        plotSystem.getPlotComposite().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        if (firstImage != null && firstImage.getRank() == 2)
            plotSystem.createPlot2D(firstImage, null, null);
        plotSystem.setKeepAspect(true);
        createRegion(firstImage, ROI_NAME);
    } catch (Exception e) {
        logger.error("Error creating the plotting system:" + e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.eclipse.andmore.AndmoreAndroidPlugin.java

License:Open Source License

/**
 * Checks the location of the SDK in the prefs is valid.
 * If it is not, display a warning dialog to the user and try to display
 * some useful link to fix the situation (setup the preferences, perform an
 * update, etc.)/*  w w  w. j  av  a2 s  .c om*/
 *
 * @return True if the SDK location points to an SDK.
 *  If false, the user has already been presented with a modal dialog explaining that.
 */
public boolean checkSdkLocationAndId() {
    String sdkLocation = AdtPrefs.getPrefs().getOsSdkFolder();

    return checkSdkLocationAndId(sdkLocation, new CheckSdkErrorHandler() {
        private String mTitle = "Android SDK";

        /**
         * Handle an error, which is the case where the check did not find any SDK.
         * This returns false to {@link AndmoreAndroidPlugin#checkSdkLocationAndId()}.
         */
        @Override
        public boolean handleError(Solution solution, String message) {
            displayMessage(solution, message, MessageDialog.ERROR);
            return false;
        }

        /**
         * Handle an warning, which is the case where the check found an SDK
         * but it might need to be repaired or is missing an expected component.
         *
         * This returns true to {@link AndmoreAndroidPlugin#checkSdkLocationAndId()}.
         */
        @Override
        public boolean handleWarning(Solution solution, String message) {
            displayMessage(solution, message, MessageDialog.WARNING);
            return true;
        }

        private void displayMessage(final Solution solution, final String message, final int dialogImageType) {
            final Display disp = getDisplay();
            disp.asyncExec(new Runnable() {
                @Override
                public void run() {
                    Shell shell = disp.getActiveShell();
                    if (shell == null) {
                        shell = AndmoreAndroidPlugin.getShell();
                    }
                    if (shell == null) {
                        return;
                    }

                    String customLabel = null;
                    switch (solution) {
                    case OPEN_ANDROID_PREFS:
                        customLabel = "Open Preferences";
                        break;
                    case OPEN_P2_UPDATE:
                        customLabel = "Check for Updates";
                        break;
                    case OPEN_SDK_MANAGER:
                        customLabel = "Open SDK Manager";
                        break;
                    default:
                        break;
                    }

                    String btnLabels[] = new String[customLabel == null ? 1 : 2];
                    btnLabels[0] = customLabel;
                    btnLabels[btnLabels.length - 1] = IDialogConstants.CLOSE_LABEL;

                    MessageDialog dialog = new MessageDialog(shell, // parent
                            mTitle, null, // dialogTitleImage
                            message, dialogImageType, btnLabels, btnLabels.length - 1);
                    int index = dialog.open();

                    if (customLabel != null && index == 0) {
                        switch (solution) {
                        case OPEN_ANDROID_PREFS:
                            openAndroidPrefs();
                            break;
                        case OPEN_P2_UPDATE:
                            openP2Update();
                            break;
                        case OPEN_SDK_MANAGER:
                            openSdkManager();
                            break;
                        default:
                            break;
                        }
                    }
                }
            });
        }

        private void openSdkManager() {
            // Open the standalone external SDK Manager since we know
            // that ADT on Windows is bound to be locking some SDK folders.
            //
            // Also when this is invoked because SdkManagerAction.run() fails, this
            // test will fail and we'll fallback on using the internal one.
            if (SdkManagerAction.openExternalSdkManager()) {
                return;
            }

            // Otherwise open the regular SDK Manager bundled within ADT
            if (!SdkManagerAction.openAdtSdkManager()) {
                // We failed because the SDK location is undefined. In this case
                // let's open the preferences instead.
                openAndroidPrefs();
            }
        }

        private void openP2Update() {
            Display disp = getDisplay();

            disp.asyncExec(new Runnable() {
                @Override
                public void run() {
                    String cmdId = "org.eclipse.equinox.p2.ui.sdk.update"; //$NON-NLS-1$
                    IWorkbench wb = PlatformUI.getWorkbench();
                    if (wb == null) {
                        return;
                    }

                    ICommandService cs = (ICommandService) wb.getService(ICommandService.class);
                    IHandlerService is = (IHandlerService) wb.getService(IHandlerService.class);
                    if (cs == null || is == null) {
                        return;
                    }

                    Command cmd = cs.getCommand(cmdId);
                    if (cmd != null && cmd.isDefined()) {
                        try {
                            is.executeCommand(cmdId, null/*event*/);
                        } catch (Exception ignore) {
                            AndmoreAndroidPlugin.log(ignore, "Failed to execute command %s", cmdId);
                        }
                    }
                }
            });
        }

        private void openAndroidPrefs() {
            PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getDisplay().getActiveShell(),
                    "org.eclipse.andmore.preferences.main", //$NON-NLS-1$ preferencePageId
                    null, // displayedIds
                    null); // data
            dialog.open();
        }
    });
}

From source file:org.eclipse.andmore.android.emulator.service.reset.ResetServiceHandler.java

License:Apache License

@Override
public IStatus singleInit(List<IInstance> instances) {
    int reset = EclipseUtils.showInformationDialog(EmulatorNLS.GEN_Warning,
            EmulatorNLS.QUESTION_AndroidEmulatorReseter_ConfirmationText,
            new String[] { EmulatorNLS.QUESTION_AndroidEmulatorReseter_Yes,
                    EmulatorNLS.QUESTION_AndroidEmulatorReseter_No },
            MessageDialog.WARNING);
    userAgreed = reset == Window.OK;

    return Status.OK_STATUS;
}

From source file:org.eclipse.andmore.traceview.editors.TraceviewEditor.java

License:Apache License

@Override
public void doSaveAs() {
    Shell shell = getSite().getShell();//  w w w.j a  va  2  s . c o m
    final IEditorInput input = getEditorInput();

    final IEditorInput newInput;

    if (input instanceof FileEditorInput) {
        // the file is part of the current workspace
        FileEditorInput fileEditorInput = (FileEditorInput) input;
        SaveAsDialog dialog = new SaveAsDialog(shell);

        IFile original = fileEditorInput.getFile();
        if (original != null) {
            dialog.setOriginalFile(original);
        }

        dialog.create();

        if (original != null && !original.isAccessible()) {
            String message = String.format("The original file ''%s'' has been deleted or is not accessible.",
                    original.getName());
            dialog.setErrorMessage(null);
            dialog.setMessage(message, IMessageProvider.WARNING);
        }

        if (dialog.open() == Window.CANCEL) {
            return;
        }

        IPath filePath = dialog.getResult();
        if (filePath == null) {
            return;
        }

        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IFile file = workspace.getRoot().getFile(filePath);

        if (copy(shell, fileEditorInput.getURI(), file.getLocationURI()) == null) {
            return;
        }

        try {
            file.refreshLocal(IResource.DEPTH_ZERO, null);
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        newInput = new FileEditorInput(file);
        setInput(newInput);
        setPartName(newInput.getName());
    } else if (input instanceof FileStoreEditorInput) {
        // the file is not part of the current workspace
        FileStoreEditorInput fileStoreEditorInput = (FileStoreEditorInput) input;
        FileDialog dialog = new FileDialog(shell, SWT.SAVE);
        IPath oldPath = URIUtil.toPath(fileStoreEditorInput.getURI());
        if (oldPath != null) {
            dialog.setFileName(oldPath.lastSegment());
            dialog.setFilterPath(oldPath.toOSString());
        }

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

        // Check whether file exists and if so, confirm overwrite
        final File localFile = new File(path);
        if (localFile.exists()) {
            MessageDialog overwriteDialog = new MessageDialog(shell, "Save As", null,
                    String.format("%s already exists.\nDo you want to replace it?", path),
                    MessageDialog.WARNING,
                    new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 1); // 'No'
            // is
            // the
            // default
            if (overwriteDialog.open() != Window.OK) {
                return;
            }
        }

        IFileStore destFileStore = copy(shell, fileStoreEditorInput.getURI(), localFile.toURI());
        if (destFileStore != null) {
            IFile file = getWorkspaceFile(destFileStore);
            if (file != null) {
                newInput = new FileEditorInput(file);
            } else {
                newInput = new FileStoreEditorInput(destFileStore);
            }
            setInput(newInput);
            setPartName(newInput.getName());
        }
    }
}

From source file:org.eclipse.b3.beelang.ui.xtext.linked.ExtLinkedXtextEditor.java

License:Open Source License

@Override
protected void performSaveAs(IProgressMonitor progressMonitor) {

    Shell shell = getSite().getShell();/*from w w w . ja  va  2 s.co m*/
    final IEditorInput input = getEditorInput();

    // Customize save as if the file is linked, and it is in the special external link project
    //
    if (input instanceof IFileEditorInput && ((IFileEditorInput) input).getFile().isLinked()
            && ((IFileEditorInput) input).getFile().getProject().getName()
                    .equals(ExtLinkedFileHelper.AUTOLINK_PROJECT_NAME)) {
        final IEditorInput newInput;
        IDocumentProvider provider = getDocumentProvider();

        // 1. If file is "untitled" suggest last save location
        // 2. ...otherwise use the file's location (i.e. likely to be a rename in same folder)
        // 3. If a "last save location" is unknown, use user's home
        //
        String suggestedName = null;
        String suggestedPath = null;
        {
            // is it "untitled"
            java.net.URI uri = ((IURIEditorInput) input).getURI();
            String tmpProperty = null;
            try {
                tmpProperty = ((IFileEditorInput) input).getFile()
                        .getPersistentProperty(TmpFileStoreEditorInput.UNTITLED_PROPERTY);
            } catch (CoreException e) {
                // ignore - tmpProperty will be null
            }
            boolean isUntitled = tmpProperty != null && "true".equals(tmpProperty);

            // suggested name
            IPath oldPath = URIUtil.toPath(uri);
            // TODO: input.getName() is probably always correct
            suggestedName = isUntitled ? input.getName() : oldPath.lastSegment();

            // suggested path
            try {
                suggestedPath = isUntitled
                        ? ((IFileEditorInput) input).getFile().getWorkspace().getRoot()
                                .getPersistentProperty(LAST_SAVEAS_LOCATION)
                        : oldPath.toOSString();
            } catch (CoreException e) {
                // ignore, suggestedPath will be null
            }

            if (suggestedPath == null) {
                // get user.home
                suggestedPath = System.getProperty("user.home");
            }
        }
        FileDialog dialog = new FileDialog(shell, SWT.SAVE);
        if (suggestedName != null)
            dialog.setFileName(suggestedName);
        if (suggestedPath != null)
            dialog.setFilterPath(suggestedPath);

        dialog.setFilterExtensions(new String[] { "*.b3", "*.*" });
        String path = dialog.open();
        if (path == null) {
            if (progressMonitor != null)
                progressMonitor.setCanceled(true);
            return;
        }

        // Check whether file exists and if so, confirm overwrite
        final File localFile = new File(path);
        if (localFile.exists()) {
            MessageDialog overwriteDialog = new MessageDialog(shell, "Save As", null,
                    path + " already exists.\nDo you want to replace it?", MessageDialog.WARNING,
                    new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 1); // 'No' is the default
            if (overwriteDialog.open() != Window.OK) {
                if (progressMonitor != null) {
                    progressMonitor.setCanceled(true);
                    return;
                }
            }
        }

        IFileStore fileStore;
        try {
            fileStore = EFS.getStore(localFile.toURI());
        } catch (CoreException ex) {
            EditorsPlugin.log(ex.getStatus());
            String title = "Problems During Save As...";
            String msg = "Save could not be completed. " + ex.getMessage();
            MessageDialog.openError(shell, title, msg);
            return;
        }

        IFile file = getWorkspaceFile(fileStore);
        if (file != null)
            newInput = new FileEditorInput(file);
        else {
            IURIEditorInput uriInput = new FileStoreEditorInput(fileStore);
            java.net.URI uri = uriInput.getURI();
            IFile linkedFile = ExtLinkedFileHelper.obtainLink(uri, false);

            newInput = new FileEditorInput(linkedFile);
        }

        if (provider == null) {
            // editor has been closed while the dialog was open
            return;
        }

        boolean success = false;
        try {

            provider.aboutToChange(newInput);
            provider.saveDocument(progressMonitor, newInput, provider.getDocument(input), true);
            success = true;

        } catch (CoreException x) {
            final IStatus status = x.getStatus();
            if (status == null || status.getSeverity() != IStatus.CANCEL) {
                String title = "Problems During Save As...";
                String msg = "Save could not be completed. " + x.getMessage();
                MessageDialog.openError(shell, title, msg);
            }
        } finally {
            provider.changed(newInput);
            if (success)
                setInput(newInput);
            // the linked file must be removed (esp. if it is an "untitled" link).
            ExtLinkedFileHelper.unlinkInput(((IFileEditorInput) input));
            // remember last saveAs location
            String lastLocation = URIUtil.toPath(((FileEditorInput) newInput).getURI()).toOSString();
            try {
                ((FileEditorInput) newInput).getFile().getWorkspace().getRoot()
                        .setPersistentProperty(LAST_SAVEAS_LOCATION, lastLocation);
            } catch (CoreException e) {
                // ignore
            }
        }

        if (progressMonitor != null)
            progressMonitor.setCanceled(!success);

        return;
    }

    super.performSaveAs(progressMonitor);
}