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

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

Introduction

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

Prototype

public static boolean openQuestion(Shell parent, String title, String message) 

Source Link

Document

Convenience method to open a simple Yes/No question dialog.

Usage

From source file:com.android.ide.eclipse.adt.internal.editors.draw9patch.Draw9PatchEditor.java

License:Apache License

@Override
public void doSave(final IProgressMonitor monitor) {
    boolean hasNinePatchExtension = mFileName.endsWith(DOT_9PNG);
    boolean doConvert = false;

    if (!hasNinePatchExtension) {
        String patchedName = NinePatchedImage.getNinePatchedFileName(mFileName);
        doConvert = MessageDialog
                .openQuestion(AdtPlugin.getDisplay().getActiveShell(), "Warning",
                        String.format(
                                "The file \"%s\" doesn't seem to be a 9-patch file. \n"
                                        + "Do you want to convert and save as \"%s\" ?",
                                mFileName, patchedName));

        if (doConvert) {
            IFile destFile = mProject.getFile(NinePatchedImage
                    .getNinePatchedFileName(mFileEditorInput.getFile().getProjectRelativePath().toOSString()));
            if (!destFile.exists()) {
                mFileEditorInput = new FileEditorInput(destFile);
                mFileName = mFileEditorInput.getName();
            } else {
                IPath relativePath = null;
                if ((relativePath = showSaveAsDialog()) != null) {
                    mFileEditorInput = new FileEditorInput(
                            ResourcesPlugin.getWorkspace().getRoot().getFile(relativePath));
                    mFileName = mFileEditorInput.getName();
                } else {
                    doConvert = false;/*from  w  w w.  jav  a 2 s. c  o m*/
                }
            }
        }
    }

    if (hasNinePatchExtension || doConvert) {
        ImageLoader loader = new ImageLoader();
        loader.data = new ImageData[] { mNinePatchedImage.getRawImageData() };

        IFile file = mFileEditorInput.getFile();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        loader.save(outputStream, SWT.IMAGE_PNG);
        byte[] byteArray = outputStream.toByteArray();

        try {
            if (file.exists()) {
                file.setContents(new ByteArrayInputStream(byteArray), true, false, monitor);
            } else {
                file.create(new ByteArrayInputStream(byteArray), true, monitor);
            }

            mNinePatchedImage.clearDirtyFlag();

            AdtPlugin.getDisplay().asyncExec(new Runnable() {
                @Override
                public void run() {
                    setPartName(mFileName);
                    firePropertyChange(PROP_DIRTY);
                }
            });
        } catch (CoreException e) {
            AdtPlugin.log(e, null);
        }
    }
}

From source file:com.android.ide.eclipse.adt.internal.editors.draw9patch.Draw9PatchEditor.java

License:Apache License

private static boolean showConvertMessageBox(String fileName) {
    return MessageDialog.openQuestion(AdtPlugin.getDisplay().getActiveShell(), "Warning", String.format(
            "The file \"%s\" doesn't seem to be a 9-patch file. \n" + "Do you want to convert?", fileName));
}

From source file:com.android.ide.eclipse.adt.internal.editors.ui.tree.UiActions.java

License:Apache License

/**
 * Called when the "Remove" button is selected.
 *
 * If the tree has a selection, remove it.
 * This simply deletes the XML node attached to the UI node: when the XML model fires the
 * update event, the tree will get refreshed.
 *//*from w w  w  .  j  a va  2 s.  c om*/
public void doRemove(final List<UiElementNode> nodes, Shell shell) {

    if (nodes == null || nodes.size() == 0) {
        return;
    }

    final int len = nodes.size();

    StringBuilder sb = new StringBuilder();
    for (UiElementNode node : nodes) {
        sb.append("\n- "); //$NON-NLS-1$
        sb.append(node.getBreadcrumbTrailDescription(false /* include_root */));
    }

    if (MessageDialog.openQuestion(shell, len > 1 ? "Remove elements from Android XML" // title
            : "Remove element from Android XML",
            String.format("Do you really want to remove %1$s?", sb.toString()))) {
        commitPendingXmlChanges();
        getRootNode().getEditor().wrapEditXmlModel(new Runnable() {
            @Override
            public void run() {
                UiElementNode previous = null;
                UiElementNode parent = null;

                for (int i = len - 1; i >= 0; i--) {
                    UiElementNode node = nodes.get(i);
                    previous = node.getUiPreviousSibling();
                    parent = node.getUiParent();

                    // delete node
                    node.deleteXmlNode();
                }

                // try to select the last previous sibling or the last parent
                if (previous != null) {
                    selectUiNode(previous);
                } else if (parent != null) {
                    selectUiNode(parent);
                }
            }
        });
    }
}

From source file:com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController.java

License:Open Source License

/**
 * Launches an android app on the device or emulator
 *
 * @param project The project we're launching
 * @param mode the mode in which to launch, one of the mode constants
 *      defined by <code>ILaunchManager</code> - <code>RUN_MODE</code> or
 *      <code>DEBUG_MODE</code>.
 * @param apk the resource to the apk to launch.
 * @param packageName the Android package name of the app
 * @param debugPackageName the Android package name to debug
 * @param debuggable the debuggable value of the app's manifest, or null if not set.
 * @param requiredApiVersionNumber the api version required by the app, or null if none.
 * @param launchAction the action to perform after app sync
 * @param config the launch configuration
 * @param launch the launch object//  www  .j  a  v a2 s. co  m
 */
