Search in sources :

Example 71 with DataContext

use of com.intellij.openapi.actionSystem.DataContext in project intellij-community by JetBrains.

the class BaseCodeInsightAction method update.

@Override
public void update(AnActionEvent event) {
    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null) {
        presentation.setEnabled(false);
        return;
    }
    final Lookup activeLookup = LookupManager.getInstance(project).getActiveLookup();
    if (activeLookup != null) {
        presentation.setEnabled(isValidForLookup());
    } else {
        super.update(event);
    }
}
Also used : Project(com.intellij.openapi.project.Project) DataContext(com.intellij.openapi.actionSystem.DataContext) Lookup(com.intellij.codeInsight.lookup.Lookup) Presentation(com.intellij.openapi.actionSystem.Presentation)

Example 72 with DataContext

use of com.intellij.openapi.actionSystem.DataContext in project intellij-community by JetBrains.

the class CodeCompletionHandlerBase method insertItemHonorBlockSelection.

private static CompletionAssertions.WatchingInsertionContext insertItemHonorBlockSelection(final CompletionProgressIndicator indicator, final LookupElement item, final char completionChar, final List<LookupElement> items, final StatisticsUpdate update) {
    final Editor editor = indicator.getEditor();
    final int caretOffset = indicator.getCaret().getOffset();
    final int idEndOffset = indicator.getOffsetMap().containsOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) ? indicator.getIdentifierEndOffset() : CompletionInitializationContext.calcDefaultIdentifierEnd(editor, caretOffset);
    final int idEndOffsetDelta = idEndOffset - caretOffset;
    CompletionAssertions.WatchingInsertionContext context;
    if (editor.getCaretModel().supportsMultipleCarets()) {
        List<CompletionAssertions.WatchingInsertionContext> contexts = new ArrayList<>();
        Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(editor);
        OffsetsInFile topLevelOffsets = indicator.getHostOffsets();
        hostEditor.getCaretModel().runForEachCaret(new CaretAction() {

            @Override
            public void perform(Caret caret) {
                PsiDocumentManager.getInstance(indicator.getProject()).commitDocument(hostEditor.getDocument());
                OffsetsInFile targetOffsets = topLevelOffsets.toInjectedIfAny(caret.getOffset());
                PsiFile targetFile = targetOffsets.getFile();
                Editor targetEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, targetFile);
                int targetCaretOffset = targetEditor.getCaretModel().getOffset();
                int idEnd = targetCaretOffset + idEndOffsetDelta;
                if (idEnd > targetEditor.getDocument().getTextLength()) {
                    // no replacement by Tab when offsets gone wrong for some reason
                    idEnd = targetCaretOffset;
                }
                CompletionAssertions.WatchingInsertionContext currentContext = insertItem(indicator, item, completionChar, items, update, targetEditor, targetFile, targetCaretOffset, idEnd, targetOffsets.getOffsets());
                contexts.add(currentContext);
            }
        });
        context = contexts.get(contexts.size() - 1);
        if (context.shouldAddCompletionChar() && context.getCompletionChar() != Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
            ApplicationManager.getApplication().runWriteAction(() -> {
                DataContext dataContext = DataManager.getInstance().getDataContext(editor.getContentComponent());
                EditorActionManager.getInstance().getTypedAction().getHandler().execute(editor, completionChar, dataContext);
            });
        }
        for (CompletionAssertions.WatchingInsertionContext insertionContext : contexts) {
            insertionContext.stopWatching();
        }
    } else {
        context = insertItem(indicator, item, completionChar, items, update, editor, indicator.getParameters().getOriginalFile(), caretOffset, idEndOffset, indicator.getOffsetMap());
    }
    return context;
}
Also used : ArrayList(java.util.ArrayList) DataContext(com.intellij.openapi.actionSystem.DataContext) PsiFile(com.intellij.psi.PsiFile)

Example 73 with DataContext

