com.intellij.openapi.editor.impl.DocumentImpl Java Examples

The following examples show how to use com.intellij.openapi.editor.impl.DocumentImpl. 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: FormattingDocumentModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static FormattingDocumentModelImpl createOn(PsiFile file) {
  Document document = getDocumentToBeUsedFor(file);
  if (document != null) {
    if (PsiDocumentManager.getInstance(file.getProject()).isUncommited(document)) {
      LOG.error("Document is uncommitted");
    }
    if (!file.textMatches(document.getImmutableCharSequence())) {
      LOG.error("Document and psi file texts should be equal: file " + file);
    }
    return new FormattingDocumentModelImpl(document, file);
  }
  else {
    return new FormattingDocumentModelImpl(new DocumentImpl(file.getText()), file);
  }

}
 
Example #2
Source File: ProjectTree.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
private void showEditor(final CodeInfo codeInfo) {
    if (codeInfo.getContents() != null && !codeInfo.getContents().isEmpty()) {
        VirtualFile virtualFile =
                null;
        try {
            virtualFile = editorDocOps.getVirtualFile(codeInfo.getAbsoluteFileName(),
                    codeInfo.getDisplayFileName(), codeInfo.getContents());
        } catch (IOException | NoSuchAlgorithmException e) {
            KBNotification.getInstance().error(e);
            e.printStackTrace();
        }
        if (virtualFile != null) {
            FileEditorManager.getInstance(windowObjects.getProject()).
                    openFile(virtualFile, true, true);
        }
        Document document = new DocumentImpl(codeInfo.getContents(), true, false);
        editorDocOps.addHighlighting(codeInfo.getLineNumbers(), document);
        editorDocOps.gotoLine(codeInfo.getLineNumbers().get(0), document);
    }
}
 
Example #3
Source File: SpotlightPane.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
@Override
public void mouseClicked(final MouseEvent e) {
    try {
        VirtualFile virtualFile = editorDocOps.getVirtualFile(fileName, displayFileName,
                windowObjects.getFileNameContentsMap().get(fileName));
        FileEditorManager.getInstance(windowObjects.getProject()).
                openFile(virtualFile, true, true);
        Document document = new DocumentImpl(
                windowObjects.getFileNameContentsMap().get(fileName), true, false);
        editorDocOps.addHighlighting(windowObjects.
                getFileNameNumbersMap().get(fileName), document);
        editorDocOps.gotoLine(windowObjects.
                getFileNameNumbersMap().get(fileName).get(0), document);
    } catch (Exception exception) {
        KBNotification.getInstance().error(exception);
        exception.printStackTrace();
    }
}
 
Example #4
Source File: LineStatusTrackerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
public LineStatusTrackerBase(@javax.annotation.Nullable final Project project,
                             @Nonnull final Document document) {
  myDocument = document;
  myProject = project;

  myApplication = ApplicationManager.getApplication();

  myDocumentListener = new MyDocumentListener();
  myDocument.addDocumentListener(myDocumentListener);

  myApplicationListener = new MyApplicationListener();
  myApplication.addApplicationListener(myApplicationListener);

  myVcsDocument = new DocumentImpl("", true);
  myVcsDocument.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
}
 
Example #5
Source File: PatchChangeBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static CharSequence getPatchedContent(@Nonnull AppliedTextPatch patch, @Nonnull String localContent) {
  PatchChangeBuilder builder = new PatchChangeBuilder();
  builder.exec(patch.getHunks());

  DocumentImpl document = new DocumentImpl(localContent, true);
  List<Hunk> appliedHunks = ContainerUtil.filter(builder.getHunks(), (h) -> h.getStatus() == HunkStatus.EXACTLY_APPLIED);
  ContainerUtil.sort(appliedHunks, Comparator.comparingInt(h -> h.getAppliedToLines().start));

  for (int i = appliedHunks.size() - 1; i >= 0; i--) {
    Hunk hunk = appliedHunks.get(i);
    LineRange appliedTo = hunk.getAppliedToLines();
    List<String> inserted = hunk.getInsertedLines();

    DiffUtil.applyModification(document, appliedTo.start, appliedTo.end, inserted);
  }

  return document.getText();
}
 
