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

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

Introduction

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

Prototype

public MessageDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage,
        int dialogImageType, int defaultIndex, String... dialogButtonLabels) 

Source Link

Document

Create a message dialog.

Usage

From source file:com.android.ide.eclipse.auidt.internal.assetstudio.CreateAssetSetWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    Map<String, Map<String, BufferedImage>> categories = mConfigureAssetPage.generateImages(false);

    IProject project = mValues.project;//from w w  w  .  j a v  a2  s. c o  m

    // Write out the images into the project
    boolean yesToAll = false;
    mCreatedFiles = new ArrayList<IResource>();

    for (Map<String, BufferedImage> previews : categories.values()) {
        for (Map.Entry<String, BufferedImage> entry : previews.entrySet()) {
            String relativePath = entry.getKey();
            IPath dest = new Path(relativePath);
            IFile file = project.getFile(dest);
            if (file.exists()) {
                // Warn that the file already exists and ask the user what to do
                if (!yesToAll) {
                    MessageDialog dialog = new MessageDialog(null, "File Already Exists", null,
                            String.format("%1$s already exists.\nWould you like to replace it?",
                                    file.getProjectRelativePath().toOSString()),
                            MessageDialog.QUESTION, new String[] {
                                    // Yes will be moved to the end because it's the default
                                    "Yes", "No", "Cancel", "Yes to All" },
                            0);
                    int result = dialog.open();
                    switch (result) {
                    case 0:
                        // Yes
                        break;
                    case 3:
                        // Yes to all
                        yesToAll = true;
                        break;
                    case 1:
                        // No
                        continue;
                    case SWT.DEFAULT:
                    case 2:
                        // Cancel
                        return false;
                    }
                }

                try {
                    file.delete(true, new NullProgressMonitor());
                } catch (CoreException e) {
                    AdtPlugin.log(e, null);
                }
            }

            NewXmlFileWizard.createWsParentDirectory(file.getParent());
            BufferedImage image = entry.getValue();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            try {
                ImageIO.write(image, "PNG", stream); //$NON-NLS-1$
                byte[] bytes = stream.toByteArray();
                InputStream is = new ByteArrayInputStream(bytes);
                file.create(is, true /*force*/, null /*progress*/);
                mCreatedFiles.add(file);
            } catch (IOException e) {
                AdtPlugin.log(e, null);
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }

            try {
                file.getParent().refreshLocal(1, new NullProgressMonitor());
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }
    }

    // Finally select the files themselves
    selectFiles(project, mCreatedFiles);

    return true;
}

From source file:com.android.ide.eclipse.auidt.internal.editors.layout.gle2.ExportScreenshotAction.java

License:Open Source License

@Override
public void run() {
    Shell shell = AdtPlugin.getDisplay().getActiveShell();

    ImageOverlay imageOverlay = mCanvas.getImageOverlay();
    BufferedImage image = imageOverlay.getAwtImage();
    if (image != null) {
        FileDialog dialog = new FileDialog(shell, SWT.SAVE);
        dialog.setFilterExtensions(new String[] { "*.png" }); //$NON-NLS-1$
        String path = dialog.open();
        if (path != null) {
            if (!path.endsWith(DOT_PNG)) {
                path = path + DOT_PNG;/*from w  w w. j a va2  s .  com*/
            }
            File file = new File(path);
            if (file.exists()) {
                MessageDialog d = new MessageDialog(null, "File Already Exists", null,
                        String.format("%1$s already exists.\nWould you like to replace it?", path),
                        MessageDialog.QUESTION, new String[] {
                                // Yes will be moved to the end because it's the default
                                "Yes", "No" },
                        0);
                int result = d.open();
                if (result != 0) {
                    return;
                }
            }
            try {
                ImageIO.write(image, "PNG", file); //$NON-NLS-1$
            } catch (IOException e) {
                AdtPlugin.log(e, null);
            }
        }
    } else {
        MessageDialog.openError(shell, "Error", "Image not available");
    }
}

From source file:com.android.ide.eclipse.auidt.internal.editors.layout.gre.ClientRulesEngine.java

License:Open Source License