public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName,
        Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction,
        final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) {

    String message = String.format("Performing %1$s", launchAction.getLaunchDescription());
    AdtPlugin.printToConsole(project, message);

    // create the launch info
    final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName,
            launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor);

    // set the debug mode
    launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE));

    // get the SDK
    Sdk currentSdk = Sdk.getCurrent();
    AvdManager avdManager = currentSdk.getAvdManager();

    // reload the AVDs to make sure we are up to date
    try {
        avdManager.reloadAvds(NullLogger.getLogger());
    } catch (AndroidLocationException e1) {
        // this happens if the AVD Manager failed to find the folder in which the AVDs are
        // stored. This is unlikely to happen, but if it does, we should force to go manual
        // to allow using physical devices.
        config.mTargetMode = TargetMode.MANUAL;
    }

    // get the sdk against which the project is built
    IAndroidTarget projectTarget = currentSdk.getTarget(project);

    // get the min required android version
    ManifestInfo mi = ManifestInfo.get(project);
    final int minApiLevel = mi.getMinSdkVersion();
    final String minApiCodeName = mi.getMinSdkCodeName();
    final AndroidVersion minApiVersion = new AndroidVersion(minApiLevel, minApiCodeName);

    // FIXME: check errors on missing sdk, AVD manager, or project target.

    // device chooser response object.
    final DeviceChooserResponse response = new DeviceChooserResponse();

    /*
     * Launch logic:
     * - Use Last Launched Device/AVD set.
     *       If user requested to use same device for future launches, and the last launched
     *       device/avd is still present, then simply launch on the same device/avd.
     * - Manual Mode
     *       Always display a UI that lets a user see the current running emulators/devices.
     *       The UI must show which devices are compatibles, and allow launching new emulators
     *       with compatible (and not yet running) AVD.
     * - Automatic Way
     *     * Preferred AVD set.
     *           If Preferred AVD is not running: launch it.
     *           Launch the application on the preferred AVD.
     *     * No preferred AVD.
     *           Count the number of compatible emulators/devices.
     *           If != 1, display a UI similar to manual mode.
     *           If == 1, launch the application on this AVD/device.
     * - Launch on multiple devices:
     *     From the currently active devices & emulators, filter out those that cannot run
     *     the app (by api level), and launch on all the others.
     */
    IDevice[] devices = AndroidDebugBridge.getBridge().getDevices();
    if (config.mReuseLastUsedDevice) {
        // check to see if the last used device is still online
        IDevice lastUsedDevice = getDeviceIfOnline(config.mLastUsedDevice, devices);
        if (lastUsedDevice != null) {
            response.setDeviceToUse(lastUsedDevice);
            continueLaunch(response, project, launch, launchInfo, config);
            return;
        }
    }

    if (config.mTargetMode == TargetMode.AUTO) {
        // first check if we have a preferred AVD name, and if it actually exists, and is valid
        // (ie able to run the project).
        // We need to check this in case the AVD was recreated with a different target that is
        // not compatible.
        AvdInfo preferredAvd = null;
        if (config.mAvdName != null) {
            preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/);
        }

        if (preferredAvd != null) {
            IAndroidTarget preferredAvdTarget = preferredAvd.getTarget();
            if (preferredAvdTarget != null && !preferredAvdTarget.getVersion().canRun(minApiVersion)) {
                preferredAvd = null;

                AdtPlugin.printErrorToConsole(project, String.format(
                        "Preferred AVD '%1$s' (API Level: %2$d) cannot run application with minApi %3$s. Looking for a compatible AVD...",
                        config.mAvdName, preferredAvdTarget.getVersion().getApiLevel(), minApiVersion));
            }
        }

        if (preferredAvd != null) {
            // We have a preferred avd that can actually run the application.
            // Now see if the AVD is running, and if so use it, otherwise launch it.

            for (IDevice d : devices) {
                String deviceAvd = d.getAvdName();
                if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) {
                    response.setDeviceToUse(d);

                    AdtPlugin.printToConsole(project, String.format(
                            "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'",
                            config.mAvdName, d));

                    continueLaunch(response, project, launch, launchInfo, config);
                    return;
                }
            }

            // at this point we have a valid preferred AVD that is not running.
            // We need to start it.
            response.setAvdToLaunch(preferredAvd);

            AdtPlugin.printToConsole(project, String.format(
                    "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.",
                    config.mAvdName));

            continueLaunch(response, project, launch, launchInfo, config);
            return;
        }

        // no (valid) preferred AVD? look for one.

        // If the API level requested in the manifest is lower than the current project
        // target, when we will iterate devices/avds later ideally we will want to find
        // a device/avd which target is as close to the manifest as possible (instead of
        // a device which target is the same as the project's target) and use it as the
        // new default.

        if (minApiCodeName != null && minApiLevel < projectTarget.getVersion().getApiLevel()) {
            int maxDist = projectTarget.getVersion().getApiLevel() - minApiLevel;
            IAndroidTarget candidate = null;

            for (IAndroidTarget target : currentSdk.getTargets()) {
                if (target.canRunOn(projectTarget)) {
                    int currDist = target.getVersion().getApiLevel() - minApiLevel;
                    if (currDist >= 0 && currDist < maxDist) {
                        maxDist = currDist;
                        candidate = target;
                        if (maxDist == 0) {
                            // Found a perfect match
                            break;
                        }
                    }
                }
            }

            if (candidate != null) {
                // We found a better SDK target candidate, that is closer to the
                // API level from minSdkVersion than the one currently used by the
                // project. Below (in the for...devices loop) we'll try to find
                // a device/AVD for it.
                projectTarget = candidate;
            }
        }

        HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>();
        boolean hasDevice = false; // if there's 1+ device running, we may force manual mode,
                                   // as we cannot always detect proper compatibility with
                                   // devices. This is the case if the project target is not
                                   // a standard platform
        for (IDevice d : devices) {
            String deviceAvd = d.getAvdName();
            if (deviceAvd != null) { // physical devices return null.
                AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/);
                if (AvdCompatibility.canRun(info, projectTarget,
                        minApiVersion) == AvdCompatibility.Compatibility.YES) {
                    compatibleRunningAvds.put(d, info);
                }
            } else {
                if (projectTarget.isPlatform()) { // means this can run on any device as long
                                                  // as api level is high enough
                    AndroidVersion deviceVersion = Sdk.getDeviceVersion(d);
                    // the deviceVersion may be null if it wasn't yet queried (device just
                    // plugged in or emulator just booting up.
                    if (deviceVersion != null && deviceVersion.canRun(projectTarget.getVersion())) {
                        // device is compatible with project
                        compatibleRunningAvds.put(d, null);
                        continue;
                    }
                } else {
                    // for non project platform, we can't be sure if a device can
                    // run an application or not, since we don't query the device
                    // for the list of optional libraries that it supports.
                }
                hasDevice = true;
            }
        }

        // depending on the number of devices, we'll simulate an automatic choice
        // from the device chooser or simply show up the device chooser.
        if (hasDevice == false && compatibleRunningAvds.size() == 0) {
            // if zero emulators/devices, we launch an emulator.
            // We need to figure out which AVD first.

            // we are going to take the closest AVD. ie a compatible AVD that has the API level
            // closest to the project target.
            AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget, minApiVersion);

            if (defaultAvd != null) {
                response.setAvdToLaunch(defaultAvd);

                AdtPlugin.printToConsole(project,
                        String.format(
                                "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'",
                                defaultAvd.getName()));

                continueLaunch(response, project, launch, launchInfo, config);
                return;
            } else {
                AdtPlugin.printToConsole(project, String.format(
                        "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName()));

                final Display display = AdtPlugin.getDisplay();
                final boolean[] searchAgain = new boolean[] { false };
                // ask the user to create a new one.
                display.syncExec(new Runnable() {
                    @Override
                    public void run() {
                        Shell shell = display.getActiveShell();
                        if (MessageDialog.openQuestion(shell, "Android AVD Error",
                                "No compatible targets were found. Do you wish to add a new Android Virtual Device?")) {
                            AvdManagerAction action = new AvdManagerAction();
                            action.run(null /*action*/);
                            searchAgain[0] = true;
                        }
                    }
                });
                if (searchAgain[0]) {
                    // attempt to reload the AVDs and find one compatible.
                    defaultAvd = findMatchingAvd(avdManager, projectTarget, minApiVersion);

                    if (defaultAvd == null) {
                        AdtPlugin.printErrorToConsole(project,
                                String.format("Still no compatible AVDs with target '%1$s': Aborting launch.",
                                        projectTarget.getName()));
                        stopLaunch(launchInfo);
                    } else {
                        response.setAvdToLaunch(defaultAvd);

                        AdtPlugin.printToConsole(project, String.format(
                                "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName()));

                        continueLaunch(response, project, launch, launchInfo, config);
                        return;
                    }
                }
            }
        } else if (hasDevice == false && compatibleRunningAvds.size() == 1) {
            Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next();
            response.setDeviceToUse(e.getKey());

            // get the AvdInfo, if null, the device is a physical device.
            AvdInfo avdInfo = e.getValue();
            if (avdInfo != null) {
                message = String.format(
                        "Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'",
                        response.getDeviceToUse(), e.getValue().getName());
            } else {
                message = String.format("Automatic Target Mode: using device '%1$s'",
                        response.getDeviceToUse());
            }
            AdtPlugin.printToConsole(project, message);

            continueLaunch(response, project, launch, launchInfo, config);
            return;
        }

        // if more than one device, we'll bring up the DeviceChooser dialog below.
        if (compatibleRunningAvds.size() >= 2) {
            message = "Automatic Target Mode: Several compatible targets. Please select a target device.";
        } else if (hasDevice) {
            message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device.";
        }

        AdtPlugin.printToConsole(project, message);
    } else if ((config.mTargetMode == TargetMode.ALL_DEVICES_AND_EMULATORS
            || config.mTargetMode == TargetMode.ALL_DEVICES || config.mTargetMode == TargetMode.ALL_EMULATORS)
            && ILaunchManager.RUN_MODE.equals(mode)) {
        // if running on multiple devices, identify all compatible devices
        boolean includeDevices = config.mTargetMode != TargetMode.ALL_EMULATORS;
        boolean includeAvds = config.mTargetMode != TargetMode.ALL_DEVICES;
        Collection<IDevice> compatibleDevices = findCompatibleDevices(devices, minApiVersion, includeDevices,
                includeAvds);
        if (compatibleDevices.size() == 0) {
            AdtPlugin.printErrorToConsole(project, "No active compatible AVD's or devices found. "
                    + "Relaunch this configuration after connecting a device or starting an AVD.");
            stopLaunch(launchInfo);
        } else {
            multiLaunch(launchInfo, compatibleDevices);
        }
        return;
    }

    // bring up the device chooser.
    final IAndroidTarget desiredProjectTarget = projectTarget;
    final AtomicBoolean continueLaunch = new AtomicBoolean(false);
    AdtPlugin.getDisplay().syncExec(new Runnable() {
        @Override
        public void run() {
            try {
                // open the chooser dialog. It'll fill 'response' with the device to use
                // or the AVD to launch.
                DeviceChooserDialog dialog = new DeviceChooserDialog(AdtPlugin.getShell(), response,
                        launchInfo.getPackageName(), desiredProjectTarget, minApiVersion,
                        config.mReuseLastUsedDevice);
                if (dialog.open() == Dialog.OK) {
                    updateLaunchConfigWithLastUsedDevice(launch.getLaunchConfiguration(), response);
                    continueLaunch.set(true);
                } else {
                    AdtPlugin.printErrorToConsole(project, "Launch canceled!");
                    stopLaunch(launchInfo);
                    return;
                }
            } catch (Exception e) {
                // there seems to be some case where the shell will be null. (might be
                // an OS X bug). Because of this the creation of the dialog will throw
                // and IllegalArg exception interrupting the launch with no user feedback.
                // So we trap all the exception and display something.
                String msg = e.getMessage();
                if (msg == null) {
                    msg = e.getClass().getCanonicalName();
                }
                AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg));
                stopLaunch(launchInfo);
            }
        }
    });

    if (continueLaunch.get()) {
        continueLaunch(response, project, launch, launchInfo, config);
    }
}

