com.intellij.openapi.util.Ref Java Examples

The following examples show how to use com.intellij.openapi.util.Ref. 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: CoreCommandProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public CommandToken startCommand(@Nullable final Project project, @Nls final String name, @Nullable final Object groupId, @Nonnull final UndoConfirmationPolicy undoConfirmationPolicy) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (project != null && project.isDisposed()) return null;

  if (CommandLog.LOG.isDebugEnabled()) {
    CommandLog.LOG.debug("startCommand: name = " + name + ", groupId = " + groupId);
  }

  if (myCurrentCommand != null) {
    return null;
  }

  Document document = groupId instanceof Document ? (Document)groupId : (groupId instanceof Ref && ((Ref)groupId).get() instanceof Document ? (Document)((Ref)groupId).get() : null);
  myCurrentCommand = new CommandDescriptor(EmptyRunnable.INSTANCE, project, name, groupId, undoConfirmationPolicy, true, document);
  fireCommandStarted();
  return myCurrentCommand;
}
 
Example #2
Source File: FlutterTestConfigProducer.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * If the current file looks like a Flutter test, initializes the run config to run it.
 * <p>
 * Returns true if successfully set up.
 */
@Override
protected boolean setupConfigurationFromContext(TestConfig config, ConfigurationContext context, Ref<PsiElement> sourceElement) {
  if (!isFlutterContext(context)) return false;

  final PsiElement elt = context.getPsiLocation();
  if (elt instanceof PsiDirectory) {
    return setupForDirectory(config, (PsiDirectory)elt);
  }

  final DartFile file = FlutterRunConfigurationProducer.getDartFile(context);
  if (file == null) {
    return false;
  }

  if (supportsFiltering(config.getSdk())) {
    final String testName = testConfigUtils.findTestName(elt);
    if (testName != null) {
      return setupForSingleTest(config, context, file, testName);
    }
  }

  return setupForDartFile(config, context, file);
}
 
Example #3
Source File: EnterHandler.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
@Override
public Result preprocessEnter(
    @NotNull PsiFile psiFile,
    @NotNull Editor editor,
    @NotNull Ref<Integer> caretOffset,
    @NotNull Ref<Integer> caretOffsetChange,
    @NotNull DataContext dataContext,
    @Nullable EditorActionHandler originalHandler) {
  if (psiFile instanceof SoyFile && isBetweenSiblingTags(psiFile, caretOffset.get())) {
    if (originalHandler != null) {
      originalHandler.execute(editor, dataContext);
    }
    return Result.Default;
  }
  return Result.Continue;
}
 
Example #4
Source File: ChangeRange.java    From consulo with Apache License 2.0 6 votes vote down vote up
public ChangeRange revert(ChangeRange reverse) throws IOException {
  final Ref<Long> first = new Ref<Long>();
  final Ref<Long> last = new Ref<Long>();
  LocalHistoryFacade.Listener l = new LocalHistoryFacade.Listener() {
    public void changeAdded(Change c) {
      if (first.isNull()) first.set(c.getId());
      last.set(c.getId());
    }
  };
  myVcs.addListener(l, null);
  try {
    myVcs.accept(new UndoChangeRevertingVisitor(myGateway, myToChangeId, myFromChangeId));
  }
  catch (UndoChangeRevertingVisitor.RuntimeIOException e) {
    throw (IOException)e.getCause();
  }
  finally {
    myVcs.removeListener(l);
  }

  if (reverse != null) {
    if (first.isNull()) first.set(reverse.myFromChangeId);
    if (last.isNull()) last.set(reverse.myToChangeId);
  }
  return new ChangeRange(myGateway, myVcs, first.get(), last.get());
}
 