@Override
public String displayFragmentSourceInput() {
    try {//ww w  .j av a 2 s . c  om
        // Compute a search scope: We need to merge all the subclasses
        // android.app.Fragment and android.support.v4.app.Fragment
        IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
        IProject project = mRulesEngine.getProject();
        final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject != null) {
            IType oldFragmentType = javaProject.findType(CLASS_V4_FRAGMENT);

            // First check to make sure fragments are available, and if not,
            // warn the user.
            IAndroidTarget target = Sdk.getCurrent().getTarget(project);
            // No, this should be using the min SDK instead!
            if (target.getVersion().getApiLevel() < 11 && oldFragmentType == null) {
                // Compatibility library must be present
                MessageDialog dialog = new MessageDialog(Display.getCurrent().getActiveShell(),
                        "Fragment Warning", null,
                        "Fragments require API level 11 or higher, or a compatibility "
                                + "library for older versions.\n\n"
                                + " Do you want to install the compatibility library?",
                        MessageDialog.QUESTION, new String[] { "Install", "Cancel" },
                        1 /* default button: Cancel */);
                int answer = dialog.open();
                if (answer == 0) {
                    if (!AddSupportJarAction.install(project)) {
                        return null;
                    }
                } else {
                    return null;
                }
            }

            // Look up sub-types of each (new fragment class and compatibility fragment
            // class, if any) and merge the two arrays - then create a scope from these
            // elements.
            IType[] fragmentTypes = new IType[0];
            IType[] oldFragmentTypes = new IType[0];
            if (oldFragmentType != null) {
                ITypeHierarchy hierarchy = oldFragmentType.newTypeHierarchy(new NullProgressMonitor());
                oldFragmentTypes = hierarchy.getAllSubtypes(oldFragmentType);
            }
            IType fragmentType = javaProject.findType(CLASS_FRAGMENT);
            if (fragmentType != null) {
                ITypeHierarchy hierarchy = fragmentType.newTypeHierarchy(new NullProgressMonitor());
                fragmentTypes = hierarchy.getAllSubtypes(fragmentType);
            }
            IType[] subTypes = new IType[fragmentTypes.length + oldFragmentTypes.length];
            System.arraycopy(fragmentTypes, 0, subTypes, 0, fragmentTypes.length);
            System.arraycopy(oldFragmentTypes, 0, subTypes, fragmentTypes.length, oldFragmentTypes.length);
            scope = SearchEngine.createJavaSearchScope(subTypes, IJavaSearchScope.SOURCES);
        }

        Shell parent = AdtPlugin.getDisplay().getActiveShell();
        final AtomicReference<String> returnValue = new AtomicReference<String>();
        final AtomicReference<SelectionDialog> dialogHolder = new AtomicReference<SelectionDialog>();
        final SelectionDialog dialog = JavaUI.createTypeDialog(parent, new ProgressMonitorDialog(parent), scope,
                IJavaElementSearchConstants.CONSIDER_CLASSES, false,
                // Use ? as a default filter to fill dialog with matches
                "?", //$NON-NLS-1$
                new TypeSelectionExtension() {
                    @Override
                    public Control createContentArea(Composite parentComposite) {
                        Composite composite = new Composite(parentComposite, SWT.NONE);
                        composite.setLayout(new GridLayout(1, false));
                        Button button = new Button(composite, SWT.PUSH);
                        button.setText("Create New...");
                        button.addSelectionListener(new SelectionAdapter() {
                            @Override
                            public void widgetSelected(SelectionEvent e) {
                                String fqcn = createNewFragmentClass(javaProject);
                                if (fqcn != null) {
                                    returnValue.set(fqcn);
                                    dialogHolder.get().close();
                                }
                            }
                        });
                        return composite;
                    }

                    @Override
                    public ITypeInfoFilterExtension getFilterExtension() {
                        return new ITypeInfoFilterExtension() {
                            @Override
                            public boolean select(ITypeInfoRequestor typeInfoRequestor) {
                                int modifiers = typeInfoRequestor.getModifiers();
                                if (!Flags.isPublic(modifiers) || Flags.isInterface(modifiers)
                                        || Flags.isEnum(modifiers)) {
                                    return false;
                                }
                                return true;
                            }
                        };
                    }
                });
        dialogHolder.set(dialog);

        dialog.setTitle("Choose Fragment Class");
        dialog.setMessage("Select a Fragment class (? = any character, * = any string):");
        if (dialog.open() == IDialogConstants.CANCEL_ID) {
            return null;
        }
        if (returnValue.get() != null) {
            return returnValue.get();
        }

        Object[] types = dialog.getResult();
        if (types != null && types.length > 0) {
            return ((IType) types[0]).getFullyQualifiedName();
        }
    } catch (JavaModelException e) {
        AdtPlugin.log(e, null);
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }
    return null;
}