From source file:com.android.ide.eclipse.auidt.internal.launch.AndroidLaunchController.java

License:Open Source License

/**
 * Launches an android app on the device or emulator
 *
 * @param project The project we're launching
 * @param mode the mode in which to launch, one of the mode constants
 *      defined by <code>ILaunchManager</code> - <code>RUN_MODE</code> or
 *      <code>DEBUG_MODE</code>.
 * @param apk the resource to the apk to launch.
 * @param packageName the Android package name of the app
 * @param debugPackageName the Android package name to debug
 * @param debuggable the debuggable value of the app's manifest, or null if not set.
 * @param requiredApiVersionNumber the api version required by the app, or null if none.
 * @param launchAction the action to perform after app sync
 * @param config the launch configuration
 * @param launch the launch object/*ww w  .j  a v  a  2s .c  o m*/
 */
public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName,
        Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction,
        final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) {

    String message = String.format("Performing %1$s", launchAction.getLaunchDescription());
    AdtPlugin.printToConsole(project, message);

    // create the launch info
    final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName,
            launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor);

    // set the debug mode
    launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE));

    // get the SDK
    Sdk currentSdk = Sdk.getCurrent();
    AvdManager avdManager = currentSdk.getAvdManager();

    // reload the AVDs to make sure we are up to date
    try {
        avdManager.reloadAvds(NullSdkLog.getLogger());
    } catch (AndroidLocationException e1) {
        // this happens if the AVD Manager failed to find the folder in which the AVDs are
        // stored. This is unlikely to happen, but if it does, we should force to go manual
        // to allow using physical devices.
        config.mTargetMode = TargetMode.MANUAL;
    }

    // get the project target
    IAndroidTarget projectTarget = currentSdk.getTarget(project);

    // FIXME: check errors on missing sdk, AVD manager, or project target.

    // device chooser response object.
    final DeviceChooserResponse response = new DeviceChooserResponse();

    /*
     * Launch logic:
     * - Use Last Launched Device/AVD set.
     *       If user requested to use same device for future launches, and the last launched
     *       device/avd is still present, then simply launch on the same device/avd.
     * - Manual Mode
     *       Always display a UI that lets a user see the current running emulators/devices.
     *       The UI must show which devices are compatibles, and allow launching new emulators
     *       with compatible (and not yet running) AVD.
     * - Automatic Way
     *     * Preferred AVD set.
     *           If Preferred AVD is not running: launch it.
     *           Launch the application on the preferred AVD.
     *     * No preferred AVD.
     *           Count the number of compatible emulators/devices.
     *           If != 1, display a UI similar to manual mode.
     *           If == 1, launch the application on this AVD/device.
     * - Launch on multiple devices:
     *     From the currently active devices & emulators, filter out those that cannot run
     *     the app (by api level), and launch on all the others.
     */
    IDevice[] devices = AndroidDebugBridge.getBridge().getDevices();
    IDevice deviceUsedInLastLaunch = DeviceChoiceCache.get(launch.getLaunchConfiguration().getName());
    if (deviceUsedInLastLaunch != null) {
        response.setDeviceToUse(deviceUsedInLastLaunch);
        continueLaunch(response, project, launch, launchInfo, config);
        return;
    }

    if (config.mTargetMode == TargetMode.AUTO) {
        // first check if we have a preferred AVD name, and if it actually exists, and is valid
        // (ie able to run the project).
        // We need to check this in case the AVD was recreated with a different target that is
        // not compatible.
        AvdInfo preferredAvd = null;
        if (config.mAvdName != null) {
            preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/);
            if (projectTarget.canRunOn(preferredAvd.getTarget()) == false) {
                preferredAvd = null;

                AdtPlugin.printErrorToConsole(project, String.format(
                        "Preferred AVD '%1$s' is not compatible with the project target '%2$s'. Looking for a compatible AVD...",
                        config.mAvdName, projectTarget.getName()));
            }
        }

        if (preferredAvd != null) {
            // look for a matching device

            for (IDevice d : devices) {
                String deviceAvd = d.getAvdName();
                if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) {
                    response.setDeviceToUse(d);

                    AdtPlugin.printToConsole(project, String.format(
                            "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'",
                            config.mAvdName, d));

                    continueLaunch(response, project, launch, launchInfo, config);
                    return;
                }
            }

            // at this point we have a valid preferred AVD that is not running.
            // We need to start it.
            response.setAvdToLaunch(preferredAvd);

            AdtPlugin.printToConsole(project, String.format(
                    "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.",
                    config.mAvdName));

            continueLaunch(response, project, launch, launchInfo, config);
            return;
        }

        // no (valid) preferred AVD? look for one.

        // If the API level requested in the manifest is lower than the current project
        // target, when we will iterate devices/avds later ideally we will want to find
        // a device/avd which target is as close to the manifest as possible (instead of
        // a device which target is the same as the project's target) and use it as the
        // new default.

        int reqApiLevel = 0;
        try {
            reqApiLevel = Integer.parseInt(requiredApiVersionNumber);

            if (reqApiLevel > 0 && reqApiLevel < projectTarget.getVersion().getApiLevel()) {
                int maxDist = projectTarget.getVersion().getApiLevel() - reqApiLevel;
                IAndroidTarget candidate = null;

                for (IAndroidTarget target : currentSdk.getTargets()) {
                    if (target.canRunOn(projectTarget)) {
                        int currDist = target.getVersion().getApiLevel() - reqApiLevel;
                        if (currDist >= 0 && currDist < maxDist) {
                            maxDist = currDist;
                            candidate = target;
                            if (maxDist == 0) {
                                // Found a perfect match
                                break;
                            }
                        }
                    }
                }

                if (candidate != null) {
                    // We found a better SDK target candidate, that is closer to the
                    // API level from minSdkVersion than the one currently used by the
                    // project. Below (in the for...devices loop) we'll try to find
                    // a device/AVD for it.
                    projectTarget = candidate;
                }
            }
        } catch (NumberFormatException e) {
            // pass
        }

        HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>();
        boolean hasDevice = false; // if there's 1+ device running, we may force manual mode,
                                   // as we cannot always detect proper compatibility with
                                   // devices. This is the case if the project target is not
                                   // a standard platform
        for (IDevice d : devices) {
            String deviceAvd = d.getAvdName();
            if (deviceAvd != null) { // physical devices return null.
                AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/);
                if (info != null && projectTarget.canRunOn(info.getTarget())) {
                    compatibleRunningAvds.put(d, info);
                }
            } else {
                if (projectTarget.isPlatform()) { // means this can run on any device as long
                                                  // as api level is high enough
                    AndroidVersion deviceVersion = Sdk.getDeviceVersion(d);
                    // the deviceVersion may be null if it wasn't yet queried (device just
                    // plugged in or emulator just booting up.
                    if (deviceVersion != null && deviceVersion.canRun(projectTarget.getVersion())) {
                        // device is compatible with project
                        compatibleRunningAvds.put(d, null);
                        continue;
                    }
                } else {
                    // for non project platform, we can't be sure if a device can
                    // run an application or not, since we don't query the device
                    // for the list of optional libraries that it supports.
                }
                hasDevice = true;
            }
        }

        // depending on the number of devices, we'll simulate an automatic choice
        // from the device chooser or simply show up the device chooser.
        if (hasDevice == false && compatibleRunningAvds.size() == 0) {
            // if zero emulators/devices, we launch an emulator.
            // We need to figure out which AVD first.

            // we are going to take the closest AVD. ie a compatible AVD that has the API level
            // closest to the project target.
            AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget);

            if (defaultAvd != null) {
                response.setAvdToLaunch(defaultAvd);

                AdtPlugin.printToConsole(project,
                        String.format(
                                "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'",
                                defaultAvd.getName()));

                continueLaunch(response, project, launch, launchInfo, config);
                return;
            } else {
                AdtPlugin.printToConsole(project, String.format(
                        "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName()));

                final Display display = AdtPlugin.getDisplay();
                final boolean[] searchAgain = new boolean[] { false };
                // ask the user to create a new one.
                display.syncExec(new Runnable() {
                    @Override
                    public void run() {
                        Shell shell = display.getActiveShell();
                        if (MessageDialog.openQuestion(shell, "Android AVD Error",
                                "No compatible targets were found. Do you wish to a add new Android Virtual Device?")) {
                            AvdManagerAction action = new AvdManagerAction();
                            action.run(null /*action*/);
                            searchAgain[0] = true;
                        }
                    }
                });
                if (searchAgain[0]) {
                    // attempt to reload the AVDs and find one compatible.
                    defaultAvd = findMatchingAvd(avdManager, projectTarget);

                    if (defaultAvd == null) {
                        AdtPlugin.printErrorToConsole(project,
                                String.format("Still no compatible AVDs with target '%1$s': Aborting launch.",
                                        projectTarget.getName()));
                        stopLaunch(launchInfo);
                    } else {
                        response.setAvdToLaunch(defaultAvd);

                        AdtPlugin.printToConsole(project, String.format(
                                "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName()));

                        continueLaunch(response, project, launch, launchInfo, config);
                        return;
                    }
                }
            }
        } else if (hasDevice == false && compatibleRunningAvds.size() == 1) {
            Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next();
            response.setDeviceToUse(e.getKey());

            // get the AvdInfo, if null, the device is a physical device.
            AvdInfo avdInfo = e.getValue();
            if (avdInfo != null) {
                message = String.format(
                        "Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'",
                        response.getDeviceToUse(), e.getValue().getName());
            } else {
                message = String.format("Automatic Target Mode: using device '%1$s'",
                        response.getDeviceToUse());
            }
            AdtPlugin.printToConsole(project, message);

            continueLaunch(response, project, launch, launchInfo, config);
            return;
        }

        // if more than one device, we'll bring up the DeviceChooser dialog below.
        if (compatibleRunningAvds.size() >= 2) {
            message = "Automatic Target Mode: Several compatible targets. Please select a target device.";
        } else if (hasDevice) {
            message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device.";
        }

        AdtPlugin.printToConsole(project, message);
    } else if ((config.mTargetMode == TargetMode.ALL_DEVICES_AND_EMULATORS
            || config.mTargetMode == TargetMode.ALL_DEVICES || config.mTargetMode == TargetMode.ALL_EMULATORS)
            && ILaunchManager.RUN_MODE.equals(mode)) {
        // if running on multiple devices, identify all compatible devices
        boolean includeDevices = config.mTargetMode != TargetMode.ALL_EMULATORS;
        boolean includeAvds = config.mTargetMode != TargetMode.ALL_DEVICES;
        Collection<IDevice> compatibleDevices = findCompatibleDevices(devices, requiredApiVersionNumber,
                includeDevices, includeAvds);
        if (compatibleDevices.size() == 0) {
            AdtPlugin.printErrorToConsole(project, "No active compatible AVD's or devices found. "
                    + "Relaunch this configuration after connecting a device or starting an AVD.");
            stopLaunch(launchInfo);
        } else {
            multiLaunch(launchInfo, compatibleDevices);
        }
        return;
    }

    // bring up the device chooser.
    final IAndroidTarget desiredProjectTarget = projectTarget;
    final AtomicBoolean continueLaunch = new AtomicBoolean(false);
    AdtPlugin.getDisplay().syncExec(new Runnable() {
        @Override
        public void run() {
            try {
                // open the chooser dialog. It'll fill 'response' with the device to use
                // or the AVD to launch.
                DeviceChooserDialog dialog = new DeviceChooserDialog(AdtPlugin.getDisplay().getActiveShell(),
                        response, launchInfo.getPackageName(), desiredProjectTarget);
                if (dialog.open() == Dialog.OK) {
                    DeviceChoiceCache.put(launch.getLaunchConfiguration().getName(), response);
                    continueLaunch.set(true);
                } else {
                    AdtPlugin.printErrorToConsole(project, "Launch canceled!");
                    stopLaunch(launchInfo);
                    return;
                }
            } catch (Exception e) {
                // there seems to be some case where the shell will be null. (might be
                // an OS X bug). Because of this the creation of the dialog will throw
                // and IllegalArg exception interrupting the launch with no user feedback.
                // So we trap all the exception and display something.
                String msg = e.getMessage();
                if (msg == null) {
                    msg = e.getClass().getCanonicalName();
                }
                AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg));
                stopLaunch(launchInfo);
            }
        }
    });

    if (continueLaunch.get()) {
        continueLaunch(response, project, launch, launchInfo, config);
    }
}

