com.intellij.openapi.project.ProjectUtil Java Examples

The following examples show how to use com.intellij.openapi.project.ProjectUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@After
@Override
public void tearDown() throws Exception {
  new RunAll(
    () -> {
      if (myProject != null && !myProject.isDisposed()) {
        PathKt.delete(ProjectUtil.getExternalConfigurationDir(myProject));
      }
    },
    () -> EdtTestUtil.runInEdtAndWait(() -> tearDownFixtures()),
    () -> myProject = null,
    () -> PathKt.delete(myTestDir.toPath()),
    () -> super.tearDown(),
    () -> resetClassFields(getClass())
  ).run();
}
 
Example #2
Source File: ProjectBuildModelImpl.java    From ok-gradle with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public GradleSettingsModel getProjectSettingsModel() {
  VirtualFile virtualFile = null;
  // If we don't have a root build file, guess the location of the settings file from the project.
  if (myProjectBuildFile == null) {
    VirtualFile projectDir = ProjectUtil.guessProjectDir(myBuildModelContext.getProject());
    if (projectDir != null) {
      File ioFile = VfsUtilCore.virtualToIoFile(projectDir);
      virtualFile = getGradleSettingsFile(ioFile);
    }
  } else {
    virtualFile = myProjectBuildFile.tryToFindSettingsFile();
  }

  if (virtualFile == null) {
    return null;
  }

  GradleSettingsFile settingsFile = myBuildModelContext.getOrCreateSettingsFile(virtualFile);
  return new GradleSettingsModelImpl(settingsFile);
}
 
Example #3
Source File: Settings.java    From weex-language-support with MIT License 6 votes vote down vote up
@Override
public void apply() throws ConfigurationException {
    try {
        PropertiesComponent.getInstance().setValue(KEY_RULES_PATH, rulesPath.getText());
        if (!TextUtils.isEmpty(rulesPath.getText())) {
            load(rulesPath.getText());
            DirectiveLint.prepare();
        } else {
            DirectiveLint.reset();
        }
    } catch (Exception e) {
        ProjectUtil.guessCurrentProject(select).getMessageBus().syncPublisher(Notifications.TOPIC).notify(
                new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID,
                        "Weex language support - bad rules",
                        e.toString(),
                        NotificationType.ERROR));
    }
    savePaths();
}
 
Example #4
Source File: FileContentUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void setFileText(@javax.annotation.Nullable Project project, final VirtualFile virtualFile, final String text) throws IOException {
  if (project == null) {
    project = ProjectUtil.guessProjectForFile(virtualFile);
  }
  if (project != null) {
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document document = psiFile == null? null : psiDocumentManager.getDocument(psiFile);
    if (document != null) {
      document.setText(text != null ? text : "");
      psiDocumentManager.commitDocument(document);
      FileDocumentManager.getInstance().saveDocument(document);
      return;
    }
  }
  VfsUtil.saveText(virtualFile, text != null ? text : "");
  virtualFile.refresh(false, false);
}
 
Example #5
Source File: SimpleCreatePropertyQuickFix.java    From intellij-sdk-docs with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) throws
      IncorrectOperationException {
  ApplicationManager.getApplication().invokeLater(() -> {
    Collection<VirtualFile> virtualFiles =
          FileTypeIndex.getFiles(SimpleFileType.INSTANCE, GlobalSearchScope.allScope(project) );
    if (virtualFiles.size() == 1) {
      createProperty(project, virtualFiles.iterator().next());
    } else {
      final FileChooserDescriptor descriptor =
            FileChooserDescriptorFactory.createSingleFileDescriptor(SimpleFileType.INSTANCE);
      descriptor.setRoots(ProjectUtil.guessProjectDir(project));
      final VirtualFile file1 = FileChooser.chooseFile(descriptor, project, null);
      if (file1 != null) {
        createProperty(project, file1);
      }
    }
  });
}
 