From source file:com.android.ide.eclipse.gldebugger.ShaderEditor.java

License:Apache License

public void widgetSelected(SelectionEvent e) {
    if (e.getSource() == uploadShader && null != current) {
        uploadShader();/*from w  w  w .  j a  va 2  s.c om*/
        return;
    } else if (e.getSource() == restoreShader && null != current) {
        current.source = styledText.getText();
        styledText.setText(current.originalSource);
        return;
    }

    if (list.getSelectionCount() < 1)
        return;
    if (null != current && !current.source.equals(styledText.getText())) {
        String[] btns = { "&Upload", "&Save", "&Discard" };
        MessageDialog dialog = new MessageDialog(this.getShell(), "Shader Edited", null,
                "Shader source has been edited", MessageDialog.QUESTION, btns, 0);
        int rc = dialog.open();
        if (rc == SWT.DEFAULT || rc == 0)
            uploadShader();
        else if (rc == 1)
            current.source = styledText.getText();
        // else if (rc == 2) do nothing; selection is changing
    }
    String[] details = list.getSelection()[0].split("\\s+");
    final int contextId = Integer.parseInt(details[0], 16);
    int name = Integer.parseInt(details[2]);
    current = mGLFramesView.debugContexts.get(contextId).currentContext.serverShader.shaders.get(name);
    styledText.setText(current.source);
}

From source file:com.android.ide.eclipse.traceview.editors.TraceviewEditor.java

License:Apache License

@Override
public void doSaveAs() {
    Shell shell = getSite().getShell();/*from w  ww .j  a  va  2s . 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(IFile.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:com.appnativa.studio.MessageDialogEx.java

License:Open Source License

/**
 * Convenience method to open a simple dialog as specified by the
 * <code>kind</code> flag.//from  w  w w  .  ja  v  a  2 s . c o m
 *
 * @param kind
 *          the kind of dialog to open, one of {@link #ERROR},
 *          {@link #INFORMATION}, {@link #QUESTION}, {@link #WARNING},
 *          {@link #CONFIRM}, or {@link #QUESTION_WITH_CANCEL}.
 * @param parent
 *          the parent shell of the dialog, or <code>null</code> if none
 * @param title
 *          the dialog's title, or <code>null</code> if none
 * @param message
 *          the message
 * @param style
 *          {@link SWT#NONE} for a default dialog, or {@link SWT#SHEET} for a
 *          dialog with sheet behavior
 * @return the id of the button pressed
 */
public static int openEx(int kind, Shell parent, String title, String message, int style) {
    MessageDialog dialog = new MessageDialog(parent, title, null, message, kind, getButtonLabels(kind), style);

    return dialog.open();
}

From source file:com.aptana.editor.common.preferences.ValidationPreferencePage.java

License:Open Source License

/**
 * If changes don't require a rebuild, return false. Otherwise prompt user and take their answer.
 * /*  w w  w .  j a va 2  s.  c o m*/
 * @return
 */
private boolean rebuild() {
    if (promptForRebuild()) {
        MessageDialog dialog = new MessageDialog(getShell(),
                Messages.ValidationPreferencePage_RebuildDialogTitle, null,
                Messages.ValidationPreferencePage_RebuildDialogMessage, MessageDialog.QUESTION,
                new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0);
        return (dialog.open() == 0);
    }
    return false;
}

From source file:com.aptana.editor.php.ui.preferences.OptionsConfigurationBlock.java

License:Open Source License

protected boolean processChanges(IWorkbenchPreferenceContainer container) {

    IScopeContext currContext = fLookupOrder[0];

    List<Key> changedOptions = new ArrayList<Key>();
    boolean needsBuild = getChanges(currContext, changedOptions);
    if (changedOptions.isEmpty()) {
        hasChanges = false;//from  w w  w . j  a v  a 2  s.c  om
        return true;
    } else {
        hasChanges = true;
    }

    boolean doBuild = false;
    if (needsBuild) {
        String[] strings = getFullBuildDialogStrings(fProject == null);
        if (strings != null) {
            MessageDialog dialog = new MessageDialog(getShell(), strings[0], null, strings[1],
                    MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL,
                            IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL },
                    2);
            int res = dialog.open();
            if (res == 0) {
                doBuild = true;
            } else if (res != 1) {
                return false; // cancel pressed
            }
        }
    }
    if (doBuild) {
        prepareForBuild();
    }
    if (container != null) {
        // no need to apply the changes to the original store: will be done by the page container
        if (doBuild) { // post build
            container.registerUpdateJob(CoreUtility.getBuildJob(fProject));
        }
    } else {
        // apply changes right away
        try {
            fManager.applyChanges();
        } catch (BackingStoreException e) {
            IdeLog.logError(PHPEplPlugin.getDefault(), "Error applying changes", e); //$NON-NLS-1$
            return false;
        }
        if (doBuild) {
            CoreUtility.getBuildJob(fProject).schedule();
        }

    }
    return true;
}