From source file:com.android.ide.eclipse.cheatsheets.actions.ImportProject.java

License:Open Source License

private void importProject(final String projectURL, final String[] params, final ICheatSheetManager manager) {
    final String projectName = params[1];
    WorkspaceJob workspaceJob = new WorkspaceJob("Importing projects ...") {

        @Override//from w  ww  . jav  a 2  s  .  c om
        public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
            IWorkspace workspace = ResourcesPlugin.getWorkspace();
            IProject project = workspace.getRoot().getProject(projectName);
            if (project.exists()) {
                Display.getDefault().syncExec(new Runnable() {

                    public void run() {
                        overwrite = MessageDialog.openQuestion(getShell(), "Question",
                                "Overwrite project " + projectName);
                    }

                });
                if (!overwrite) {
                    return Status.CANCEL_STATUS;
                }
                project.delete(true, true, monitor);
            }
            InputStream in = null;
            OutputStream out = null;
            File file = null;
            try {
                URL url = new URL(projectURL);
                URL entry = FileLocator.resolve(url);
                file = File.createTempFile("HelloWorld", ".zip"); //$NON-NLS-1$//$NON-NLS-2$
                file.deleteOnExit();
                in = entry.openStream();
                out = new FileOutputStream(file);
                copy(in, out);
            } catch (MalformedURLException e) {
                Activator.log(e);
                return Status.CANCEL_STATUS;
            } catch (IOException e) {
                Activator.log(e);
                return Status.CANCEL_STATUS;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
            project.create(monitor);
            project.open(monitor);
            ZipFile sourceFile;
            try {
                sourceFile = new ZipFile(file);
            } catch (IOException e) {
                Activator.log(e);
                return Status.CANCEL_STATUS;
            }
            ZipFileStructureProvider structureProvider = new ZipFileStructureProvider(sourceFile);

            Enumeration<? extends ZipEntry> entries = sourceFile.entries();
            ZipEntry entry = null;
            List<ZipEntry> filesToImport = new ArrayList<ZipEntry>();
            String prefix = projectName + "/"; //$NON-NLS-1$
            while (entries.hasMoreElements()) {
                entry = entries.nextElement();
                if (entry.getName().startsWith(prefix)) {
                    filesToImport.add(entry);
                }
            }

            ImportOperation operation = new ImportOperation(workspace.getRoot().getFullPath(),
                    structureProvider.getRoot(), structureProvider, OVERWRITE_ALL_QUERY, filesToImport);
            operation.setContext(getShell());
            try {
                operation.run(new NullProgressMonitor());
            } catch (InvocationTargetException e) {
                Activator.log(e);
                return Status.CANCEL_STATUS;
            } catch (InterruptedException e) {
                Activator.log(e);
                return Status.CANCEL_STATUS;
            } finally {
                file.delete();
            }
            return Status.OK_STATUS;
        }

    };
    workspaceJob.setUser(true);

    workspaceJob.addJobChangeListener(new IJobChangeListener() {

        public void aboutToRun(IJobChangeEvent event) {

        }

        public void awake(IJobChangeEvent event) {

        }

        public void done(IJobChangeEvent event) {
            try {
                Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, new NullProgressMonitor());
                IWorkspace workspace = ResourcesPlugin.getWorkspace();
                IProject project = workspace.getRoot().getProject(projectName);
                Sdk currentSdk = Sdk.getCurrent();
                if (currentSdk != null && project.isOpen()) {
                    IJavaProject javaProject = JavaCore.create(project);
                    ProjectState state = Sdk.getProjectState(project);
                    IAndroidTarget projectTarget = state.getTarget();
                    if (projectTarget == null) {
                        IAndroidTarget[] targets = Sdk.getCurrent().getTargets();
                        if (targets != null && targets.length > 0) {
                            IAndroidTarget newTarget = targets[0];
                            ProjectPropertiesWorkingCopy mPropertiesWorkingCopy = state.getProperties()
                                    .makeWorkingCopy();
                            mPropertiesWorkingCopy.setProperty(ProjectProperties.PROPERTY_TARGET,
                                    newTarget.hashString());
                            try {
                                mPropertiesWorkingCopy.save();
                                IResource defaultProp = project.findMember(SdkConstants.FN_DEFAULT_PROPERTIES);
                                defaultProp.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());

                                ProjectHelper.fixProject(project);
                            } catch (Exception e) {
                                String msg = String.format("Failed to save %1$s for project %2$s",
                                        SdkConstants.FN_DEFAULT_PROPERTIES, project.getName());
                                AdtPlugin.log(e, msg);
                            }
                        } else {
                            Display.getDefault().syncExec(new Runnable() {

                                public void run() {
                                    MessageDialog.openInformation(getShell(), "Hello World target",
                                            "'Hello world' cheatsheet requires "
                                                    + "an Android target. You can download "
                                                    + "them using the 'Open SDK and AVD Manager'" + " action.");
                                }
                            });
                        }
                    }
                }
                Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, new NullProgressMonitor());
                if (params[2] != null) {
                    new OpenFile().run(new String[] { params[1], "src", params[2] }, manager);
                }
            } catch (OperationCanceledException e) {
                Activator.log(e);
            } catch (InterruptedException e) {
                Activator.log(e);
            }
        }

        public void running(IJobChangeEvent event) {

        }

        public void scheduled(IJobChangeEvent event) {

        }

        public void sleeping(IJobChangeEvent event) {

        }

    });
    workspaceJob.schedule();
}

