private static PsiDirectory[] filterSourceDirectories(
     PsiDirectory baseDir, Project project, PsiDirectory[] moduleDirectories) {
   final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
   if (fileIndex.isInTestSourceContent(baseDir.getVirtualFile())) {
     List<PsiDirectory> result = new ArrayList<PsiDirectory>();
     for (PsiDirectory moduleDirectory : moduleDirectories) {
       if (fileIndex.isInTestSourceContent(moduleDirectory.getVirtualFile())) {
         result.add(moduleDirectory);
       }
     }
     moduleDirectories = result.toArray(new PsiDirectory[result.size()]);
   }
   return moduleDirectories;
 }
  protected void performRefactoring(
      Project project,
      PsiDirectory directory,
      PsiPackage aPackage,
      boolean searchInComments,
      boolean searchForTextOccurences) {
    final VirtualFile sourceRoot =
        ProjectRootManager.getInstance(project)
            .getFileIndex()
            .getSourceRootForFile(directory.getVirtualFile());
    if (sourceRoot == null) {
      Messages.showErrorDialog(
          project,
          RefactoringBundle.message("destination.directory.does.not.correspond.to.any.package"),
          RefactoringBundle.message("cannot.move"));
      return;
    }
    final JavaRefactoringFactory factory = JavaRefactoringFactory.getInstance(project);
    final MoveDestination destination =
        myPreserveSourceRoot.isSelected() && myPreserveSourceRoot.isVisible()
            ? factory.createSourceFolderPreservingMoveDestination(aPackage.getQualifiedName())
            : factory.createSourceRootMoveDestination(aPackage.getQualifiedName(), sourceRoot);

    MoveClassesOrPackagesProcessor processor =
        new MoveClassesOrPackagesProcessor(
            myDirectory.getProject(),
            myElementsToMove,
            destination,
            searchInComments,
            searchForTextOccurences,
            myMoveCallback);
    if (processor.verifyValidPackageName()) {
      processor.run();
    }
  }
    @Override
    protected void addCompletions(
        @NotNull CompletionParameters completionParameters,
        final ProcessingContext processingContext,
        @NotNull final CompletionResultSet completionResultSet) {

      PsiFile originalFile = completionParameters.getOriginalFile();
      final PsiDirectory containingDirectory = originalFile.getContainingDirectory();
      if (containingDirectory == null) {
        return;
      }

      final VirtualFile containingDirectoryFiles = containingDirectory.getVirtualFile();
      VfsUtil.visitChildrenRecursively(
          containingDirectoryFiles,
          new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile file) {

              String relativePath = VfsUtil.getRelativePath(file, containingDirectoryFiles, '/');
              if (relativePath == null) {
                return super.visitFile(file);
              }

              completionResultSet.addElement(
                  LookupElementBuilder.create(relativePath).withIcon(file.getFileType().getIcon()));

              return super.visitFile(file);
            }
          });
    }
  @Nullable
  public static PsiDirectory selectDirectory(
      Project project,
      PsiDirectory[] packageDirectories,
      PsiDirectory defaultDirectory,
      String postfixToShow) {
    ProjectFileIndex projectFileIndex = getInstance(project).getFileIndex();

    ArrayList<PsiDirectory> possibleDirs = new ArrayList<>();
    for (PsiDirectory dir : packageDirectories) {
      if (!dir.isValid()) continue;
      if (!dir.isWritable()) continue;
      if (possibleDirs.contains(dir)) continue;
      if (!projectFileIndex.isInContent(dir.getVirtualFile())) continue;
      possibleDirs.add(dir);
    }

    if (possibleDirs.isEmpty()) return null;
    if (possibleDirs.size() == 1) return possibleDirs.get(0);

    if (getApplication().isUnitTestMode()) return possibleDirs.get(0);

    DirectoryChooser chooser = new DirectoryChooser(project);
    chooser.setTitle(message("title.choose.destination.directory"));
    chooser.fillList(
        possibleDirs.toArray(new PsiDirectory[possibleDirs.size()]),
        defaultDirectory,
        project,
        postfixToShow);
    return chooser.showAndGet() ? chooser.getSelectedDirectory() : null;
  }
 @Override
 public boolean isSourceRoot(@NotNull PsiDirectory dir) {
   final VirtualFile file = dir.getVirtualFile();
   final VirtualFile sourceRoot =
       ProjectRootManager.getInstance(dir.getProject()).getFileIndex().getSourceRootForFile(file);
   return file.equals(sourceRoot);
 }
