/** Sets current LAF. The method doesn't update component hierarchy. */
  @Override
  public void setCurrentLookAndFeel(UIManager.LookAndFeelInfo lookAndFeelInfo) {
    if (findLaf(lookAndFeelInfo.getClassName()) == null) {
      LOG.error("unknown LookAndFeel : " + lookAndFeelInfo);
      return;
    }
    // Set L&F
    if (IdeaLookAndFeelInfo.CLASS_NAME.equals(
        lookAndFeelInfo.getClassName())) { // that is IDEA default LAF
      IdeaLaf laf = new IdeaLaf();
      MetalLookAndFeel.setCurrentTheme(new IdeaBlueMetalTheme());
      try {
        UIManager.setLookAndFeel(laf);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    } else if (DarculaLookAndFeelInfo.CLASS_NAME.equals(lookAndFeelInfo.getClassName())) {
      DarculaLaf laf = new DarculaLaf();
      try {
        UIManager.setLookAndFeel(laf);
        JBColor.setDark(true);
        IconLoader.setUseDarkIcons(true);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    } else { // non default LAF
      try {
        LookAndFeel laf =
            ((LookAndFeel) Class.forName(lookAndFeelInfo.getClassName()).newInstance());
        if (laf instanceof MetalLookAndFeel) {
          MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
        }
        UIManager.setLookAndFeel(laf);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    }
    myCurrentLaf =
        ObjectUtils.chooseNotNull(findLaf(lookAndFeelInfo.getClassName()), lookAndFeelInfo);

    checkLookAndFeel(lookAndFeelInfo, false);
  }
  private void chooseDirectoryAndMove(Project project, PsiFile myFile) {
    try {
      PsiDirectory directory =
          MoveClassesOrPackagesUtil.chooseDestinationPackage(project, myTargetPackage, null);

      if (directory == null) {
        return;
      }
      String error = RefactoringMessageUtil.checkCanCreateFile(directory, myFile.getName());
      if (error != null) {
        Messages.showMessageDialog(
            project, error, CommonBundle.getErrorTitle(), Messages.getErrorIcon());
        return;
      }
      new MoveClassesOrPackagesProcessor(
              project,
              new PsiElement[] {((PsiJavaFile) myFile).getClasses()[0]},
              new SingleSourceRootMoveDestination(
                  PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(directory)),
                  directory),
              false,
              false,
              null)
          .run();
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  public static void copyAsFiles(
      PsiElement[] elements, @Nullable PsiDirectory defaultTargetDirectory, Project project) {
    PsiDirectory targetDirectory = null;
    String newName = null;
    boolean openInEditor = true;

    if (ApplicationManager.getApplication().isUnitTestMode()) {
      targetDirectory = defaultTargetDirectory;
    } else {
      CopyFilesOrDirectoriesDialog dialog =
          new CopyFilesOrDirectoriesDialog(elements, defaultTargetDirectory, project, false);
      if (dialog.showAndGet()) {
        newName = elements.length == 1 ? dialog.getNewName() : null;
        targetDirectory = dialog.getTargetDirectory();
        openInEditor = dialog.openInEditor();
      }
    }

    if (targetDirectory != null) {
      try {
        for (PsiElement element : elements) {
          PsiFileSystemItem psiElement = (PsiFileSystemItem) element;
          if (psiElement.isDirectory()) {
            MoveFilesOrDirectoriesUtil.checkIfMoveIntoSelf(psiElement, targetDirectory);
          }
        }
      } catch (IncorrectOperationException e) {
        CommonRefactoringUtil.showErrorHint(
            project, null, e.getMessage(), CommonBundle.getErrorTitle(), null);
        return;
      }

      copyImpl(elements, newName, targetDirectory, false, openInEditor);
    }
  }
 static void chooseAmbiguousTargetAndPerform(
     @NotNull final Project project,
     final Editor editor,
     @NotNull PsiElementProcessor<PsiElement> processor) {
   if (editor == null) {
     Messages.showMessageDialog(
         project,
         FindBundle.message("find.no.usages.at.cursor.error"),
         CommonBundle.getErrorTitle(),
         Messages.getErrorIcon());
   } else {
     int offset = editor.getCaretModel().getOffset();
     boolean chosen =
         GotoDeclarationAction.chooseAmbiguousTarget(
             editor,
             offset,
             processor,
             FindBundle.message("find.usages.ambiguous.title", "crap"),
             null);
     if (!chosen) {
       ApplicationManager.getApplication()
           .invokeLater(
               new Runnable() {
                 @Override
                 public void run() {
                   if (editor.isDisposed() || !editor.getComponent().isShowing()) return;
                   HintManager.getInstance()
                       .showErrorHint(
                           editor, FindBundle.message("find.no.usages.at.cursor.error"));
                 }
               },
               project.getDisposed());
     }
   }
 }
  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file)
      throws IncorrectOperationException {
    if (!(file instanceof GroovyFile)) return;

    VirtualFile vfile = file.getVirtualFile();
    if (vfile == null) return;

    final Module module = ModuleUtilCore.findModuleForFile(vfile, project);
    if (module == null) return;

    final String packageName = ((GroovyFile) file).getPackageName();
    PsiDirectory directory =
        PackageUtil.findOrCreateDirectoryForPackage(module, packageName, null, true);
    if (directory == null) return;

    String error = RefactoringMessageUtil.checkCanCreateFile(directory, file.getName());
    if (error != null) {
      Messages.showMessageDialog(
          project, error, CommonBundle.getErrorTitle(), Messages.getErrorIcon());
      return;
    }
    new MoveFilesOrDirectoriesProcessor(
            project, new PsiElement[] {file}, directory, false, false, false, null, null)
        .run();
  }
  @Override
  public void actionPerformed(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null) return;
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);

    UsageTarget[] usageTargets = UsageView.USAGE_TARGETS_KEY.getData(dataContext);
    if (usageTargets != null) {
      FileEditor fileEditor = PlatformDataKeys.FILE_EDITOR.getData(dataContext);
      if (fileEditor != null) {
        usageTargets[0].findUsagesInEditor(fileEditor);
      }
    } else if (editor == null) {
      Messages.showMessageDialog(
          project,
          FindBundle.message("find.no.usages.at.cursor.error"),
          CommonBundle.getErrorTitle(),
          Messages.getErrorIcon());
    } else {
      HintManager.getInstance()
          .showErrorHint(editor, FindBundle.message("find.no.usages.at.cursor.error"));
    }
  }
 @Nullable
 public static AndroidSdkData parse(@NotNull String path, @NotNull final Component component) {
   MessageBuildingSdkLog log = new MessageBuildingSdkLog();
   AndroidSdkData sdkData = parse(path, log);
   if (sdkData == null) {
     String message = log.getErrorMessage();
     if (message.length() > 0) {
       message = "Android SDK is parsed incorrectly. Parsing log:\n" + message;
       Messages.showInfoMessage(component, message, CommonBundle.getErrorTitle());
     }
   }
   return sdkData;
 }
  @Override
  protected void doOKAction() {
    final String resourceName = getResourceName();
    final String fileName = getFileName();
    final List<String> dirNames = getDirNames();
    final Module module = getModule();

    if (resourceName.length() == 0) {
      Messages.showErrorDialog(
          myPanel, "Resource name is not specified", CommonBundle.getErrorTitle());
    } else if (!AndroidResourceUtil.isCorrectAndroidResourceName(resourceName)) {
      Messages.showErrorDialog(
          myPanel, resourceName + " is not correct resource name", CommonBundle.getErrorTitle());
    } else if (fileName.length() == 0) {
      Messages.showErrorDialog(myPanel, "File name is not specified", CommonBundle.getErrorTitle());
    } else if (dirNames.size() == 0) {
      Messages.showErrorDialog(
          myPanel, "Directories are not selected", CommonBundle.getErrorTitle());
    } else if (module == null) {
      Messages.showErrorDialog(myPanel, "Module is not specified", CommonBundle.getErrorTitle());
    } else {
      super.doOKAction();
    }
  }
  @Nullable
  public static VirtualFile createManifestFile(
      final @NotNull VirtualFile directory, final @NotNull Project project) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final Ref<IOException> exc = Ref.create(null);
    final VirtualFile file =
        new WriteAction<VirtualFile>() {
          protected void run(@NotNull final Result<VirtualFile> result) {
            VirtualFile dir = directory;
            try {
              if (!dir.getName().equals(MANIFEST_DIR_NAME)) {
                dir = VfsUtil.createDirectoryIfMissing(dir, MANIFEST_DIR_NAME);
              }
              final VirtualFile file = dir.createChildData(this, MANIFEST_FILE_NAME);
              final OutputStream output = file.getOutputStream(this);
              try {
                final Manifest manifest = new Manifest();
                ManifestBuilder.setVersionAttribute(manifest.getMainAttributes());
                manifest.write(output);
              } finally {
                output.close();
              }
              result.setResult(file);
            } catch (IOException e) {
              exc.set(e);
            }
          }
        }.execute().getResultObject();

    final IOException exception = exc.get();
    if (exception != null) {
      LOG.info(exception);
      Messages.showErrorDialog(project, exception.getMessage(), CommonBundle.getErrorTitle());
      return null;
    }
    return file;
  }
  @Override
  @Nullable
  protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project) {
    if (aClass instanceof PsiAnonymousClass) {
      Messages.showMessageDialog(
          project,
          CodeInsightBundle.message("error.attempt.to.generate.constructor.for.anonymous.class"),
          CommonBundle.getErrorTitle(),
          Messages.getErrorIcon());
      return null;
    }

    myCopyJavadoc = false;
    PsiMethod[] baseConstructors = null;
    PsiClass baseClass = aClass.getSuperClass();
    if (baseClass != null) {
      ArrayList<PsiMethod> array = new ArrayList<PsiMethod>();
      for (PsiMethod method : baseClass.getConstructors()) {
        if (JavaPsiFacade.getInstance(method.getProject())
            .getResolveHelper()
            .isAccessible(method, aClass, null)) {
          array.add(method);
        }
      }
      if (!array.isEmpty()) {
        if (array.size() == 1) {
          baseConstructors = new PsiMethod[] {array.get(0)};
        } else {
          final PsiSubstitutor substitutor =
              TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY);
          PsiMethodMember[] constructors =
              ContainerUtil.map2Array(
                  array,
                  PsiMethodMember.class,
                  new Function<PsiMethod, PsiMethodMember>() {
                    @Override
                    public PsiMethodMember fun(final PsiMethod s) {
                      return new PsiMethodMember(s, substitutor);
                    }
                  });
          MemberChooser<PsiMethodMember> chooser =
              new MemberChooser<PsiMethodMember>(constructors, false, true, project);
          chooser.setTitle(
              CodeInsightBundle.message("generate.constructor.super.constructor.chooser.title"));
          chooser.show();
          List<PsiMethodMember> elements = chooser.getSelectedElements();
          if (elements == null || elements.isEmpty()) return null;
          baseConstructors = new PsiMethod[elements.size()];
          for (int i = 0; i < elements.size(); i++) {
            final ClassMember member = elements.get(i);
            baseConstructors[i] = ((PsiMethodMember) member).getElement();
          }
          myCopyJavadoc = chooser.isCopyJavadoc();
        }
      }
    }

    ClassMember[] allMembers = getAllOriginalMembers(aClass);
    ClassMember[] members;
    if (allMembers.length == 0) {
      members = ClassMember.EMPTY_ARRAY;
    } else {
      members = chooseMembers(allMembers, true, false, project, null);
      if (members == null) return null;
    }
    if (baseConstructors != null) {
      ArrayList<ClassMember> array = new ArrayList<ClassMember>();
      for (PsiMethod baseConstructor : baseConstructors) {
        array.add(new PsiMethodMember(baseConstructor));
      }
      ContainerUtil.addAll(array, members);
      members = array.toArray(new ClassMember[array.size()]);
    }

    return members;
  }
  public boolean canClose(String inputString) {
    final String subDirName = inputString;

    if (subDirName.length() == 0) {
      Messages.showMessageDialog(
          myProject,
          IdeBundle.message("error.name.should.be.specified"),
          CommonBundle.getErrorTitle(),
          Messages.getErrorIcon());
      return false;
    }

    final boolean multiCreation = StringUtil.containsAnyChar(subDirName, myDelimiters);
    if (!multiCreation) {
      try {
        myDirectory.checkCreateSubdirectory(subDirName);
      } catch (IncorrectOperationException ex) {
        Messages.showMessageDialog(
            myProject,
            CreateElementActionBase.filterMessage(ex.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return false;
      }
    }

    Runnable command =
        new Runnable() {
          public void run() {
            final Runnable run =
                new Runnable() {
                  public void run() {
                    LocalHistoryAction action = LocalHistoryAction.NULL;
                    try {
                      String actionName;
                      String dirPath = myDirectory.getVirtualFile().getPresentableUrl();
                      actionName =
                          IdeBundle.message(
                              "progress.creating.directory", dirPath, File.separator, subDirName);
                      action = LocalHistory.getInstance().startAction(actionName);

                      createDirectories(subDirName);

                    } catch (final IncorrectOperationException ex) {
                      ApplicationManager.getApplication()
                          .invokeLater(
                              new Runnable() {
                                public void run() {
                                  Messages.showMessageDialog(
                                      myProject,
                                      CreateElementActionBase.filterMessage(ex.getMessage()),
                                      CommonBundle.getErrorTitle(),
                                      Messages.getErrorIcon());
                                }
                              });
                    } finally {
                      action.finish();
                    }
                  }
                };
            ApplicationManager.getApplication().runWriteAction(run);
          }
        };
    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            command,
            myIsDirectory
                ? IdeBundle.message("command.create.directory")
                : IdeBundle.message("command.create.package"),
            null);

    return myCreatedElement != null;
  }
  @Nullable
  public static Project openProject(
      final String path, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
    File file = new File(path);
    if (!file.exists()) {
      Messages.showErrorDialog(
          IdeBundle.message("error.project.file.does.not.exist", path),
          CommonBundle.getErrorTitle());
      return null;
    }

    if (file.isDirectory() && !new File(file, Project.DIRECTORY_STORE_FOLDER).exists()) {
      String message =
          IdeBundle.message(
              "error.project.file.does.not.exist",
              new File(file, Project.DIRECTORY_STORE_FOLDER).getPath());
      Messages.showErrorDialog(message, CommonBundle.getErrorTitle());
      return null;
    }

    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    for (Project project : openProjects) {
      if (!project.isDefault() && isSameProject(path, project)) {
        focusProjectWindow(project, false);
        return project;
      }
    }

    if (!forceOpenInNewFrame && openProjects.length > 0) {
      int exitCode = confirmOpenNewProject(false);
      if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
        final Project toClose =
            projectToClose != null ? projectToClose : openProjects[openProjects.length - 1];
        if (!closeAndDispose(toClose)) return null;
      } else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
        return null;
      }
    }

    ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
    Project project = null;
    try {
      project = projectManager.loadAndOpenProject(path);
    } catch (IOException e) {
      Messages.showMessageDialog(
          IdeBundle.message("error.cannot.load.project", e.getMessage()),
          IdeBundle.message("title.cannot.load.project"),
          Messages.getErrorIcon());
    } catch (JDOMException e) {
      LOG.info(e);
      Messages.showMessageDialog(
          IdeBundle.message("error.project.file.is.corrupted"),
          IdeBundle.message("title.cannot.load.project"),
          Messages.getErrorIcon());
    } catch (InvalidDataException e) {
      LOG.info(e);
      Messages.showMessageDialog(
          IdeBundle.message("error.project.file.is.corrupted"),
          IdeBundle.message("title.cannot.load.project"),
          Messages.getErrorIcon());
    }
    return project;
  }
  @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
  private boolean initializeDdmlib(@NotNull Project project) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    while (true) {
      final MyInitializeDdmlibTask task = new MyInitializeDdmlibTask(project);

      AdbErrors.clear();

      Thread t =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  doInitializeDdmlib();
                  task.finish();
                }
              });

      t.start();

      boolean retryWas = false;

      while (!task.isFinished()) {
        ProgressManager.getInstance().run(task);

        boolean finished = task.isFinished();

        if (task.isCanceled()) {
          myAdbCrashed = !finished;
          forceInterrupt(t);
          return false;
        }

        myAdbCrashed = false;

        if (!finished) {
          final String adbErrorString = combine(AdbErrors.getErrors());
          final int result =
              Messages.showDialog(
                  project,
                  "ADB not responding. You can wait more, or kill \""
                      + SdkConstants.FN_ADB
                      + "\" process manually and click 'Restart'"
                      + (adbErrorString.length() > 0
                          ? "\nErrors from ADB:\n" + adbErrorString
                          : ""),
                  CommonBundle.getErrorTitle(),
                  new String[] {"&Wait more", "&Restart", "&Cancel"},
                  0,
                  Messages.getErrorIcon());
          if (result == 2) {
            // cancel
            myAdbCrashed = true;
            forceInterrupt(t);
            return false;
          } else if (result == 1) {
            // restart
            myAdbCrashed = true;
            retryWas = true;
          }
        }
      }

      // task finished, but if we had problems, ddmlib can be still initialized incorrectly, so we
      // invoke initialize once again
      if (!retryWas) {
        break;
      }
    }

    return true;
  }
 protected String getErrorTitle() {
   return CommonBundle.getErrorTitle();
 }
  @Override
  public boolean setupSdkPaths(@NotNull Sdk sdk, @NotNull SdkModel sdkModel) {
    final List<String> javaSdks = Lists.newArrayList();
    final Sdk[] sdks = sdkModel.getSdks();
    for (Sdk jdk : sdks) {
      if (Jdks.isApplicableJdk(jdk)) {
        javaSdks.add(jdk.getName());
      }
    }

    if (javaSdks.isEmpty()) {
      Messages.showErrorDialog(
          AndroidBundle.message("no.jdk.for.android.found.error"), "No Java SDK Found");
      return false;
    }

    MessageBuildingSdkLog log = new MessageBuildingSdkLog();
    AndroidSdkData sdkData = getSdkData(sdk);

    if (sdkData == null) {
      String errorMessage =
          !log.getErrorMessage().isEmpty()
              ? log.getErrorMessage()
              : AndroidBundle.message("cannot.parse.sdk.error");
      Messages.showErrorDialog(errorMessage, "SDK Parsing Error");
      return false;
    }

    IAndroidTarget[] targets = sdkData.getTargets();

    if (targets.length == 0) {
      if (Messages.showOkCancelDialog(
              AndroidBundle.message("no.android.targets.error"),
              CommonBundle.getErrorTitle(),
              "Open SDK Manager",
              Messages.CANCEL_BUTTON,
              Messages.getErrorIcon())
          == Messages.OK) {
        RunAndroidSdkManagerAction.runSpecificSdkManager(null, sdkData.getLocation());
      }
      return false;
    }

    String[] targetNames = new String[targets.length];

    String newestPlatform = null;
    AndroidVersion version = null;

    for (int i = 0; i < targets.length; i++) {
      IAndroidTarget target = targets[i];
      String targetName = getTargetPresentableName(target);
      targetNames[i] = targetName;
      if (target.isPlatform() && (version == null || target.getVersion().compareTo(version) > 0)) {
        newestPlatform = targetName;
        version = target.getVersion();
      }
    }

    AndroidNewSdkDialog dialog =
        new AndroidNewSdkDialog(
            null,
            javaSdks,
            javaSdks.get(0),
            Arrays.asList(targetNames),
            newestPlatform != null ? newestPlatform : targetNames[0]);
    if (!dialog.showAndGet()) {
      return false;
    }
    String name = javaSdks.get(dialog.getSelectedJavaSdkIndex());
    Sdk jdk = sdkModel.findSdk(name);
    IAndroidTarget target = targets[dialog.getSelectedTargetIndex()];
    String sdkName = chooseNameForNewLibrary(target);
    setUpSdk(sdk, sdkName, sdks, target, jdk, true);

    return true;
  }
  @Override
  public boolean setupSdkPaths(Sdk sdk, SdkModel sdkModel) {
    final List<String> javaSdks = new ArrayList<String>();
    final Sdk[] sdks = sdkModel.getSdks();
    for (Sdk jdk : sdks) {
      if (AndroidSdkUtils.isApplicableJdk(jdk)) {
        javaSdks.add(jdk.getName());
      }
    }

    if (javaSdks.isEmpty()) {
      Messages.showErrorDialog(
          AndroidBundle.message("no.jdk.for.android.found.error"), "No Java SDK Found");
      return false;
    }

    int choice =
        Messages.showChooseDialog(
            "Please select Java SDK",
            "Select Internal Java Platform",
            ArrayUtil.toStringArray(javaSdks),
            javaSdks.get(0),
            Messages.getQuestionIcon());

    if (choice == -1) {
      return false;
    }

    final String name = javaSdks.get(choice);
    final Sdk jdk = sdkModel.findSdk(name);

    MessageBuildingSdkLog log = new MessageBuildingSdkLog();
    AndroidSdkData sdkData = AndroidSdkData.parse(sdk.getHomePath(), log);

    if (sdkData == null) {
      String errorMessage =
          log.getErrorMessage().length() > 0
              ? log.getErrorMessage()
              : AndroidBundle.message("cannot.parse.sdk.error");
      Messages.showErrorDialog(errorMessage, "SDK Parsing Error");
      return false;
    }

    IAndroidTarget[] targets = sdkData.getTargets();

    if (targets.length == 0) {
      Messages.showErrorDialog(
          AndroidBundle.message("no.android.targets.error"), CommonBundle.getErrorTitle());
      return false;
    }

    String[] targetNames = new String[targets.length];

    String newestPlatform = null;
    AndroidVersion version = null;

    for (int i = 0; i < targets.length; i++) {
      IAndroidTarget target = targets[i];
      String targetName = AndroidSdkUtils.getTargetPresentableName(target);
      targetNames[i] = targetName;
      if (target.isPlatform() && (version == null || target.getVersion().compareTo(version) > 0)) {
        newestPlatform = targetName;
        version = target.getVersion();
      }
    }

    choice =
        Messages.showChooseDialog(
            "Select build target",
            "Create New Android SDK",
            targetNames,
            newestPlatform != null ? newestPlatform : targetNames[0],
            Messages.getQuestionIcon());

    if (choice == -1) {
      return false;
    }

    AndroidSdkUtils.setUpSdk(sdk, jdk, sdks, targets[choice], true);

    return true;
  }