com.intellij.openapi.util.Pair Java Examples

The following examples show how to use com.intellij.openapi.util.Pair. 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: MsilPropertyAsCSharpPropertyDeclaration.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
public MsilPropertyAsCSharpPropertyDeclaration(PsiElement parent, MsilPropertyEntry variable, List<Pair<DotNetXAccessor, MsilMethodEntry>> pairs)
{
	super(parent, getAdditionalModifiers(variable, pairs), variable);
	myAccessors = buildAccessors(this, pairs);

	myTypeForImplementValue = NullableLazyValue.of(() ->
	{
		String nameFromBytecode = getVariable().getNameFromBytecode();
		String typeBeforeDot = StringUtil.getPackageName(nameFromBytecode);
		SomeType someType = SomeTypeParser.parseType(typeBeforeDot, nameFromBytecode);
		if(someType != null)
		{
			return new DummyType(getProject(), MsilPropertyAsCSharpPropertyDeclaration.this, someType);
		}
		return null;
	});
}
 
Example #2
Source File: MyEditorWriteActionHandler.java    From dummytext-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected final void doExecute(@NotNull final Editor editor, @Nullable final Caret caret, final DataContext dataContext) {
    MyApplicationComponent.setAction(actionClass);

    final Pair<Boolean, T> additionalParameter = beforeWriteAction(editor, dataContext);
    if (!additionalParameter.first) {
        return;
    }

    final Runnable runnable = () -> executeWriteAction(editor, caret, dataContext, additionalParameter.second);
    new EditorWriteActionHandler(false) {
        @Override
        public void executeWriteAction(Editor editor1, @Nullable Caret caret1, DataContext dataContext1) {
            runnable.run();
        }
    }.doExecute(editor, caret, dataContext);
}
 
Example #3
Source File: ShowIntentionsPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean markActionInvoked(@Nonnull Project project, @Nonnull final Editor editor, @Nonnull IntentionAction action) {
  final int offset = ((EditorEx)editor).getExpectedCaretOffset();

  List<HighlightInfo> infos = new ArrayList<>();
  DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true, new CommonProcessors.CollectProcessor<>(infos));
  boolean removed = false;
  for (HighlightInfo info : infos) {
    if (info.quickFixActionMarkers != null) {
      for (Pair<HighlightInfo.IntentionActionDescriptor, RangeMarker> pair : info.quickFixActionMarkers) {
        HighlightInfo.IntentionActionDescriptor actionInGroup = pair.first;
        if (actionInGroup.getAction() == action) {
          // no CME because the list is concurrent
          removed |= info.quickFixActionMarkers.remove(pair);
        }
      }
    }
  }
  return removed;
}
 
Example #4
Source File: LSPReferencesAction.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (editor != null) {
        EditorEventManager eventManager = EditorEventManagerBase.forEditor(editor);
        if (eventManager == null) {
            return;
        }
        List<PsiElement2UsageTargetAdapter> targets = new ArrayList<>();
        Pair<List<PsiElement>, List<VirtualFile>> references = eventManager
                .references(editor.getCaretModel().getCurrentCaret().getOffset());
        if (references.first != null && references.second != null) {
            references.first.forEach(element -> targets.add(new PsiElement2UsageTargetAdapter(element)));
        }
        showReferences(editor, targets, editor.getCaretModel().getCurrentCaret().getLogicalPosition());
    }
}
 
Example #5
Source File: GeneratorDialog.java    From idea-gitignore with MIT License 6 votes vote down vote up
/**
 * Updates editor's content depending on the selected {@link TreePath}.
 *
 * @param path selected tree path
 */