示例#6
0
  @Nullable
  private PsiDirectory chooseDirectory(final Project project, final PsiFile file) {
    PsiDirectory preferredDirectory =
        myWritableDirectoryList.isEmpty() ? null : myWritableDirectoryList.get(0);
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final VirtualFile virtualFile = file.getVirtualFile();
    assert virtualFile != null;
    final Module moduleForFile = fileIndex.getModuleForFile(virtualFile);
    if (myWritableDirectoryList.size() > 1
        && !ApplicationManager.getApplication().isUnitTestMode()) {
      if (moduleForFile != null) {
        for (PsiDirectory directory : myWritableDirectoryList) {
          if (fileIndex.getModuleForFile(directory.getVirtualFile()) == moduleForFile) {
            preferredDirectory = directory;
            break;
          }
        }
      }

      return DirectoryChooserUtil.chooseDirectory(
          myWritableDirectoryList.toArray(new PsiDirectory[myWritableDirectoryList.size()]),
          preferredDirectory,
          project,
          new HashMap<PsiDirectory, String>());
    }
    return preferredDirectory;
  }
 @Override
 public PsiPackage getPackage(@NotNull PsiDirectory dir) {
   ProjectFileIndex projectFileIndex =
       ProjectRootManager.getInstance(dir.getProject()).getFileIndex();
   String packageName = projectFileIndex.getPackageNameByDirectory(dir.getVirtualFile());
   if (packageName == null) return null;
   return JavaPsiFacade.getInstance(dir.getProject()).findPackage(packageName);
 }
 @Override
 protected String getActionName(PsiDirectory directory, String newName) {
   return IdeBundle.message(
       "progress.creating.file",
       directory.getVirtualFile().getPresentableUrl(),
       File.separator,
       newName);
 }
  @SuppressWarnings("DialogTitleCapitalization")
  @Nullable
  public static PsiFile createFileFromTemplate(
      @SuppressWarnings("NullableProblems") @NotNull String name,
      @NotNull FileTemplate template,
      @NotNull PsiDirectory dir,
      @Nullable String defaultTemplateProperty) {
    // TODO: Do we *have* to hack the IntelliJ source?
    // This is a roughly a copy/paste then slight adaptation from the IntelliJ definition of this
    // method.
    // We can't override it directly, and more importantly we can't override its call to
    // FileTemplateUtil.createFromTemplate()
    List<String> pathItems = FileUtil.getPathFromSourceRoot(dir.getProject(), dir.getVirtualFile());
    // modulePrefix is the empty string if the module is either in the top
    // level directory or one of the subdirectories start with a lower-case
    // letter.
    final String modulePrefix =
        pathItems == null || invalidPathItems(pathItems) ? "" : StringUtil.join(pathItems, ".");

    // Adapted from super definition.
    CreateFileAction.MkDirs mkdirs = new CreateFileAction.MkDirs(name, dir);
    name = mkdirs.newName;
    dir = mkdirs.directory;
    PsiElement element;
    Project project = dir.getProject();
    try {
      // Patch props with custom property.
      Properties props = FileTemplateManager.getInstance().getDefaultProperties(project);
      props.setProperty(
          "HASKELL_MODULE_NAME", modulePrefix.isEmpty() ? name : modulePrefix + '.' + name);
      element = FileTemplateUtil.createFromTemplate(template, name, props, dir);

      final PsiFile psiFile = element.getContainingFile();

      final VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile != null) {
        FileEditorManager.getInstance(project).openFile(virtualFile, true);
        if (defaultTemplateProperty != null) {
          PropertiesComponent.getInstance(project)
              .setValue(defaultTemplateProperty, template.getName());
        }
        return psiFile;
      }
    } catch (ParseException e) {
      Messages.showErrorDialog(
          project,
          "Error parsing Velocity template: " + e.getMessage(),
          "Create File from Template");
      return null;
    } catch (IncorrectOperationException e) {
      throw e;
    } catch (Exception e) {
      LOG.error(e);
    }

    return null;
  }
 @Nullable
 public MoveDestination selectDirectory(
     final PackageWrapper targetPackage, final boolean showChooserWhenDefault) {
   final DirectoryChooser.ItemWrapper selectedItem =
       (DirectoryChooser.ItemWrapper) getComboBox().getSelectedItem();
   if (selectedItem == null || selectedItem == NULL_WRAPPER) {
     return new MultipleRootsMoveDestination(targetPackage);
   }
   final PsiDirectory selectedPsiDirectory = selectedItem.getDirectory();
   VirtualFile selectedDestination = selectedPsiDirectory.getVirtualFile();
   if (showChooserWhenDefault
       && selectedDestination == myInitialTargetDirectory.getVirtualFile()
       && mySourceRoots.length > 1) {
     selectedDestination =
         MoveClassesOrPackagesUtil.chooseSourceRoot(
             targetPackage, mySourceRoots, myInitialTargetDirectory);
   }
   if (selectedDestination == null) return null;
   return new AutocreatingSingleSourceRootMoveDestination(targetPackage, selectedDestination);
 }
  private static LanguageLevel getLanguageLevelInner(@NotNull PsiDirectory dir) {
    final VirtualFile virtualFile = dir.getVirtualFile();
    final Project project = dir.getProject();
    final Module module =
        ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
    if (module != null) {
      return LanguageLevelUtil.getEffectiveLanguageLevel(module);
    }

    return LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();
  }
  protected void doCheckCreate(PsiDirectory dir, String parameterName, String typeName)
      throws IncorrectOperationException {
    // check to see if a file with the same name already exists

    String fileName = fileNameFromTypeName(typeName, parameterName);

    VirtualFile targetFile = dir.getVirtualFile().findFileByRelativePath(fileName);
    if (targetFile != null) {
      throw new IncorrectOperationException(
          GoBundle.message("target.file.exists", targetFile.getPath()));
    }
  }