Example #6
Source File: ExportToFileUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected JComponent createCenterPanel() {
  final Document document = ((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(true);
  ((DocumentImpl)document).setAcceptSlashR(true);

  myTextArea = EditorFactory.getInstance().createEditor(document, myProject, PlainTextFileType.INSTANCE, true);
  final EditorSettings settings = myTextArea.getSettings();
  settings.setLineNumbersShown(false);
  settings.setLineMarkerAreaShown(false);
  settings.setFoldingOutlineShown(false);
  settings.setRightMarginShown(false);
  settings.setAdditionalLinesCount(0);
  settings.setAdditionalColumnsCount(0);
  settings.setAdditionalPageAtBottom(false);
  ((EditorEx)myTextArea).setBackgroundColor(UIUtil.getInactiveTextFieldBackgroundColor());
  return myTextArea.getComponent();
}
 
Example #7
Source File: AsyncFilterRunner.java    From consulo with Apache License 2.0 5 votes vote down vote up
HighlighterJob(@Nonnull Project project, @Nonnull Filter filter, int startLine, int endLine, @Nonnull Document document) {
  myProject = project;
  this.startLine = new AtomicInteger(startLine);
  this.endLine = endLine;
  this.filter = filter;

  delta = new DeltaTracker(document, document.getLineEndOffset(endLine));

  snapshot = ((DocumentImpl)document).freeze();
}
 
Example #8
Source File: ConsoleViewImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void runHeavyFilters(int line1, int endLine) {
  final int startLine = Math.max(0, line1);

  final Document document = myEditor.getDocument();
  final int startOffset = document.getLineStartOffset(startLine);
  String text = document.getText(new TextRange(startOffset, document.getLineEndOffset(endLine)));
  final Document documentCopy = new DocumentImpl(text, true);
  documentCopy.setReadOnly(true);

  myJLayeredPane.startUpdating();
  final int currentValue = myHeavyUpdateTicket;
  myHeavyAlarm.addRequest(() -> {
    if (!myFilters.shouldRunHeavy()) return;
    try {
      myFilters.applyHeavyFilter(documentCopy, startOffset, startLine, additionalHighlight -> addFlushRequest(0, new FlushRunnable(true) {
        @Override
        public void doRun() {
          if (myHeavyUpdateTicket != currentValue) return;
          TextAttributes additionalAttributes = additionalHighlight.getTextAttributes(null);
          if (additionalAttributes != null) {
            ResultItem item = additionalHighlight.getResultItems().get(0);
            myHyperlinks.addHighlighter(item.getHighlightStartOffset(), item.getHighlightEndOffset(), additionalAttributes);
          }
          else {
            myHyperlinks.highlightHyperlinks(additionalHighlight, 0);
          }
        }
      }));
    }
    catch (IndexNotReadyException ignore) {
    }
    finally {
      if (myHeavyAlarm.getActiveRequestCount() <= 1) { // only the current request
        UIUtil.invokeLaterIfNeeded(() -> myJLayeredPane.finishUpdating());
      }
    }
  }, 0);
}
 
Example #9
Source File: FoldingUpdate.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void getFoldingsFor(@Nonnull PsiFile file, @Nonnull Document document, @Nonnull List<? super RegionInfo> elementsToFold, boolean quick) {
  final FileViewProvider viewProvider = file.getViewProvider();
  TextRange docRange = TextRange.from(0, document.getTextLength());
  Comparator<Language> preferBaseLanguage = Comparator.comparing((Language l) -> l != viewProvider.getBaseLanguage());
  List<Language> languages = ContainerUtil.sorted(viewProvider.getLanguages(), preferBaseLanguage.thenComparing(Language::getID));

  DocumentEx copyDoc = languages.size() > 1 ? new DocumentImpl(document.getImmutableCharSequence()) : null;
  List<RangeMarker> hardRefToRangeMarkers = new ArrayList<>();

  for (Language language : languages) {
    final PsiFile psi = viewProvider.getPsi(language);
    final FoldingBuilder foldingBuilder = LanguageFolding.INSTANCE.forLanguage(language);
    if (psi != null && foldingBuilder != null) {
      for (FoldingDescriptor descriptor : LanguageFolding.buildFoldingDescriptors(foldingBuilder, psi, document, quick)) {
        PsiElement psiElement = descriptor.getElement().getPsi();
        if (psiElement == null) {
          LOG.error("No PSI for folding descriptor " + descriptor);
          continue;
        }
        TextRange range = descriptor.getRange();
        if (!docRange.contains(range)) {
          diagnoseIncorrectRange(psi, document, language, foldingBuilder, descriptor, psiElement);
          continue;
        }

        if (copyDoc != null && !addNonConflictingRegion(copyDoc, range, hardRefToRangeMarkers)) {
          continue;
        }

        RegionInfo regionInfo = new RegionInfo(descriptor, psiElement, foldingBuilder);
        elementsToFold.add(regionInfo);
      }
    }
  }
}
 
Example #10
Source File: CompletionInitializationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void syncAcceptSlashR(Document originalDocument, Document documentCopy) {
  if (!(originalDocument instanceof DocumentImpl) || !(documentCopy instanceof DocumentImpl)) {
    return;
  }

  ((DocumentImpl)documentCopy).setAcceptSlashR(((DocumentImpl)originalDocument).acceptsSlashR());
}
 
Example #11
Source File: TextViewer.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Document createDocument(@Nonnull String initialText) {
  final Document document = EditorFactory.getInstance().createDocument(initialText);
  if (document instanceof DocumentImpl) {
    ((DocumentImpl)document).setAcceptSlashR(true);
  }
  return document;
}
 
Example #12
Source File: CoreApplicationEnvironment.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CoreApplicationEnvironment(@Nonnull Disposable parentDisposable) {
  myParentDisposable = parentDisposable;

  myFileTypeRegistry = new CoreFileTypeRegistry();

  myApplication = createApplication(myParentDisposable);
  ApplicationManager.setApplication(myApplication, myParentDisposable);
  myLocalFileSystem = createLocalFileSystem();
  myJarFileSystem = createJarFileSystem();

  final InjectingContainer appContainer = myApplication.getInjectingContainer();
  registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl(DocumentImpl::new, null));

  VirtualFileSystem[] fs = {myLocalFileSystem, myJarFileSystem};
  VirtualFileManagerImpl virtualFileManager = new VirtualFileManagerImpl(myApplication, fs);
  registerComponentInstance(appContainer, VirtualFileManager.class, virtualFileManager);

  registerApplicationExtensionPoint(ASTLazyFactory.EP.getExtensionPointName(), ASTLazyFactory.class);
  registerApplicationExtensionPoint(ASTLeafFactory.EP.getExtensionPointName(), ASTLeafFactory.class);
  registerApplicationExtensionPoint(ASTCompositeFactory.EP.getExtensionPointName(), ASTCompositeFactory.class);

  addExtension(ASTLazyFactory.EP.getExtensionPointName(), new DefaultASTLazyFactory());
  addExtension(ASTLeafFactory.EP.getExtensionPointName(), new DefaultASTLeafFactory());
  addExtension(ASTCompositeFactory.EP.getExtensionPointName(), new DefaultASTCompositeFactory());

  registerApplicationService(EncodingManager.class, new CoreEncodingRegistry());
  registerApplicationService(VirtualFilePointerManager.class, createVirtualFilePointerManager());
  registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl());
  registerApplicationService(ReferenceProvidersRegistry.class, new MockReferenceProvidersRegistry());
  registerApplicationService(StubTreeLoader.class, new CoreStubTreeLoader());
  registerApplicationService(PsiReferenceService.class, new PsiReferenceServiceImpl());
  registerApplicationService(MetaDataRegistrar.class, new MetaRegistry());

  registerApplicationService(ProgressManager.class, createProgressIndicatorProvider());

  registerApplicationService(JobLauncher.class, createJobLauncher());
  registerApplicationService(CodeFoldingSettings.class, new CodeFoldingSettings());
  registerApplicationService(CommandProcessor.class, new CoreCommandProcessor());
}
 
