Java Code Examples for com.intellij.openapi.project.ProjectUtil#guessProjectForFile()

The following examples show how to use com.intellij.openapi.project.ProjectUtil#guessProjectForFile() . 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: 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 2
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 3
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 4
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;
}
 
Example 5
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 6
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 7
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 8
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 9
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());
    }
  };
}