public void initialize(
      @NotNull final String vcsContent, @NotNull RevisionPack baseRevisionNumber) {
    myApplication.assertIsDispatchThread();

    synchronized (myLock) {
      try {
        if (myReleased) return;
        if (myBaseRevisionNumber != null && myBaseRevisionNumber.contains(baseRevisionNumber))
          return;

        myBaseRevisionNumber = baseRevisionNumber;

        myVcsDocument.setReadOnly(false);
        myVcsDocument.setText(vcsContent);
        myVcsDocument.setReadOnly(true);
        reinstallRanges();

        if (myDocumentListener == null) {
          myDocumentListener = new MyDocumentListener();
          myDocument.addDocumentListener(myDocumentListener);
        }
      } finally {
        myInitialized = true;
      }
    }
  }
 protected void beforeListenersAttached(Document original, Document copy) {
   boolean writable = copy.isWritable();
   Document copyEx = copy;
   if (!writable) copyEx.setReadOnly(false);
   replaceString(
       copy,
       0,
       copy.getTextLength(),
       subText(original, myRangeMarker.getStartOffset(), getLength()));
   copyEx.setReadOnly(!writable);
 }
 public void write() {
   if (!isPopulated()) {
     Flog.warn("Unable to write %s because it's not populated yet.", path);
     return;
   }
   VirtualFile virtualFile = getVirtualFile();
   if (virtualFile == null) {
     virtualFile = createFile();
     if (virtualFile == null) {
       context.errorMessage("The Floobits plugin was unable to write to a file.");
       return;
     }
   }
   Document d = Buf.getDocumentForVirtualFile(virtualFile);
   if (d != null) {
     try {
       Listener.flooDisable();
       d.setReadOnly(false);
       d.setText(buf);
     } finally {
       Listener.flooEnable();
     }
     return;
   }
   Flog.warn("Tried to write to null document: %s", path);
   try {
     virtualFile.setBinaryContent(buf.getBytes());
   } catch (IOException e) {
     Flog.warn(e);
     context.errorMessage("The Floobits plugin was unable to write to a file.");
   }
 }