From source file:com.android.ide.eclipse.editors.ui.tree.UiActions.java

License:Apache License

/**
 * Called when the "Remove" button is selected.
 * //from w  w  w  .  j  a  v  a 2  s . co  m
 * If the tree has a selection, remove it.
 * This simply deletes the XML node attached to the UI node: when the XML model fires the
 * update event, the tree will get refreshed.
 */
public void doRemove(final List<UiElementNode> nodes, Shell shell) {

    if (nodes == null || nodes.size() == 0) {
        return;
    }

    final int len = nodes.size();

    StringBuilder sb = new StringBuilder();
    for (UiElementNode node : nodes) {
        sb.append("\n- "); //$NON-NLS-1$
        sb.append(node.getBreadcrumbTrailDescription(false /* include_root */));
    }

    if (MessageDialog.openQuestion(shell, len > 1 ? "Remove elements from Android XML" // title
            : "Remove element from Android XML",
            String.format("Do you really want to remove %1$s?", sb.toString()))) {
        commitPendingXmlChanges();
        getRootNode().getEditor().editXmlModel(new Runnable() {
            public void run() {
                UiElementNode previous = null;
                UiElementNode parent = null;

                for (int i = len - 1; i >= 0; i--) {
                    UiElementNode node = nodes.get(i);
                    previous = node.getUiPreviousSibling();
                    parent = node.getUiParent();

                    // delete node
                    node.deleteXmlNode();
                }

                // try to select the last previous sibling or the last parent
                if (previous != null) {
                    selectUiNode(previous);
                } else if (parent != null) {
                    selectUiNode(parent);
                }
            }
        });
    }
}