Example #5
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Script getScriptSync(@NotNull final ScriptRef scriptRef) {
  final Ref<Script> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getObject(isolateRef.getId(), scriptRef.getId(), new GetObjectConsumer() {
    @Override
    public void received(Obj script) {
      resultRef.set((Script)script);
      semaphore.up();
    }

    @Override
    public void received(Sentinel response) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });

  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #6
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private Library getLibrary(LibraryRef libraryRef) {
  // TODO(devoncarew): Consider changing the signature to `CompletableFuture getLibrary(LibraryRef instance)`
  // (see also the EvalOnDartLibrary implementation).

  final Ref<Library> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getLibrary(isolateRef.getId(), libraryRef.getId(), new GetLibraryConsumer() {
    @Override
    public void received(Library library) {
      resultRef.set(library);
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });
  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #7
Source File: TroveUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void processBatches(@Nonnull IntStream stream, int batchSize, @Nonnull Consumer<TIntHashSet> consumer) {
  Ref<TIntHashSet> batch = new Ref<>(new TIntHashSet());
  stream.forEach(commit -> {
    batch.get().add(commit);
    if (batch.get().size() >= batchSize) {
      try {
        consumer.consume(batch.get());
      }
      finally {
        batch.set(new TIntHashSet());
      }
    }
  });

  if (!batch.get().isEmpty()) {
    consumer.consume(batch.get());
  }
}
 
Example #8
Source File: ModuleTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
protected Module loadAllModulesUnder(@Nonnull VirtualFile rootDir, @javax.annotation.Nullable final Consumer<Module> moduleConsumer) {
  final Ref<Module> result = Ref.create();

 /* VfsUtilCore.visitChildrenRecursively(rootDir, new VirtualFileVisitor() {
    @Override
    public boolean visitFile(@NotNull VirtualFile file) {
      if (!file.isDirectory() && file.getName().endsWith(ModuleFileType.DOT_DEFAULT_EXTENSION)) {
        ModuleImpl module = (ModuleImpl)loadModule(file);
        if (moduleConsumer != null) {
          moduleConsumer.consume(module);
        }
        result.setIfNull(module);
      }
      return true;
    }
  });*/

  return result.get();
}
 
Example #9
Source File: HintUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void configureLabel(@Nonnull HintLabel label,
                                   @Nullable HyperlinkListener hyperlinkListener,
                                   @Nullable MouseListener mouseListener,
                                   @Nullable Ref<? super Consumer<? super String>> updatedTextConsumer) {
  if (hyperlinkListener != null) {
    label.myPane.addHyperlinkListener(hyperlinkListener);
  }
  if (mouseListener != null) {
    label.myPane.addMouseListener(mouseListener);
  }
  if (updatedTextConsumer != null) {
    Consumer<? super String> consumer = s -> {
      label.myPane.setText(s);

      // Force preferred size recalculation.
      label.setPreferredSize(null);
      label.myPane.setPreferredSize(null);
    };
    updatedTextConsumer.set(consumer);
  }
}
 
Example #10
Source File: GraphQLInjectionIndex.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
public GraphQLInjectionIndex() {
    myDataIndexer = inputData -> {
        final Ref<String> environment = new Ref<>();
        inputData.getPsiFile().accept(new PsiRecursiveElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                if (!GraphQLLanguageInjectionUtil.isJSGraphQLLanguageInjectionTarget(element, environment)) {
                    // visit deeper until injection found
                    super.visitElement(element);
                }
            }
        });
        return environment.isNull() ? Collections.emptyMap() : INJECTED_KEY;
    };
    includedFileTypes = GraphQLFindUsagesUtil.getService().getIncludedFileTypes();
}
 
Example #11
Source File: BazelTestConfigProducerTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Ignore("https://github.com/flutter/flutter-intellij/issues/3583")
public void producesFileConfigurationInsideABazelWorkspace() throws Exception {
  run(() -> {
    // Set up the configuration producer.
    final ConfigurationContext context = getMainContext();
    final BazelTestConfig config = getEmptyBazelTestConfig();
    final BazelTestConfigProducer testConfigProducer = new TestBazelConfigProducer(true, true, bazelTestConfigUtils);

    // Produce and check a run configuration.
    final boolean result = testConfigProducer.setupConfigurationFromContext(config, context, new Ref<>());
    assertThat(result, equalTo(true));
    assertThat(config.getFields().getTestName(), equalTo(null));
    assertThat(config.getFields().getEntryFile(), equalTo("/workspace/foo/bar.dart"));
    assertThat(config.getFields().getBazelTarget(), equalTo(null));
  });
}
 
Example #12
Source File: BashUnmatchedBraceEnterProcessor.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@Override
public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, @Nullable EditorActionHandler originalHandler) {
    Project project = editor.getProject();

    if (CodeInsightSettings.getInstance().INSERT_BRACE_ON_ENTER && file instanceof BashFile && project != null) {
        Document document = editor.getDocument();
        CharSequence chars = document.getCharsSequence();

        int offset = caretOffset.get();
        int length = chars.length();

        if (offset < length && offset >= 1 && chars.charAt(offset - 1) == '{') {
            int start = offset + 1;
            int end = offset + 1 + "function".length();

            if (start < length && end < length && "function".contentEquals(chars.subSequence(start, end))) {
                document.insertString(start, "\n");
                PsiDocumentManager.getInstance(project).commitDocument(document);
            }
        }
    }

    return Result.Continue;
}
 
