Java Code Examples for com.intellij.codeInsight.completion.impl.CompletionServiceImpl#setCompletionPhase()

The following examples show how to use com.intellij.codeInsight.completion.impl.CompletionServiceImpl#setCompletionPhase() . 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: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void scheduleContributorsAfterAsyncCommit(CompletionInitializationContextImpl initContext, CompletionProgressIndicator indicator, OffsetsInFile hostCopyOffsets, boolean hasModifiers) {
  CompletionPhase phase;
  if (synchronous) {
    phase = new CompletionPhase.BgCalculation(indicator);
    indicator.makeSureLookupIsShown(0);
  }
  else {
    phase = new CompletionPhase.CommittingDocuments(indicator, InjectedLanguageUtil.getTopLevelEditor(indicator.getEditor()));
  }
  CompletionServiceImpl.setCompletionPhase(phase);

  AppUIExecutor.onUiThread().withDocumentsCommitted(initContext.getProject()).expireWith(phase).execute(() -> {
    if (phase instanceof CompletionPhase.CommittingDocuments) {
      ((CompletionPhase.CommittingDocuments)phase).replaced = true;
    }
    CompletionServiceImpl.setCompletionPhase(new CompletionPhase.BgCalculation(indicator));
    startContributorThread(initContext, indicator, hostCopyOffsets, hasModifiers);
  });
}
 
Example 2
Source File: CompletionProgressIndicator.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void finishCompletionProcess(boolean disposeOffsetMap) {
  cancel();

  ApplicationManager.getApplication().assertIsDispatchThread();
  Disposer.dispose(myQueue);
  LookupManager.getInstance(getProject()).removePropertyChangeListener(myLookupManagerListener);

  CompletionServiceImpl.assertPhase(CompletionPhase.BgCalculation.class, CompletionPhase.ItemsCalculated.class, CompletionPhase.Synchronous.class, CompletionPhase.CommittingDocuments.class);

  CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCurrentCompletionProgressIndicator();
  LOG.assertTrue(currentCompletion == this, currentCompletion + "!=" + this);

  CompletionPhase oldPhase = CompletionServiceImpl.getCompletionPhase();
  if (oldPhase instanceof CompletionPhase.CommittingDocuments) {
    LOG.assertTrue(((CompletionPhase.CommittingDocuments)oldPhase).indicator != null, oldPhase);
    ((CompletionPhase.CommittingDocuments)oldPhase).replaced = true;
  }
  CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
  if (disposeOffsetMap) {
    disposeIndicator();
  }
}
 
Example 3
Source File: CompletionProgressIndicator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@TestOnly
public static void cleanupForNextTest() {
  CompletionService completionService = ServiceManager.getService(CompletionService.class);
  if (!(completionService instanceof CompletionServiceImpl)) {
    return;
  }

  CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCurrentCompletionProgressIndicator();
  if (currentCompletion != null) {
    currentCompletion.finishCompletionProcess(true);
    CompletionServiceImpl.assertPhase(CompletionPhase.NoCompletion.getClass());
  }
  else {
    CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
  }
  StatisticsUpdate.cancelLastCompletionStatisticsUpdate();
}
 
Example 4
Source File: CompletionProgressIndicator.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean hideAutopopupIfMeaningless() {
  if (!myLookup.isLookupDisposed() && isAutopopupCompletion() && !myLookup.isSelectionTouched() && !myLookup.isCalculating()) {
    myLookup.refreshUi(true, false);
    final List<LookupElement> items = myLookup.getItems();

    for (LookupElement item : items) {
      if (!isAlreadyInTheEditor(item)) {
        return false;
      }

      if (item.isValid() && item.isWorthShowingInAutoPopup()) {
        return false;
      }
    }

    myLookup.hideLookup(false);
    LOG.assertTrue(CompletionServiceImpl.getCompletionService().getCurrentCompletion() == null);
    CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
    return true;
  }
  return false;
}
 
Example 5
Source File: CompletionProgressIndicator.java    From consulo with Apache License 2.0 6 votes vote down vote up
void handleEmptyLookup(boolean awaitSecondInvocation) {
  if (isAutopopupCompletion() && ApplicationManager.getApplication().isUnitTestMode()) {
    return;
  }

  LOG.assertTrue(!isAutopopupCompletion());

  CompletionParameters parameters = getParameters();
  if (myHandler.invokedExplicitly && parameters != null) {
    LightweightHint hint = showErrorHint(getProject(), getEditor(), getNoSuggestionsMessage(parameters));
    if (awaitSecondInvocation) {
      CompletionServiceImpl.setCompletionPhase(new CompletionPhase.NoSuggestionsHint(hint, this));
      return;
    }
  }
  CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
}
 
Example 6
Source File: CompletionPhase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int newCompletionStarted(int time, boolean repeated) {
  CompletionServiceImpl.setCompletionPhase(NoCompletion);
  if (repeated) {
    indicator.restorePrefix(restorePrefix);
  }
  return indicator.nextInvocationCount(time, repeated);
}
 