From source file:com.android.ide.eclipse.monitor.MonitorApplication.java

License:Apache License

@Override
public Object start(IApplicationContext context) throws Exception {
    Display display = PlatformUI.createDisplay();

    // set workspace location
    Location instanceLoc = Platform.getInstanceLocation();
    IPath workspacePath = new Path(AndroidLocation.getFolder()).append(MONITOR_WORKSPACE_PATH);
    instanceLoc.set(workspacePath.toFile().toURI().toURL(), true);

    // figure out path to SDK
    String sdkPath = findSdkPath(display);
    if (!isValidSdkLocation(sdkPath)) {
        // exit with return code -1
        return Integer.valueOf(-1);
    }//  w  ww.  j av a 2  s  .co  m
    MonitorPlugin.getDefault().setSdkFolder(new File(sdkPath));

    // install platform tools if necessary
    ILogger sdkLog = NullLogger.getLogger();
    SdkManager manager = SdkManager.createManager(sdkPath, sdkLog);
    if (manager.getPlatformToolsVersion() == null) {
        boolean install = MessageDialog.openQuestion(new Shell(display), "Monitor",
                "The platform tools package that provides adb is missing from your SDK installation. "
                        + "Monitor requires this package to work properly. Would you like to install that package now?");
        if (!install) {
            return Integer.valueOf(-1);
        }
        AdtUpdateDialog window = new AdtUpdateDialog(new Shell(display), sdkLog, sdkPath);
        window.installPlatformTools();
    }

    // If this is the first time using ddms or adt, open up the stats service
    // opt out dialog, and request user for permissions.
    // Note that the actual ping is performed in MonitorStartup
    SdkStatsService stats = new SdkStatsService();
    stats.checkUserPermissionForPing(new Shell(display));

    // open up RCP
    try {
        int returnCode = PlatformUI.createAndRunWorkbench(display, new MonitorWorkbenchAdvisor());
        if (returnCode == PlatformUI.RETURN_RESTART) {
            return IApplication.EXIT_RESTART;
        }
        return IApplication.EXIT_OK;
    } finally {
        display.dispose();
    }
}

