/**
   * Returns the currently selected file, based on which VcsBranch or StatusBar components will
   * identify the current repository root.
   */
  @Nullable
  public static VirtualFile getSelectedFile(@NotNull Project project) {
    StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
    final FileEditor fileEditor = StatusBarUtil.getCurrentFileEditor(project, statusBar);
    VirtualFile result = null;
    if (fileEditor != null) {
      if (fileEditor instanceof TextEditor) {
        Document document = ((TextEditor) fileEditor).getEditor().getDocument();
        result = FileDocumentManager.getInstance().getFile(document);
      } else if (fileEditor instanceof ImageFileEditor) {
        result = ((ImageFileEditor) fileEditor).getImageEditor().getFile();
      }
    }

    if (result == null) {
      final FileEditorManager manager = FileEditorManager.getInstance(project);
      if (manager != null) {
        Editor editor = manager.getSelectedTextEditor();
        if (editor != null) {
          result = FileDocumentManager.getInstance().getFile(editor.getDocument());
        }
      }
    }
    return result;
  }
  @NotNull
  private static Document setupFileEditorAndDocument(
      @NotNull String fileName, @NotNull String fileText) throws IOException {
    EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
    EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject())
        .setEncoding(null, CharsetToolkit.UTF8_CHARSET);
    PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting();
    deleteVFile();
    myVFile = getSourceRoot().createChildData(null, fileName);
    VfsUtil.saveText(myVFile, fileText);
    final FileDocumentManager manager = FileDocumentManager.getInstance();
    final Document document = manager.getDocument(myVFile);
    assertNotNull("Can't create document for '" + fileName + "'", document);
    manager.reloadFromDisk(document);
    document.insertString(0, " ");
    document.deleteString(0, 1);
    myFile = getPsiManager().findFile(myVFile);
    assertNotNull(
        "Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile);
    assertTrue(myFile.isPhysical());
    myEditor = createEditor(myVFile);
    myVFile.setCharset(CharsetToolkit.UTF8_CHARSET);

    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    return document;
  }
 @Nullable
 public static Language getDocumentLanguage(@NotNull Document document) {
   FileDocumentManager manager = FileDocumentManager.getInstance();
   VirtualFile file = manager.getFile(document);
   if (file != null && file.isValid()) {
     return LanguageUtil.getFileLanguage(file);
   }
   return null;
 }
 public IDoc makeVFile(FileImpl vFile) {
   Document document = FileDocumentManager.getInstance().getDocument(vFile.virtualFile);
   if (document == null) {
     return null;
   }
   return new DocImpl(context, document);
 }
  @Override
  public void setupRootModel(final ModifiableRootModel modifiableRootModel)
      throws ConfigurationException {
    String contentEntryPath = getContentEntryPath();
    if (StringUtil.isEmpty(contentEntryPath)) {
      return;
    }
    File contentRootDir = new File(contentEntryPath);
    FileUtilRt.createDirectory(contentRootDir);
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    VirtualFile modelContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir);
    if (modelContentRootDir == null) {
      return;
    }

    modifiableRootModel.addContentEntry(modelContentRootDir);
    modifiableRootModel.inheritSdk();

    final Project project = modifiableRootModel.getProject();

    setupGradleBuildFile(modelContentRootDir);
    setupGradleSettingsFile(modelContentRootDir, modifiableRootModel);

    if (myWizardContext.isCreatingNewProject()) {
      String externalProjectPath = FileUtil.toCanonicalPath(project.getBasePath());
      getExternalProjectSettings().setExternalProjectPath(externalProjectPath);
      AbstractExternalSystemSettings settings =
          ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID);
      //noinspection unchecked
      settings.linkProject(getExternalProjectSettings());
    } else {
      FileDocumentManager.getInstance().saveAllDocuments();
      ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, false);
    }
  }
  private void insertString(VirtualFile file, int offset, @NotNull CharSequence s)
      throws InterruptedException {
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    assertNotNull(document);
    AccessToken token = WriteAction.start();
    try {
      document.insertString(offset, s);
    } finally {
      token.finish();
    }

    semaphore.down();
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    FileDocumentManager.getInstance().saveAllDocuments();
    await();
  }
  @Override
  public boolean canPutAt(
      @NotNull final VirtualFile file, final int line, @NotNull final Project project) {
    final Ref<Boolean> stoppable = Ref.create(false);
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document != null) {
      if (file.getFileType() == PythonFileType.INSTANCE) {
        XDebuggerUtil.getInstance()
            .iterateLine(
                project,
                document,
                line,
                new Processor<PsiElement>() {
                  @Override
                  public boolean process(PsiElement psiElement) {
                    if (psiElement instanceof PsiWhiteSpace || psiElement instanceof PsiComment)
                      return true;
                    if (psiElement.getNode() != null
                        && notStoppableElementType(psiElement.getNode().getElementType()))
                      return true;

                    // Python debugger seems to be able to stop on pretty much everything
                    stoppable.set(true);
                    return false;
                  }
                });

        if (PyDebugSupportUtils.isContinuationLine(document, line - 1)) {
          stoppable.set(false);
        }
      }
    }

    return stoppable.get();
  }
 @Override
 public int getTextLength() {
   VirtualFile file = getVirtualFile();
   Document document = FileDocumentManager.getInstance().getDocument(file);
   assert document != null : file.getUrl();
   return document.getTextLength();
 }
  private void doDeannotate(@NonNls final String testPath, String hint1, String hint2)
      throws Throwable {
    myFixture.configureByFile(testPath);
    final PsiFile file = myFixture.getFile();
    final Editor editor = myFixture.getEditor();

    assertNotAvailable(hint1);
    assertNotAvailable(hint2);

    final DeannotateIntentionAction deannotateFix = new DeannotateIntentionAction();
    assertTrue(deannotateFix.isAvailable(myProject, editor, file));

    final PsiModifierListOwner container = DeannotateIntentionAction.getContainer(editor, file);
    startListening(container, AnnotationUtil.NOT_NULL, true);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        ExternalAnnotationsManager.getInstance(myProject)
            .deannotate(container, AnnotationUtil.NOT_NULL);
      }
    }.execute();
    stopListeningAndCheckEvents();

    FileDocumentManager.getInstance().saveAllDocuments();

    IntentionAction fix = myFixture.findSingleIntention(hint1);
    assertNotNull(fix);

    fix = myFixture.findSingleIntention(hint2);
    assertNotNull(fix);

    assertFalse(deannotateFix.isAvailable(myProject, editor, file));
  }
 private void updateForFile(@Nullable("null means update anyway") VirtualFile file) {
   if (file == null) {
     update();
   } else {
     updateForDocument(FileDocumentManager.getInstance().getCachedDocument(file));
   }
 }
 @Override
 public void beforeDocumentSaving(@NotNull Document document) {
   // This is fired when any document is saved, regardless of whether it is part of a save-all or
   // a save-one operation
   final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
   applySettings(file);
 }
  private void doStuff(String rootDir, String itemRepr, String itemName)
      throws FileNotFoundException {
    String patternName =
        getTestDataPath() + getTestRoot() + getTestName(true) + "/after/" + itemName;

    File patternFile = new File(patternName);

    PrintWriter writer;
    if (!patternFile.exists()) {
      writer = new PrintWriter(new FileOutputStream(patternFile));
      try {
        writer.print(itemRepr);
      } finally {
        writer.close();
      }

      System.out.println("Pattern not found, file " + patternName + " created.");

      LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patternFile);
    }

    File graFile =
        new File(
            FileUtil.getTempDirectory() + File.separator + rootDir + File.separator + itemName);

    writer = new PrintWriter(new FileOutputStream(graFile));
    try {
      writer.print(itemRepr);
    } finally {
      writer.close();
    }

    LocalFileSystem.getInstance().refreshAndFindFileByIoFile(graFile);
    FileDocumentManager.getInstance().saveAllDocuments();
  }
 @Override
 public void actionPerformed(AnActionEvent e) {
   Document doc = getDocument(e);
   if (doc != null) {
     FileDocumentManager.getInstance().saveDocument(doc);
   }
 }
  public XValueHint(
      @NotNull Project project,
      @NotNull Editor editor,
      @NotNull Point point,
      @NotNull ValueHintType type,
      @NotNull ExpressionInfo expressionInfo,
      @NotNull XDebuggerEvaluator evaluator,
      @NotNull XDebugSession session) {
    super(project, editor, point, type, expressionInfo.getTextRange());

    myEvaluator = evaluator;
    myDebugSession = session;
    myExpression =
        XDebuggerEvaluateActionHandler.getExpressionText(expressionInfo, editor.getDocument());
    myValueName =
        XDebuggerEvaluateActionHandler.getDisplayText(expressionInfo, editor.getDocument());
    myExpressionInfo = expressionInfo;

    VirtualFile file;
    ConsoleView consoleView = ConsoleViewImpl.CONSOLE_VIEW_IN_EDITOR_VIEW.get(editor);
    if (consoleView instanceof LanguageConsoleView) {
      LanguageConsoleImpl console = ((LanguageConsoleView) consoleView).getConsole();
      file = console.getHistoryViewer() == editor ? console.getVirtualFile() : null;
    } else {
      file = FileDocumentManager.getInstance().getFile(editor.getDocument());
    }

    myExpressionPosition =
        file != null
            ? XDebuggerUtil.getInstance()
                .createPositionByOffset(file, expressionInfo.getTextRange().getStartOffset())
            : null;
  }
  public boolean move(VirtualFile file, VirtualFile toDir) throws IOException {
    File srcFile = getIOFile(file);
    File dstFile = new File(getIOFile(toDir), file.getName());

    final SvnVcs vcs = getVCS(toDir);
    final SvnVcs sourceVcs = getVCS(file);
    if (vcs == null && sourceVcs == null) return false;

    if (vcs == null) {
      return false;
    }

    FileDocumentManager.getInstance().saveAllDocuments();
    if (sourceVcs == null) {
      return createItem(toDir, file.getName(), file.isDirectory(), true);
    }

    if (isPendingAdd(vcs.getProject(), toDir)) {

      myMovedFiles.add(new MovedFileInfo(sourceVcs.getProject(), srcFile, dstFile));
      return true;
    } else {
      final VirtualFile oldParent = file.getParent();
      myFilesToRefresh.add(oldParent);
      myFilesToRefresh.add(toDir);
      return doMove(sourceVcs, srcFile, dstFile);
    }
  }
  TextEditorComponent(
      @NotNull final Project project,
      @NotNull final VirtualFile file,
      @NotNull final TextEditorImpl textEditor) {
    super(new BorderLayout(), textEditor);

    myProject = project;
    myFile = file;
    myTextEditor = textEditor;

    myDocument = FileDocumentManager.getInstance().getDocument(myFile);
    LOG.assertTrue(myDocument != null);
    myDocumentListener = new MyDocumentListener();
    myDocument.addDocumentListener(myDocumentListener);

    myEditorMouseListener = new MyEditorMouseListener();
    myEditorPropertyChangeListener = new MyEditorPropertyChangeListener();

    myConnection = project.getMessageBus().connect();
    myConnection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());

    myVirtualFileListener = new MyVirtualFileListener();
    myFile.getFileSystem().addVirtualFileListener(myVirtualFileListener);
    myEditor = createEditor();
    add(myEditor.getComponent(), BorderLayout.CENTER);
    myModified = isModifiedImpl();
    myValid = isEditorValidImpl();
    LOG.assertTrue(myValid);
  }
  @Nullable
  @Override
  public Document getDocument(@NotNull PsiFile file) {
    if (file instanceof PsiBinaryFile) return null;

    Document document = getCachedDocument(file);
    if (document != null) {
      if (!file.getViewProvider().isPhysical() && document.getUserData(HARD_REF_TO_PSI) == null) {
        cachePsi(document, file);
      }
      return document;
    }

    if (!file.getViewProvider().isEventSystemEnabled()) return null;
    document =
        FileDocumentManager.getInstance().getDocument(file.getViewProvider().getVirtualFile());

    if (document != null) {
      if (document.getTextLength() != file.getTextLength()) {
        throw new AssertionError(
            "Modified PSI with no document: "
                + file
                + "; physical="
                + file.getViewProvider().isPhysical());
      }

      if (!file.getViewProvider().isPhysical()) {
        cachePsi(document, file);
      }
    }

    return document;
  }
  protected void doTest(final PerformAction performAction, final String testName) throws Exception {
    String path = getTestDataPath() + getTestRoot() + testName;

    String pathBefore = path + "/before";
    final VirtualFile rootDir =
        PsiTestUtil.createTestProjectStructure(
            myProject, myModule, pathBefore, myFilesToDelete, false);
    prepareProject(rootDir);
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    String pathAfter = path + "/after";
    final VirtualFile rootAfter =
        LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));

    performAction.performAction(rootDir, rootAfter);
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
              }
            });

    FileDocumentManager.getInstance().saveAllDocuments();

    if (myDoCompare) {
      PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir);
    }
  }
 public static void runSmartTestProcess(
     @NotNull final VirtualFile taskDir,
     @NotNull final StudyTestRunner testRunner,
     final String taskFileName,
     @NotNull final TaskFile taskFile,
     @NotNull final Project project) {
   final TaskFile answerTaskFile = new TaskFile();
   answerTaskFile.name = taskFileName;
   final VirtualFile virtualFile = taskDir.findChild(taskFileName);
   if (virtualFile == null) {
     return;
   }
   final VirtualFile answerFile =
       getCopyWithAnswers(taskDir, virtualFile, taskFile, answerTaskFile);
   for (final AnswerPlaceholder answerPlaceholder : answerTaskFile.getAnswerPlaceholders()) {
     final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
     if (document == null) {
       continue;
     }
     StudySmartChecker.smartCheck(
         answerPlaceholder,
         project,
         answerFile,
         answerTaskFile,
         taskFile,
         testRunner,
         virtualFile,
         document);
   }
   StudyUtils.deleteFile(answerFile);
 }
    public BookmarkInContextInfo invoke() {
      myBookmarkAtPlace = null;
      myFile = null;
      myLine = -1;

      BookmarkManager bookmarkManager = BookmarkManager.getInstance(myProject);
      if (ToolWindowManager.getInstance(myProject).isEditorComponentActive()) {
        Editor editor = CommonDataKeys.EDITOR.getData(myDataContext);
        if (editor != null) {
          Document document = editor.getDocument();
          myLine = editor.getCaretModel().getLogicalPosition().line;
          myFile = FileDocumentManager.getInstance().getFile(document);
          myBookmarkAtPlace = bookmarkManager.findEditorBookmark(document, myLine);
        }
      }

      if (myFile == null) {
        myFile = CommonDataKeys.VIRTUAL_FILE.getData(myDataContext);
        myLine = -1;

        if (myBookmarkAtPlace == null && myFile != null) {
          myBookmarkAtPlace = bookmarkManager.findFileBookmark(myFile);
        }
      }
      return this;
    }
  public LanguageConsoleImpl(
      Project project, String title, LightVirtualFile lightFile, boolean initComponents) {
    myProject = project;
    myTitle = title;
    myVirtualFile = lightFile;
    EditorFactory editorFactory = EditorFactory.getInstance();
    myHistoryFile = new LightVirtualFile(getTitle() + ".history.txt", FileTypes.PLAIN_TEXT, "");
    myEditorDocument = FileDocumentManager.getInstance().getDocument(lightFile);
    reparsePsiFile();
    assert myEditorDocument != null;
    myConsoleEditor = (EditorEx) editorFactory.createEditor(myEditorDocument, myProject);
    myConsoleEditor.addFocusListener(myFocusListener);
    myCurrentEditor = myConsoleEditor;
    myHistoryViewer =
        (EditorEx)
            editorFactory.createViewer(
                ((EditorFactoryImpl) editorFactory).createDocument(true), myProject);
    myUpdateQueue = new MergingUpdateQueue("ConsoleUpdateQueue", 300, true, null);
    Disposer.register(this, myUpdateQueue);

    // action shortcuts are not yet registered
    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              @Override
              public void run() {
                installEditorFactoryListener();
              }
            });

    if (initComponents) {
      initComponents();
    }
  }
        @Override
        public void caretPositionChanged(CaretEvent event) {

          if (project.isDisposed()) {
            return;
          }

          VirtualFile file =
              FileDocumentManager.getInstance().getFile(event.getEditor().getDocument());

          // Make sure file exists
          if (file == null) {
            return;
          }

          // Make sure file is in the project
          if (!ProjectFileIndex.SERVICE.getInstance(project).isInSource(file)) {
            return;
          }

          int offset = event.getEditor().logicalPositionToOffset(event.getNewPosition());

          // Get path relative to project root (e.g. src/Sample.java)
          Path basePath = Paths.get(project.getBasePath());
          Path absoluteFilePath = Paths.get(file.getPath());
          String relativeFilePath = basePath.relativize(absoluteFilePath).toString();

          CursorMovement cursorMovement = new CursorMovement(-1, relativeFilePath, offset);

          for (EditorEvent editorEvent : events) {
            editorEvent.sendCursorMovement(cursorMovement);
          }
        }
 public static FragmentContent fromRangeMarker(RangeMarker rangeMarker, Project project) {
   Document document = rangeMarker.getDocument();
   VirtualFile file = FileDocumentManager.getInstance().getFile(document);
   FileType type = FileTypeManager.getInstance().getFileTypeByFile(file);
   return new FragmentContent(
       new DocumentContent(project, document), TextRange.create(rangeMarker), project, type);
 }
  @Nullable
  public Runnable startNonCustomTemplates(
      final Map<TemplateImpl, String> template2argument,
      final Editor editor,
      @Nullable final PairProcessor<String, String> processor) {
    final int caretOffset = editor.getCaretModel().getOffset();
    final Document document = editor.getDocument();
    final CharSequence text = document.getCharsSequence();

    if (template2argument == null || template2argument.isEmpty()) {
      return null;
    }
    if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), myProject)) {
      return null;
    }

    return () -> {
      if (template2argument.size() == 1) {
        TemplateImpl template = template2argument.keySet().iterator().next();
        String argument = template2argument.get(template);
        int templateStart = getTemplateStart(template, argument, caretOffset, text);
        startTemplateWithPrefix(editor, template, templateStart, processor, argument);
      } else {
        ListTemplatesHandler.showTemplatesLookup(myProject, editor, template2argument);
      }
    };
  }