Example #6
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void documentChanged(@Nonnull DocumentEvent e) {
  final Document document = e.getDocument();
  if (!ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.ExternalDocumentChange.class)) {
    myUnsavedDocuments.add(document);
  }
  final Runnable currentCommand = CommandProcessor.getInstance().getCurrentCommand();
  Project project = currentCommand == null ? null : CommandProcessor.getInstance().getCurrentCommandProject();
  if (project == null) project = ProjectUtil.guessProjectForFile(getFile(document));
  String lineSeparator = CodeStyle.getProjectOrDefaultSettings(project).getLineSeparator();
  document.putUserData(LINE_SEPARATOR_KEY, lineSeparator);

  // avoid documents piling up during batch processing
  if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) {
    saveAllDocumentsLater();
  }
}
 
Example #7
Source File: ReferencePointTab.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Updates the contained fields for the given project. Sets the given reference point name as the
 * new directory name. Sets the base path of the chosen project as the base directory for the new
 * directory.
 *
 * <p>Also sets the default option for the selected project. If the name of the project root
 * directory matches the name of the shared reference point or the project contains a module with
 * a content root that matches the given reference point name, the option to use it for the
 * resource negotiation is selected by default. Otherwise, the option to create a new directory is
 * selected by default.
 *
 * @param project the newly selected project to set the default values and selection for
 */
private void updateFieldsForProjectChange(@NotNull Project project) {
  newDirectoryNameTextField.setText(referencePointName);

  VirtualFile projectBaseDir = ProjectUtil.guessProjectDir(project);
  if (projectBaseDir != null) {
    newDirectoryBasePathTextField.setText(projectBaseDir.getPath());

    if (projectBaseDir.getName().equals(referencePointName)) {
      useExistingDirectoryRadioButton.doClick();

      existingDirectoryPathTextField.setText(projectBaseDir.getPath());

      return;
    }
  }

  Module[] modules = ModuleManager.getInstance(project).getModules();
  for (Module module : modules) {
    for (VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) {
      if (contentRoot.getName().equals(referencePointName)) {
        useExistingDirectoryRadioButton.doClick();

        existingDirectoryPathTextField.setText(contentRoot.getPath());

        return;
      }
    }
  }

  createNewDirectoryRadioButton.doClick();
}
 
Example #8
Source File: DirectoryChooser.java    From consulo with Apache License 2.0 5 votes vote down vote up
public String getRelativeToProjectPath() {
  if (myRelativeToProjectPath == null) {
    final PsiDirectory directory = getDirectory();
    final VirtualFile virtualFile = directory != null ? directory.getVirtualFile() : null;
    myRelativeToProjectPath = virtualFile != null
           ? ProjectUtil.calcRelativeToProjectPath(virtualFile, directory.getProject(), true, false, true)
           : getPresentableUrl();
  }
  return myRelativeToProjectPath;
}
 
Example #9
Source File: CodeStyleAbstractPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void updateEditor(boolean useDefaultSample) {
  if (!myShouldUpdatePreview || (!ApplicationManager.getApplication().isUnitTestMode() && !myEditor.getComponent().isShowing())) {
    return;
  }

  if (myLastDocumentModificationStamp != myEditor.getDocument().getModificationStamp()) {
    myTextToReformat = myEditor.getDocument().getText();
  }
  else if (useDefaultSample || myTextToReformat == null) {
    myTextToReformat = getPreviewText();
  }

  int currOffs = myEditor.getScrollingModel().getVerticalScrollOffset();

  final Project finalProject = ProjectUtil.guessCurrentProject(getPanel());
  CommandProcessor.getInstance().executeCommand(finalProject, new Runnable() {
    @Override
    @RequiredUIAccess
    public void run() {
      replaceText(finalProject);
    }
  }, null, null);

  myEditor.getSettings().setRightMargin(getAdjustedRightMargin());
  myLastDocumentModificationStamp = myEditor.getDocument().getModificationStamp();
  myEditor.getScrollingModel().scrollVertically(currOffs);
}
 
Example #10
Source File: TabbedLanguageCodeStylePanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void applyLanguageSettings(Language lang) {
  final Project currProject = ProjectUtil.guessCurrentProject(getPanel());
  CodeStyleSettings rootSettings = CodeStyle.getSettings(currProject);
  CodeStyleSettings targetSettings = getSettings();

  applyLanguageSettings(lang, rootSettings, targetSettings);
  reset(targetSettings);
  onSomethingChanged();
}
 