private void updateDescriptionPanel(@NotNull TreePath path) {
    final TemplateTreeNode node = (TemplateTreeNode) path.getLastPathComponent();
    final Resources.Template template = node.getTemplate();

    ApplicationManager.getApplication().runWriteAction(
            () -> CommandProcessor.getInstance().runUndoTransparentAction(() -> {
                String content = template != null ?
                        StringUtil.notNullize(template.getContent()).replace('\r', '\0') : "";
                previewDocument.replaceString(0, previewDocument.getTextLength(), content);

                List<Pair<Integer, Integer>> pairs =
                        getFilterRanges(profileFilter.getTextEditor().getText(), content);
                highlightWords(pairs);
            })
    );
}
 
Example #6
Source File: TabbedShowHistoryAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static Pair<FilePath, VirtualFile> getPathAndParentFile(@Nonnull VcsContext context) {
  if (context.getSelectedFilesStream().findAny().isPresent()) {
    VirtualFile file = getIfSingle(context.getSelectedFilesStream());
    return file != null ? Pair.create(VcsUtil.getFilePath(file), file) : Pair.empty();
  }

  File[] ioFiles = context.getSelectedIOFiles();
  if (ioFiles != null && ioFiles.length > 0) {
    for (File ioFile : ioFiles) {
      VirtualFile parent = getParentVirtualFile(ioFile);
      if (parent != null) return Pair.create(VcsUtil.getFilePath(parent, ioFile.getName()), parent);
    }
  }

  return Pair.empty();
}
 
Example #7
Source File: TypoTolerantMatcher.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean processErrors(int start, int end, Processor<? super Pair<Integer, Error>> processor) {
  if (myBase != null && start < myDeriveIndex) {
    if (!myBase.processErrors(start, myDeriveIndex, processor)) {
      return false;
    }
  }

  if (myErrors != null) {
    for (Pair<Integer, Error> error : myErrors) {
      if (start <= error.first && error.first < end) {
        if (!processor.process(error)) {
          return false;
        }
      }
    }
  }

  return true;
}
 
Example #8
Source File: ComponentStoreImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public final void save(@Nonnull List<Pair<StateStorage.SaveSession, File>> readonlyFiles) {
  ExternalizationSession externalizationSession = myComponents.isEmpty() ? null : getStateStorageManager().startExternalization();
  if (externalizationSession != null) {
    String[] names = ArrayUtil.toStringArray(myComponents.keySet());
    Arrays.sort(names);
    for (String name : names) {
      StateComponentInfo<?> componentInfo = myComponents.get(name);

      commitComponentInsideSingleUIWriteThread(componentInfo, externalizationSession);
    }
  }

  for (SettingsSavingComponent settingsSavingComponent : mySettingsSavingComponents) {
    try {
      settingsSavingComponent.save();
    }
    catch (Throwable e) {
      LOG.error(e);
    }
  }

  doSave(externalizationSession == null ? null : externalizationSession.createSaveSessions(), readonlyFiles);
}
 
Example #9
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Pair<PsiFile, Editor> chooseBetweenHostAndInjected(@Nonnull PsiFile hostFile,
                                                                 @Nonnull Editor hostEditor,
                                                                 @Nullable PsiFile injectedFile,
                                                                 @Nonnull PairProcessor<? super PsiFile, ? super Editor> predicate) {
  Editor editorToApply = null;
  PsiFile fileToApply = null;

  Editor injectedEditor = null;
  if (injectedFile != null) {
    injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, injectedFile);
    if (predicate.process(injectedFile, injectedEditor)) {
      editorToApply = injectedEditor;
      fileToApply = injectedFile;
    }
  }

  if (editorToApply == null && hostEditor != injectedEditor && predicate.process(hostFile, hostEditor)) {
    editorToApply = hostEditor;
    fileToApply = hostFile;
  }
  if (editorToApply == null) return null;
  return Pair.create(fileToApply, editorToApply);
}
 