From source file:com.android.sdkuilib.ApkConfigWidget.java

License:Apache License

public ApkConfigWidget(final Composite parent) {
    final Composite apkConfigComp = new Composite(parent, SWT.NONE);
    apkConfigComp.setLayoutData(new GridData(GridData.FILL_BOTH));
    apkConfigComp.setLayout(new GridLayout(2, false));

    mApkConfigTable = new Table(apkConfigComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
    mApkConfigTable.setHeaderVisible(true);
    mApkConfigTable.setLinesVisible(true);

    GridData data = new GridData();
    data.grabExcessVerticalSpace = true;
    data.grabExcessHorizontalSpace = true;
    data.horizontalAlignment = GridData.FILL;
    data.verticalAlignment = GridData.FILL;
    mApkConfigTable.setLayoutData(data);

    // create the table columns
    final TableColumn column0 = new TableColumn(mApkConfigTable, SWT.NONE);
    column0.setText("Name");
    column0.setWidth(100);//  ww  w .  java 2  s. c  o  m
    final TableColumn column1 = new TableColumn(mApkConfigTable, SWT.NONE);
    column1.setText("Configuration");
    column1.setWidth(100);

    Composite buttonComp = new Composite(apkConfigComp, SWT.NONE);
    buttonComp.setLayoutData(new GridData(GridData.FILL_VERTICAL));
    GridLayout gl;
    buttonComp.setLayout(gl = new GridLayout(1, false));
    gl.marginHeight = gl.marginWidth = 0;

    Button newButton = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
    newButton.setText("New...");
    newButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    mEditButton = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
    mEditButton.setText("Edit...");
    mEditButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    mDelButton = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
    mDelButton.setText("Delete");
    mDelButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    newButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            ApkConfigEditDialog dlg = new ApkConfigEditDialog(null /*name*/, null /*filter*/,
                    apkConfigComp.getShell());
            if (dlg.open() == Dialog.OK) {
                TableItem item = new TableItem(mApkConfigTable, SWT.NONE);
                item.setText(INDEX_NAME, dlg.getName());
                item.setText(INDEX_FILTER, dlg.getFilter());

                onSelectionChanged();
            }
        }
    });

    mEditButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            // get the current selection (single mode so we don't care about any item beyond
            // index 0).
            TableItem[] items = mApkConfigTable.getSelection();
            if (items.length != 0) {
                ApkConfigEditDialog dlg = new ApkConfigEditDialog(items[0].getText(INDEX_NAME),
                        items[0].getText(INDEX_FILTER), apkConfigComp.getShell());
                if (dlg.open() == Dialog.OK) {
                    items[0].setText(INDEX_NAME, dlg.getName());
                    items[0].setText(INDEX_FILTER, dlg.getFilter());
                }
            }
        }
    });

    mDelButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            // get the current selection (single mode so we don't care about any item beyond
            // index 0).
            int[] indices = mApkConfigTable.getSelectionIndices();
            if (indices.length != 0) {
                TableItem item = mApkConfigTable.getItem(indices[0]);
                if (MessageDialog.openQuestion(parent.getShell(), "Apk Configuration deletion", String.format(
                        "Are you sure you want to delete configuration '%1$s'?", item.getText(INDEX_NAME)))) {
                    // delete the item.
                    mApkConfigTable.remove(indices[0]);

                    onSelectionChanged();
                }
            }
        }
    });

    // Add a listener to resize the column to the full width of the table
    mApkConfigTable.addControlListener(new ControlAdapter() {
        @Override
        public void controlResized(ControlEvent e) {
            Rectangle r = mApkConfigTable.getClientArea();
            column0.setWidth(r.width * 30 / 100); // 30%  
            column1.setWidth(r.width * 70 / 100); // 70%
        }
    });

    // add a selection listener on the table, to enable/disable buttons.
    mApkConfigTable.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            onSelectionChanged();
        }
    });
}