Example #13
Source File: BazelTestConfigProducerTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Ignore("https://github.com/flutter/flutter-intellij/issues/3583")
public void producesNoConfigurationWithAnInvalidTestFile() throws Exception {
  run(() -> {
    // Set up the configuration producer.
    final ConfigurationContext context = getTest1Context();
    final BazelTestConfig config = getEmptyBazelTestConfig();
    final BazelTestConfigProducer testConfigProducer = new TestBazelConfigProducer(true, false, bazelTestConfigUtils);

    // Produce and check a run configuration.
    final boolean result = testConfigProducer.setupConfigurationFromContext(config, context, new Ref<>());
    assertThat(result, equalTo(false));
    assertThat(config.getFields().getTestName(), equalTo(null));
    assertThat(config.getFields().getEntryFile(), equalTo(null));
    assertThat(config.getFields().getBazelTarget(), equalTo(null));
  });
}
 
Example #14
Source File: VcsUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean runVcsProcessWithProgress(final VcsRunnable runnable, String progressTitle, boolean canBeCanceled, Project project)
        throws VcsException {
  final Ref<VcsException> ex = new Ref<>();
  boolean result = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
    @Override
    public void run() {
      try {
        runnable.run();
      }
      catch (VcsException e) {
        ex.set(e);
      }
    }
  }, progressTitle, canBeCanceled, project);
  if (!ex.isNull()) {
    throw ex.get();
  }
  return result;
}
 
Example #15
Source File: PhpInjectFileReferenceIndex.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
public static PhpInjectFileReference getInjectFileReference(@NotNull Project project, @NotNull Function function, int argumentIndex) {
    FileBasedIndex index = FileBasedIndex.getInstance();
    GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    Ref<List<PhpInjectFileReference>> result = new Ref<>(ContainerUtil.emptyList());
    result.set(index.getValues(KEY, function.getFQN() + ":" + argumentIndex, scope));

    if (result.get().isEmpty() && function instanceof PhpClassMember) {
        PhpClassHierarchyUtils.processSuperMembers((PhpClassMember)function, (classMember, subClass, baseClass) -> {
            List<PhpInjectFileReference> values = index.getValues(KEY, classMember.getFQN() + ":" + argumentIndex, scope);
            if (values.isEmpty()) {
                return true;
            } else {
                result.set(values);
                return false;
            }
        });
    }

    if (result.get().isEmpty()) {
        return null;
    }
    return result.get().get(0);
}
 
Example #16
Source File: GraphQLLanguageInjectionUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
public static String getEnvironment(PsiFile file) {
    if (file instanceof JSFile) {
        // for JS Files we have to check the kind of environment being used
        final Ref<String> envRef = new Ref<>();
        file.accept(new PsiRecursiveElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                if (!isJSGraphQLLanguageInjectionTarget(element, envRef)) {
                    // no match yet, so keep visiting
                    super.visitElement(element);
                }
            }
        });
        final String environment = envRef.get();
        if (environment != null) {
            return environment;
        }
    } else if (file instanceof GraphQLFile) {
        final Ref<String> tag = new Ref<>();
        if (file.getContext() != null && isJSGraphQLLanguageInjectionTarget(file.getContext(), tag)) {
            return tag.get();
        }
    }
    // fallback is traditional GraphQL
    return GRAPHQL_ENVIRONMENT;
}
 