Example #13
Source File: PsiDocumentManagerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeDocumentChange(@Nonnull DocumentEvent event) {
  if (myStopTrackingDocuments || myProject.isDisposed()) return;

  final Document document = event.getDocument();
  VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
  boolean isRelevant = virtualFile != null && isRelevant(virtualFile);

  if (document instanceof DocumentImpl && !myUncommittedInfos.containsKey(document)) {
    myUncommittedInfos.put(document, new UncommittedInfo((DocumentImpl)document));
  }

  final FileViewProvider viewProvider = getCachedViewProvider(document);
  boolean inMyProject = viewProvider != null && viewProvider.getManager() == myPsiManager;
  if (!isRelevant || !inMyProject) {
    return;
  }

  final List<PsiFile> files = viewProvider.getAllFiles();
  PsiFile psiCause = null;
  for (PsiFile file : files) {
    if (file == null) {
      throw new AssertionError("View provider " + viewProvider + " (" + viewProvider.getClass() + ") returned null in its files array: " + files + " for file " + viewProvider.getVirtualFile());
    }

    if (PsiToDocumentSynchronizer.isInsideAtomicChange(file)) {
      psiCause = file;
    }
  }

  if (psiCause == null) {
    beforeDocumentChangeOnUnlockedDocument(viewProvider);
  }
}
 
