List of usage examples for com.intellij.openapi.ui Messages showErrorDialog
public static void showErrorDialog(String message, @NotNull @Nls(capitalization = Nls.Capitalization.Title) String title)
From source file:com.android.tools.idea.gradle.variant.view.BuildVariantUpdater.java
License:Apache License
private static void logAndShowUpdateFailure(@NotNull String buildVariantName, @NotNull String reason) { String prefix = String.format("Unable to select build variant '%1$s'", buildVariantName); LOG.error(prefix + ": " + reason); String msg = prefix + ".\n\nConsult IDE log for more details (Help | Show Log)"; Messages.showErrorDialog(msg, "Error"); }
From source file:com.android.tools.idea.monitor.AndroidToolWindowFactory.java
License:Apache License
@Override public void createToolWindowContent(@NotNull final Project project, @NotNull final ToolWindow toolWindow) { // In order to use the runner layout ui, the runner infrastructure needs to be initialized. // Otherwise it is not possible to for example drag one of the tabs out of the tool window. // The object that needs to be created is the content manager of the execution manager for this project. ExecutionManager.getInstance(project).getContentManager(); RunnerLayoutUi layoutUi = RunnerLayoutUi.Factory.getInstance(project).create("Android", TOOL_WINDOW_ID, "Profiling Tools", project); toolWindow.setIcon(AndroidIcons.AndroidToolWindow); toolWindow.setAvailable(true, null); toolWindow.setToHideOnEmptyContent(true); toolWindow.setTitle(TOOL_WINDOW_ID); DeviceContext deviceContext = new DeviceContext(); // TODO Remove global handlers. These handlers are global, but are set per project. // if there are two projects opened, things go very wrong. ClientData.setMethodProfilingHandler(new OpenVmTraceHandler(project)); Content logcatContent = createLogcatContent(layoutUi, project, deviceContext); final AndroidLogcatView logcatView = logcatContent.getUserData(AndroidLogcatView.ANDROID_LOGCAT_VIEW_KEY); assert logcatView != null; logcatContent.setSearchComponent(logcatView.createSearchComponent()); layoutUi.addContent(logcatContent, 0, PlaceInGrid.center, false); MonitorContentFactory.createMonitorContent(project, deviceContext, layoutUi); layoutUi.getOptions().setLeftToolbar(getToolbarActions(project, deviceContext), ActionPlaces.UNKNOWN); layoutUi.addListener(new ContentManagerAdapter() { @Override/*from w ww .ja v a2s . c om*/ public void selectionChanged(ContentManagerEvent event) { Content selectedContent = event.getContent(); BaseMonitorView view = selectedContent.getUserData(BaseMonitorView.MONITOR_VIEW_KEY); if (view != null && event.getOperation() == ContentManagerEvent.ContentOperation.add) { UsageTracker.getInstance() .log(AndroidStudioEvent.newBuilder() .setCategory(AndroidStudioEvent.EventCategory.PROFILING) .setKind(AndroidStudioEvent.EventKind.MONITOR_RUNNING) .setMonitorType(view.getMonitorType())); } } }, project); final JBLoadingPanel loadingPanel = new JBLoadingPanel(new BorderLayout(), project); DevicePanel devicePanel = new DevicePanel(project, deviceContext); JPanel panel = devicePanel.getComponent(); panel.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM)); loadingPanel.add(panel, BorderLayout.NORTH); loadingPanel.add(layoutUi.getComponent(), BorderLayout.CENTER); final ContentManager contentManager = toolWindow.getContentManager(); Content c = contentManager.getFactory().createContent(loadingPanel, "", true); // Store references to the logcat & device panel views, so that these views can be retrieved directly from // the DDMS tool window. (e.g. to clear logcat before a launch, select a particular device, etc) c.putUserData(AndroidLogcatView.ANDROID_LOGCAT_VIEW_KEY, logcatView); c.putUserData(DEVICES_PANEL_KEY, devicePanel); contentManager.addContent(c); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { logcatView.activate(); final ToolWindow window = ToolWindowManager.getInstance(project).getToolWindow(TOOL_WINDOW_ID); if (window != null && window.isVisible()) { ConsoleView console = logcatView.getLogConsole().getConsole(); if (console != null) { checkFacetAndSdk(project, console); } } } }, project.getDisposed()); final File adb = AndroidSdkUtils.getAdb(project); if (adb == null) { return; } loadingPanel.setLoadingText("Initializing ADB"); loadingPanel.startLoading(); ListenableFuture<AndroidDebugBridge> future = AdbService.getInstance().getDebugBridge(adb); Futures.addCallback(future, new FutureCallback<AndroidDebugBridge>() { @Override public void onSuccess(@Nullable AndroidDebugBridge bridge) { Logger.getInstance(AndroidToolWindowFactory.class).info("Successfully obtained debug bridge"); loadingPanel.stopLoading(); } @Override public void onFailure(@NotNull Throwable t) { loadingPanel.stopLoading(); // If we cannot connect to ADB in a reasonable amount of time (10 seconds timeout in AdbService), then something is seriously // wrong. The only identified reason so far is that some machines have incompatible versions of adb that were already running. // e.g. Genymotion, some HTC flashing software, Ubuntu's adb package may all conflict with the version of adb in the SDK. Logger.getInstance(AndroidToolWindowFactory.class).info("Unable to obtain debug bridge", t); String msg; if (t.getMessage() != null) { msg = t.getMessage(); } else { msg = String.format("Unable to establish a connection to adb.\n\n" + "Check the Event Log for possible issues.\n" + "This can happen if you have an incompatible version of adb running already.\n" + "Try re-opening %1$s after killing any existing adb daemons.\n\n" + "If this happens repeatedly, please file a bug at http://b.android.com including the following:\n" + " 1. Output of the command: '%2$s devices'\n" + " 2. Your idea.log file (Help | Show Log in Explorer)\n", ApplicationNamesInfo.getInstance().getProductName(), adb.getAbsolutePath()); } Messages.showErrorDialog(msg, "ADB Connection Error"); } }, EdtExecutor.INSTANCE); }
From source file:com.android.tools.idea.npw.NewModuleWizardDynamic.java
License:Apache License
protected boolean checkSdk() { if (!AndroidSdkUtils.isAndroidSdkAvailable() || !TemplateManager.templatesAreValid()) { String title = "SDK problem"; String msg = "<html>Your Android SDK is missing, out of date, or is missing templates.<br>" + "You can configure your SDK via <b>Configure | Project Defaults | Project Structure | SDKs</b></html>"; Messages.showErrorDialog(msg, title); return false; }/* w ww. j a v a 2s. c o m*/ return true; }
From source file:com.android.tools.idea.npw.NewProjectWizardDynamic.java
License:Apache License
protected void checkSdk() { if (!AndroidSdkUtils.isAndroidSdkAvailable() || !TemplateManager.templatesAreValid()) { String title = "SDK problem"; String msg = "<html>Your Android SDK is missing, out of date, or is missing templates.<br>" + "You can configure your SDK via <b>Configure | Project Defaults | Project Structure | SDKs</b></html>"; Messages.showErrorDialog(msg, title); throw new IllegalStateException("Android SDK missing"); }/*from www. j a v a 2s. co m*/ }
From source file:com.android.tools.idea.npw.NewProjectWizardDynamic.java
License:Apache License
private void runFinish() { if (ApplicationManager.getApplication().isUnitTestMode()) { return;/*from w w w . ja v a 2 s . com*/ } GradleProjectImporter projectImporter = GradleProjectImporter.getInstance(); String rootPath = getState().get(PROJECT_LOCATION_KEY); if (rootPath == null) { LOG.error("No root path specified for project"); return; } File rootLocation = new File(rootPath); File wrapperPropertiesFilePath = GradleWrapper.getDefaultPropertiesFilePath(rootLocation); try { GradleWrapper.get(wrapperPropertiesFilePath).updateDistributionUrl(SdkConstants.GRADLE_LATEST_VERSION); } catch (IOException e) { // Unlikely to happen. Continue with import, the worst-case scenario is that sync fails and the error message has a "quick fix". LOG.warn("Failed to update Gradle wrapper file", e); } String projectName = getState().get(APPLICATION_NAME_KEY); if (projectName == null) { projectName = "Unnamed Project"; } // Pick the highest language level of all the modules/form factors. // We have to pick the language level up front while creating the project rather than // just reacting to it during sync, because otherwise the user gets prompted with // a changing-language-level-requires-reopening modal dialog box and have to reload // the project LanguageLevel initialLanguageLevel = null; for (FormFactor factor : FormFactor.values()) { Object version = getState().get(FormFactorUtils.getLanguageLevelKey(factor)); if (version != null) { LanguageLevel level = LanguageLevel.parse(version.toString()); if (level != null && (initialLanguageLevel == null || level.isAtLeast(initialLanguageLevel))) { initialLanguageLevel = level; } } } // This is required for Android plugin in IDEA if (!IdeInfo.getInstance().isAndroidStudio()) { final Sdk jdk = IdeSdks.getInstance().getJdk(); if (jdk != null) { ApplicationManager.getApplication() .runWriteAction(() -> ProjectRootManager.getInstance(myProject).setProjectSdk(jdk)); } } try { GradleSyncListener listener = new PostStartupGradleSyncListener(() -> { Iterable<File> targetFiles = myState.get(TARGET_FILES_KEY); assert targetFiles != null; TemplateUtils.reformatAndRearrange(myProject, targetFiles); Collection<File> filesToOpen = myState.get(FILES_TO_OPEN_KEY); assert filesToOpen != null; TemplateUtils.openEditors(myProject, filesToOpen, true); }); GradleProjectImporter.Request request = new GradleProjectImporter.Request(); request.setLanguageLevel(initialLanguageLevel).setProject(myProject); projectImporter.importProject(projectName, rootLocation, request, listener); } catch (IOException | ConfigurationException e) { Messages.showErrorDialog(e.getMessage(), ERROR_MSG_TITLE); LOG.error(e); } }
From source file:com.android.tools.idea.npw.NewProjectWizardDynamic.java
License:Apache License
@Override public void doFinishAction() { if (!checkFinish()) return;// w w w . ja va 2 s .com final String projectLocation = myState.get(PROJECT_LOCATION_KEY); assert projectLocation != null; boolean couldEnsureLocationExists = WriteCommandAction.runWriteCommandAction(getProject(), new Computable<Boolean>() { @Override public Boolean compute() { // We generally assume that the path has passed a fair amount of prevalidation checks // at the project configuration step before. Write permissions check can be tricky though in some cases, // e.g., consider an unmounted device in the middle of wizard execution or changed permissions. // Anyway, it seems better to check that we were really able to create the target location and are able to // write to it right here when the wizard is about to close, than running into some internal IDE errors // caused by these problems downstream // Note: this change was originally caused by http://b.android.com/219851, but then // during further discussions that a more important bug was in path validation in the old wizards, // where File.canWrite() always returned true as opposed to the correct Files.isWritable(), which is // already used in new wizard's PathValidator. // So the change below is therefore a more narrow case than initially supposed (however it still needs to be handled) try { if (VfsUtil.createDirectoryIfMissing(projectLocation) != null && FileOpUtils.create().canWrite(new File(projectLocation))) { return true; } } catch (Exception e) { LOG.error(String.format("Exception thrown when creating target project location: %1$s", projectLocation), e); } return false; } }); if (!couldEnsureLocationExists) { Messages.showErrorDialog( String.format( "Could not ensure the target project location exists and is accessible:\n\n%1$s\n\n" + "Please try to specify another path.", projectLocation), "Error Creating Project"); navigateToNamedStep(ConfigureAndroidProjectStep.STEP_NAME, true); myHost.shakeWindow(); return; } // Create project in the dispatch thread. (super.doFinishAction also calls doFinish, but in other thread.) try { doFinish(); } catch (IOException e) { LOG.error(e); } }
From source file:com.android.tools.idea.run.AvdComboBox.java
License:Apache License
public AvdComboBox(@Nullable Project project, boolean addEmptyElement, boolean showNotLaunchedOnly) { myProject = project;/*from w w w .java 2s. c o m*/ myAddEmptyElement = addEmptyElement; myShowNotLaunchedOnly = showNotLaunchedOnly; addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final AndroidPlatform platform = findAndroidPlatform(); AvdComboBox avdComboBox = AvdComboBox.this; if (platform == null) { Messages.showErrorDialog(avdComboBox, "Cannot find any configured Android SDK"); return; } RunAndroidAvdManagerAction action = new RunAndroidAvdManagerAction(); action.openAvdManager(myProject); AvdInfo selected = action.getSelected(); if (selected != null) { getComboBox().setSelectedItem(IdDisplay.create(selected.getName(), "")); } } }); setMinimumSize(new Dimension(JBUI.scale(100), getMinimumSize().height)); }
From source file:com.android.tools.idea.sdk.DefaultSdks.java
License:Apache License
private static void updateLocalPropertiesAndSync(@NotNull final File sdkHomePath) { ProjectManager projectManager = ApplicationManager.getApplication().getComponent(ProjectManager.class); Project[] openProjects = projectManager.getOpenProjects(); if (openProjects.length == 0) { return;/* w ww .j a va 2 s.c o m*/ } final List<String> projectsToUpdateNames = Lists.newArrayList(); List<Pair<Project, LocalProperties>> localPropertiesToUpdate = Lists.newArrayList(); for (Project project : openProjects) { if (!Projects.isGradleProject(project)) { continue; } try { LocalProperties localProperties = new LocalProperties(project); if (!FileUtil.filesEqual(sdkHomePath, localProperties.getAndroidSdkPath())) { localPropertiesToUpdate.add(Pair.create(project, localProperties)); projectsToUpdateNames.add("'" + project.getName() + "'"); } } catch (IOException e) { // Exception thrown when local.properties file exists but cannot be read (e.g. no writing permissions.) logAndShowErrorWhenUpdatingLocalProperties(project, e, "read", sdkHomePath); } } if (!localPropertiesToUpdate.isEmpty()) { if (!ApplicationManager.getApplication().isUnitTestMode()) { UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { String format = "The local.properties files in projects %1$s will be modified with the path of Android Studio's default Android SDK:\n" + "'%2$s'"; Messages.showErrorDialog(String.format(format, projectsToUpdateNames, sdkHomePath), "Sync Android SDKs"); } }); } GradleProjectImporter projectImporter = GradleProjectImporter.getInstance(); for (Pair<Project, LocalProperties> toUpdate : localPropertiesToUpdate) { Project project = toUpdate.getFirst(); try { LocalProperties localProperties = toUpdate.getSecond(); if (!FileUtil.filesEqual(sdkHomePath, localProperties.getAndroidSdkPath())) { localProperties.setAndroidSdkPath(sdkHomePath); localProperties.save(); } } catch (IOException e) { logAndShowErrorWhenUpdatingLocalProperties(project, e, "update", sdkHomePath); // No point in syncing project if local.properties is pointing to the wrong SDK. continue; } if (ApplicationManager.getApplication().isUnitTestMode()) { // Don't sync in tests. For now. continue; } projectImporter.requestProjectSync(project, null); } } }
From source file:com.android.tools.idea.sdk.install.patch.PatchInstallingRestarter.java
License:Apache License
/** * Either restart and install the given patch or delete it (if it's already installed). *//* w ww.j av a 2 s . c o m*/ private void processPatch(File androidSdkPath, StudioLoggerProgressIndicator progress, File patchDir) { RepoPackage pendingPackage = null; File installDir = null; try { RepoManager mgr = mySdkHandler.getSdkManager(progress); Repository repo = InstallerUtil.readPendingPackageXml(patchDir, mgr, myFileOp, progress); if (repo != null) { File patch = new File(patchDir, PatchInstallerUtil.PATCH_JAR_FN); pendingPackage = repo.getLocalPackage(); boolean remote = false; if (pendingPackage != null) { // If the pending package was local, use the corresponding installed local package. installDir = mgr.getPackages().getLocalPackages().get(pendingPackage.getPath()).getLocation(); } else { // Otherwise it's remote. pendingPackage = repo.getRemotePackage().get(0); installDir = ((RemotePackage) pendingPackage).getInstallDir(mgr, progress); remote = true; } File existingPackageXml = new File(installDir, LocalRepoLoaderImpl.PACKAGE_XML_FN); File oldPackageXml = new File(patchDir, OLD_PACKAGE_XML_FN); if (patch.exists() && existingPackageXml.renameTo(oldPackageXml)) { // This will exit the app. // Main.installPatch("sdk", PatchInstallerUtil.PATCH_JAR_FN, FileUtil.getTempDirectory(), patch, installDir.getAbsolutePath()); } else { // The patch is already installed, or was cancelled. String relativePath = FileOpUtils.makeRelative(androidSdkPath, installDir, myFileOp); // Use the old mechanism to get the version, since it's actually part of the package itself. Thus we can tell if the patch // has already been applied. Revision rev = AndroidCommonUtils.parsePackageRevision(androidSdkPath.getPath(), relativePath); if (rev != null && rev.equals(pendingPackage.getVersion())) { // We need to make sure the listeners are fired, so create an installer that does nothing and invoke it. InstallerFactory dummyFactory = new DummyInstallerFactory(); dummyFactory.setListenerFactory(new StudioSdkInstallListenerFactory(mySdkHandler)); if (remote) { Installer installer = dummyFactory.createInstaller((RemotePackage) pendingPackage, mgr, new StudioDownloader(), myFileOp); installer.complete(progress); } else { Uninstaller uninstaller = dummyFactory.createUninstaller((LocalPackage) pendingPackage, mgr, myFileOp); uninstaller.complete(progress); } } else { // something went wrong. Move the old package.xml back into place. progress.logWarning("Failed to find version information in " + new File(androidSdkPath, SdkConstants.FN_SOURCE_PROP)); oldPackageXml.renameTo(existingPackageXml); } } } } catch (Exception e) { StringBuilder message = new StringBuilder("A problem occurred while installing "); message.append(pendingPackage != null ? pendingPackage.getDisplayName() : "an SDK package"); if (installDir != null) { message.append(" in ").append(installDir); } message.append(". Please try again."); Messages.showErrorDialog(message.toString(), "Error Launching SDK Component Installer"); progress.logWarning("Failed to install SDK package", e); } // If we get here we either got an error or the patch was already installed. Delete the patch dir. try { myFileOp.deleteFileOrFolder(patchDir); } catch (Exception e) { progress.logWarning("Problem during patch cleanup", e); } }
From source file:com.android.tools.idea.sdk.wizard.HaxmWizard.java
License:Apache License
@Override public void doCancelAction() { if (myHaxmPath.canPerformFinishingActions()) { doFinishAction();// w ww . j av a 2 s . c o m return; } // The wizard was invoked to install, but installer invocation failed or was cancelled. // Have to ensure the SDK package is removed if (!myInvokedToUninstall) { try { AndroidSdkHandler sdkHandler = AndroidSdks.getInstance().tryToChooseSdkHandler(); ComponentInstaller componentInstaller = new ComponentInstaller(sdkHandler); ProgressIndicator progress = new StudioLoggerProgressIndicator(getClass()); sdkHandler.getSdkManager(progress).reloadLocalIfNeeded(progress); componentInstaller.ensureSdkPackagesUninstalled(myHaxmPath.myHaxm.getRequiredSdkPackages(), progress); } catch (Exception e) { Messages.showErrorDialog(SDK_PACKAGE_CLEANUP_FAILED, "Cleanup Error"); LOG.warn("Failed to make sure HAXM SDK package is uninstalled after HAXM wizard was cancelled", e); } } super.doCancelAction(); }