示例#13
0
 public static List<PsiDirectory> getWritableDirectoryListDefault(
     @Nullable final PsiPackage context,
     final GlobalSearchScope scope,
     final PsiManager psiManager) {
   if (LOG.isDebugEnabled()) {
     LOG.debug(
         "Getting writable directory list for package '"
             + (context == null ? null : context.getQualifiedName())
             + "', scope="
             + scope);
   }
   final List<PsiDirectory> writableDirectoryList = new ArrayList<PsiDirectory>();
   if (context != null) {
     for (PsiDirectory directory : context.getDirectories()) {
       if (LOG.isDebugEnabled()) {
         LOG.debug("Package directory: " + directory);
       }
       if (directory.isWritable() && scope.contains(directory.getVirtualFile())) {
         writableDirectoryList.add(directory);
       }
     }
   } else {
     for (VirtualFile root :
         ProjectRootManager.getInstance(psiManager.getProject()).getContentSourceRoots()) {
       PsiDirectory directory = psiManager.findDirectory(root);
       if (LOG.isDebugEnabled()) {
         LOG.debug("Root: " + root + ", directory: " + directory);
       }
       if (directory != null
           && directory.isWritable()
           && scope.contains(directory.getVirtualFile())) {
         writableDirectoryList.add(directory);
       }
     }
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("Result " + writableDirectoryList);
   }
   return writableDirectoryList;
 }
 public static List<VirtualFile> getPotentialRoots(Module module) {
   final PsiDirectory[] dirs = getIntentionDescriptionsDirs(module);
   final List<VirtualFile> result = new ArrayList<VirtualFile>();
   if (dirs.length != 0) {
     for (PsiDirectory dir : dirs) {
       final PsiDirectory parent = dir.getParentDirectory();
       if (parent != null) result.add(parent.getVirtualFile());
     }
   } else {
     ContainerUtil.addAll(result, ModuleRootManager.getInstance(module).getSourceRoots());
   }
   return result;
 }
 private static boolean isTestDirectory(final Module module, final PsiElement element) {
   final PsiDirectory dir = (PsiDirectory) element;
   final ModuleRootManager manager = ModuleRootManager.getInstance(module);
   final ContentEntry[] entries = manager.getContentEntries();
   for (ContentEntry entry : entries) {
     for (SourceFolder folder : entry.getSourceFolders()) {
       if (folder.isTestSource() && folder.getFile() == dir.getVirtualFile()) {
         return true;
       }
     }
   }
   return false;
 }
 @Override
 protected String getContainerText(PsiFileSystemItem element, String name) {
   PsiFileSystemItem parent = element.getParent();
   final PsiDirectory psiDirectory = parent instanceof PsiDirectory ? (PsiDirectory) parent : null;
   if (psiDirectory == null) return null;
   final VirtualFile virtualFile = psiDirectory.getVirtualFile();
   final String relativePath = getRelativePath(virtualFile, element.getProject());
   if (relativePath == null) return "( " + File.separator + " )";
   String path =
       FilePathSplittingPolicy.SPLIT_BY_SEPARATOR.getOptimalTextForComponent(
           name + "          ", new File(relativePath), this, myMaxWidth);
   return "(" + path + ")";
 }
  private void updateErrorMessage(
      Pass<String> updateErrorMessage, ProjectFileIndex fileIndex, Object selectedItem) {
    updateErrorMessage.pass(null);
    if (myInitialTargetDirectory != null
        && selectedItem instanceof DirectoryChooser.ItemWrapper
        && selectedItem != NULL_WRAPPER) {
      final PsiDirectory directory = ((DirectoryChooser.ItemWrapper) selectedItem).getDirectory();
      final boolean isSelectionInTestSourceContent =
          fileIndex.isInTestSourceContent(directory.getVirtualFile());
      final boolean inTestSourceContent =
          fileIndex.isInTestSourceContent(myInitialTargetDirectory.getVirtualFile());
      if (isSelectionInTestSourceContent != inTestSourceContent) {
        if (inTestSourceContent && reportBaseInTestSelectionInSource()) {
          updateErrorMessage.pass("Source root is selected while the test root is expected");
        }

        if (isSelectionInTestSourceContent && reportBaseInSourceSelectionInTest()) {
          updateErrorMessage.pass("Test root is selected while the source root is expected");
        }
      }
    }
  }
  private static boolean allowed(@NotNull GoNamedElement element) {
    GoFile file = element.getContainingFile();
    if (GoPsiImplUtil.builtin(element) || !GoUtil.allowed(file) || GoUtil.isExcludedFile(file))
      return false;
    PsiDirectory directory = file.getContainingDirectory();
    if (directory != null) {
      VirtualFile vFile = directory.getVirtualFile();
      if (vFile.getPath().endsWith("go/doc/testdata")) return false;
    }

    if (StringUtil.equals(file.getPackageName(), GoConstants.MAIN)) return false;
    return true;
  }