Example #11
Source File: TrailingSpacesStripper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Project getProject(@Nonnull Document document, @Nullable Editor editor) {
  if (editor != null) return editor.getProject();
  VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file != null) {
    return ProjectUtil.guessProjectForFile(file);
  }
  return null;
}
 
Example #12
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void saveAllDocumentsLater() {
  // later because some document might have been blocked by PSI right now
  TransactionGuard.getInstance().submitTransactionLater(ApplicationManager.getApplication(), () -> {
    final Document[] unsavedDocuments = getUnsavedDocuments();
    for (Document document : unsavedDocuments) {
      VirtualFile file = getFile(document);
      if (file == null) continue;
      Project project = ProjectUtil.guessProjectForFile(file);
      if (project == null) continue;
      if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue;

      saveDocument(document);
    }
  });
}
 
Example #13
Source File: InfoAndProgressPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Component getAnchor(@Nonnull JRootPane pane) {
  Component tabWrapper = UIUtil.findComponentOfType(pane, TabbedPaneWrapper.TabWrapper.class);
  if (tabWrapper != null) {
    return tabWrapper;
  }
  EditorsSplitters splitters = AWTComponentProviderUtil.findChild(pane, EditorsSplitters.class);
  if (splitters != null) {
    return splitters.isShowing() ? splitters.getComponent() : pane;
  }
  FileEditorManagerEx ex = FileEditorManagerEx.getInstanceEx(ProjectUtil.guessCurrentProject(pane));
  if (ex == null) return pane;
  splitters = ex.getSplitters();
  return splitters.isShowing() ? splitters.getComponent() : pane;
}
 
Example #14
Source File: WorkspaceEditHandler.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Opens an editor when needed and gets the Runnable
 *
 * @param edits         The text edits
 * @param uri           The uri of the file
 * @param version       The version of the file
 * @param openedEditors
 * @param curProject
 * @param name
 * @return The runnable containing the edits
 */
private static Runnable manageUnopenedEditor(List<TextEdit> edits, String uri, int version,
                                             List<VirtualFile> openedEditors, Project[] curProject, String name) {
    Project[] projects = ProjectManager.getInstance().getOpenProjects();
    //Infer the project from the uri
    Project project = Stream.of(projects)
            .map(p -> new ImmutablePair<>(FileUtils.VFSToURI(ProjectUtil.guessProjectDir(p)), p))
            .filter(p -> uri.startsWith(p.getLeft())).sorted(Collections.reverseOrder())
            .map(ImmutablePair::getRight).findFirst().orElse(projects[0]);
    VirtualFile file = null;
    try {
        file = LocalFileSystem.getInstance().findFileByIoFile(new File(new URI(FileUtils.sanitizeURI(uri))));
    } catch (URISyntaxException e) {
        LOG.warn(e);
    }
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file);
    Editor editor = ApplicationUtils
            .computableWriteAction(() -> fileEditorManager.openTextEditor(descriptor, false));
    openedEditors.add(file);
    curProject[0] = editor.getProject();
    Runnable runnable = null;
    EditorEventManager manager = EditorEventManagerBase.forEditor(editor);
    if (manager != null) {
        runnable = manager.getEditsRunnable(version, edits, name, true);
    }
    return runnable;
}
 