Exemple #25
0
  @Override
  public void execute(
      final Editor editor,
      final DataContext dataContext,
      @Nullable final Producer<Transferable> producer) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;

    final Document document = editor.getDocument();
    if (!FileDocumentManager.getInstance()
        .requestWriting(document, CommonDataKeys.PROJECT.getData(dataContext))) {
      return;
    }

    DataContext context = dataContext;
    if (producer != null) {
      context =
          new DataContext() {
            @Override
            public Object getData(@NonNls String dataId) {
              return PasteAction.TRANSFERABLE_PROVIDER.is(dataId)
                  ? producer
                  : dataContext.getData(dataId);
            }
          };
    }

    final Project project = editor.getProject();
    if (project == null
        || editor.isColumnMode()
        || editor.getSelectionModel().hasBlockSelection()
        || editor.getCaretModel().getCaretCount() > 1) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    document.startGuardedBlockChecking();
    try {
      for (PasteProvider provider : Extensions.getExtensions(EP_NAME)) {
        if (provider.isPasteEnabled(context)) {
          provider.performPaste(context);
          return;
        }
      }
      doPaste(editor, project, file, document, producer);
    } catch (ReadOnlyFragmentModificationException e) {
      EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e);
    } finally {
      document.stopGuardedBlockChecking();
    }
  }
  private void doTest(
      @NotNull String fileName, int lineNumber, @NotNull Function1<VirtualFile, String> className) {
    if (rootDir == null) {
      configure();
    }
    assert rootDir != null;

    Filter filter = new JetExceptionFilterFactory().create(GlobalSearchScope.allScope(myProject));

    VirtualFile expectedFile = VfsUtilCore.findRelativeFile(fileName, rootDir);
    assertNotNull(expectedFile);

    String line = createStackTraceElementLine(fileName, className.invoke(expectedFile), lineNumber);
    Filter.Result result = filter.applyFilter(line, 0);

    assertNotNull(result);
    HyperlinkInfo info = result.getFirstHyperlinkInfo();
    assertNotNull(info);
    assertInstanceOf(info, OpenFileHyperlinkInfo.class);
    OpenFileDescriptor descriptor = ((OpenFileHyperlinkInfo) info).getDescriptor();
    assertNotNull(descriptor);

    assertEquals(expectedFile, descriptor.getFile());

    Document document = FileDocumentManager.getInstance().getDocument(expectedFile);
    assertNotNull(document);
    int expectedOffset = document.getLineStartOffset(lineNumber - 1);
    assertEquals(expectedOffset, descriptor.getOffset());
  }
  @Nullable("returns null if charset set cannot be determined from content")
  private static Charset cachedCharsetFromContent(final VirtualFile virtualFile) {
    if (virtualFile == null) return null;
    final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
    if (document == null) return null;

    return EncodingManager.getInstance().getCachedCharsetFromContent(document);
  }
 @Override
 public void editorCreated(@NotNull EditorFactoryEvent event) {
   Document document = event.getEditor().getDocument();
   VirtualFile file = FileDocumentManager.getInstance().getFile(document);
   if (file != null && file.getFileType() instanceof CoqFileType) {
     checkForUpdates();
   }
 }
  public void testGetDocument_FirstGet() throws Exception {
    VirtualFile vFile = createFile();
    final PsiFile file = new MockPsiFile(vFile, getPsiManager());

    final Document document = getPsiDocumentManager().getDocument(file);
    assertNotNull(document);
    assertSame(document, FileDocumentManager.getInstance().getDocument(vFile));
  }
 @Override
 public StructureViewBuilder getStructureViewBuilder() {
   Document document = myComponent.getEditor().getDocument();
   VirtualFile file = FileDocumentManager.getInstance().getFile(document);
   if (file == null || !file.isValid()) return null;
   return StructureViewBuilder.PROVIDER.getStructureViewBuilder(
       file.getFileType(), file, myProject);
 }