Example #10
Source File: Messages.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Pair<String, Boolean> showInputDialogWithCheckBox(String message,
                                                                String title,
                                                                String checkboxText,
                                                                boolean checked,
                                                                boolean checkboxEnabled,
                                                                @Nullable Icon icon,
                                                                @NonNls String initialValue,
                                                                @Nullable InputValidator validator) {
  if (isApplicationInUnitTestOrHeadless()) {
    return new Pair<String, Boolean>(ourTestInputImplementation.show(message), checked);
  }
  else {
    InputDialogWithCheckbox dialog = new InputDialogWithCheckbox(message, title, checkboxText, checked, checkboxEnabled, icon, initialValue, validator);
    dialog.show();
    return new Pair<String, Boolean>(dialog.getInputString(), dialog.isChecked());
  }
}
 
Example #11
Source File: NamedScopeDescriptor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(@Nonnull PsiFile psiFile) {
  Pair<NamedScopesHolder, NamedScope> resolved = resolveScope(psiFile.getProject());
  if (resolved == null) {
    resolved = resolveScope(ProjectManager.getInstance().getDefaultProject());
  }
  if (resolved != null) {
    PackageSet fileSet = resolved.second.getValue();
    if (fileSet != null) {
      return fileSet.contains(psiFile, resolved.first);
    }
  }
  if (myFileSet != null) {
    NamedScopesHolder holder = DependencyValidationManager.getInstance(psiFile.getProject());
    return myFileSet.contains(psiFile, holder);
  }
  return false;
}
 
Example #12
Source File: PersistentFSImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void applyCreateEventsInDirectory(@Nonnull VirtualDirectoryImpl parent, @Nonnull Collection<? extends VFileCreateEvent> createEvents) {
  int parentId = getFileId(parent);
  NewVirtualFile vf = findFileById(parentId);
  if (!(vf instanceof VirtualDirectoryImpl)) return;
  parent = (VirtualDirectoryImpl)vf;  // retain in myIdToDirCache at least for the duration of this block in order to subsequent findFileById() won't crash
  final NewVirtualFileSystem delegate = replaceWithNativeFS(getDelegate(parent));
  TIntHashSet parentChildrenIds = new TIntHashSet(createEvents.size());

  List<ChildInfo> childrenAdded = getOrCreateChildInfos(parent, createEvents, VFileCreateEvent::getChildName, parentChildrenIds, delegate, (createEvent, childId) -> {
    createEvent.resetCache();
    String name = createEvent.getChildName();
    Pair<FileAttributes, String> childData = getChildData(delegate, createEvent.getParent(), name, createEvent.getAttributes(), createEvent.getSymlinkTarget());
    if (childData == null) return null;
    childId = makeChildRecord(parentId, name, childData, delegate);
    return new ChildInfoImpl(childId, name, childData.first, createEvent.getChildren(), createEvent.getSymlinkTarget());
  });
  FSRecords.updateList(parentId, parentChildrenIds.toArray());
  parent.createAndAddChildren(childrenAdded, false, (__, ___) -> {
  });

  saveScannedChildrenRecursively(createEvents, delegate);
}
 
Example #13
Source File: P4CommandUtil.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
public List<Pair<IFileSpec, IFileRevisionData>> getExactHistory(IOptionsServer server, List<IFileSpec> specs)
        throws P4JavaException {
    GetRevisionHistoryOptions opts = new GetRevisionHistoryOptions()
            .setMaxRevs(1)
            .setContentHistory(false)
            .setIncludeInherited(false)
            .setLongOutput(true)
            .setTruncatedLongOutput(false);
    Map<IFileSpec, List<IFileRevisionData>> res = server.getRevisionHistory(specs, opts);
    List<Pair<IFileSpec, IFileRevisionData>> ret = new ArrayList<>(res.size());
    for (Map.Entry<IFileSpec, List<IFileRevisionData>> entry: res.entrySet()) {
        // it can return empty values for a server message
        List<IFileRevisionData> value = entry.getValue();
        if (value != null && !value.isEmpty()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Mapped " + entry.getKey().getDepotPath() + " to " + entry.getValue());
            }
            if (entry.getValue().size() != 1) {
                throw new IllegalStateException("Unexpected revision count for " + entry.getKey().getDepotPath());
            }
            ret.add(Pair.create(entry.getKey(), entry.getValue().get(0)));
        }
    }
    return ret;
}
 
