@Override
  public boolean isPastePossible(@NotNull DataContext dataContext) {
    if (myConfigurable.getSingleSelectedGroup() == null) return false;

    String s = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
    return s != null && s.startsWith("<template ");
  }
  @Override
  public void performPaste(@NotNull DataContext dataContext) {
    TemplateGroup group = myConfigurable.getSingleSelectedGroup();
    assert group != null;

    String buffer = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
    assert buffer != null;

    try {
      for (Element templateElement :
          JDOMUtil.load(new StringReader("<root>" + buffer + "</root>"))
              .getChildren(TemplateSettings.TEMPLATE)) {
        TemplateImpl template =
            TemplateSettings.readTemplateFromElement(
                group.getName(), templateElement, getClass().getClassLoader());
        while (group.containsTemplate(template.getKey(), template.getId())) {
          template.setKey(template.getKey() + "1");
          if (template.getId() != null) {
            template.setId(template.getId() + "1");
          }
        }
        myConfigurable.addTemplate(template);
      }
    } catch (JDOMException ignore) {
    } catch (IOException ignore) {
    }
  }
 @Override
 public void performCopy(DataContext dataContext) {
   final Node selectedNode = getSelectedNode();
   assert selectedNode != null;
   final String plainText = selectedNode.getText(UsageViewImpl.this);
   CopyPasteManager.getInstance().setContents(new StringSelection(plainText.trim()));
 }
  private static boolean doCopy(
      final PsiElement element, @Nullable final Project project, @Nullable Editor editor) {
    String fqn = elementToFqn(element, editor);
    if (fqn == null) return false;

    CopyPasteManager.getInstance().setContents(new MyTransferable(fqn));

    setStatusBarText(project, IdeBundle.message("message.reference.to.fqn.has.been.copied", fqn));
    return true;
  }
 @Nullable
 private String calculatePath() {
   final Transferable contents = CopyPasteManager.getInstance().getContents();
   if (contents != null) {
     final List<File> fileList = FileCopyPasteUtil.getFileList(contents);
     if (fileList != null) {
       if (fileList.size() > 0) {
         return fileList.get(0).getAbsolutePath();
       }
     }
   }
   return null;
 }