Example 7
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void trySynchronousCompletion(CompletionInitializationContextImpl initContext,
                                      boolean hasModifiers,
                                      long startingTime,
                                      CompletionProgressIndicator indicator,
                                      OffsetsInFile hostCopyOffsets) {
  CompletionServiceImpl.setCompletionPhase(new CompletionPhase.Synchronous(indicator));

  Future<?> future = startContributorThread(initContext, indicator, hostCopyOffsets, hasModifiers);
  if (future == null) {
    return;
  }

  int timeout = calcSyncTimeOut(startingTime);
  indicator.makeSureLookupIsShown(timeout);
  if (indicator.blockingWaitForFinish(timeout)) {
    checkForExceptions(future);
    try {
      indicator.getLookup().refreshUi(true, false);
      completionFinished(indicator, hasModifiers);
    }
    catch (Throwable e) {
      indicator.closeAndFinish(true);
      CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
      LOG.error(e);
    }
    return;
  }

  CompletionServiceImpl.setCompletionPhase(new CompletionPhase.BgCalculation(indicator));
  indicator.showLookup();
}
 
Example 8
Source File: CompletionProgressIndicator.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void processModifier(KeyEvent e) {
  final int code = e.getKeyCode();
  if (code == KeyEvent.VK_CONTROL || code == KeyEvent.VK_META || code == KeyEvent.VK_ALT || code == KeyEvent.VK_SHIFT) {
    myContentComponent.removeKeyListener(this);
    final CompletionPhase phase = CompletionServiceImpl.getCompletionPhase();
    if (phase instanceof CompletionPhase.BgCalculation) {
      ((CompletionPhase.BgCalculation)phase).modifiersChanged = true;
    }
    else if (phase instanceof CompletionPhase.InsertedSingleItem) {
      CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
    }
  }
}
 
Example 9
Source File: CompletionPhase.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void scheduleAsyncCompletion(@Nonnull Editor _editor,
                                           @Nonnull CompletionType completionType,
                                           @Nullable Condition<? super PsiFile> condition,
                                           @Nonnull Project project,
                                           @Nullable CompletionProgressIndicator prevIndicator) {
  Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(_editor);
  int offset = topLevelEditor.getCaretModel().getOffset();

  CommittingDocuments phase = new CommittingDocuments(prevIndicator, topLevelEditor);
  CompletionServiceImpl.setCompletionPhase(phase);
  phase.ignoreCurrentDocumentChange();

  boolean autopopup = prevIndicator == null || prevIndicator.isAutopopupCompletion();

  ReadAction.nonBlocking(() -> {
    // retrieve the injected file from scratch since our typing might have destroyed the old one completely
    PsiFile topLevelFile = PsiDocumentManager.getInstance(project).getPsiFile(topLevelEditor.getDocument());
    Editor completionEditor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(topLevelEditor, topLevelFile, offset);
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(completionEditor.getDocument());
    if (file == null || autopopup && shouldSkipAutoPopup(completionEditor, file) || condition != null && !condition.value(file)) {
      return null;
    }

    loadContributorsOutsideEdt(completionEditor, file);

    return completionEditor;
  }).withDocumentsCommitted(project).expireWith(phase).expireWhen(() -> phase.isExpired()).finishOnUiThread(ModalityState.current(), completionEditor -> {
    if (completionEditor != null) {
      int time = prevIndicator == null ? 0 : prevIndicator.getInvocationCount();
      CodeCompletionHandlerBase handler = CodeCompletionHandlerBase.createHandler(completionType, false, autopopup, false);
      handler.invokeCompletion(project, completionEditor, time, false);
    }
    else if (phase == CompletionServiceImpl.getCompletionPhase()) {
      CompletionServiceImpl.setCompletionPhase(NoCompletion);
    }
  }).submit(ourExecutor).onError(__ -> AppUIUtil.invokeOnEdt(() -> {
    if (phase == CompletionServiceImpl.getCompletionPhase()) {
      CompletionServiceImpl.setCompletionPhase(NoCompletion);
    }
  }));
}
 
Example 10
Source File: CompletionPhase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public int newCompletionStarted(int time, boolean repeated) {
  CompletionServiceImpl.assertPhase(NoCompletion.getClass()); // will fail and log valuable info
  CompletionServiceImpl.setCompletionPhase(NoCompletion);
  return time;
}
 
Example 11
Source File: CompletionPhase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public int newCompletionStarted(int time, boolean repeated) {
  CompletionServiceImpl.setCompletionPhase(NoCompletion);
  return indicator.nextInvocationCount(time, repeated);
}
 