Example #14
Source File: PathsVerifier.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public Collection<FilePatch> filterBadFileTypePatches() {
  List<Pair<VirtualFile, ApplyTextFilePatch>> failedTextPatches =
          ContainerUtil.findAll(myTextPatches, new Condition<Pair<VirtualFile, ApplyTextFilePatch>>() {
            @Override
            public boolean value(Pair<VirtualFile, ApplyTextFilePatch> textPatch) {
              final VirtualFile file = textPatch.getFirst();
              if (file.isDirectory()) return false;
              return !isFileTypeOk(file);
            }
          });
  myTextPatches.removeAll(failedTextPatches);
  return ContainerUtil.map(failedTextPatches, new Function<Pair<VirtualFile, ApplyTextFilePatch>, FilePatch>() {
    @Override
    public FilePatch fun(Pair<VirtualFile, ApplyTextFilePatch> patchInfo) {
      return patchInfo.getSecond().getPatch();
    }
  });
}
 
Example #15
Source File: VcsLogGraphTable.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private Pair<TIntHashSet, Integer> findRowsToSelectAndScroll(@Nonnull GraphTableModel model,
                                                             @Nonnull VisibleGraph<Integer> visibleGraph) {
  TIntHashSet rowsToSelect = new TIntHashSet();

  if (model.getRowCount() == 0) {
    // this should have been covered by facade.getVisibleCommitCount,
    // but if the table is empty (no commits match the filter), the GraphFacade is not updated, because it can't handle it
    // => it has previous values set.
    return Pair.create(rowsToSelect, null);
  }

  Integer rowToScroll = null;
  for (int row = 0;
       row < visibleGraph.getVisibleCommitCount() && (rowsToSelect.size() < mySelectedCommits.size() || rowToScroll == null);
       row++) { //stop iterating if found all hashes
    int commit = visibleGraph.getRowInfo(row).getCommit();
    if (mySelectedCommits.contains(commit)) {
      rowsToSelect.add(row);
    }
    if (myVisibleSelectedCommit != null && myVisibleSelectedCommit == commit) {
      rowToScroll = row;
    }
  }
  return Pair.create(rowsToSelect, rowToScroll);
}
 
Example #16
Source File: JreSettingsTest.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
@Test
void getProperty() {
    Properties props = System.getProperties();
    for (String key : props.stringPropertyNames()) {
        JreSettings.setOverrides((Map<String, String>) null);
        String value = props.getProperty(key);
        assertEquals(value, JreSettings.getProperty(key));
        JreSettings.setOverrides(new Pair<>(key, "--" + value));
        assertEquals("--" + value, JreSettings.getProperty(key));
        JreSettings.setOverrides(new Pair<>(key, null));
        assertNull(JreSettings.getProperty(key));
        assertEquals("abc", JreSettings.getProperty(key, "abc"));
    }

    JreSettings.setOverrides((Map<String, String>) null);

    int i = 0;
    String notExist;
    do {
        i++;
        notExist = "not-exist-" + i;
    } while (props.getProperty(notExist) != null);
    assertNull(JreSettings.getProperty(notExist));
    assertEquals("abc", JreSettings.getProperty(notExist, "abc"));
}
 
Example #17
Source File: HaxeTestFinder.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public Collection<PsiElement> findTestsForClass(@NotNull PsiElement element) {
  final HaxeClass haxeClass = findSourceElement(element);
  if (haxeClass == null) {
    return Collections.emptyList();
  }
  final Collection<PsiElement> result = new THashSet<PsiElement>();
  final Pair<String, String> packageAndName = HaxeResolveUtil.splitQName(haxeClass.getQualifiedName());
  final GlobalSearchScope searchScope = GlobalSearchScope.projectScope(element.getProject());
  result.addAll(HaxeComponentIndex.getItemsByName(packageAndName.getSecond() + "Test", element.getProject(), searchScope));
  result.addAll(HaxeComponentIndex.getItemsByName("Test" + packageAndName.getSecond(), element.getProject(), searchScope));
  return result;
}
 