Exemple #6
0
 @Override
 public void performCopy(@NotNull DataContext dataContext) {
   List<String> hashes = ContainerUtil.newArrayList();
   for (int row : getSelectedRows()) {
     Hash hash = ((AbstractVcsLogTableModel) getModel()).getHashAtRow(row);
     if (hash != null) {
       hashes.add(hash.asString());
     }
   }
   if (!hashes.isEmpty()) {
     CopyPasteManager.getInstance()
         .setContents(new StringSelection(StringUtil.join(hashes, "\n")));
   }
 }
  @Nullable
  private static String getStringContent(@Nullable Producer<Transferable> producer) {
    Transferable content = null;
    if (producer != null) {
      content = producer.produce();
    } else {
      CopyPasteManager manager = CopyPasteManager.getInstance();
      if (manager.areDataFlavorsAvailable(DataFlavor.stringFlavor)) {
        content = manager.getContents();
      }
    }
    if (content == null) return null;

    RawText raw = RawText.fromTransferable(content);
    if (raw != null) return raw.rawText;

    try {
      return (String) content.getTransferData(DataFlavor.stringFlavor);
    } catch (UnsupportedFlavorException ignore) {
    } catch (IOException ignore) {
    }

    return null;
  }
 @Override
 public void performCopy(@NotNull DataContext dataContext) {
   List<VcsFullCommitDetails> details =
       VcsLogUtil.collectFirstPackOfLoadedSelectedDetails(myUI.getVcsLog());
   if (!details.isEmpty()) {
     CopyPasteManager.getInstance()
         .setContents(
             new StringSelection(
                 StringUtil.join(
                     details,
                     new Function<VcsFullCommitDetails, String>() {
                       @Override
                       public String fun(VcsFullCommitDetails details) {
                         return details.getSubject();
                       }
                     },
                     "\n")));
   }
 }
  public void actionPerformed(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
    Project project = PlatformDataKeys.PROJECT.getData(dataContext);
    PsiElement element = getElementToCopy(editor, dataContext);

    if (!doCopy(element, project, editor) && editor != null) {
      Document document = editor.getDocument();
      PsiFile file = PsiDocumentManager.getInstance(project).getCachedPsiFile(document);
      if (file != null) {
        String toCopy =
            getFileFqn(file) + ":" + (editor.getCaretModel().getLogicalPosition().line + 1);
        CopyPasteManager.getInstance().setContents(new StringSelection(toCopy));
        setStatusBarText(project, toCopy + " has been copied");
      }
      return;
    }

    HighlightManager highlightManager = HighlightManager.getInstance(project);
    EditorColorsManager manager = EditorColorsManager.getInstance();
    TextAttributes attributes =
        manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    if (element != null && editor != null) {
      PsiElement nameIdentifier = HighlightUsagesHandler.getNameIdentifier(element);
      if (nameIdentifier != null) {
        highlightManager.addOccurrenceHighlights(
            editor, new PsiElement[] {nameIdentifier}, attributes, true, null);
      } else {
        PsiReference reference =
            TargetElementUtilBase.findReference(editor, editor.getCaretModel().getOffset());
        if (reference != null) {
          highlightManager.addOccurrenceHighlights(
              editor, new PsiReference[] {reference}, attributes, true, null);
        } else {
          highlightManager.addOccurrenceHighlights(
              editor, new PsiElement[] {element}, attributes, true, null);
        }
      }
    }
  }
  @Override
  public void performCopy(@NotNull DataContext dataContext) {
    final Set<TemplateImpl> templates = myConfigurable.getSelectedTemplates().keySet();

    CopyPasteManager.getInstance()
        .setContents(
            new StringSelection(
                StringUtil.join(
                    templates,
                    new Function<TemplateImpl, String>() {
                      @Override
                      public String fun(TemplateImpl template) {
                        TemplateContext zeroContext = new TemplateContext();
                        for (TemplateContextType type :
                            TemplateContextType.EP_NAME.getExtensions()) {
                          zeroContext.setEnabled(type, false);
                        }
                        return JDOMUtil.writeElement(
                            TemplateSettings.serializeTemplate(template, zeroContext));
                      }
                    },
                    SystemProperties.getLineSeparator())));
  }
 protected boolean valueIsCut() {
   return CopyPasteManager.getInstance().isCutElement(getValue());
 }