Example 12
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void invokeCompletion(@Nonnull Project project, @Nonnull Editor editor, int time, boolean hasModifiers, @Nonnull Caret caret) {
  markCaretAsProcessed(caret);

  if (invokedExplicitly) {
    StatisticsUpdate.applyLastCompletionStatisticsUpdate();
  }

  checkNoWriteAccess();

  CompletionAssertions.checkEditorValid(editor);

  int offset = editor.getCaretModel().getOffset();
  if (editor.isViewer() || editor.getDocument().getRangeGuard(offset, offset) != null) {
    editor.getDocument().fireReadOnlyModificationAttempt();
    EditorModificationUtil.checkModificationAllowed(editor);
    return;
  }

  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }

  CompletionPhase phase = CompletionServiceImpl.getCompletionPhase();
  boolean repeated = phase.indicator != null && phase.indicator.isRepeatedInvocation(completionType, editor);

  final int newTime = phase.newCompletionStarted(time, repeated);
  if (invokedExplicitly) {
    time = newTime;
  }
  final int invocationCount = time;
  if (CompletionServiceImpl.isPhase(CompletionPhase.InsertedSingleItem.class)) {
    CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
  }
  CompletionServiceImpl.assertPhase(CompletionPhase.NoCompletion.getClass(), CompletionPhase.CommittingDocuments.class);

  if (invocationCount > 1 && completionType == CompletionType.BASIC) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.SECOND_BASIC_COMPLETION);
  }

  long startingTime = System.currentTimeMillis();

  Runnable initCmd = () -> {
    CompletionInitializationContextImpl context =
            withTimeout(calcSyncTimeOut(startingTime), () -> CompletionInitializationUtil.createCompletionInitializationContext(project, editor, caret, invocationCount, completionType));

    boolean hasValidContext = context != null;
    if (!hasValidContext) {
      final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project);
      context = new CompletionInitializationContextImpl(editor, caret, psiFile, completionType, invocationCount);
    }

    doComplete(context, hasModifiers, hasValidContext, startingTime);
  };
  try {
    if (autopopup) {
      CommandProcessor.getInstance().runUndoTransparentAction(initCmd);
    }
    else {
      CommandProcessor.getInstance().executeCommand(project, initCmd, null, null, editor.getDocument());
    }
  }
  catch (IndexNotReadyException e) {
    if (invokedExplicitly) {
      DumbService.getInstance(project).showDumbModeNotification("Code completion is not available here while indices are being built");
    }
  }
}
 
Example 13
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void checkNotSync(CompletionProgressIndicator indicator, List<LookupElement> allItems) {
  if (CompletionServiceImpl.isPhase(CompletionPhase.Synchronous.class)) {
    LOG.error("sync phase survived: " + allItems + "; indicator=" + CompletionServiceImpl.getCompletionPhase().indicator + "; myIndicator=" + indicator);
    CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
  }
}
 
Example 14
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected void completionFinished(final CompletionProgressIndicator indicator, boolean hasModifiers) {
  List<LookupElement> items = indicator.getLookup().getItems();
  if (items.isEmpty()) {
    LookupManager.hideActiveLookup(indicator.getProject());

    Caret nextCaret = getNextCaretToProcess(indicator.getEditor());
    if (nextCaret != null) {
      invokeCompletion(indicator.getProject(), indicator.getEditor(), indicator.getInvocationCount(), hasModifiers, nextCaret);
    }
    else {
      indicator.handleEmptyLookup(true);
      checkNotSync(indicator, items);
    }
    return;
  }

  LOG.assertTrue(!indicator.isRunning(), "running");
  LOG.assertTrue(!indicator.isCanceled(), "canceled");

  try {
    CompletionParameters parameters = indicator.getParameters();
    AutoCompletionDecision decision = parameters == null ? AutoCompletionDecision.CLOSE_LOOKUP : shouldAutoComplete(indicator, items, parameters);
    if (decision == AutoCompletionDecision.SHOW_LOOKUP) {
      indicator.getLookup().setCalculating(false);
      indicator.showLookup();
      CompletionServiceImpl.setCompletionPhase(new CompletionPhase.ItemsCalculated(indicator));
    }
    else if (decision instanceof AutoCompletionDecision.InsertItem) {
      final Runnable restorePrefix = rememberDocumentState(indicator.getEditor());

      final LookupElement item = ((AutoCompletionDecision.InsertItem)decision).getElement();
      CommandProcessor.getInstance().executeCommand(indicator.getProject(), () -> {
        indicator.setMergeCommand();
        indicator.getLookup().finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR, item);
      }, "Autocompletion", null);

      // the insert handler may have started a live template with completion
      if (CompletionService.getCompletionService().getCurrentCompletion() == null &&
          // ...or scheduled another autopopup
          !CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class)) {
        CompletionServiceImpl.setCompletionPhase(hasModifiers ? new CompletionPhase.InsertedSingleItem(indicator, restorePrefix) : CompletionPhase.NoCompletion);
      }
    }
    else if (decision == AutoCompletionDecision.CLOSE_LOOKUP) {
      LookupManager.hideActiveLookup(indicator.getProject());
    }
  }
  catch (Throwable e) {
    CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
    LOG.error(e);
  }
  finally {
    checkNotSync(indicator, items);
  }
}