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

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

Introduction

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

Prototype

public static void openError(Shell parent, String title, String message) 

Source Link

Document

Convenience method to open a standard error dialog.

Usage

From source file:com.android.ide.eclipse.adt.internal.wizards.templates.InstallDependencyPage.java

License:Open Source License

@Override
public void widgetSelected(SelectionEvent e) {
    Object source = e.getSource();
    if (source == mCheckButton) {
        sCachedName = null;/*from   w  ww  . ja v  a 2  s .c o m*/
        if (isInstalled()) {
            showNextPage();
        }
        updateVersionLabels();
    } else if (source == mInstallButton) {
        sCachedName = null;
        for (Pair<String, Integer> dependency : mTemplate.getDependencies()) {
            String name = dependency.getFirst();
            if (SUPPORT_LIBRARY_NAME.equals(name)) {
                int version = dependency.getSecond();
                File installed = AddSupportJarAction.installSupport(version);
                if (installed != null) {
                    showNextPage();
                }
                updateVersionLabels();
            }
        }
    } else if (source == mLink) {
        try {
            IWorkbench workbench = PlatformUI.getWorkbench();
            IWebBrowser browser = workbench.getBrowserSupport().getExternalBrowser();
            browser.openURL(new URL(URL));
        } catch (Exception ex) {
            String message = String.format("Could not open browser. Vist\n%1$s\ninstead.", URL);
            MessageDialog.openError(getShell(), "Browser Error", message);
        }
    }
}

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

License:Open Source License

/**
 * Looks for and returns an existing {@link ILaunchConfiguration} object for a
 * specified project./*  w ww. j  av  a 2 s .  c  o m*/
 * @param manager The {@link ILaunchManager}.
 * @param type The {@link ILaunchConfigurationType}.
 * @param projectName The name of the project
 * @return an existing <code>ILaunchConfiguration</code> object matching the project, or
 *      <code>null</code>.
 */
private static ILaunchConfiguration findConfig(ILaunchManager manager, ILaunchConfigurationType type,
        String projectName) {
    try {
        ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type);

        for (ILaunchConfiguration config : configs) {
            if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "") //$NON-NLS-1$
                    .equals(projectName)) {
                return config;
            }
        }
    } catch (CoreException e) {
        MessageDialog.openError(AdtPlugin.getDisplay().getActiveShell(), "Launch Error",
                e.getStatus().getMessage());
    }

    // didn't find anything that matches. Return null
    return null;

}

From source file:com.android.ide.eclipse.adt.wizards.newproject.NewProjectWizard.java

License:Open Source License

/**
 * Runs the operation in a different thread and display generated
 * exceptions./*from w w w. ja va  2s  .c om*/
 *
 * @param op The asynchronous operation to run.
 */
private void runAsyncOperation(WorkspaceModifyOperation op) {
    try {
        getContainer().run(true /* fork */, true /* cancelable */, op);
    } catch (InvocationTargetException e) {
        // The runnable threw an exception
        Throwable t = e.getTargetException();
        if (t instanceof CoreException) {
            CoreException core = (CoreException) t;
            if (core.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
                // The error indicates the file system is not case sensitive
                // and there's a resource with a similar name.
                MessageDialog.openError(getShell(), "Error", "Error: Case Variant Exists");
            } else {
                ErrorDialog.openError(getShell(), "Error", null, core.getStatus());
            }
        } else {
            // Some other kind of exception
            MessageDialog.openError(getShell(), "Error", t.getMessage());
        }
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

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  ava 2s .  c om
            }
            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.launch.AndroidLaunchController.java

License:Open Source License

/**
 * Looks for and returns an existing {@link ILaunchConfiguration} object for a
 * specified project.//www  . ja  va  2 s  .c  o  m
 * @param manager The {@link ILaunchManager}.
 * @param type The {@link ILaunchConfigurationType}.
 * @param projectName The name of the project
 * @return an existing <code>ILaunchConfiguration</code> object matching the project, or
 *      <code>null</code>.
 */
private static ILaunchConfiguration findConfig(ILaunchManager manager, ILaunchConfigurationType type,
        String projectName) {
    try {
        ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type);

        for (ILaunchConfiguration config : configs) {
            if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "") //$NON-NLS-1$
                    .equals(projectName)) {
                return config;
            }
        }
    } catch (CoreException e) {
        MessageDialog.openError(AdtPlugin.getDisplay().getActiveShell(), "Launch Error",
                e.getStatus().getMessage());
    }

    // didn't find anything that matches. Return null
    return null;
}