Example #15
Source File: ReferencePointTab.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks all open projects if the name of its base directory or the name of one of the content
 * roots of one of its modules matches the name of the shared reference point. If such a directory
 * is found, the corresponding project is chosen as the default selection. If multiple of such
 * projects exist, the first one found by the search is used. If no project is found, the first
 * one of the list is selected instead.
 *
 * <p>Calls {@link #setInitialInputForProject(Project)} with the selected project to determine the
 * default values and selection for the other fields.
 */
private void setInitialInput() {
  int projectCount = projectComboBox.getItemCount();

  for (int i = 0; i < projectCount; i++) {
    Project project = projectComboBox.getItemAt(i);

    VirtualFile projectBaseDir = ProjectUtil.guessProjectDir(project);
    if (projectBaseDir != null && projectBaseDir.getName().equals(referencePointName)) {
      setInitialInputForProject(project);

      return;
    }

    Module[] modules = ModuleManager.getInstance(project).getModules();
    for (Module module : modules) {
      for (VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) {
        if (contentRoot.getName().equals(referencePointName)) {
          setInitialInputForProject(project);

          return;
        }
      }
    }
  }

  if (projectCount > 0) {
    setInitialInputForProject(projectComboBox.getItemAt(0));
  }
}
 
Example #16
Source File: Utils.java    From idea-gitignore with MIT License 5 votes vote down vote up
/**
 * Wraps {@link ProjectUtil#guessProjectDir} and returns null for the default project.
 *
 * @param project to check
 * @return project's dir or null if project is default
 */
public static VirtualFile guessProjectDir(@Nullable Project project) {
    if (project == null) {
        return null;
    }
    try {
        return ProjectUtil.guessProjectDir(project);
    } catch (IllegalStateException e) {
        return null;
    }
}
 
Example #17
Source File: LatteFileListener.java    From intellij-latte with MIT License 5 votes vote down vote up
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
    for (VFileEvent event : events) {
        VirtualFile file = event.getFile();
        if (!(file instanceof XmlFile) || !file.getName().equals("latte-intellij.xml") || file.isValid()) {
            continue;
        }

        XmlDocument document = ((XmlFile) file).getDocument();
        if (document == null || document.getRootTag() == null) {
            continue;
        }

        LatteXmlFileData.VendorResult vendorResult = LatteXmlFileDataFactory.getVendor(document);
        if (vendorResult == null) {
            continue;
        }

        List<Project> projects = new ArrayList<>();
        Project project = ProjectUtil.guessProjectForContentFile(file);
        if (project != null) {
            projects.add(project);
        } else {
            Collections.addAll(projects, ProjectManager.getInstance().getOpenProjects());
        }

        LatteIndexUtil.notifyRemovedFiles(projects);
    }
}
 
Example #18
Source File: ImagesProjectNode.java    From intellij-sdk-docs with Apache License 2.0 5 votes vote down vote up
private void addAllByExt(Project project, String ext) {
  final Set<VirtualFile> imagesFiles = getImagesFiles(project);
  final VirtualFile projectDir = ProjectUtil.guessProjectDir(project);
  for (VirtualFile file : FilenameIndex.getAllFilesByExt(project, ext)) {
    while (file != null && !file.equals(projectDir)) {
      imagesFiles.add(file);
      file = file.getParent();
    }
  }
}
 
Example #19
Source File: ImagesProjectNode.java    From intellij-sdk-docs with Apache License 2.0 4 votes vote down vote up
public ImagesProjectNode(final Project project) {
  super(project, ProjectUtil.guessProjectDir(project));
  scanImages(project);

  subscribeToVFS(project);
}
 
Example #20
Source File: DiagnosticsNode.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nullable
private Project getProject(@NotNull VirtualFile file) {
  return app != null ? app.getProject() : ProjectUtil.guessProjectForFile(file);
}
 
Example #21
Source File: OpenInXcodeAction.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static void openFile(@NotNull VirtualFile file) {
  final Project project = ProjectUtil.guessProjectForFile(file);
  final FlutterSdk sdk = project != null ? FlutterSdk.getFlutterSdk(project) : null;
  if (sdk == null) {
    FlutterSdkAction.showMissingSdkDialog(project);
    return;
  }

  final PubRoot pubRoot = PubRoot.forFile(file);
  if (pubRoot == null) {
    FlutterMessages.showError("Error Opening Xcode", "Unable to run `flutter build` (no pub root found)");
    return;
  }

  // Trigger an iOS build if necessary.
  if (!hasBeenBuilt(pubRoot)) {
    final ProgressHelper progressHelper = new ProgressHelper(project);
    progressHelper.start("Building for iOS");

    // TODO(pq): consider a popup explaining why we're doing a build.
    // Note: we build only for the simulator to bypass device provisioning issues.
    final OSProcessHandler processHandler = sdk.flutterBuild(pubRoot, "ios", "--simulator").startInConsole(project);
    if (processHandler == null) {
      progressHelper.done();
      FlutterMessages.showError("Error Opening Xcode", "unable to run `flutter build`");
    }
    else {
      processHandler.addProcessListener(new ProcessAdapter() {
        @Override
        public void processTerminated(@NotNull ProcessEvent event) {
          progressHelper.done();

          final int exitCode = event.getExitCode();
          if (exitCode != 0) {
            FlutterMessages.showError("Error Opening Xcode", "`flutter build` returned: " + exitCode);
            return;
          }

          openWithXcode(file.getPath());
        }
      });
    }
  }
  else {
    openWithXcode(file.getPath());
  }
}
 