From source file:com.aptana.formatter.ui.preferences.OptionsConfigurationBlock.java

License:Open Source License

protected boolean processChanges(IWorkbenchPreferenceContainer container) {
    IScopeContext currContext = fLookupOrder[0];

    List<PreferenceKey> changedOptions = new ArrayList<PreferenceKey>();
    boolean needsBuild = getChanges(currContext, changedOptions);
    if (changedOptions.isEmpty()) {
        return true;
    }/*  w ww.  j ava2  s.c om*/
    if (needsBuild) {
        int count = getRebuildCount();
        if (count > fRebuildCount) {
            needsBuild = false; // build already requested
            fRebuildCount = count;
        }
    }

    boolean doBuild = false;
    if (needsBuild) {
        IPreferenceChangeRebuildPrompt prompt = getPreferenceChangeRebuildPrompt(fProject == null,
                changedOptions);
        if (prompt != null) {
            MessageDialog dialog = new MessageDialog(getShell(), prompt.getTitle(), null, prompt.getMessage(),
                    MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL,
                            IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL },
                    2);
            int res = dialog.open();
            if (res == 0) {
                doBuild = true;
            } else if (res != 1) {
                return false; // cancel pressed
            }
        }
    }
    if (container != null) {
        // no need to apply the changes to the original store: will be done
        // by the page container
        if (doBuild) { // post build
            incrementRebuildCount();
            for (Job job : createBuildJobs(fProject)) {
                container.registerUpdateJob(job);
            }
        }
    } else {
        // apply changes right away
        try {
            fManager.applyChanges();
        } catch (BackingStoreException e) {
            IdeLog.logError(FormatterUIEplPlugin.getDefault(), e, IDebugScopes.DEBUG);
            return false;
        }
        if (doBuild) {
            for (Job job : createBuildJobs(fProject)) {
                job.schedule();
            }
        }

    }
    return true;
}

From source file:com.aptana.git.ui.internal.actions.DiffHandler.java

License:Open Source License

@Override
protected Object doExecute(ExecutionEvent event) throws ExecutionException {
    Map<String, String> diffs = new HashMap<String, String>();
    List<ChangedFile> changedFiles = getSelectedChangedFiles();
    if (changedFiles == null || changedFiles.isEmpty()) {
        return null;
    }/* w w  w .  j av  a2s. co m*/

    GitRepository repo = getSelectedRepository();
    if (repo == null) {
        return null;
    }
    for (ChangedFile file : changedFiles) {
        if (file == null) {
            continue;
        }

        if (diffs.containsKey(file.getPath())) {
            continue; // already calculated diff...
        }
        String diff = repo.index().diffForFile(file, file.hasStagedChanges(), 3);
        diffs.put(file.getPath(), diff);
    }
    if (diffs.isEmpty()) {
        return null;
    }

    String diff = ""; //$NON-NLS-1$
    try {
        diff = DiffFormatter.toHTML(diffs);
    } catch (Throwable t) {
        IdeLog.logError(GitUIPlugin.getDefault(), "Failed to turn diff into HTML", t, IDebugScopes.DEBUG); //$NON-NLS-1$
    }

    final String finalDiff = diff;
    UIUtils.showMessageDialogFromBgThread(new SafeMessageDialogRunnable() {
        public int openMessageDialog() {
            MessageDialog dialog = new MessageDialog(getShell(), Messages.GitProjectView_GitDiffDialogTitle,
                    null, "", 0, new String[] { IDialogConstants.OK_LABEL }, 0) //$NON-NLS-1$
            {
                @Override
                protected Control createCustomArea(Composite parent) {
                    Browser diffArea = new Browser(parent, SWT.BORDER);
                    GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
                    data.heightHint = 300;
                    diffArea.setLayoutData(data);
                    diffArea.setText(finalDiff);
                    return diffArea;
                }

                @Override
                protected boolean isResizable() {
                    return true;
                }
            };
            return dialog.open();
        }
    });

    return null;
}