From source file:com.android.ide.eclipse.auidt.internal.wizards.newproject.NewProjectCreator.java

License:Open Source License

/**
 * Runs the operation in a different thread and display generated
 * exceptions.//from w w w  . java2s.  c  o  m
 *
 * @param op The asynchronous operation to run.
 */
private void runAsyncOperation(WorkspaceModifyOperation op) {
    try {
        mRunnableContext.run(true /* fork */, true /* cancelable */, op);
    } catch (InvocationTargetException e) {

        AdtPlugin.log(e, "New Project Wizard failed");

        // The runnable threw an exception
        Throwable t = e.getTargetException();
        if (t instanceof CoreException) {
            CoreException core = (CoreException) t;
            if (core.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
                // The error indicates the file system is not case sensitive
                // and there's a resource with a similar name.
                MessageDialog.openError(AdtPlugin.getDisplay().getActiveShell(), "Error",
                        "Error: Case Variant Exists");
            } else {
                ErrorDialog.openError(AdtPlugin.getDisplay().getActiveShell(), "Error", core.getMessage(),
                        core.getStatus());
            }
        } else {
            // Some other kind of exception
            String msg = t.getMessage();
            Throwable t1 = t;
            while (msg == null && t1.getCause() != null) {
                msg = t1.getMessage();
                t1 = t1.getCause();
            }
            if (msg == null) {
                msg = t.toString();
            }
            MessageDialog.openError(AdtPlugin.getDisplay().getActiveShell(), "Error", msg);
        }
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.android.ide.eclipse.ddms.DdmsPlugin.java

License:Apache License

@Override
public void start(BundleContext context) throws Exception {
    super.start(context);

    final Display display = getDisplay();

    // get the eclipse store
    final IPreferenceStore eclipseStore = getPreferenceStore();

    AndroidDebugBridge.addDeviceChangeListener(this);

    DdmUiPreferences.setStore(eclipseStore);

    //DdmUiPreferences.displayCharts();

    // set the consoles.
    mDdmsConsole = new MessageConsole("DDMS", null); //$NON-NLS-1$
    ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { mDdmsConsole });

    final MessageConsoleStream consoleStream = mDdmsConsole.newMessageStream();
    final MessageConsoleStream errorConsoleStream = mDdmsConsole.newMessageStream();
    mRed = new Color(display, 0xFF, 0x00, 0x00);

    // because this can be run, in some cases, by a non UI thread, and because
    // changing the console properties update the UI, we need to make this change
    // in the UI thread.
    display.asyncExec(new Runnable() {
        @Override/*  w ww. j  av a2s . com*/
        public void run() {
            errorConsoleStream.setColor(mRed);
        }
    });

    // set up the ddms log to use the ddms console.
    Log.setLogOutput(new ILogOutput() {
        @Override
        public void printLog(LogLevel logLevel, String tag, String message) {
            if (logLevel.getPriority() >= LogLevel.ERROR.getPriority()) {
                printToStream(errorConsoleStream, tag, message);
                showConsoleView(mDdmsConsole);
            } else {
                printToStream(consoleStream, tag, message);
            }
        }

        @Override
        public void printAndPromptLog(final LogLevel logLevel, final String tag, final String message) {
            printLog(logLevel, tag, message);
            // dialog box only run in UI thread..
            display.asyncExec(new Runnable() {
                @Override
                public void run() {
                    Shell shell = display.getActiveShell();
                    if (logLevel == LogLevel.ERROR) {
                        MessageDialog.openError(shell, tag, message);
                    } else {
                        MessageDialog.openWarning(shell, tag, message);
                    }
                }
            });
        }

    });

    // set up the ddms console to use this objects
    DdmConsole.setConsole(new IDdmConsole() {
        @Override
        public void printErrorToConsole(String message) {
            printToStream(errorConsoleStream, null, message);
            showConsoleView(mDdmsConsole);
        }

        @Override
        public void printErrorToConsole(String[] messages) {
            for (String m : messages) {
                printToStream(errorConsoleStream, null, m);
            }
            showConsoleView(mDdmsConsole);
        }

        @Override
        public void printToConsole(String message) {
            printToStream(consoleStream, null, message);
        }

        @Override
        public void printToConsole(String[] messages) {
            for (String m : messages) {
                printToStream(consoleStream, null, m);
            }
        }
    });

    // set the listener for the preference change
    eclipseStore.addPropertyChangeListener(new IPropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent event) {
            // get the name of the property that changed.
            String property = event.getProperty();

            if (PreferenceInitializer.ATTR_DEBUG_PORT_BASE.equals(property)) {
                DdmPreferences
                        .setDebugPortBase(eclipseStore.getInt(PreferenceInitializer.ATTR_DEBUG_PORT_BASE));
            } else if (PreferenceInitializer.ATTR_SELECTED_DEBUG_PORT.equals(property)) {
                DdmPreferences.setSelectedDebugPort(
                        eclipseStore.getInt(PreferenceInitializer.ATTR_SELECTED_DEBUG_PORT));
            } else if (PreferenceInitializer.ATTR_THREAD_INTERVAL.equals(property)) {
                DdmUiPreferences.setThreadRefreshInterval(
                        eclipseStore.getInt(PreferenceInitializer.ATTR_THREAD_INTERVAL));
            } else if (PreferenceInitializer.ATTR_LOG_LEVEL.equals(property)) {
                DdmPreferences.setLogLevel(eclipseStore.getString(PreferenceInitializer.ATTR_LOG_LEVEL));
            } else if (PreferenceInitializer.ATTR_TIME_OUT.equals(property)) {
                DdmPreferences.setTimeOut(eclipseStore.getInt(PreferenceInitializer.ATTR_TIME_OUT));
            } else if (PreferenceInitializer.ATTR_USE_ADBHOST.equals(property)) {
                DdmPreferences.setUseAdbHost(eclipseStore.getBoolean(PreferenceInitializer.ATTR_USE_ADBHOST));
            } else if (PreferenceInitializer.ATTR_ADBHOST_VALUE.equals(property)) {
                DdmPreferences
                        .setAdbHostValue(eclipseStore.getString(PreferenceInitializer.ATTR_ADBHOST_VALUE));
            }
        }
    });

    // do some last initializations

    // set the preferences.
    PreferenceInitializer.setupPreferences();

    // this class is set as the main source revealer and will look at all the implementations
    // of the extension point. see #reveal(String, String, int)
    StackTracePanel.setSourceRevealer(this);

    /*
     * Load the extension point implementations.
     * The first step is to load the IConfigurationElement representing the implementations.
     * The 2nd step is to use these objects to instantiate the implementation classes.
     *
     * Because the 2nd step will trigger loading the plug-ins providing the implementations,
     * and those plug-ins could access DDMS classes (like ADT), this 2nd step should be done
     * in a Job to ensure that DDMS is loaded, so that the other plug-ins can load.
     *
     * Both steps could be done in the 2nd step but some of DDMS UI rely on knowing if there
     * is an implementation or not (DeviceView), so we do the first steps in start() and, in
     * some case, record it.
     *
     */

    // get the IConfigurationElement for the debuggerConnector right away.
    final IConfigurationElement[] dcce = findConfigElements("com.android.ide.eclipse.ddms.debuggerConnector"); //$NON-NLS-1$
    mHasDebuggerConnectors = dcce.length > 0;

    // get the other configElements and instantiante them in a Job.
    new Job(Messages.DdmsPlugin_DDMS_Post_Create_Init) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                // init the lib
                AndroidDebugBridge.init(true /* debugger support */);

                // get the available adb locators
                IConfigurationElement[] elements = findConfigElements(
                        "com.android.ide.eclipse.ddms.toolsLocator"); //$NON-NLS-1$

                IToolsLocator[] locators = instantiateToolsLocators(elements);

                for (IToolsLocator locator : locators) {
                    try {
                        String adbLocation = locator.getAdbLocation();
                        String traceviewLocation = locator.getTraceViewLocation();
                        String hprofConvLocation = locator.getHprofConvLocation();
                        if (adbLocation != null && traceviewLocation != null && hprofConvLocation != null) {
                            // checks if the location is valid.
                            if (setToolsLocation(adbLocation, hprofConvLocation, traceviewLocation)) {

                                AndroidDebugBridge.createBridge(sAdbLocation, true /* forceNewBridge */);

                                // no need to look at the other locators.
                                break;
                            }
                        }
                    } catch (Throwable t) {
                        // ignore, we'll just not use this implementation.
                    }
                }

                // get the available debugger connectors
                mDebuggerConnectors = instantiateDebuggerConnectors(dcce);

                // get the available Traceview Launchers.
                elements = findConfigElements("com.android.ide.eclipse.ddms.traceviewLauncher"); //$NON-NLS-1$
                mTraceviewLaunchers = instantiateTraceviewLauncher(elements);

                return Status.OK_STATUS;
            } catch (CoreException e) {
                return e.getStatus();
            }
        }
    }.schedule();
}