Example #22
Source File: ChangelistConflictTracker.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ChangelistConflictTracker(@Nonnull Project project,
                                 @Nonnull ChangeListManager changeListManager,
                                 @Nonnull FileStatusManager fileStatusManager,
                                 @Nonnull EditorNotifications editorNotifications) {
  myProject = project;

  myChangeListManager = changeListManager;
  myEditorNotifications = editorNotifications;
  myDocumentManager = FileDocumentManager.getInstance();
  myFileStatusManager = fileStatusManager;
  myCheckSetLock = new Object();
  myCheckSet = new HashSet<>();

  final Application application = ApplicationManager.getApplication();
  final ZipperUpdater zipperUpdater = new ZipperUpdater(300, Alarm.ThreadToUse.SWING_THREAD, project);
  final Runnable runnable = () -> {
    if (application.isDisposed() || myProject.isDisposed() || !myProject.isOpen()) {
      return;
    }
    final Set<VirtualFile> localSet;
    synchronized (myCheckSetLock) {
      localSet = new HashSet<>();
      localSet.addAll(myCheckSet);
      myCheckSet.clear();
    }
    checkFiles(localSet);
  };
  myDocumentListener = new DocumentAdapter() {
    @Override
    public void documentChanged(DocumentEvent e) {
      if (!myOptions.TRACKING_ENABLED) {
        return;
      }
      Document document = e.getDocument();
      VirtualFile file = myDocumentManager.getFile(document);
      if (ProjectUtil.guessProjectForFile(file) == myProject) {
        synchronized (myCheckSetLock) {
          myCheckSet.add(file);
        }
        zipperUpdater.queue(runnable);
      }
    }
  };

  myChangeListListener = new ChangeListAdapter() {
    @Override
    public void changeListChanged(ChangeList list) {
      if (myChangeListManager.isDefaultChangeList(list)) {
        clearChanges(list.getChanges());
      }
    }

    @Override
    public void changesMoved(Collection<Change> changes, ChangeList fromList, ChangeList toList) {
      if (myChangeListManager.isDefaultChangeList(toList)) {
        clearChanges(changes);
      }
    }

    @Override
    public void changesRemoved(Collection<Change> changes, ChangeList fromList) {
      clearChanges(changes);
    }

    @Override
    public void defaultListChanged(ChangeList oldDefaultList, ChangeList newDefaultList) {
      clearChanges(newDefaultList.getChanges());
    }
  };
}
 
Example #23
Source File: DiagnosticsNode.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nullable
private Project getProject(@NotNull VirtualFile file) {
  return app != null ? app.getProject() : ProjectUtil.guessProjectForFile(file);
}
 