Example #17
Source File: ResourceCompilerConfiguration.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean isResourceFile(String name, @Nullable VirtualFile parent) {
  final Ref<String> parentRef = Ref.create(null);
  //noinspection ForLoopReplaceableByForEach
  for (int i = 0; i < myCompiledPatterns.size(); i++) {
    if (matches(name, parent, parentRef, myCompiledPatterns.get(i))) {
      return true;
    }
  }

  if (myNegatedCompiledPatterns.isEmpty()) {
    return false;
  }

  //noinspection ForLoopReplaceableByForEach
  for (int i = 0; i < myNegatedCompiledPatterns.size(); i++) {
    if (matches(name, parent, parentRef, myNegatedCompiledPatterns.get(i))) {
      return false;
    }
  }
  return true;
}
 
Example #18
Source File: MoveDirectoryWithClassesProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
  final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
  for (PsiFile psiFile : myFilesToMove.keySet()) {
    try {
      myFilesToMove.get(psiFile).checkMove(psiFile);
    }
    catch (IncorrectOperationException e) {
      conflicts.putValue(psiFile, e.getMessage());
    }
  }
  for (MoveDirectoryWithClassesHelper helper : MoveDirectoryWithClassesHelper.findAll()) {
    helper.preprocessUsages(myProject, myFilesToMove.keySet(), refUsages.get(), myTargetDirectory, conflicts);
  }
  return showConflicts(conflicts, refUsages.get());
}
 
Example #19
Source File: BazelTestConfigProducer.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * If the current file looks like a Flutter test, initializes the run config to run it.
 * <p>
 * Returns true if successfully set up.
 */
@Override
protected boolean setupConfigurationFromContext(@NotNull BazelTestConfig config,
                                                @NotNull ConfigurationContext context,
                                                @NotNull Ref<PsiElement> sourceElement) {
  if (!isBazelFlutterContext(context)) return false;

  final PsiElement elt = context.getPsiLocation();

  final DartFile file = FlutterUtils.getDartFile(elt);
  if (file == null) {
    return false;
  }

  final String testName = bazelTestConfigUtils.findTestName(elt);
  if (testName != null) {
    return setupForSingleTest(config, context, file, testName);
  }

  return setupForDartFile(config, context, file);
}
 
Example #20
Source File: FlutterTestConfigProducer.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * If the current file looks like a Flutter test, initializes the run config to run it.
 * <p>
 * Returns true if successfully set up.
 */
@Override
protected boolean setupConfigurationFromContext(TestConfig config, ConfigurationContext context, Ref<PsiElement> sourceElement) {
  if (!isFlutterContext(context)) return false;

  final PsiElement elt = context.getPsiLocation();
  if (elt instanceof PsiDirectory) {
    return setupForDirectory(config, (PsiDirectory)elt);
  }

  final DartFile file = FlutterRunConfigurationProducer.getDartFile(context);
  if (file == null) {
    return false;
  }

  if (supportsFiltering(config.getSdk())) {
    final String testName = testConfigUtils.findTestName(elt);
    if (testName != null) {
      return setupForSingleTest(config, context, file, testName);
    }
  }

  return setupForDartFile(config, context, file);
}
 
Example #21
Source File: PantsPythonTestRunConfigurationProducer.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private boolean buildFromPyTest(
  PsiElement testElem,
  String elemStr,
  String path,
  List<String> targets,
  ExternalSystemTaskExecutionSettings taskSettings,
  Ref<PsiElement> sourceElement,
  ExternalSystemRunConfiguration configuration
) {
  sourceElement.set(testElem);
  configuration.setName("Pants tests in " + elemStr);
  taskSettings.setExternalProjectPath(path);
  String scriptParams = StringUtil.join(targets, " ");
  scriptParams += " " + PantsConstants.PANTS_CLI_OPTION_PYTEST + "=\"-k " + elemStr + "\"";
  final Optional<String> rcIterate = IJRC.getIteratePantsRc(path);
  scriptParams += rcIterate.orElse("");

  taskSettings.setExecutionName(elemStr);
  taskSettings.setScriptParameters(scriptParams);
  return true;
}
 