From source file:com.android.ide.eclipse.ddms.editors.UiAutomatorViewer.java

License:Apache License

@Override
public void createPartControl(Composite parent) {
    Composite c = new Composite(parent, SWT.NONE);
    c.setLayout(new GridLayout(1, false));
    GridData gd = new GridData(GridData.FILL_BOTH);
    c.setLayoutData(gd);/*from   w  w  w.  j  a va  2  s. c o m*/

    mView = new UiAutomatorView(c, SWT.BORDER);
    mView.setLayoutData(new GridData(GridData.FILL_BOTH));

    if (mFilePath == null) {
        return;
    }

    UiAutomatorModel model = null;
    File modelFile = new File(mFilePath);
    try {
        model = new UiAutomatorModel(modelFile);
    } catch (Exception e) {
        MessageDialog.openError(parent.getShell(), "Error opening " + mFilePath,
                "Unexpected error while parsing input: " + e.getMessage());
        return;
    }

    mView.setModel(model, modelFile, null);
}

From source file:com.android.ide.eclipse.ddms.views.DeviceView.java

License:Apache License

@Override
public void createPartControl(Composite parent) {
    mParentShell = parent.getShell();/*  w w w  . j  a  va2  s  .co  m*/

    ImageLoader loader = ImageLoader.getDdmUiLibLoader();

    mDeviceList = new DevicePanel(USE_SELECTED_DEBUG_PORT);
    mDeviceList.createPanel(parent);
    mDeviceList.addSelectionListener(this);

    DdmsPlugin plugin = DdmsPlugin.getDefault();
    mDeviceList.addSelectionListener(plugin);
    plugin.setListeningState(true);

    mCaptureAction = new Action(Messages.DeviceView_Screen_Capture) {
        @Override
        public void run() {
            ScreenShotDialog dlg = new ScreenShotDialog(DdmsPlugin.getDisplay().getActiveShell());
            dlg.open(mDeviceList.getSelectedDevice());
        }
    };
    mCaptureAction.setToolTipText(Messages.DeviceView_Screen_Capture_Tooltip);
    mCaptureAction.setImageDescriptor(loader.loadDescriptor("capture.png")); //$NON-NLS-1$

    mViewUiAutomatorHierarchyAction = new Action("Dump View Hierarchy for UI Automator") {
        @Override
        public void run() {
            takeUiAutomatorSnapshot(mDeviceList.getSelectedDevice(), DdmsPlugin.getDisplay().getActiveShell());
        }
    };
    mViewUiAutomatorHierarchyAction.setToolTipText("Dump View Hierarchy for UI Automator");
    mViewUiAutomatorHierarchyAction.setImageDescriptor(DdmsPlugin.getImageDescriptor("icons/uiautomator.png")); //$NON-NLS-1$

    mSystraceAction = new Action("Capture System Wide Trace") {
        @Override
        public void run() {
            launchSystrace(mDeviceList.getSelectedDevice(), DdmsPlugin.getDisplay().getActiveShell());
        }
    };
    mSystraceAction.setToolTipText("Capture system wide trace using Android systrace");
    mSystraceAction.setImageDescriptor(DdmsPlugin.getImageDescriptor("icons/systrace.png")); //$NON-NLS-1$
    mSystraceAction.setEnabled(true);

    mResetAdbAction = new Action(Messages.DeviceView_Reset_ADB) {
        @Override
        public void run() {
            AndroidDebugBridge bridge = AndroidDebugBridge.getBridge();
            if (bridge != null) {
                if (bridge.restart() == false) {
                    // get the current Display
                    final Display display = DdmsPlugin.getDisplay();

                    // dialog box only run in ui thread..
                    display.asyncExec(new Runnable() {
                        @Override
                        public void run() {
                            Shell shell = display.getActiveShell();
                            MessageDialog.openError(shell, Messages.DeviceView_ADB_Error,
                                    Messages.DeviceView_ADB_Failed_Restart);
                        }
                    });
                }
            }
        }
    };
    mResetAdbAction.setToolTipText(Messages.DeviceView_Reset_ADB_Host_Deamon);
    mResetAdbAction.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJS_WARN_TSK));

    mKillAppAction = new Action() {
        @Override
        public void run() {
            mDeviceList.killSelectedClient();
        }
    };

    mKillAppAction.setText(Messages.DeviceView_Stop_Process);
    mKillAppAction.setToolTipText(Messages.DeviceView_Stop_Process_Tooltip);
    mKillAppAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_HALT));

    mGcAction = new Action() {
        @Override
        public void run() {
            mDeviceList.forceGcOnSelectedClient();
        }
    };

    mGcAction.setText(Messages.DeviceView_Cause_GC);
    mGcAction.setToolTipText(Messages.DeviceView_Cause_GC_Tooltip);
    mGcAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_GC));

    mHprofAction = new Action() {
        @Override
        public void run() {
            mDeviceList.dumpHprof();
            doSelectionChanged(mDeviceList.getSelectedClient());
        }
    };
    mHprofAction.setText(Messages.DeviceView_Dump_HPROF_File);
    mHprofAction.setToolTipText(Messages.DeviceView_Dump_HPROF_File_Tooltip);
    mHprofAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_HPROF));

    mUpdateHeapAction = new Action(Messages.DeviceView_Update_Heap, IAction.AS_CHECK_BOX) {
        @Override
        public void run() {
            boolean enable = mUpdateHeapAction.isChecked();
            mDeviceList.setEnabledHeapOnSelectedClient(enable);
        }
    };
    mUpdateHeapAction.setToolTipText(Messages.DeviceView_Update_Heap_Tooltip);
    mUpdateHeapAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_HEAP));

    mUpdateThreadAction = new Action(Messages.DeviceView_Threads, IAction.AS_CHECK_BOX) {
        @Override
        public void run() {
            boolean enable = mUpdateThreadAction.isChecked();
            mDeviceList.setEnabledThreadOnSelectedClient(enable);
        }
    };
    mUpdateThreadAction.setToolTipText(Messages.DeviceView_Threads_Tooltip);
    mUpdateThreadAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_THREAD));

    mTracingAction = new Action() {
        @Override
        public void run() {
            mDeviceList.toggleMethodProfiling();
        }
    };
    mTracingAction.setText(Messages.DeviceView_Start_Method_Profiling);
    mTracingAction.setToolTipText(Messages.DeviceView_Start_Method_Profiling_Tooltip);
    mTracingStartImage = loader.loadDescriptor(DevicePanel.ICON_TRACING_START);
    mTracingStopImage = loader.loadDescriptor(DevicePanel.ICON_TRACING_STOP);
    mTracingAction.setImageDescriptor(mTracingStartImage);

    mDebugAction = new Action(Messages.DeviceView_Debug_Process) {
        @Override
        public void run() {
            if (DdmsPlugin.getDefault().hasDebuggerConnectors()) {
                Client currentClient = mDeviceList.getSelectedClient();
                if (currentClient != null) {
                    ClientData clientData = currentClient.getClientData();

                    // make sure the client can be debugged
                    switch (clientData.getDebuggerConnectionStatus()) {
                    case ERROR: {
                        Display display = DdmsPlugin.getDisplay();
                        Shell shell = display.getActiveShell();
                        MessageDialog.openError(shell, Messages.DeviceView_Debug_Process_Title,
                                Messages.DeviceView_Process_Debug_Already_In_Use);
                        return;
                    }
                    case ATTACHED: {
                        Display display = DdmsPlugin.getDisplay();
                        Shell shell = display.getActiveShell();
                        MessageDialog.openError(shell, Messages.DeviceView_Debug_Process_Title,
                                Messages.DeviceView_Process_Already_Being_Debugged);
                        return;
                    }
                    }

                    // get the name of the client
                    String packageName = clientData.getClientDescription();
                    if (packageName != null) {

                        // try all connectors till one returns true.
                        IDebuggerConnector[] connectors = DdmsPlugin.getDefault().getDebuggerConnectors();

                        if (connectors != null) {
                            for (IDebuggerConnector connector : connectors) {
                                try {
                                    if (connector.connectDebugger(packageName,
                                            currentClient.getDebuggerListenPort(),
                                            DdmPreferences.getSelectedDebugPort())) {
                                        return;
                                    }
                                } catch (Throwable t) {
                                    // ignore, we'll just not use this
                                    // implementation
                                }
                            }
                        }

                        // if we get to this point, then we failed to find a
                        // project
                        // that matched the application to debug
                        Display display = DdmsPlugin.getDisplay();
                        Shell shell = display.getActiveShell();
                        MessageDialog.openError(shell, Messages.DeviceView_Debug_Process_Title,
                                String.format(Messages.DeviceView_Debug_Session_Failed, packageName));
                    }
                }
            }
        }
    };
    mDebugAction.setToolTipText(Messages.DeviceView_Debug_Process_Tooltip);
    mDebugAction.setImageDescriptor(loader.loadDescriptor("debug-attach.png")); //$NON-NLS-1$
    mDebugAction.setEnabled(DdmsPlugin.getDefault().hasDebuggerConnectors());

    placeActions();

    // disabling all action buttons
    selectionChanged(null, null);

    ClientData.setHprofDumpHandler(new HProfHandler(mParentShell));
    AndroidDebugBridge.addClientChangeListener(this);
    ClientData.setMethodProfilingHandler(new MethodProfilingHandler(mParentShell) {
        @Override
        protected void open(String tempPath) {
            if (DdmsPlugin.getDefault().launchTraceview(tempPath) == false) {
                super.open(tempPath);
            }
        }
    });
}