Example #24
Source File: OpenInXcodeAction.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static void openFile(@NotNull VirtualFile file) {
  final Project project = ProjectUtil.guessProjectForFile(file);
  final FlutterSdk sdk = project != null ? FlutterSdk.getFlutterSdk(project) : null;
  if (sdk == null) {
    FlutterSdkAction.showMissingSdkDialog(project);
    return;
  }

  final PubRoot pubRoot = PubRoot.forFile(file);
  if (pubRoot == null) {
    FlutterMessages.showError("Error Opening Xcode", "Unable to run `flutter build` (no pub root found)");
    return;
  }

  // Trigger an iOS build if necessary.
  if (!hasBeenBuilt(pubRoot)) {
    final ProgressHelper progressHelper = new ProgressHelper(project);
    progressHelper.start("Building for iOS");

    // TODO(pq): consider a popup explaining why we're doing a build.
    // Note: we build only for the simulator to bypass device provisioning issues.
    final OSProcessHandler processHandler = sdk.flutterBuild(pubRoot, "ios", "--simulator").startInConsole(project);
    if (processHandler == null) {
      progressHelper.done();
      FlutterMessages.showError("Error Opening Xcode", "unable to run `flutter build`");
    }
    else {
      processHandler.addProcessListener(new ProcessAdapter() {
        @Override
        public void processTerminated(@NotNull ProcessEvent event) {
          progressHelper.done();

          final int exitCode = event.getExitCode();
          if (exitCode != 0) {
            FlutterMessages.showError("Error Opening Xcode", "`flutter build` returned: " + exitCode);
            return;
          }

          openWithXcode(file.getPath());
        }
      });
    }
  }
  else {
    openWithXcode(file.getPath());
  }
}
 
Example #25
Source File: CodeStyleAbstractPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
private int getAdjustedRightMargin() {
  int result = getRightMargin();
  return result > 0 ? result : CodeStyleFacade.getInstance(ProjectUtil.guessCurrentProject(getPanel())).getRightMargin(getDefaultLanguage());
}
 
Example #26
Source File: CodeStyleAbstractPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
public final void applyPredefinedSettings(@Nonnull PredefinedCodeStyle codeStyle) {
  CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(ProjectUtil.guessCurrentProject(getPanel())).clone();
  codeStyle.apply(settings);
  reset(settings);
  onSomethingChanged();
}
 
Example #27
Source File: CustomizableLanguageCodeStylePanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
protected EditorHighlighter createHighlighter(final EditorColorsScheme scheme) {
  FileType fileType = getFileType();
  return FileTypeEditorHighlighterProviders.INSTANCE.forFileType(fileType).getEditorHighlighter(ProjectUtil.guessCurrentProject(getPanel()), fileType, null, scheme);
}
 
Example #28
Source File: IdeaFrameTitleBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public String getFileTitle(@Nonnull final Project project, @Nonnull final VirtualFile file) {
  return ProjectUtil.calcRelativeToProjectPath(file, project, !SystemInfo.isMac, true, false);
}
 
Example #29
Source File: BackwardDependenciesBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void analyze() {
  AnalysisScope scope = myForwardScope;
  final DependenciesBuilder builder = new ForwardDependenciesBuilder(getProject(), scope, getScopeOfInterest());
  builder.setTotalFileCount(myTotalFileCount);
  builder.analyze();

  subtractScope(builder, getScope());
  final PsiManager psiManager = PsiManager.getInstance(getProject());
  psiManager.startBatchFilesProcessingMode();
  try {
    final int fileCount = getScope().getFileCount();
    getScope().accept(new PsiRecursiveElementVisitor() {
      @Override public void visitFile(final PsiFile file) {
        ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
        if (indicator != null) {
          if (indicator.isCanceled()) {
            throw new ProcessCanceledException();
          }
          indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text"));
          final VirtualFile virtualFile = file.getVirtualFile();
          if (virtualFile != null) {
            indicator.setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, getProject()));
          }
          if (fileCount > 0) {
            indicator.setFraction(((double)++myFileCount) / myTotalFileCount);
          }
        }
        final Map<PsiFile, Set<PsiFile>> dependencies = builder.getDependencies();
        for (final PsiFile psiFile : dependencies.keySet()) {
          if (dependencies.get(psiFile).contains(file)) {
            Set<PsiFile> fileDeps = getDependencies().get(file);
            if (fileDeps == null) {
              fileDeps = new HashSet<PsiFile>();
              getDependencies().put(file, fileDeps);
            }
            fileDeps.add(psiFile);
          }
        }
        psiManager.dropResolveCaches();
        InjectedLanguageManager.getInstance(file.getProject()).dropFileCaches(file);
      }
    });
  }
  finally {
    psiManager.finishBatchFilesProcessingMode();
  }
}
 