Exemple #12
0
  private static void doPaste(
      final Editor editor,
      final Project project,
      final PsiFile file,
      final Document document,
      final Producer<Transferable> producer) {
    Transferable content = null;

    if (producer != null) {
      content = producer.produce();
    } else {
      CopyPasteManager manager = CopyPasteManager.getInstance();
      if (manager.areDataFlavorsAvailable(DataFlavor.stringFlavor)) {
        content = manager.getContents();
        if (content != null) {
          manager.stopKillRings();
        }
      }
    }

    if (content != null) {
      String text = null;
      try {
        text = (String) content.getTransferData(DataFlavor.stringFlavor);
      } catch (Exception e) {
        editor.getComponent().getToolkit().beep();
      }
      if (text == null) return;

      final CodeInsightSettings settings = CodeInsightSettings.getInstance();

      final Map<CopyPastePostProcessor, TextBlockTransferableData> extraData =
          new HashMap<CopyPastePostProcessor, TextBlockTransferableData>();
      for (CopyPastePostProcessor processor :
          Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) {
        TextBlockTransferableData data = processor.extractTransferableData(content);
        if (data != null) {
          extraData.put(processor, data);
        }
      }

      text = TextBlockTransferable.convertLineSeparators(text, "\n", extraData.values());

      final CaretModel caretModel = editor.getCaretModel();
      final SelectionModel selectionModel = editor.getSelectionModel();
      final int col = caretModel.getLogicalPosition().column;

      // There is a possible case that we want to perform paste while there is an active selection
      // at the editor and caret is located
      // inside it (e.g. Ctrl+A is pressed while caret is not at the zero column). We want to insert
      // the text at selection start column
      // then, hence, inserted block of text should be indented according to the selection start as
      // well.
      final int blockIndentAnchorColumn;
      final int caretOffset = caretModel.getOffset();
      if (selectionModel.hasSelection() && caretOffset >= selectionModel.getSelectionStart()) {
        blockIndentAnchorColumn =
            editor.offsetToLogicalPosition(selectionModel.getSelectionStart()).column;
      } else {
        blockIndentAnchorColumn = col;
      }

      // We assume that EditorModificationUtil.insertStringAtCaret() is smart enough to remove
      // currently selected text (if any).

      RawText rawText = RawText.fromTransferable(content);
      String newText = text;
      for (CopyPastePreProcessor preProcessor :
          Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
        newText = preProcessor.preprocessOnPaste(project, file, editor, newText, rawText);
      }
      int indentOptions =
          text.equals(newText) ? settings.REFORMAT_ON_PASTE : CodeInsightSettings.REFORMAT_BLOCK;
      text = newText;

      if (LanguageFormatting.INSTANCE.forContext(file) == null
          && indentOptions != CodeInsightSettings.NO_REFORMAT) {
        indentOptions = CodeInsightSettings.INDENT_BLOCK;
      }

      final String _text = text;
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  EditorModificationUtil.insertStringAtCaret(editor, _text, false, true);
                }
              });

      int length = text.length();
      int offset = caretModel.getOffset() - length;
      if (offset < 0) {
        length += offset;
        offset = 0;
      }
      final RangeMarker bounds = document.createRangeMarker(offset, offset + length);

      caretModel.moveToOffset(bounds.getEndOffset());
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
      selectionModel.removeSelection();

      final Ref<Boolean> indented = new Ref<Boolean>(Boolean.FALSE);
      for (Map.Entry<CopyPastePostProcessor, TextBlockTransferableData> e : extraData.entrySet()) {
        //noinspection unchecked
        e.getKey()
            .processTransferableData(project, editor, bounds, caretOffset, indented, e.getValue());
      }

      boolean pastedTextContainsWhiteSpacesOnly =
          CharArrayUtil.shiftForward(document.getCharsSequence(), bounds.getStartOffset(), " \n\t")
              >= bounds.getEndOffset();

      VirtualFile virtualFile = file.getVirtualFile();
      if (!pastedTextContainsWhiteSpacesOnly
          && (virtualFile == null
              || !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile))) {
        final int indentOptions1 = indentOptions;
        ApplicationManager.getApplication()
            .runWriteAction(
                new Runnable() {
                  @Override
                  public void run() {
                    switch (indentOptions1) {
                      case CodeInsightSettings.INDENT_BLOCK:
                        if (!indented.get()) {
                          indentBlock(
                              project,
                              editor,
                              bounds.getStartOffset(),
                              bounds.getEndOffset(),
                              blockIndentAnchorColumn);
                        }
                        break;

                      case CodeInsightSettings.INDENT_EACH_LINE:
                        if (!indented.get()) {
                          indentEachLine(
                              project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                        }
                        break;

                      case CodeInsightSettings.REFORMAT_BLOCK:
                        indentEachLine(
                            project,
                            editor,
                            bounds.getStartOffset(),
                            bounds
                                .getEndOffset()); // this is needed for example when inserting a
                                                  // comment before method
                        reformatBlock(
                            project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                        break;
                    }
                  }
                });
      }

      if (bounds.isValid()) {
        caretModel.moveToOffset(bounds.getEndOffset());
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        selectionModel.removeSelection();
        editor.putUserData(EditorEx.LAST_PASTED_REGION, TextRange.create(bounds));
      }
    }
  }
 @Override
 public void performCopy(@NotNull DataContext dataContext) {
   ImageDocument document = imageComponent.getDocument();
   BufferedImage image = document.getValue();
   CopyPasteManager.getInstance().setContents(new ImageTransferable(image));
 }