Example #18
Source File: IgnoreEntryOccurrence.java    From idea-gitignore with MIT License 5 votes vote down vote up
/**
 * Static helper to write given {@link IgnoreEntryOccurrence} to the output stream.
 *
 * @param out   output stream
 * @param entry entry to write
 * @throws IOException I/O exception
 */
public static synchronized void serialize(@NotNull DataOutput out, @NotNull IgnoreEntryOccurrence entry)
        throws IOException {
    out.writeUTF(entry.url);
    out.writeInt(entry.items.size());
    for (Pair<String, Boolean> item : entry.items) {
        out.writeUTF(item.first);
        out.writeBoolean(item.second);
    }
}
 
Example #19
Source File: P4ServerComponent.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@NotNull
public static <R extends P4CommandRunner.ServerResult> P4CommandRunner.FutureResult<R> syncQuery(
        @NotNull Project project,
        @NotNull OptionalClientServerConfig config,
        @NotNull P4CommandRunner.SyncServerQuery<R> query) {
    final Pair<P4ServerComponent, Boolean> instance = findInstance(project);
    P4CommandRunner.FutureResult<R> ret = instance.first.getCommandRunner().syncQuery(config, query);
    if (instance.second) {
        ret.getPromise().whenAnyState(instance.first::dispose);
    }
    return ret;
}
 
Example #20
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Returned Point is in layered pane coordinate system.
 * Second value is a {@link HintManager.PositionFlags position flag}.
 */
static Pair<Point, Short> chooseBestHintPosition(Editor editor, VisualPosition pos, LightweightHint hint, short preferredPosition, boolean showLookupHint) {
  if (ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment()) return Pair.pair(new Point(), HintManager.DEFAULT);

  HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl();
  Dimension hintSize = hint.getComponent().getPreferredSize();
  JComponent editorComponent = editor.getComponent();
  JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane();

  Point p1;
  Point p2;
  if (showLookupHint) {
    p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER);
    p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE);
  }
  else {
    p1 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.UNDER);
    p2 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.ABOVE);
  }

  boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight();
  boolean p2Ok = p2.y >= 0;

  if (!showLookupHint) {
    if (preferredPosition != HintManager.DEFAULT) {
      if (preferredPosition == HintManager.ABOVE) {
        if (p2Ok) return new Pair<>(p2, HintManager.ABOVE);
      }
      else if (preferredPosition == HintManager.UNDER) {
        if (p1Ok) return new Pair<>(p1, HintManager.UNDER);
      }
    }
  }
  if (p1Ok) return new Pair<>(p1, HintManager.UNDER);
  if (p2Ok) return new Pair<>(p2, HintManager.ABOVE);

  int underSpace = layeredPane.getHeight() - p1.y;
  int aboveSpace = p2.y;
  return aboveSpace > underSpace ? new Pair<>(new Point(p2.x, 0), HintManager.UNDER) : new Pair<>(p1, HintManager.ABOVE);
}
 
Example #21
Source File: TFSCommittedChangesProvider.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Override
public Pair<TFSChangeList, FilePath> getOneList(final VirtualFile file, final VcsRevisionNumber number) throws VcsException {
    final ChangeBrowserSettings settings = createDefaultSettings();
    settings.USE_CHANGE_AFTER_FILTER = true;
    settings.USE_CHANGE_BEFORE_FILTER = true;
    settings.CHANGE_BEFORE = settings.CHANGE_AFTER = String.valueOf(((TfsRevisionNumber) number).getValue());
    final FilePath filePath = VcsContextFactory.SERVICE.getInstance().createFilePathOn(file);
    final List<TFSChangeList> list = getCommittedChanges(settings, getLocationFor(filePath), 1);
    if (list.size() == 1) {
        return Pair.create(list.get(0), filePath);
    }
    return null;
}
 