Example #22
Source File: AbstractVcsTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Creates directory inside a write action and returns the resulting reference to it.
 * If the directory already exists, does nothing.
 * @param parent Parent directory.
 * @param name   Name of the directory.
 * @return reference to the created or already existing directory.
 */
public VirtualFile createDirInCommand(final VirtualFile parent, final String name) {
  final Ref<VirtualFile> result = new Ref<VirtualFile>();
  new WriteCommandAction.Simple(myProject) {
    @Override
    protected void run() throws Throwable {
      try {
        VirtualFile dir = parent.findChild(name);
        if (dir == null) {
          dir = parent.createChildDirectory(this, name);
        }
        result.set(dir);
      }
      catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }.execute();
  return result.get();
}
 
Example #23
Source File: BazelTestConfigProducerTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Ignore("https://github.com/flutter/flutter-intellij/issues/3583")
public void producesTestNameConfigurationInsideABazelWorkspace() throws Exception {
  run(() -> {
    // Set up the configuration producer.
    final ConfigurationContext context = getTest1Context();
    final BazelTestConfig config = getEmptyBazelTestConfig();
    final BazelTestConfigProducer testConfigProducer = new TestBazelConfigProducer(true, true, bazelTestConfigUtils);

    // Produce and check a run configuration.
    final boolean result = testConfigProducer.setupConfigurationFromContext(config, context, new Ref<>());
    assertThat(result, equalTo(true));
    assertThat(config.getFields().getTestName(), equalTo("test 1"));
    assertThat(config.getFields().getEntryFile(), equalTo("/workspace/foo/bar.dart"));
    assertThat(config.getFields().getBazelTarget(), equalTo(null));
  });
}
 
Example #24
Source File: BazelTestConfigProducerTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Ignore("https://github.com/flutter/flutter-intellij/issues/3583")
public void producesNoConfigurationWithAnInvalidTestFile() throws Exception {
  run(() -> {
    // Set up the configuration producer.
    final ConfigurationContext context = getTest1Context();
    final BazelTestConfig config = getEmptyBazelTestConfig();
    final BazelTestConfigProducer testConfigProducer = new TestBazelConfigProducer(true, false, bazelTestConfigUtils);

    // Produce and check a run configuration.
    final boolean result = testConfigProducer.setupConfigurationFromContext(config, context, new Ref<>());
    assertThat(result, equalTo(false));
    assertThat(config.getFields().getTestName(), equalTo(null));
    assertThat(config.getFields().getEntryFile(), equalTo(null));
    assertThat(config.getFields().getBazelTarget(), equalTo(null));
  });
}
 
Example #25
Source File: SpecsExecutionProducer.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean setupConfigurationFromContext(RunConfiguration configuration, ConfigurationContext configurationContext, Ref ref) {
    VirtualFile[] selectedFiles = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(configurationContext.getDataContext());
    Module module = configurationContext.getModule();
    if (selectedFiles == null || module == null)
        return false;
    if (selectedFiles.length == 1) {
        if (!selectedFiles[0].isDirectory()) {
            return false;
        } else if (selectedFiles[0].getPath().equals(configurationContext.getProject().getBasePath())) {
            configuration.setName(DEFAULT_CONFIGURATION_NAME);
            ((GaugeRunConfiguration) configuration).setModule(module);
            return true;
        }
    }

    List<String> specsToExecute = getSpecs(selectedFiles);
    if (specsToExecute.size() == 0) {
        return false;
    }
    configuration.setName(DEFAULT_CONFIGURATION_NAME);
    ((GaugeRunConfiguration) configuration).setModule(module);
    ((GaugeRunConfiguration) configuration).setSpecsArrayToExecute(specsToExecute);
    return true;
}
 
Example #26
Source File: RecentLocationsAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void initSearchActions(@Nonnull Project project,
                                      @Nonnull RecentLocationsDataModel data,
                                      @Nonnull ListWithFilter<RecentLocationItem> listWithFilter,
                                      @Nonnull JBList<RecentLocationItem> list,
                                      @Nonnull JBCheckBox checkBox,
                                      @Nonnull JBPopup popup,
                                      @Nonnull Ref<? super Boolean> navigationRef) {
  listWithFilter.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent event) {
      int clickCount = event.getClickCount();
      if (clickCount > 1 && clickCount % 2 == 0) {
        event.consume();
        navigateToSelected(project, list, popup, navigationRef);
      }
    }
  });

  DumbAwareAction.create(e -> navigateToSelected(project, list, popup, navigationRef)).registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), listWithFilter, popup);

  DumbAwareAction.create(e -> removePlaces(project, listWithFilter, list, data, checkBox.isSelected()))
          .registerCustomShortcutSet(CustomShortcutSet.fromString("DELETE", "BACK_SPACE"), listWithFilter, popup);
}
 