From source file:com.android.sdkuilib.internal.repository.LocalPackagesPage.java

License:Apache License

private void onDeleteSelected() {
    ISelection sel = mTableViewerPackages.getSelection();
    if (sel instanceof IStructuredSelection) {
        Object elem = ((IStructuredSelection) sel).getFirstElement();
        if (elem instanceof Package) {

            String title = "Delete SDK Package";
            String error = null;/*w w w  .  j av  a  2 s  .co m*/

            Package p = (Package) elem;
            Archive[] archives = p.getArchives();
            if (archives.length == 1 && archives[0] != null && archives[0].isLocal()) {
                Archive archive = archives[0];
                String osPath = archive.getLocalOsPath();

                File dir = new File(osPath);
                if (dir.isDirectory()) {
                    String msg = String.format(
                            "Are you sure you want to delete '%1$s' at '%2$s'? This cannot be undone.",
                            p.getShortDescription(), osPath);

                    if (MessageDialog.openQuestion(getShell(), title, msg)) {
                        archive.deleteLocal();

                        // refresh list
                        onRefreshSelected();
                    }
                } else {
                    error = "Directory not found for this package";
                }
            } else {
                error = "No local archive found for this package";
            }

            if (error != null) {
                MessageDialog.openError(getShell(), title, error);
            }

            return;
        }
    }
}