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);
    }
  }
  @Override
  public void moduleAdded() {
    if (!myModuleInitialized) {
      myConnection.subscribe(
          ProjectTopics.PROJECT_ROOTS,
          new ModuleRootAdapter() {
            @Override
            public void rootsChanged(ModuleRootEvent event) {
              scheduleUpdate();
            }
          });
      myConnection.subscribe(GoLibrariesService.LIBRARIES_TOPIC, newRootUrls -> scheduleUpdate());

      Project project = myModule.getProject();
      StartupManager.getInstance(project)
          .runWhenProjectIsInitialized(
              () -> {
                if (!project.isDisposed() && !myModule.isDisposed()) {
                  for (PsiFileSystemItem vendor :
                      FilenameIndex.getFilesByName(
                          project, GoConstants.VENDOR, GoUtil.moduleScope(myModule), true)) {
                    if (vendor.isDirectory()) {
                      showVendoringNotification();
                      break;
                    }
                  }
                }
              });

      VirtualFileManager.getInstance().addVirtualFileListener(myFilesListener);
    }
    scheduleUpdate(0);
    myModuleInitialized = true;
  }
 public static boolean isRoot(PsiFileSystemItem directory) {
   if (directory == null) return true;
   VirtualFile vFile = directory.getVirtualFile();
   if (vFile == null) return true;
   ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(directory.getProject());
   return Comparing.equal(fileIndex.getClassRootForFile(vFile), vFile)
       || Comparing.equal(fileIndex.getContentRootForFile(vFile), vFile)
       || Comparing.equal(fileIndex.getSourceRootForFile(vFile), vFile);
 }
 @Override
 @NotNull
 public Collection<PsiFileSystemItem> getContexts(
     final Project project, @NotNull final VirtualFile file) {
   final PsiFileSystemItem item = getPsiFileSystemItem(project, file);
   if (item != null) {
     final PsiFileSystemItem parent = item.getParent();
     if (parent != null) {
       return Collections.singleton(parent);
     }
   }
   return Collections.emptyList();
 }
 @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 + ")";
 }
  /**
   * @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);
    }
  }
Ejemplo n.º 7
0
 private PsiDirectory findOurSourceRoot(PsiFileSystemItem item) {
   for (VirtualFile sourceRoot : ModuleRootManager.getInstance(myIdeaModule).getSourceRoots()) {
     String rootPath = sourceRoot.toString();
     String itemPath = item.getVirtualFile().toString();
     if (itemPath.startsWith(rootPath)) {
       return PsiManager.getInstance(myIdeaModule.getProject()).findDirectory(sourceRoot);
     }
   }
   return null;
 }
 public void processIncludingFiles(
     PsiFile context, Processor<Pair<VirtualFile, FileIncludeInfo>> processor) {
   context = context.getOriginalFile();
   VirtualFile contextFile = context.getVirtualFile();
   if (contextFile == null) return;
   MultiMap<VirtualFile, FileIncludeInfoImpl> infoList =
       FileIncludeIndex.getIncludingFileCandidates(
           context.getName(), GlobalSearchScope.allScope(myProject));
   for (VirtualFile candidate : infoList.keySet()) {
     PsiFile psiFile = myPsiManager.findFile(candidate);
     if (psiFile == null || context.equals(psiFile)) continue;
     for (FileIncludeInfo info : infoList.get(candidate)) {
       PsiFileSystemItem item = resolveFileInclude(info, psiFile);
       if (item != null && contextFile.equals(item.getVirtualFile())) {
         if (!processor.process(Pair.create(candidate, info))) {
           return;
         }
       }
     }
   }
 }
 @Nullable
 public static List<File> asFileList(final PsiElement[] elements) {
   final List<File> result = new ArrayList<File>();
   for (PsiElement element : elements) {
     final PsiFileSystemItem psiFile;
     if (element instanceof PsiFileSystemItem) {
       psiFile = (PsiFileSystemItem) element;
     } else if (element instanceof PsiDirectoryContainer) {
       final PsiDirectory[] directories = ((PsiDirectoryContainer) element).getDirectories();
       psiFile = directories[0];
     } else {
       psiFile = element.getContainingFile();
     }
     if (psiFile != null) {
       VirtualFile vFile = psiFile.getVirtualFile();
       if (vFile != null && vFile.getFileSystem() instanceof LocalFileSystem) {
         result.add(new File(vFile.getPath()));
       }
     }
   }
   return result.isEmpty() ? null : result;
 }
  @Nullable
  public BundleManifest getManifest(@NotNull PsiFileSystemItem item) {
    VirtualFile file = item.getVirtualFile();
    if (file != null) {
      List<OrderEntry> entries = myIndex.getOrderEntriesForFile(file);
      if (entries.size() == 1 && entries.get(0) instanceof JdkOrderEntry) {
        return new JdkBundleManifest();
      }

      Module module = myIndex.getModuleForFile(file);
      if (module != null) {
        return getManifest(module);
      }

      VirtualFile libRoot = myIndex.getClassRootForFile(file);
      if (libRoot != null) {
        return getManifest(libRoot);
      }
    }

    return null;
  }
  @Override
  public Object[] getFileReferenceCompletionVariants(final FileReference reference) {
    final String s = reference.getText();
    if (s != null && s.equals("/")) {
      return ArrayUtil.EMPTY_OBJECT_ARRAY;
    }

    final CommonProcessors.CollectUniquesProcessor<PsiFileSystemItem> collector =
        new CommonProcessors.CollectUniquesProcessor<PsiFileSystemItem>();
    final PsiElementProcessor<PsiFileSystemItem> processor =
        new PsiElementProcessor<PsiFileSystemItem>() {
          @Override
          public boolean execute(@NotNull PsiFileSystemItem fileSystemItem) {
            return new FilteringProcessor<PsiFileSystemItem>(
                    reference.getFileReferenceSet().getReferenceCompletionFilter(), collector)
                .process(FileReference.getOriginalFile(fileSystemItem));
          }
        };

    List<Object> additionalItems = ContainerUtil.newArrayList();
    for (PsiFileSystemItem context : reference.getContexts()) {
      for (final PsiElement child : context.getChildren()) {
        if (child instanceof PsiFileSystemItem) {
          processor.execute((PsiFileSystemItem) child);
        }
      }
      if (context instanceof FileReferenceResolver) {
        additionalItems.addAll(((FileReferenceResolver) context).getVariants(reference));
      }
    }

    final FileType[] types = reference.getFileReferenceSet().getSuitableFileTypes();
    final THashSet<PsiElement> set =
        new THashSet<PsiElement>(collector.getResults(), VARIANTS_HASHING_STRATEGY);
    final PsiElement[] candidates = PsiUtilCore.toPsiElementArray(set);

    final Object[] variants = new Object[candidates.length + additionalItems.size()];
    for (int i = 0; i < candidates.length; i++) {
      PsiElement candidate = candidates[i];
      Object item = reference.createLookupItem(candidate);
      if (item == null) {
        item = FileInfoManager.getFileLookupItem(candidate);
      }
      if (candidate instanceof PsiFile
          && item instanceof LookupElement
          && types.length > 0
          && ArrayUtil.contains(((PsiFile) candidate).getFileType(), types)) {
        item = PrioritizedLookupElement.withPriority((LookupElement) item, Double.MAX_VALUE);
      }
      variants[i] = item;
    }

    for (int i = 0; i < additionalItems.size(); i++) {
      variants[i + candidates.length] = additionalItems.get(i);
    }
    if (!reference.getFileReferenceSet().isUrlEncoded()) {
      return variants;
    }
    List<Object> encodedVariants = new ArrayList<Object>(variants.length + additionalItems.size());
    for (int i = 0; i < candidates.length; i++) {
      final PsiElement element = candidates[i];
      if (element instanceof PsiNamedElement) {
        final PsiNamedElement psiElement = (PsiNamedElement) element;
        String name = psiElement.getName();
        final String encoded = reference.encode(name, psiElement);
        if (encoded == null) continue;
        if (!encoded.equals(name)) {
          final Icon icon =
              psiElement.getIcon(Iconable.ICON_FLAG_READ_STATUS | Iconable.ICON_FLAG_VISIBILITY);
          LookupElementBuilder item =
              FileInfoManager.getFileLookupItem(candidates[i], encoded, icon);
          encodedVariants.add(item.withTailText(" (" + name + ")"));
        } else {
          encodedVariants.add(variants[i]);
        }
      }
    }
    encodedVariants.addAll(additionalItems);
    return ArrayUtil.toObjectArray(encodedVariants);
  }
  @Nullable
  @Override
  public PsiElement[] getGotoDeclarationTargets(
      @Nullable PsiElement sourceElement, int offset, Editor editor) {
    ArrayList<PsiElement> result = new ArrayList<PsiElement>();
    if (sourceElement != null)
      for (PsiReference reference : sourceElement.getReferences())
        if (reference instanceof PsiPolyVariantReference)
          for (ResolveResult resolveResult :
              ((PsiPolyVariantReference) reference).multiResolve(false))
            result.add(resolveResult.getElement());
        else result.add(reference.resolve());

    // add shadowed variables declaration
    if (sourceElement instanceof PerlVariableNameElement) {
      PsiElement variable = sourceElement.getParent();

      if (variable instanceof PerlVariable) {
        PsiElement variableContainer = sourceElement.getParent().getParent();
        PsiFile myFile = sourceElement.getContainingFile();

        if (myFile instanceof PerlFileElement
            && (variableContainer instanceof PsiPerlVariableDeclarationLexical
                || variableContainer instanceof PsiPerlVariableDeclarationGlobal)) {
          PerlVariable shadowedVariable =
              ((PerlFileElement) myFile).getLexicalDeclaration((PerlVariable) variable);
          if (shadowedVariable != null && !result.contains(shadowedVariable))
            result.add(shadowedVariable);
        }
      }
    }
    // additional procesing for subname
    else if (sourceElement instanceof PerlSubNameElement) {
      PsiElement elementParent = sourceElement.getParent();

      // suppress declaration if there is a definition and declaration
      if (result.size() == 2
          && !(elementParent instanceof PerlSubDefinition
              || elementParent instanceof PerlSubDeclaration))
        if (result.get(0).getOriginalElement() instanceof PerlSubDeclaration
            && result.get(1).getOriginalElement() instanceof PerlSubDefinition) result.remove(0);

    }
    // string content to file jump
    else if (sourceElement instanceof PerlStringContentElement
        && ((PerlStringContentElement) sourceElement).looksLikePath()) {
      String tokenText = sourceElement.getText().replaceAll("\\\\", "/").replaceAll("/+", "/");
      Project project = sourceElement.getProject();

      String fileName = ((PerlStringContentElement) sourceElement).getContentFileName();

      for (String file : FilenameIndex.getAllFilenames(project))
        if (file.contains(fileName)) {
          // fixme somehow if includeDirectories is true - no files found
          for (PsiFileSystemItem fileItem :
              FilenameIndex.getFilesByName(project, file, GlobalSearchScope.allScope(project))) {
            String canonicalPath = fileItem.getVirtualFile().getCanonicalPath();
            if (canonicalPath != null)
              if (canonicalPath.contains(tokenText + ".")) // higer priority
              result.add(0, fileItem);
              else if (canonicalPath.contains(tokenText)) result.add(fileItem);
          }
          for (PsiFileSystemItem fileItem :
              FilenameIndex.getFilesByName(
                  project, file, GlobalSearchScope.allScope(project), true)) {
            String canonicalPath = fileItem.getVirtualFile().getCanonicalPath();
            if (canonicalPath != null) if (canonicalPath.contains(tokenText)) result.add(fileItem);
          }
        }
    }

    return result.toArray(new PsiElement[result.size()]);
  }
 @Override
 public String getElementText(PsiFileSystemItem element) {
   return element.getName();
 }