From source file:com.android.ide.eclipse.ddms.views.DeviceView.java

License:Apache License

private void launchSystrace(final IDevice device, final Shell parentShell) {
    final File systraceAssets = new File(DdmsPlugin.getPlatformToolsFolder(), "systrace"); //$NON-NLS-1$
    if (!systraceAssets.isDirectory()) {
        MessageDialog.openError(parentShell, "Systrace",
                "Updated version of platform-tools (18.0.1 or greater) is required.\n"
                        + "Please update your platform-tools using SDK Manager.");
        return;/* ww w . j av a 2  s  .  c  om*/
    }

    SystraceVersionDetector detector = new SystraceVersionDetector(device);
    try {
        new ProgressMonitorDialog(parentShell).run(true, false, detector);
    } catch (InvocationTargetException e) {
        MessageDialog.openError(parentShell, "Systrace",
                "Unexpected error while detecting atrace version: " + e);
        return;
    } catch (InterruptedException e) {
        return;
    }

    final ISystraceOptionsDialog dlg;
    if (detector.getVersion() == SystraceVersionDetector.SYSTRACE_V1) {
        dlg = new SystraceOptionsDialogV1(parentShell);
    } else {
        Client[] clients = device.getClients();
        List<String> apps = new ArrayList<String>(clients.length);
        for (int i = 0; i < clients.length; i++) {
            String name = clients[i].getClientData().getClientDescription();
            if (name != null && !name.isEmpty()) {
                apps.add(name);
            }
        }
        dlg = new SystraceOptionsDialogV2(parentShell, detector.getTags(), apps);
    }

    if (dlg.open() != SystraceOptionsDialogV1.OK) {
        return;
    }

    final ISystraceOptions options = dlg.getSystraceOptions();

    // set trace tag if necessary:
    //      adb shell setprop debug.atrace.tags.enableflags <tag>
    String tag = options.getTags();
    if (tag != null) {
        CountDownLatch setTagLatch = new CountDownLatch(1);
        CollectingOutputReceiver receiver = new CollectingOutputReceiver(setTagLatch);
        try {
            String cmd = "setprop debug.atrace.tags.enableflags " + tag;
            device.executeShellCommand(cmd, receiver);
            setTagLatch.await(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            MessageDialog.openError(parentShell, "Systrace", "Unexpected error while setting trace tags: " + e);
            return;
        }

        String shellOutput = receiver.getOutput();
        if (shellOutput.contains("Error type")) { //$NON-NLS-1$
            throw new RuntimeException(receiver.getOutput());
        }
    }

    // obtain the output of "adb shell atrace <trace-options>" and generate the html file
    ProgressMonitorDialog d = new ProgressMonitorDialog(parentShell);
    try {
        d.run(true, true, new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                boolean COMPRESS_DATA = true;

                monitor.setTaskName("Collecting Trace Information");
                final String atraceOptions = options.getOptions() + (COMPRESS_DATA ? " -z" : "");
                SystraceTask task = new SystraceTask(device, atraceOptions);
                Thread t = new Thread(task, "Systrace Output Receiver");
                t.start();

                // check if the user has cancelled tracing every so often
                while (true) {
                    t.join(1000);

                    if (t.isAlive()) {
                        if (monitor.isCanceled()) {
                            task.cancel();
                            return;
                        }
                    } else {
                        break;
                    }
                }

                if (task.getError() != null) {
                    throw new RuntimeException(task.getError());
                }

                monitor.setTaskName("Saving trace information");
                SystraceOutputParser parser = new SystraceOutputParser(COMPRESS_DATA,
                        SystraceOutputParser.getJs(systraceAssets), SystraceOutputParser.getCss(systraceAssets),
                        SystraceOutputParser.getHtmlPrefix(systraceAssets),
                        SystraceOutputParser.getHtmlSuffix(systraceAssets));

                parser.parse(task.getAtraceOutput());

                String html = parser.getSystraceHtml();
                try {
                    Files.write(html.getBytes(), new File(dlg.getTraceFilePath()));
                } catch (IOException e) {
                    throw new InvocationTargetException(e);
                }
            }
        });
    } catch (InvocationTargetException e) {
        ErrorDialog.openError(parentShell, "Systrace", "Unable to collect system trace.",
                new Status(Status.ERROR, DdmsPlugin.PLUGIN_ID,
                        "Unexpected error while collecting system trace.", e.getCause()));
    } catch (InterruptedException ignore) {
    }
}