示例#19
0
  public static boolean isInsideProjectSources(AnActionEvent event) {
    ProjectFileIndex projectFileIndex =
        ProjectRootManager.getInstance(event.getProject()).getFileIndex();
    final IdeView view = event.getData(DataKeys.IDE_VIEW);

    for (PsiDirectory dir : view.getDirectories()) {
      if (projectFileIndex.isInSourceContent(dir.getVirtualFile())
          && JavaDirectoryService.getInstance().getPackage(dir) != null) {
        return true;
      }
    }
    return false;
  }
 @Override
 protected void notifyByBalloon(
     JUnitRunningModel model, boolean started, final JUnitConsoleProperties consoleProperties) {
   if (myFoundTests) {
     super.notifyByBalloon(model, started, consoleProperties);
   } else {
     final String packageName = myConfiguration.getPackage();
     if (packageName == null) return;
     final Project project = myConfiguration.getProject();
     final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
     if (aPackage == null) return;
     final Module module = myConfiguration.getConfigurationModule().getModule();
     if (module == null) return;
     final Set<Module> modulesWithPackage = new HashSet<Module>();
     final PsiDirectory[] directories = aPackage.getDirectories();
     for (PsiDirectory directory : directories) {
       final Module currentModule =
           ModuleUtil.findModuleForFile(directory.getVirtualFile(), project);
       if (module != currentModule && currentModule != null) {
         modulesWithPackage.add(currentModule);
       }
     }
     if (!modulesWithPackage.isEmpty()) {
       final String testRunDebugId =
           consoleProperties.isDebug() ? ToolWindowId.DEBUG : ToolWindowId.RUN;
       final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
       final Function<Module, String> moduleNameRef =
           new Function<Module, String>() {
             @Override
             public String fun(Module module) {
               final String moduleName = module.getName();
               return "<a href=\"" + moduleName + "\">" + moduleName + "</a>";
             }
           };
       String message = "Tests were not found in module \"" + module.getName() + "\".\n" + "Use ";
       if (modulesWithPackage.size() == 1) {
         message += "module \"" + moduleNameRef.fun(modulesWithPackage.iterator().next()) + "\" ";
       } else {
         message += "one of\n" + StringUtil.join(modulesWithPackage, moduleNameRef, "\n") + "\n";
       }
       message += "instead";
       toolWindowManager.notifyByBalloon(
           testRunDebugId,
           MessageType.WARNING,
           message,
           null,
           new ResetConfigurationModuleAdapter(
               project, consoleProperties, toolWindowManager, testRunDebugId));
     }
   }
 }
  @Nullable
  protected DirCoverageInfo getDirCoverageInfo(
      @NotNull final PsiDirectory directory, @NotNull final CoverageSuitesBundle currentSuite) {
    final VirtualFile dir = directory.getVirtualFile();

    final boolean isInTestContent = TestSourcesFilter.isTestSources(dir, directory.getProject());
    if (!currentSuite.isTrackTestFolders() && isInTestContent) {
      return null;
    }

    final String path = normalizeFilePath(dir.getPath());

    return isInTestContent ? myTestDirCoverageInfos.get(path) : myDirCoverageInfos.get(path);
  }
  @Override
  public ProblemDescriptor[] checkClass(
      @NotNull PsiClass aClass, @NotNull InspectionManager manager, boolean isOnTheFly) {
    final Project project = aClass.getProject();
    final PsiIdentifier nameIdentifier = aClass.getNameIdentifier();
    final Module module = ModuleUtil.findModuleForPsiElement(aClass);

    if (nameIdentifier == null || module == null || !PsiUtil.isInstanciatable(aClass)) return null;

    final PsiClass base =
        JavaPsiFacade.getInstance(project)
            .findClass(INTENTION, GlobalSearchScope.allScope(project));

    if (base == null || !aClass.isInheritor(base, true)) return null;

    String descriptionDir = getDescriptionDirName(aClass);
    if (StringUtil.isEmptyOrSpaces(descriptionDir)) {
      return null;
    }

    for (PsiDirectory description : getIntentionDescriptionsDirs(module)) {
      PsiDirectory dir = description.findSubdirectory(descriptionDir);
      if (dir == null) continue;
      final PsiFile descr = dir.findFile("description.html");
      if (descr != null) {
        if (!hasBeforeAndAfterTemplate(dir.getVirtualFile())) {
          PsiElement problem = aClass.getNameIdentifier();
          ProblemDescriptor problemDescriptor =
              manager.createProblemDescriptor(
                  problem == null ? nameIdentifier : problem,
                  "Intention must have 'before.*.template' and 'after.*.template' beside 'description.html'",
                  isOnTheFly,
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
          return new ProblemDescriptor[] {problemDescriptor};
        }

        return null;
      }
    }

    final PsiElement problem = aClass.getNameIdentifier();
    final ProblemDescriptor problemDescriptor =
        manager.createProblemDescriptor(
            problem == null ? nameIdentifier : problem,
            "Intention does not have a description",
            isOnTheFly,
            new LocalQuickFix[] {new CreateHtmlDescriptionFix(descriptionDir, module, true)},
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    return new ProblemDescriptor[] {problemDescriptor};
  }
  @Override
  public ProblemDescriptor[] checkClass(
      @NotNull PsiClass aClass, @NotNull InspectionManager manager, boolean isOnTheFly) {
    final Project project = aClass.getProject();
    final PsiIdentifier nameIdentifier = aClass.getNameIdentifier();
    final Module module = ModuleUtilCore.findModuleForPsiElement(aClass);

    if (nameIdentifier == null || module == null || !PsiUtil.isInstantiable(aClass)) return null;

    final PsiClass base =
        JavaPsiFacade.getInstance(project).findClass(getClassName(), aClass.getResolveScope());
    if (base == null || !aClass.isInheritor(base, true)) return null;

    String descriptionDir = DescriptionCheckerUtil.getDescriptionDirName(aClass);
    if (StringUtil.isEmptyOrSpaces(descriptionDir)) {
      return null;
    }

    for (PsiDirectory description : getDescriptionsDirs(module)) {
      PsiDirectory dir = description.findSubdirectory(descriptionDir);
      if (dir == null) continue;
      final PsiFile descr = dir.findFile("description.html");
      if (descr != null) {
        if (!hasBeforeAndAfterTemplate(dir.getVirtualFile())) {
          PsiElement problem = aClass.getNameIdentifier();
          ProblemDescriptor problemDescriptor =
              manager.createProblemDescriptor(
                  problem == null ? nameIdentifier : problem,
                  getHasNotBeforeAfterError(),
                  isOnTheFly,
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
                  false);
          return new ProblemDescriptor[] {problemDescriptor};
        }

        return null;
      }
    }

    final PsiElement problem = aClass.getNameIdentifier();
    final ProblemDescriptor problemDescriptor =
        manager.createProblemDescriptor(
            problem == null ? nameIdentifier : problem,
            getHasNotDescriptionError(),
            isOnTheFly,
            new LocalQuickFix[] {getFix(module, descriptionDir)},
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    return new ProblemDescriptor[] {problemDescriptor};
  }
示例#24
0
 public static String getPackageName(PsiDirectory directory, boolean includeRootDir) {
   PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
   if (aPackage == null) {
     return directory.getVirtualFile().getPresentableUrl();
   } else {
     String packageName = getPackageName(aPackage);
     if (includeRootDir) {
       String rootDir = getRootDirectoryForPackage(directory);
       if (rootDir != null) {
         return UsageViewBundle.message("usage.target.package.in.directory", packageName, rootDir);
       }
     }
     return packageName;
   }
 }
    @Override
    public boolean canClose(final String inputString) {
      if (inputString.length() == 0) {
        return super.canClose(inputString);
      }

      final PsiDirectory psiDirectory = getDirectory();

      final Project project = psiDirectory.getProject();
      final boolean[] result = {false};
      FileTypeChooser.getKnownFileTypeOrAssociate(
          psiDirectory.getVirtualFile(), getFileName(inputString), project);
      result[0] = super.canClose(getFileName(inputString));
      return result[0];
    }
示例#26
0
  public static String getRootDirectoryForPackage(PsiDirectory directory) {
    PsiManager manager = directory.getManager();
    final VirtualFile virtualFile = directory.getVirtualFile();
    final ProjectFileIndex fileIndex =
        ProjectRootManager.getInstance(manager.getProject()).getFileIndex();
    VirtualFile root = fileIndex.getSourceRootForFile(virtualFile);

    if (root == null) {
      root = fileIndex.getClassRootForFile(virtualFile);
    }
    if (root != null) {
      return root.getPresentableUrl();
    }
    return null;
  }
示例#27
0
  @Nullable
  public static String getSourcePositionPackageDisplayName(
      DebugProcessImpl debugProcess, @Nullable SourcePosition position) {
    if (position == null) {
      return null;
    }
    final PsiFile positionFile = position.getFile();
    if (positionFile instanceof JspFile) {
      final PsiDirectory dir = positionFile.getContainingDirectory();
      return dir != null ? dir.getVirtualFile().getPresentableUrl() : null;
    }

    final PsiClass psiClass = getClassAt(position);

    if (psiClass != null) {
      PsiClass toplevel = PsiUtil.getTopLevelClass(psiClass);
      if (toplevel != null) {
        String qName = toplevel.getQualifiedName();
        if (qName != null) {
          int i = qName.lastIndexOf('.');
          return i > 0 ? qName.substring(0, i) : "";
        }
      }
    }

    if (positionFile instanceof PsiClassOwner) {
      String name = ((PsiClassOwner) positionFile).getPackageName();
      if (!StringUtil.isEmpty(name)) {
        return name;
      }
    }

    if (debugProcess != null && debugProcess.isAttached()) {
      List<ReferenceType> allClasses = debugProcess.getPositionManager().getAllClasses(position);
      if (!allClasses.isEmpty()) {
        final String className = allClasses.get(0).name();
        int dotIndex = className.lastIndexOf('.');
        if (dotIndex >= 0) {
          return className.substring(0, dotIndex);
        }
      }
    }
    return "";
  }
  /**
   * @param elementToCopy PsiFile or PsiDirectory
   * @param newName can be not null only if elements.length == 1
   * @param choice a horrible way to pass/keep user preference
   * @return first copied PsiFile (recursively); null if no PsiFiles copied
   */
  @Nullable
  public static PsiFile copyToDirectory(
      @NotNull PsiFileSystemItem elementToCopy,
      @Nullable String newName,
      @NotNull PsiDirectory targetDirectory,
      @Nullable int[] choice)
      throws IncorrectOperationException, IOException {
    if (elementToCopy instanceof PsiFile) {
      PsiFile file = (PsiFile) elementToCopy;
      String name = newName == null ? file.getName() : newName;
      if (checkFileExist(targetDirectory, choice, file, name, "Copy")) return null;
      return targetDirectory.copyFileFrom(name, file);
    } else if (elementToCopy instanceof PsiDirectory) {
      PsiDirectory directory = (PsiDirectory) elementToCopy;
      if (directory.equals(targetDirectory)) {
        return null;
      }
      if (newName == null) newName = directory.getName();
      final PsiDirectory existing = targetDirectory.findSubdirectory(newName);
      final PsiDirectory subdirectory =
          existing == null ? targetDirectory.createSubdirectory(newName) : existing;
      EncodingRegistry.doActionAndRestoreEncoding(
          directory.getVirtualFile(),
          new ThrowableComputable<VirtualFile, IOException>() {
            @Override
            public VirtualFile compute() {
              return subdirectory.getVirtualFile();
            }
          });

      PsiFile firstFile = null;
      PsiElement[] children = directory.getChildren();
      for (PsiElement child : children) {
        PsiFileSystemItem item = (PsiFileSystemItem) child;
        PsiFile f = copyToDirectory(item, item.getName(), subdirectory, choice);
        if (firstFile == null) {
          firstFile = f;
        }
      }
      return firstFile;
    } else {
      throw new IllegalArgumentException("unexpected elementToCopy: " + elementToCopy);
    }
  }
  @Nullable
  private RunnerAndConfigurationSettings createConfiguration(final PsiClass aClass) {
    final Project project = aClass.getProject();
    RunnerAndConfigurationSettings settings =
        RunManagerEx.getInstanceEx(project).createConfiguration("", getConfigurationFactory());
    final GroovyScriptRunConfiguration configuration =
        (GroovyScriptRunConfiguration) settings.getConfiguration();
    final PsiFile file = aClass.getContainingFile().getOriginalFile();
    final PsiDirectory dir = file.getContainingDirectory();
    if (dir == null) return null;
    configuration.setWorkDir(dir.getVirtualFile().getPath());
    final VirtualFile vFile = file.getVirtualFile();
    if (vFile == null) return null;
    configuration.setScriptPath(vFile.getPath());
    RunConfigurationModule module = configuration.getConfigurationModule();

    String name = getConfigurationName(aClass, module);
    configuration.setName(name);
    configuration.setModule(JavaExecutionUtil.findModule(aClass));
    return settings;
  }
  public void setData(
      PsiElement[] psiElements, PsiDirectory initialTargetDirectory, @NonNls String helpID) {
    if (psiElements.length == 1) {
      String text;
      if (psiElements[0] instanceof PsiFile) {
        text =
            RefactoringBundle.message(
                "move.file.0", ((PsiFile) psiElements[0]).getVirtualFile().getPresentableUrl());
      } else {
        text =
            RefactoringBundle.message(
                "move.directory.0",
                ((PsiDirectory) psiElements[0]).getVirtualFile().getPresentableUrl());
      }
      myNameLabel.setText(text);
    } else {
      boolean isFile = true;
      boolean isDirectory = true;
      for (PsiElement psiElement : psiElements) {
        isFile &= psiElement instanceof PsiFile;
        isDirectory &= psiElement instanceof PsiDirectory;
      }
      myNameLabel.setText(
          isFile
              ? RefactoringBundle.message("move.specified.files")
              : isDirectory
                  ? RefactoringBundle.message("move.specified.directories")
                  : RefactoringBundle.message("move.specified.elements"));
    }

    myTargetDirectoryField
        .getChildComponent()
        .setText(
            initialTargetDirectory == null
                ? ""
                : initialTargetDirectory.getVirtualFile().getPresentableUrl());

    validateOKButton();
    myHelpID = helpID;
  }