Example #27
Source File: DustEnterHandler.java    From Intellij-Dust with MIT License 6 votes vote down vote up
public Result preprocessEnter(@NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Ref<Integer> caretOffset, @NotNull final Ref<Integer> caretAdvance,
                              @NotNull final DataContext dataContext, final EditorActionHandler originalHandler) {
  /**
   * if we are between open and close tags, we ensure the caret ends up in the "logical" place on Enter.
   * i.e. "{#foo}<caret>{/foo}" becomes the following on Enter:
   *
   * {#foo}
   * <caret>
   * {/foo}
   *
   * (Note: <caret> may be indented depending on formatter settings.)
   */
  if (file instanceof DustFile
      && isBetweenHbTags(editor, file, caretOffset.get())) {
    originalHandler.execute(editor, dataContext);
    return Result.Default;
  }
  return Result.Continue;
}
 
Example #28
Source File: LegacyCompletionContributor.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean completeReference(final CompletionParameters parameters, final CompletionResultSet result) {
  final CompletionData completionData = getCompletionData(parameters);
  if (completionData == null) {
    return false;
  }

  final Ref<Boolean> hasVariants = Ref.create(false);
  processReferences(parameters, result, (reference, resultSet) -> {
    final Set<LookupElement> lookupSet = new LinkedHashSet<>();
    completionData.completeReference(reference, lookupSet, parameters.getPosition(), parameters.getOriginalFile());
    for (final LookupElement item : lookupSet) {
      if (resultSet.getPrefixMatcher().prefixMatches(item)) {
        if (!item.isValid()) {
          LOG.error(completionData + " has returned an invalid lookup element " + item + " of " + item.getClass() +
                    " in " + parameters.getOriginalFile() + " of " + parameters.getOriginalFile().getClass() +
                    "; reference=" + reference + " of " + reference.getClass());
        }
        hasVariants.set(true);
        resultSet.addElement(item);
      }
    }
  });
  return hasVariants.get().booleanValue();
}
 
Example #29
Source File: ShowImplementationsAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateInBackground(Editor editor,
                                @Nullable PsiElement element,
                                @Nonnull ImplementationViewComponent component,
                                String title,
                                @Nonnull AbstractPopup popup,
                                @Nonnull Ref<UsageView> usageView) {
  final ImplementationsUpdaterTask updaterTask = SoftReference.dereference(myTaskRef);
  if (updaterTask != null) {
    updaterTask.cancelTask();
  }

  if (element == null) return; //already found
  final ImplementationsUpdaterTask task = new ImplementationsUpdaterTask(element, editor, title, isIncludeAlwaysSelf(), component);
  task.init(popup, new ImplementationViewComponentUpdater(component, isIncludeAlwaysSelf() ? 1 : 0), usageView);

  myTaskRef = new WeakReference<>(task);
  ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, new BackgroundableProcessIndicator(task));
}
 
Example #30
Source File: ChangesTreeList.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int findRowContainingFile(@Nonnull TreeNode root, @Nonnull final VirtualFile toSelect) {
  final Ref<Integer> row = Ref.create(-1);
  TreeUtil.traverse(root, node -> {
    if (node instanceof DefaultMutableTreeNode) {
      Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
      if (userObject instanceof Change) {
        if (matches((Change)userObject, toSelect)) {
          TreeNode[] path = ((DefaultMutableTreeNode)node).getPath();
          row.set(getRowForPath(new TreePath(path)));
        }
      }
    }

    return row.get() == -1;
  });
  return row.get();
}