Example #30
Source File: MarkdownUtils.java    From markdown-image-kit with MIT License 4 votes vote down vote up
/**
 * 不使用正则, 因为需要记录偏移量
 *
 * @param virtualFile the virtual file 当前处理的文件
 * @param lineText    the line text    当前处理的文本行
 * @param line        the line         在文本中的行数
 * @return the markdown image
 */
@Nullable
public static MarkdownImage analysisImageMark(VirtualFile virtualFile, String lineText, int line) {
    int[] offset = resolveText(lineText);
    if (offset == null) {
        return null;
    }
    MarkdownImage markdownImage = new MarkdownImage();
    markdownImage.setFileName(virtualFile.getName());
    markdownImage.setOriginalLineText(lineText);
    markdownImage.setLineNumber(line);
    markdownImage.setLineStartOffset(offset[0]);
    markdownImage.setLineEndOffset(offset[1]);


    // 解析 markdown 图片标签
    try {
        // 如果以 `<a` 开始, 以 `a>` 结束, 需要修改偏移量
        if (lineText.contains(ImageContents.HTML_TAG_A_START) && lineText.contains(ImageContents.HTML_TAG_A_END)) {
            markdownImage.setLineStartOffset(lineText.indexOf(ImageContents.HTML_TAG_A_START));
            markdownImage.setLineEndOffset(lineText.indexOf(ImageContents.HTML_TAG_A_END) + 2);
            // 解析标签类型
            if (lineText.contains(ImageContents.LARG_IMAGE_MARK_ID)) {
                markdownImage.setImageMarkType(ImageMarkEnum.LARGE_PICTURE);
            } else if (lineText.contains(ImageContents.COMMON_IMAGE_MARK_ID)) {
                markdownImage.setImageMarkType(ImageMarkEnum.COMMON_PICTURE);
            } else {
                markdownImage.setImageMarkType(ImageMarkEnum.CUSTOM);
            }
        } else {
            markdownImage.setImageMarkType(ImageMarkEnum.ORIGINAL);
        }
        // 截取 markdown image 标签
        markdownImage.setOriginalMark(lineText.substring(markdownImage.getLineStartOffset(), markdownImage.getLineEndOffset()));

        String title = lineText.substring(lineText.indexOf(ImageContents.IMAGE_MARK_PREFIX) + ImageContents.IMAGE_MARK_PREFIX.length(),
                                          lineText.indexOf(ImageContents.IMAGE_MARK_MIDDLE)).trim();

        String path = lineText.substring(lineText.indexOf(ImageContents.IMAGE_MARK_MIDDLE) + ImageContents.IMAGE_MARK_MIDDLE.length(),
                                         lineText.indexOf(ImageContents.IMAGE_MARK_SUFFIX)).trim();

        markdownImage.setTitle(title);

        // 设置图片位置类型
        if (path.startsWith(ImageContents.IMAGE_LOCATION)) {
            markdownImage.setLocation(ImageLocationEnum.NETWORK);
            // 图片 url
            markdownImage.setPath(path);
            // 解析图片名
            String imageName = path.substring(path.lastIndexOf("/") + 1);
            markdownImage.setImageName(imageName);
            markdownImage.setExtension(ImageUtils.getFileExtension(imageName));
        } else {
            markdownImage.setLocation(ImageLocationEnum.LOCAL);
            // 图片文件的相对路径
            markdownImage.setPath(path);
            String imagename = path.substring(path.lastIndexOf(File.separator) + 1);

            Project project = ProjectUtil.guessProjectForFile(virtualFile);
            VirtualFile imageVirtualFile = UploadUtils.searchVirtualFileByName(project, imagename);

            markdownImage.setExtension(imageVirtualFile.getExtension());
            markdownImage.setInputStream(imageVirtualFile.getInputStream());
            markdownImage.setVirtualFile(imageVirtualFile);
            markdownImage.setImageName(imagename);
        }
        return markdownImage;
    } catch (IOException e) {
        log.trace("markdown imge mark analysis error", e);
    }
    return null;
}