Example #14
Source File: EventLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String getStatusText(DocumentImpl logDoc, AtomicBoolean showMore, List<RangeMarker> lineSeparators, String indent, boolean hasHtml) {
  DocumentImpl statusDoc = new DocumentImpl(logDoc.getImmutableCharSequence(), true);
  List<RangeMarker> statusSeparators = new ArrayList<RangeMarker>();
  for (RangeMarker separator : lineSeparators) {
    if (separator.isValid()) {
      statusSeparators.add(statusDoc.createRangeMarker(separator.getStartOffset(), separator.getEndOffset()));
    }
  }
  removeJavaNewLines(statusDoc, statusSeparators, indent, hasHtml);
  insertNewLineSubstitutors(statusDoc, showMore, statusSeparators);

  return statusDoc.getText();
}
 
Example #15
Source File: EventLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void indentNewLines(DocumentImpl logDoc, List<RangeMarker> lineSeparators, RangeMarker afterTitle, boolean hasHtml, String indent) {
  if (!hasHtml) {
    int i = -1;
    while (true) {
      i = StringUtil.indexOf(logDoc.getText(), '\n', i + 1);
      if (i < 0) {
        break;
      }
      lineSeparators.add(logDoc.createRangeMarker(i, i + 1));
    }
  }
  if (!lineSeparators.isEmpty() && afterTitle != null && afterTitle.isValid()) {
    lineSeparators.add(afterTitle);
  }
  int nextLineStart = -1;
  for (RangeMarker separator : lineSeparators) {
    if (separator.isValid()) {
      int start = separator.getStartOffset();
      if (start == nextLineStart) {
        continue;
      }

      logDoc.replaceString(start, separator.getEndOffset(), "\n" + indent);
      nextLineStart = start + 1 + indent.length();
      while (nextLineStart < logDoc.getTextLength() && Character.isWhitespace(logDoc.getCharsSequence().charAt(nextLineStart))) {
        logDoc.deleteString(nextLineStart, nextLineStart + 1);
      }
    }
  }
}
 
Example #16
Source File: HttpFileEditor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public Editor getEditor() {
  final TextEditor fileEditor = myPanel.getFileEditor();
  if (fileEditor != null) {
    return fileEditor.getEditor();
  }
  if (myMockTextEditor == null) {
    myMockTextEditor = EditorFactory.getInstance().createViewer(new DocumentImpl(""), myProject);
  }
  return myMockTextEditor;
}
 