Example #22
Source File: BlockUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static Pair<List<DataLanguageBlockWrapper>, List<DataLanguageBlockWrapper>> splitBlocksByRightBound(@Nonnull Block parent, @Nonnull TextRange bounds) {
  final List<Block> subBlocks = parent.getSubBlocks();
  if (subBlocks.size() == 0) return new Pair<List<DataLanguageBlockWrapper>, List<DataLanguageBlockWrapper>>(Collections.<DataLanguageBlockWrapper>emptyList(), Collections.<DataLanguageBlockWrapper>emptyList());
  final ArrayList<DataLanguageBlockWrapper> before = new ArrayList<DataLanguageBlockWrapper>(subBlocks.size() / 2);
  final ArrayList<DataLanguageBlockWrapper> after = new ArrayList<DataLanguageBlockWrapper>(subBlocks.size() / 2);
  splitByRightBoundAndCollectBlocks(subBlocks, before, after, bounds);
  return new Pair<List<DataLanguageBlockWrapper>, List<DataLanguageBlockWrapper>>(before, after);
}
 
Example #23
Source File: HistoryDialogModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected Pair<Revision, List<RevisionItem>> calcRevisionsCache() {
  return ApplicationManager.getApplication().runReadAction(new Computable<Pair<Revision, List<RevisionItem>>>() {
    public Pair<Revision, List<RevisionItem>> compute() {
      myGateway.registerUnsavedDocuments(myVcs);
      String path = myFile.getPath();
      RootEntry root = myGateway.createTransientRootEntry();
      RevisionsCollector collector = new RevisionsCollector(myVcs, root, path, myProject.getLocationHash(), myFilter);

      List<Revision> all = collector.getResult();
      return Pair.create(all.get(0), groupRevisions(all.subList(1, all.size())));
    }
  });
}
 
Example #24
Source File: RemoteRevisionsNumbersCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void switchVcs(final VcsRoot oldVcsRoot, final VcsRoot newVcsRoot, final String key) {
  synchronized (myLock) {
    final LazyRefreshingSelfQueue<String> oldQueue = getQueue(oldVcsRoot);
    final LazyRefreshingSelfQueue<String> newQueue = getQueue(newVcsRoot);
    myData.put(key, Pair.create(newVcsRoot, NOT_LOADED));
    oldQueue.forceRemove(key);
    newQueue.addRequest(key);
  }
}
 
Example #25
Source File: RepositoryLocationCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
public RepositoryLocationCache(final Project project) {
  myProject = project;
  myMap = Collections.synchronizedMap(new HashMap<Pair<String, String>, RepositoryLocation>());
  final MessageBusConnection connection = myProject.getMessageBus().connect();
  final VcsListener listener = new VcsListener() {
    @Override
    public void directoryMappingChanged() {
      reset();
    }
  };
  connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, listener);
  connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED_IN_PLUGIN, listener);
}
 
Example #26
Source File: EditorAPITextPositionTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCalculateOffsetsOneLineSelection() {
  int startLine = 3;
  int endLine = 3;
  TextSelection textSelection = selection(startLine, 7, endLine, 9);

  Editor editor = new EditorBuild().withLineOffsetLookupAnswer(startLine, 11).build();

  Pair<Integer, Integer> expectedOffsets = offsets(18, 20);

  Pair<Integer, Integer> calculatedOffsets = EditorAPI.calculateOffsets(editor, textSelection);

  assertEquals(expectedOffsets, calculatedOffsets);
}
 
Example #27
Source File: TextEditorWithPreview.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public DoublingEventListenerDelegate removeListenerAndGetDelegate(@Nonnull PropertyChangeListener listener) {
  final Pair<Integer, DoublingEventListenerDelegate> oldPair = myMap.get(listener);
  if (oldPair == null) {
    return null;
  }

  if (oldPair.getFirst() == 1) {
    myMap.remove(listener);
  }
  else {
    myMap.put(listener, Pair.create(oldPair.getFirst() - 1, oldPair.getSecond()));
  }
  return oldPair.getSecond();
}
 