use of com.intellij.openapi.actionSystem.DataContext in project intellij-community by JetBrains.

the class AutoPopupController method setupListeners.

private void setupListeners() {
    ActionManagerEx.getInstanceEx().addAnActionListener(new AnActionListener() {

        @Override
        public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
            cancelAllRequest();
        }

        @Override
        public void beforeEditorTyping(char c, DataContext dataContext) {
            cancelAllRequest();
        }

        @Override
        public void afterActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
        }
    }, this);
    IdeEventQueue.getInstance().addActivityListener(() -> cancelAllRequest(), this);
}
Also used : DataContext(com.intellij.openapi.actionSystem.DataContext) AnActionListener(com.intellij.openapi.actionSystem.ex.AnActionListener) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) AnAction(com.intellij.openapi.actionSystem.AnAction)

Example 74 with DataContext

use of com.intellij.openapi.actionSystem.DataContext in project intellij-community by JetBrains.

the class SaveAsTemplateAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    Editor editor = Objects.requireNonNull(CommonDataKeys.EDITOR.getData(dataContext));
    PsiFile file = Objects.requireNonNull(CommonDataKeys.PSI_FILE.getData(dataContext));
    final Project project = file.getProject();
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    final TextRange selection = new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd());
    PsiElement current = file.findElementAt(selection.getStartOffset());
    int startOffset = selection.getStartOffset();
    while (current instanceof PsiWhiteSpace) {
        current = current.getNextSibling();
        if (current == null)
            break;
        startOffset = current.getTextRange().getStartOffset();
    }
    if (startOffset >= selection.getEndOffset())
        startOffset = selection.getStartOffset();
    final PsiElement[] psiElements = PsiTreeUtil.collectElements(file, new PsiElementFilter() {

        @Override
        public boolean isAccepted(PsiElement element) {
            return selection.contains(element.getTextRange()) && element.getReferences().length > 0;
        }
    });
    final Document document = EditorFactory.getInstance().createDocument(editor.getDocument().getText().substring(startOffset, selection.getEndOffset()));
    final boolean isXml = file.getLanguage().is(StdLanguages.XML);
    final int offsetDelta = startOffset;
    new WriteCommandAction.Simple(project, (String) null) {

        @Override
        protected void run() throws Throwable {
            Map<RangeMarker, String> rangeToText = new HashMap<>();
            for (PsiElement element : psiElements) {
                for (PsiReference reference : element.getReferences()) {
                    if (!(reference instanceof PsiQualifiedReference) || ((PsiQualifiedReference) reference).getQualifier() == null) {
                        String canonicalText = reference.getCanonicalText();
                        TextRange referenceRange = reference.getRangeInElement();
                        final TextRange elementTextRange = element.getTextRange();
                        LOG.assertTrue(elementTextRange != null, elementTextRange);
                        final TextRange range = elementTextRange.cutOut(referenceRange).shiftRight(-offsetDelta);
                        final String oldText = document.getText(range);
                        // workaround for Java references: canonicalText contains generics, and we need to cut them off because otherwise
                        // they will be duplicated
                        int pos = canonicalText.indexOf('<');
                        if (pos > 0 && !oldText.contains("<")) {
                            canonicalText = canonicalText.substring(0, pos);
                        }
                        if (isXml) {
                            //strip namespace prefixes
                            pos = canonicalText.lastIndexOf(':');
                            if (pos >= 0 && pos < canonicalText.length() - 1 && !oldText.contains(":")) {
                                canonicalText = canonicalText.substring(pos + 1);
                            }
                        }
                        if (!canonicalText.equals(oldText)) {
                            rangeToText.put(document.createRangeMarker(range), canonicalText);
                        }
                    }
                }
            }
            List<RangeMarker> markers = new ArrayList<>();
            for (RangeMarker m1 : rangeToText.keySet()) {
                boolean nested = false;
                for (RangeMarker m2 : rangeToText.keySet()) {
                    if (m1 != m2 && m2.getStartOffset() <= m1.getStartOffset() && m1.getEndOffset() <= m2.getEndOffset()) {
                        nested = true;
                        break;
                    }
                }
                if (!nested) {
                    markers.add(m1);
                }
            }
            for (RangeMarker marker : markers) {
                final String value = rangeToText.get(marker);
                document.replaceString(marker.getStartOffset(), marker.getEndOffset(), value);
            }
        }
    }.execute();
    final TemplateImpl template = new TemplateImpl(TemplateListPanel.ABBREVIATION, document.getText(), TemplateSettings.USER_GROUP_NAME);
    template.setToReformat(true);
    OffsetKey startKey = OffsetKey.create("pivot");
    OffsetsInFile offsets = new OffsetsInFile(file);
    offsets.getOffsets().addOffset(startKey, startOffset);
    OffsetsInFile copy = TemplateManagerImpl.copyWithDummyIdentifier(offsets, editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd(), CompletionUtil.DUMMY_IDENTIFIER_TRIMMED);
    Set<TemplateContextType> applicable = TemplateManagerImpl.getApplicableContextTypes(copy.getFile(), copy.getOffsets().getOffset(startKey));
    for (TemplateContextType contextType : TemplateManagerImpl.getAllContextTypes()) {
        template.getTemplateContext().setEnabled(contextType, applicable.contains(contextType));
    }
    final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
    ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> configurable.getTemplateListPanel().addTemplate(template));
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) OffsetsInFile(com.intellij.codeInsight.completion.OffsetsInFile) Document(com.intellij.openapi.editor.Document) DataContext(com.intellij.openapi.actionSystem.DataContext) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) PsiElementFilter(com.intellij.psi.util.PsiElementFilter) Project(com.intellij.openapi.project.Project) OffsetKey(com.intellij.codeInsight.completion.OffsetKey) Editor(com.intellij.openapi.editor.Editor) HashMap(com.intellij.util.containers.HashMap) TemplateContextType(com.intellij.codeInsight.template.TemplateContextType)