Example #17
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void prepareForRangeMarkerUpdate(Map<VirtualFile, Document> strongRefsToDocuments, VirtualFile virtualFile) {
  Document document = myFileDocumentManager.getCachedDocument(virtualFile);
  if (document == null && DocumentImpl.areRangeMarkersRetainedFor(virtualFile)) {
    // re-create document with the old contents prior to this event
    // then contentChanged() will diff the document with the new contents and update the markers
    document = myFileDocumentManager.getDocument(virtualFile);
  }
  // save document strongly to make it live until contentChanged()
  if (document != null) {
    strongRefsToDocuments.put(virtualFile, document);
  }
}
 
Example #18
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Document createDocument(@Nonnull CharSequence text, @Nonnull VirtualFile file) {
  boolean acceptSlashR = file instanceof LightVirtualFile && StringUtil.indexOf(text, '\r') >= 0;
  boolean freeThreaded = Boolean.TRUE.equals(file.getUserData(AbstractFileViewProvider.FREE_THREADED));
  DocumentImpl document = (DocumentImpl)((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(text, acceptSlashR, freeThreaded);
  document.documentCreatedFrom(file);
  return document;
}
 
Example #19
Source File: LayeredLexerEditorHighlighter.java    From consulo with Apache License 2.0 5 votes vote down vote up
private Mapper(@Nonnull LayerDescriptor descriptor) {
  doc = new DocumentImpl("", true);

  mySyntaxHighlighter = descriptor.getLayerHighlighter();
  myBackground = descriptor.getBackgroundKey();
  highlighter = new LexerEditorHighlighter(mySyntaxHighlighter, getScheme());
  mySeparator = descriptor.getTokenSeparator();
  highlighter.setEditor(this);
  doc.addDocumentListener(highlighter);
}
 
Example #20
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
private static String getStatusText(DocumentImpl logDoc, AtomicBoolean showMore, List<RangeMarker> lineSeparators, boolean hasHtml) {
    DocumentImpl statusDoc = new DocumentImpl(logDoc.getImmutableCharSequence(), true);
    List<RangeMarker> statusSeparators = new ArrayList<RangeMarker>();
    for(RangeMarker separator : lineSeparators) {
        if(separator.isValid()) {
            statusSeparators.add(statusDoc.createRangeMarker(separator.getStartOffset(), separator.getEndOffset()));
        }
    }
    removeJavaNewLines(statusDoc, statusSeparators, hasHtml);
    insertNewLineSubstitutors(statusDoc, showMore, statusSeparators);

    return statusDoc.getText();
}
 
Example #21
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
private static void indentNewLines(DocumentImpl logDoc, List<RangeMarker> lineSeparators, RangeMarker afterTitle, boolean hasHtml, String indent) {
    if(!hasHtml) {
        int i = -1;
        while(true) {
            i = StringUtil.indexOf(logDoc.getText(), '\n', i + 1);
            if(i < 0) {
                break;
            }
            lineSeparators.add(logDoc.createRangeMarker(i, i + 1));
        }
    }
    if(!lineSeparators.isEmpty() && afterTitle != null && afterTitle.isValid()) {
        lineSeparators.add(afterTitle);
    }
    int nextLineStart = -1;
    for(RangeMarker separator : lineSeparators) {
        if(separator.isValid()) {
            int start = separator.getStartOffset();
            if(start == nextLineStart) {
                continue;
            }

            logDoc.replaceString(start, separator.getEndOffset(), "\n" + indent);
            nextLineStart = start + 1 + indent.length();
            while(nextLineStart < logDoc.getTextLength() && Character.isWhitespace(logDoc.getCharsSequence().charAt(nextLineStart))) {
                logDoc.deleteString(nextLineStart, nextLineStart + 1);
            }
        }
    }
}
 
Example #22
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 4 votes vote down vote up
public static LogEntry formatForLog(@NotNull final Notification notification, String indent) {
    DocumentImpl logDoc = new DocumentImpl("", true);
    AtomicBoolean showMore = new AtomicBoolean(false);
    Map<RangeMarker, HyperlinkInfo> links = new LinkedHashMap<RangeMarker, HyperlinkInfo>();
    List<RangeMarker> lineSeparators = new ArrayList<RangeMarker>();

    String title = truncateLongString(showMore, notification.getTitle());
    String content = truncateLongString(showMore, notification.getContent());

    RangeMarker afterTitle = null;
    boolean hasHtml = parseHtmlContent(title, notification, logDoc, showMore, links, lineSeparators);
    if(StringUtil.isNotEmpty(title)) {
        if(StringUtil.isNotEmpty(content)) {
            appendText(logDoc, ": ");
            afterTitle = logDoc.createRangeMarker(logDoc.getTextLength() - 2, logDoc.getTextLength());
        }
    }
    hasHtml |= parseHtmlContent(content, notification, logDoc, showMore, links, lineSeparators);

    String status = getStatusText(logDoc, showMore, lineSeparators, hasHtml);

    indentNewLines(logDoc, lineSeparators, afterTitle, hasHtml, indent);

    ArrayList<Pair<TextRange, HyperlinkInfo>> list = new ArrayList<Pair<TextRange, HyperlinkInfo>>();
    for(RangeMarker marker : links.keySet()) {
        if(!marker.isValid()) {
            showMore.set(true);
            continue;
        }
        list.add(Pair.create(new TextRange(marker.getStartOffset(), marker.getEndOffset()), links.get(marker)));
    }

    if(showMore.get()) {
        String sb = "show balloon";
        if(!logDoc.getText().endsWith(" ")) {
            appendText(logDoc, " ");
        }
        appendText(logDoc, "(" + sb + ")");
        list.add(new Pair<TextRange, HyperlinkInfo>(TextRange.from(logDoc.getTextLength() - 1 - sb.length(), sb.length()),
            new ShowBalloon(notification)));
    }

    return new LogEntry(logDoc.getText(), status, list);
}
 
Example #23
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static String stripTrailingSpaces(String actualText, Project project) {
  final Document document = EditorFactory.getInstance().createDocument(actualText);
  ((DocumentImpl)document).stripTrailingSpaces(project);
  actualText = document.getText();
  return actualText;
}
 
Example #24
Source File: PsiDocumentManagerBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
private UncommittedInfo(@Nonnull DocumentImpl original) {
  myFrozen = original.freeze();
}
 
Example #25
Source File: MockEditorFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public Document createDocument(@Nonnull CharSequence text) {
  return new DocumentImpl(text);
}
 
Example #26
Source File: MockEditorFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
public Document createDocument(String text) {
  return new DocumentImpl(text);
}
 
Example #27
Source File: LineStatusTracker.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void markLinesUnchanged(int startLine, int endLine) {
  if (myDocument.getTextLength() == 0) return; // empty document has no lines
  if (startLine == endLine) return;
  ((DocumentImpl)myDocument).clearLineModificationFlags(startLine, endLine);
}
 
Example #28
Source File: ApplyPatchViewer.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ApplyPatchViewer(@Nonnull DiffContext context, @Nonnull ApplyPatchRequest request) {
  myProject = context.getProject();
  myContext = context;
  myPatchRequest = request;


  DocumentContent resultContent = request.getResultContent();
  DocumentContent patchContent = DiffContentFactory.getInstance().create(new DocumentImpl("", true), resultContent);

  myResultHolder = TextEditorHolder.create(myProject, resultContent);
  myPatchHolder = TextEditorHolder.create(myProject, patchContent);

  myResultEditor = myResultHolder.getEditor();
  myPatchEditor = myPatchHolder.getEditor();

  if (isReadOnly()) myResultEditor.setViewer(true);
  myPatchEditor.setViewer(true);

  DiffUtil.disableBlitting(myResultEditor);
  DiffUtil.disableBlitting(myPatchEditor);

  ((EditorMarkupModel)myResultEditor.getMarkupModel()).setErrorStripeVisible(false);
  myResultEditor.setVerticalScrollbarOrientation(EditorEx.VERTICAL_SCROLLBAR_LEFT);

  myPatchEditor.getGutterComponentEx().setForceShowRightFreePaintersArea(true);
  ((EditorMarkupModel)myPatchEditor.getMarkupModel()).setErrorStripeVisible(false);


  List<TextEditorHolder> holders = ContainerUtil.list(myResultHolder, myPatchHolder);
  List<EditorEx> editors = ContainerUtil.list(myResultEditor, myPatchEditor);
  JComponent resultTitle = DiffUtil.createTitle(myPatchRequest.getResultTitle());
  JComponent patchTitle = DiffUtil.createTitle(myPatchRequest.getPatchTitle());
  List<JComponent> titleComponents = DiffUtil.createSyncHeightComponents(ContainerUtil.list(resultTitle, patchTitle));

  myContentPanel = new TwosideContentPanel(holders, titleComponents);
  myPanel = new SimpleDiffPanel(myContentPanel, this, myContext);

  myModel = new MyModel(myProject, myResultEditor.getDocument());

  myFocusTrackerSupport = new FocusTrackerSupport.Twoside(holders);
  myFocusTrackerSupport.setCurrentSide(Side.LEFT);
  myPrevNextDifferenceIterable = new MyPrevNextDifferenceIterable();
  myStatusPanel = new MyStatusPanel();
  myFoldingModel = new MyFoldingModel(myResultEditor, this);


  new MyFocusOppositePaneAction().install(myPanel);
  new TextDiffViewerUtil.EditorActionsPopup(createEditorPopupActions()).install(editors, myPanel);

  new TextDiffViewerUtil.EditorFontSizeSynchronizer(editors).install(this);

  myEditorSettingsAction = new SetEditorSettingsAction(getTextSettings(), editors);
  myEditorSettingsAction.applyDefaults();

  if (!isReadOnly()) {
    DiffUtil.registerAction(new ApplySelectedChangesAction(true), myPanel);
    DiffUtil.registerAction(new IgnoreSelectedChangesAction(true), myPanel);
  }

  ProxyUndoRedoAction.register(myProject, myResultEditor, myContentPanel);
}
 
Example #29
Source File: MergedDiffRequestPresentable.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static SimpleDiffRequest createBadDiffRequest(@javax.annotation.Nullable final Project project,
                                                     @Nonnull final VirtualFile file,
                                                     @Nonnull ApplyPatchForBaseRevisionTexts texts,
                                                     boolean readonly) {
  final String fullPath = file.getParent() == null ? file.getPath() : file.getParent().getPath();
  final String title = "Result Of Patch Apply To " + file.getName() + " (" + fullPath + ")";

  final SimpleDiffRequest simpleRequest = new SimpleDiffRequest(project, title);
  final DocumentImpl patched = new DocumentImpl(texts.getPatched());
  patched.setReadOnly(false);

  final DocumentContent mergedContent =
          new DocumentContent(project, patched, file.getFileType());
  mergedContent.getDocument().setReadOnly(readonly);
  final SimpleContent originalContent = new SimpleContent(texts.getLocal().toString(), file.getFileType());

  simpleRequest.setContents(originalContent, mergedContent);
  simpleRequest.setContentTitles(VcsBundle.message("diff.title.local"), "Patched (with problems)");
  simpleRequest.addHint(DiffTool.HINT_SHOW_MODAL_DIALOG);
  simpleRequest.addHint(DiffTool.HINT_DIFF_IS_APPROXIMATE);

  if (!readonly) {
    simpleRequest.setOnOkRunnable(new Runnable() {
      @Override
      public void run() {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
          @Override
          public void run() {
            final String resultText = mergedContent.getDocument().getText();
            final Document document = FileDocumentManager.getInstance().getDocument(file);
            if (document == null) {
              try {
                VfsUtil.saveText(file, resultText);
              }
              catch (IOException e) {
                // todo bad: we had already returned success by now
                showIOException(project, file.getName(), e);
              }
            }
            else {
              document.setText(resultText);
              FileDocumentManager.getInstance().saveDocument(document);
            }
          }
        });
      }
    });
  }
  return simpleRequest;
}
 
Example #30
Source File: LightFileDocumentManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
public LightFileDocumentManager() {
  myFactory = DocumentImpl::new;
  myCachedDocumentKey = null;
}