Example #28
Source File: AllLinesIterator.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<Integer, CharSequence> next() {
  int offset1 = myDocument.getLineStartOffset(myLine);
  int offset2 = myDocument.getLineEndOffset(myLine);

  CharSequence text = myDocument.getImmutableCharSequence().subSequence(offset1, offset2);

  Pair<Integer, CharSequence> pair = new Pair<>(myLine, text);
  myLine++;

  return pair;
}
 
Example #29
Source File: CachedIntentions.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
IntentionActionWithTextCaching wrapAction(@Nonnull HighlightInfo.IntentionActionDescriptor descriptor,
                                          @Nonnull PsiElement element,
                                          @Nonnull PsiFile containingFile,
                                          @Nullable Editor containingEditor) {
  IntentionActionWithTextCaching cachedAction = new IntentionActionWithTextCaching(descriptor, (cached, action) -> {
    if (action instanceof QuickFixWrapper) {
      // remove only inspection fixes after invocation,
      // since intention actions might be still available
      removeActionFromCached(cached);
      markInvoked(action);
    }
  });
  final List<IntentionAction> options = descriptor.getOptions(element, containingEditor);
  if (options == null) return cachedAction;
  for (IntentionAction option : options) {
    Editor editor = ObjectUtils.chooseNotNull(myEditor, containingEditor);
    if (editor == null) continue;
    Pair<PsiFile, Editor> availableIn = ShowIntentionActionsHandler.chooseBetweenHostAndInjected(myFile, editor, containingFile, (f, e) -> ShowIntentionActionsHandler.availableFor(f, e, option));
    if (availableIn == null) continue;
    IntentionActionWithTextCaching textCaching = new IntentionActionWithTextCaching(option);
    boolean isErrorFix = myErrorFixes.contains(textCaching);
    if (isErrorFix) {
      cachedAction.addErrorFix(option);
    }
    boolean isInspectionFix = myInspectionFixes.contains(textCaching);
    if (isInspectionFix) {
      cachedAction.addInspectionFix(option);
    }
    else {
      cachedAction.addIntention(option);
    }
  }
  return cachedAction;
}
 
Example #30
Source File: MuleLanguageInjector.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
                                 @NotNull InjectedLanguagePlaces injectedLanguagePlaces) {
    if (MuleConfigUtils.isMuleFile(host.getContainingFile())) {
        if (host instanceof XmlAttributeValue) {
            // Try to inject a language, somewhat abusing the lazy evaluation of predicates :(
            for (Pair<String, String> language : languages) {
                if (tryInjectLanguage(language.getFirst(), language.getSecond(), host, injectedLanguagePlaces)) {
                    break;
                }
            }
        } else if (host instanceof XmlText) {
            final XmlTag tag = ((XmlText) host).getParentTag();
            if (tag != null) {
                final QName tagName = MuleConfigUtils.getQName(tag);
                if (tagName.equals(globalFunctions) || tagName.equals(expressionComponent) || tagName.equals(expressionTransformer)) {
                    final String scriptingName = MelLanguage.MEL_LANGUAGE_ID;
                    injectLanguage(host, injectedLanguagePlaces, scriptingName);
                } else if (tagName.equals(scriptingScript)) {
                    final String engine = tag.getAttributeValue("engine");
                    if (engine != null) {
                        injectLanguage(host, injectedLanguagePlaces, StringUtil.capitalize(engine));
                    }
                } else if (tagName.equals(dwSetPayload) || tagName.equals(dwSetProperty) || tagName.equals(dwSetVariable) || tagName.equals(dwSetSessionVar)) {
                    injectLanguage(host, injectedLanguagePlaces, WEAVE_LANGUAGE_ID);
                }
            }
        }
    }
}