示例#4
0
 private Document documentFromRevision(final ContentRevision cr) throws VcsException {
   final Document oldDocument =
       new DocumentImpl(StringUtil.convertLineSeparators(notNullContentRevision(cr)), true);
   // todo !!! a question how to show line separators in diff etc
   // todo currently document doesn't allow to put \r as separator
   oldDocument.setReadOnly(true);
   return oldDocument;
 }
 protected Document createCopy() {
   final Document originalDocument = myRangeMarker.getDocument();
   String textInRange =
       originalDocument
           .getCharsSequence()
           .subSequence(myRangeMarker.getStartOffset(), myRangeMarker.getEndOffset())
           .toString();
   final Document result = EditorFactory.getInstance().createDocument(textInRange);
   result.setReadOnly(!originalDocument.isWritable());
   result.putUserData(ORIGINAL_DOCUMENT, originalDocument);
   return result;
 }
 @Override
 public void clearReadOnlyState() {
   for (String path : readOnlyBufferIds) {
     VirtualFile file = getVirtualFile(path);
     if (file == null) {
       continue;
     }
     Document document = FileDocumentManager.getInstance().getDocument(file);
     if (document == null) {
       continue;
     }
     document.setReadOnly(false);
   }
   readOnlyBufferIds.clear();
 }
  public ImplementationViewComponent(PsiElement[] elements, final int index) {
    super(new BorderLayout());

    final Project project = elements.length > 0 ? elements[0].getProject() : null;
    EditorFactory factory = EditorFactory.getInstance();
    Document doc = factory.createDocument("");
    doc.setReadOnly(true);
    myEditor = factory.createEditor(doc, project);
    ((EditorEx) myEditor).setBackgroundColor(EditorFragmentComponent.getBackgroundColor(myEditor));

    final EditorSettings settings = myEditor.getSettings();
    settings.setAdditionalLinesCount(1);
    settings.setAdditionalColumnsCount(1);
    settings.setLineMarkerAreaShown(false);
    settings.setIndentGuidesShown(false);
    settings.setLineNumbersShown(false);
    settings.setFoldingOutlineShown(false);

    myBinarySwitch = new CardLayout();
    myViewingPanel = new JPanel(myBinarySwitch);
    myEditor.setBorder(null);
    ((EditorEx) myEditor).getScrollPane().setViewportBorder(JBScrollPane.createIndentBorder());
    myViewingPanel.add(myEditor.getComponent(), TEXT_PAGE_KEY);

    myBinaryPanel = new JPanel(new BorderLayout());
    myViewingPanel.add(myBinaryPanel, BINARY_PAGE_KEY);

    add(myViewingPanel, BorderLayout.CENTER);

    myToolbar = createToolbar();
    myLocationLabel = new JLabel();
    myCountLabel = new JLabel();

    final JPanel header = new JPanel(new BorderLayout(2, 0));
    header.setBorder(
        BorderFactory.createCompoundBorder(
            IdeBorderFactory.createBorder(SideBorder.BOTTOM),
            IdeBorderFactory.createEmptyBorder(0, 0, 0, 5)));
    final JPanel toolbarPanel = new JPanel(new GridBagLayout());
    final GridBagConstraints gc =
        new GridBagConstraints(
            GridBagConstraints.RELATIVE,
            0,
            1,
            1,
            0,
            0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(0, 2, 0, 0),
            0,
            0);
    toolbarPanel.add(myToolbar.getComponent(), gc);

    setPreferredSize(new Dimension(600, 400));

    update(
        elements,
        new PairFunction<PsiElement[], List<FileDescriptor>, Boolean>() {
          @Override
          public Boolean fun(
              final PsiElement[] psiElements, final List<FileDescriptor> fileDescriptors) {
            if (psiElements.length == 0) return false;
            myElements = psiElements;

            myIndex = index < myElements.length ? index : 0;
            PsiFile psiFile = getContainingFile(myElements[myIndex]);

            VirtualFile virtualFile = psiFile.getVirtualFile();
            EditorHighlighter highlighter;
            if (virtualFile != null)
              highlighter = HighlighterFactory.createHighlighter(project, virtualFile);
            else {
              String fileName = psiFile.getName(); // some artificial psi file, lets do best we can
              highlighter = HighlighterFactory.createHighlighter(project, fileName);
            }

            ((EditorEx) myEditor).setHighlighter(highlighter);

            gc.fill = GridBagConstraints.HORIZONTAL;
            gc.weightx = 1;
            if (myElements.length > 1) {
              myFileChooser =
                  new ComboBox(
                      fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]), 250);
              updateRenderer(project);

              myFileChooser.addActionListener(
                  new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                      int index = myFileChooser.getSelectedIndex();
                      if (myIndex != index) {
                        myIndex = index;
                        updateControls();
                      }
                    }
                  });

              myLabel = new JLabel();
              myLabel.setVisible(false);
              toolbarPanel.add(myFileChooser, gc);
            } else {
              myFileChooser = new ComboBox();
              myFileChooser.setVisible(false);
              myCountLabel.setVisible(false);

              myLabel = new JLabel();
              VirtualFile file = psiFile.getVirtualFile();
              if (file != null) {
                myLabel.setIcon(getIconForFile(psiFile));
                myLabel.setForeground(
                    FileStatusManager.getInstance(project).getStatus(file).getColor());
                myLabel.setText(file.getPresentableName());
                myLabel.setBorder(
                    new CompoundBorder(
                        IdeBorderFactory.createRoundedBorder(),
                        IdeBorderFactory.createEmptyBorder(0, 0, 0, 5)));
              }
              toolbarPanel.add(myLabel, gc);
            }

            gc.fill = GridBagConstraints.NONE;
            gc.weightx = 0;
            toolbarPanel.add(myCountLabel, gc);

            header.add(toolbarPanel, BorderLayout.CENTER);
            header.add(myLocationLabel, BorderLayout.EAST);

            add(header, BorderLayout.NORTH);

            updateControls();
            return true;
          }
        });
  }
  public void patch(final FlooPatch res) {
    final TextBuf b = this;
    Flog.info("Got _on_patch");

    String text;
    String md5FromDoc;
    final Document d;

    String oldText = buf;
    VirtualFile virtualFile = b.getVirtualFile();
    if (virtualFile == null) {
      Flog.warn("VirtualFile is null, no idea what do do. Aborting everything %s", this);
      getBuf();
      return;
    }
    d = Buf.getDocumentForVirtualFile(virtualFile);
    if (d == null) {
      Flog.warn("Document not found for %s", virtualFile);
      getBuf();
      return;
    }
    String viewText;
    if (virtualFile.exists()) {
      viewText = d.getText();
      if (viewText.equals(oldText)) {
        b.forced_patch = false;
      } else if (!b.forced_patch) {
        b.forced_patch = true;
        oldText = viewText;
        b.send_patch(viewText);
        Flog.warn("Sending force patch for %s. this is dangerous!", b.path);
      }
    } else {
      viewText = oldText;
    }

    b.cancelTimeout();

    String md5Before = DigestUtils.md5Hex(viewText);
    if (!md5Before.equals(res.md5_before)) {
      Flog.warn("starting md5s don't match for %s. this is dangerous!", b.path);
    }

    List<diff_match_patch.Patch> patches = dmp.patch_fromText(res.patch);
    final Object[] results = dmp.patch_apply((LinkedList<diff_match_patch.Patch>) patches, oldText);
    final String patchedContents = (String) results[0];
    final boolean[] patchesClean = (boolean[]) results[1];
    final FlooPatchPosition[] positions = (FlooPatchPosition[]) results[2];

    for (boolean clean : patchesClean) {
      if (!clean) {
        Flog.log("Patch not clean for %s. Sending get_buf and setting readonly.", d);
        getBuf();
        return;
      }
    }
    // XXX: If patchedContents have carriage returns this will be a problem:
    String md5After = DigestUtils.md5Hex(patchedContents);
    if (!md5After.equals(res.md5_after)) {
      Flog.info("MD5 after mismatch (ours %s remote %s)", md5After, res.md5_after);
    }

    if (!d.isWritable()) {
      d.setReadOnly(false);
    }
    if (!ReadonlyStatusHandler.ensureDocumentWritable(context.project, d)) {
      Flog.info("Document: %s is not writable.", d);
      return;
    }

    final Editor[] editors = EditorFactory.getInstance().getEditors(d, context.project);
    final HashMap<ScrollingModel, Integer[]> original = new HashMap<ScrollingModel, Integer[]>();
    for (Editor editor : editors) {
      if (editor.isDisposed()) {
        continue;
      }
      ScrollingModel scrollingModel = editor.getScrollingModel();
      original.put(
          scrollingModel,
          new Integer[] {
            scrollingModel.getHorizontalScrollOffset(), scrollingModel.getVerticalScrollOffset()
          });
    }
    for (FlooPatchPosition flooPatchPosition : positions) {
      int start = Math.max(0, flooPatchPosition.start);
      int end_ld = Math.max(start + flooPatchPosition.end, start);
      end_ld = Math.min(end_ld, d.getTextLength());
      String contents = NEW_LINE.matcher(flooPatchPosition.text).replaceAll("\n");
      Throwable e = null;
      try {
        Listener.flooDisable();
        d.replaceString(start, end_ld, contents);
      } catch (Throwable exception) {
        e = exception;
      } finally {
        Listener.flooEnable();
      }

      if (e != null) {
        Flog.warn(e);
        getBuf();
        return;
      }
    }
    text = d.getText();
    md5FromDoc = DigestUtils.md5Hex(text);
    if (!md5FromDoc.equals(res.md5_after)) {
      Flog.info("md5FromDoc mismatch (ours %s remote %s)", md5FromDoc, res.md5_after);
      b.setGetBufTimeout();
    }

    for (Map.Entry<ScrollingModel, Integer[]> entry : original.entrySet()) {
      ScrollingModel model = entry.getKey();
      Integer[] offsets = entry.getValue();
      model.scrollHorizontally(offsets[0]);
      model.scrollVertically(offsets[1]);
    }

    b.set(text, md5FromDoc);
    Flog.log("Patched %s", res.path);
  }