Example 75 with DataContext

use of com.intellij.openapi.actionSystem.DataContext in project intellij-community by JetBrains.

the class SaveAsTemplateAction method update.

@Override
public void update(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);
    if (file == null || editor == null) {
        e.getPresentation().setEnabled(false);
    } else {
        e.getPresentation().setEnabled(editor.getSelectionModel().hasSelection());
    }
}
Also used : DataContext(com.intellij.openapi.actionSystem.DataContext) Editor(com.intellij.openapi.editor.Editor)

Aggregations

DataContext (com.intellij.openapi.actionSystem.DataContext)204 Project (com.intellij.openapi.project.Project)73 VirtualFile (com.intellij.openapi.vfs.VirtualFile)29 NotNull (org.jetbrains.annotations.NotNull)23 IpnbFileEditor (org.jetbrains.plugins.ipnb.editor.IpnbFileEditor)23 Editor (com.intellij.openapi.editor.Editor)22 Nullable (org.jetbrains.annotations.Nullable)21 FileEditor (com.intellij.openapi.fileEditor.FileEditor)20 PsiFile (com.intellij.psi.PsiFile)17 IpnbFilePanel (org.jetbrains.plugins.ipnb.editor.panels.IpnbFilePanel)16 Module (com.intellij.openapi.module.Module)13 PsiElement (com.intellij.psi.PsiElement)13 SimpleDataContext (com.intellij.openapi.actionSystem.impl.SimpleDataContext)11 Presentation (com.intellij.openapi.actionSystem.Presentation)10 DataManager (com.intellij.ide.DataManager)9 AnActionEvent (com.intellij.openapi.actionSystem.AnActionEvent)9 List (java.util.List)9 Consumer (com.intellij.util.Consumer)7 AnAction (com.intellij.openapi.actionSystem.AnAction)6 Transferable (java.awt.datatransfer.Transferable)6