Java Code Examples for com.intellij.ide.PowerSaveMode

The following examples show how to use com.intellij.ide.PowerSaveMode. These examples are extracted from open source projects. 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 Project: railways   Source File: RoutesViewPane.java    License: MIT License 6 votes vote down vote up
@Override
public void childrenChanged(@NotNull PsiTreeChangeEvent event) {
    if (PowerSaveMode.isEnabled() || !myRoutesManager.getState().autoUpdate)
        return;

    // Handle only changes in routes file.
    PsiFile f = event.getFile();

    if (f == null)
        return;

    VirtualFile changedFile = f.getVirtualFile();

    boolean anyRouteFileChanged = routesFiles.allFiles().anyMatch(changedFile::equals);
    if (!anyRouteFileChanged)
        return;

    // Don't perform update if panel or tool window is invisible.
    if (!myToolWindow.isVisible() || !myContent.isSelected()) {
        invalidateRoutes();
        return;
    }

    alarm.cancelAllRequests();
    alarm.addRequest(RoutesViewPane.this::updateRoutes, 700, ModalityState.NON_MODAL);
}
 
Example 2
Source Project: consulo   Source File: AutoPopupControllerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void scheduleAutoPopup(@Nonnull Editor editor, @Nonnull CompletionType completionType, @Nullable final Condition<? super PsiFile> condition) {
  //if (ApplicationManager.getApplication().isUnitTestMode() && !TestModeFlags.is(CompletionAutoPopupHandler.ourTestingAutopopup)) {
  //  return;
  //}

  boolean alwaysAutoPopup = Boolean.TRUE.equals(editor.getUserData(ALWAYS_AUTO_POPUP));
  if (!CodeInsightSettings.getInstance().AUTO_POPUP_COMPLETION_LOOKUP && !alwaysAutoPopup) {
    return;
  }
  if (PowerSaveMode.isEnabled()) {
    return;
  }

  if (!CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class, CompletionPhase.NoCompletion.getClass())) {
    return;
  }

  final CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCurrentCompletionProgressIndicator();
  if (currentCompletion != null) {
    currentCompletion.closeAndFinish(true);
  }

  CompletionPhase.CommittingDocuments.scheduleAsyncCompletion(editor, completionType, condition, myProject, null);
}
 
Example 3
Source Project: consulo   Source File: PsiAwareFileEditorManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
public PsiAwareFileEditorManagerImpl(Project project,
                                     PsiManager psiManager,
                                     Provider<WolfTheProblemSolver> problemSolver,
                                     DockManager dockManager) {
  super(project, dockManager);

  myPsiManager = psiManager;
  myProblemSolver = problemSolver;
  myPsiTreeChangeListener = new MyPsiTreeChangeListener();
  myProblemListener = new MyProblemListener();
  registerExtraEditorDataProvider(new TextEditorPsiDataProvider(), null);

  // reinit syntax highlighter for Groovy. In power save mode keywords are highlighted by GroovySyntaxHighlighter insteadof
  // GrKeywordAndDeclarationHighlighter. So we need to drop caches for token types attributes in LayeredLexerEditorHighlighter
  project.getMessageBus().connect().subscribe(PowerSaveMode.TOPIC, new PowerSaveMode.Listener() {
    @Override
    public void powerSaveStateChanged() {
      UIUtil.invokeLaterIfNeeded(() -> {
        for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
          ((EditorEx)editor).reinitSettings();
        }
      });
    }
  });
}
 
Example 4
Source Project: railways   Source File: RoutesView.java    License: MIT License 5 votes vote down vote up
@Override
public void modificationCountChanged() {
    if (PowerSaveMode.isEnabled() ||
            myToolWindow == null || !myToolWindow.isVisible() ||
            !isLiveHighlightingEnabled())
        return;

    alarm.cancelAllRequests();
    alarm.addRequest(RoutesView.this::refreshRouteActionsStatus, 1000, ModalityState.NON_MODAL);
}
 
Example 5
/**
     * PhpTypedHandler.scheduleAutoPopup but use SMART since BASIC is blocked
     */
    public void scheduleAutoPopup(final Project project, final Editor editor, @Nullable final Condition<PsiFile> condition) {
        if (ApplicationManager.getApplication().isUnitTestMode()/* && !CompletionAutoPopupHandler.ourTestingAutopopup*/) {
            return;
        }

        if (!CodeInsightSettings.getInstance().AUTO_POPUP_COMPLETION_LOOKUP) {
            return;
        }
        if (PowerSaveMode.isEnabled()) {
            return;
        }

        if (!CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class, CompletionPhase.NoCompletion.getClass())) {
            return;
        }
//
//        final CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCompletionService().getCurrentCompletion();
//        if (currentCompletion != null) {
//            currentCompletion.closeAndFinish(true);
//        }
//
//        final CompletionPhase.CommittingDocuments phase = new CompletionPhase.CommittingDocuments(null, editor);
//        CompletionServiceImpl.setCompletionPhase(phase);
//
//        CompletionAutoPopupHandler.runLaterWithCommitted(project, editor.getDocument(), new Runnable() {
//            @Override
//            public void run() {
//                CompletionAutoPopupHandler.invokeCompletion(CompletionType.BASIC, true, project, editor, 0, false);
//            }
//        });
    }
 
Example 6
Source Project: consulo   Source File: ScrollSettings.java    License: Apache License 2.0 5 votes vote down vote up
static boolean isEligibleFor(Component component) {
  if (component == null || !component.isShowing()) return false;

  Application application = getApplication();
  if (application == null || application.isUnitTestMode()) return false;
  if (PowerSaveMode.isEnabled()) return false;
  if (RemoteDesktopService.isRemoteSession()) return false;

  UISettings settings = UISettings.getInstanceOrNull();
  return settings != null && settings.SMOOTH_SCROLLING;
}
 
Example 7
Source Project: consulo   Source File: InfoAndProgressPanel.java    License: Apache License 2.0 5 votes vote down vote up
private void updateProgressIcon() {
  AsyncProcessIcon progressIcon = myProgressIcon.isComputed() ? myProgressIcon.getValue() : null;
  if (progressIcon == null) {
    return;
  }

  if (myOriginals.isEmpty() || PowerSaveMode.isEnabled() || myOriginals.stream().map(ProgressSuspender::getSuspender).allMatch(s -> s != null && s.isSuspended())) {
    progressIcon.suspend();
  }
  else {
    progressIcon.resume();
  }
}
 
Example 8
Source Project: consulo   Source File: InfoAndProgressPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void updateProgressNow() {
  myProgress.setVisible(!PowerSaveMode.isEnabled() || !isPaintingIndeterminate());
  super.updateProgressNow();
  if (myPresentationModeProgressPanel != null) myPresentationModeProgressPanel.update();
  if (myOriginal == getLatestProgress() && myMultiProcessLink != null) {
    myMultiProcessLink.setText(getMultiProgressLinkText());
  }
}
 
Example 9
Source Project: consulo   Source File: TrafficLightRenderer.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private Icon getIcon(@Nonnull DaemonCodeAnalyzerStatus status) {
  updatePanel(status);
  Icon icon = this.icon;
  if (PowerSaveMode.isEnabled() || status.reasonWhySuspended != null || status.reasonWhyDisabled != null || status.errorAnalyzingFinished) {
    return icon;
  }
  return AllIcons.General.InspectionsEye;
}
 
Example 10
Source Project: consulo   Source File: AutoPopupControllerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void autoPopupParameterInfo(@Nonnull final Editor editor, @Nullable final Object highlightedMethod) {
  if (DumbService.isDumb(myProject)) return;
  if (PowerSaveMode.isEnabled()) return;

  ApplicationManager.getApplication().assertIsDispatchThread();
  final CodeInsightSettings settings = CodeInsightSettings.getInstance();
  if (settings.AUTO_POPUP_PARAMETER_INFO) {
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    PsiFile file = documentManager.getPsiFile(editor.getDocument());
    if (file == null) return;

    if (!documentManager.isUncommited(editor.getDocument())) {
      file = documentManager.getPsiFile(InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file).getDocument());
      if (file == null) return;
    }

    Runnable request = () -> {
      if (!myProject.isDisposed() && !DumbService.isDumb(myProject) && !editor.isDisposed() && (EditorActivityManager.getInstance().isVisible(editor))) {
        int lbraceOffset = editor.getCaretModel().getOffset() - 1;
        try {
          PsiFile file1 = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument());
          if (file1 != null) {
            ShowParameterInfoHandler.invoke(myProject, editor, file1, lbraceOffset, highlightedMethod, false, true, null, e -> {
            });
          }
        }
        catch (IndexNotReadyException ignored) { //anything can happen on alarm
        }
      }
    };

    addRequest(() -> documentManager.performLaterWhenAllCommitted(request), settings.PARAMETER_INFO_DELAY);
  }
}
 
Example 11
Source Project: consulo   Source File: CodeCompletionPanel.java    License: Apache License 2.0 5 votes vote down vote up
public void reset() {
  CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();

  final String value;
  switch(codeInsightSettings.COMPLETION_CASE_SENSITIVE){
    case CodeInsightSettings.ALL:
      value = CASE_SENSITIVE_ALL;
      break;

    case CodeInsightSettings.NONE:
      value = CASE_SENSITIVE_NONE;
      break;

    default:
      value = CASE_SENSITIVE_FIRST_LETTER;
      break;
  }
  myCaseSensitiveCombo.setSelectedItem(value);

  myCbSelectByChars.setSelected(codeInsightSettings.SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS);

  myCbOnCodeCompletion.setSelected(codeInsightSettings.AUTOCOMPLETE_ON_CODE_COMPLETION);
  myCbOnSmartTypeCompletion.setSelected(codeInsightSettings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION);

  myCbAutocompletion.setSelected(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);

  myCbAutopopupJavaDoc.setSelected(codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
  myAutopopupJavaDocField.setEnabled(codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
  myAutopopupJavaDocField.setText(String.valueOf(codeInsightSettings.JAVADOC_INFO_DELAY));

  myCbParameterInfoPopup.setSelected(codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
  myParameterInfoDelayField.setEnabled(codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
  myParameterInfoDelayField.setText(String.valueOf(codeInsightSettings.PARAMETER_INFO_DELAY));
  myCbShowFullParameterSignatures.setSelected(codeInsightSettings.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO);

  myCbAutocompletion.setSelected(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
  myCbSorting.setSelected(UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY);

  myCbAutocompletion.setText("Autopopup code completion" + (PowerSaveMode.isEnabled() ? " (not available in Power Save mode)" : ""));
}
 
Example 12
Source Project: consulo   Source File: TogglePopupHintsPanel.java    License: Apache License 2.0 5 votes vote down vote up
private void updateStatus(PsiFile file) {
  if (isDisposed()) return;
  if (isStateChangeable(file)) {
    if (PowerSaveMode.isEnabled()) {
      myCurrentIcon = ImageEffects.grayed(AllIcons.Ide.HectorOff);
      myToolTipText = "Code analysis is disabled in power save mode.\n";
    }
    else if (HighlightingLevelManager.getInstance(getProject()).shouldInspect(file)) {
      myCurrentIcon = AllIcons.Ide.HectorOn;
      InspectionProfileImpl profile = InspectionProjectProfileManager.getInstance(file.getProject()).getCurrentProfile();
      if (profile.wasInitialized()) myToolTipText = "Current inspection profile: " + profile.getName() + ".\n";
    }
    else if (HighlightingLevelManager.getInstance(getProject()).shouldHighlight(file)) {
      myCurrentIcon = AllIcons.Ide.HectorSyntax;
      myToolTipText = "Highlighting level is: Syntax.\n";
    }
    else {
      myCurrentIcon = AllIcons.Ide.HectorOff;
      myToolTipText = "Inspections are off.\n";
    }
    myToolTipText += UIBundle.message("popup.hints.panel.click.to.configure.highlighting.tooltip.text");
  }
  else {
    myCurrentIcon = file != null ? ImageEffects.grayed(AllIcons.Ide.HectorOff) : null;
    myToolTipText = null;
  }

  if (!ApplicationManager.getApplication().isUnitTestMode() && myStatusBar != null) {
    myStatusBar.updateWidget(ID());
  }
}
 
Example 13
Source Project: consulo   Source File: PostponableLogRefresher.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean keepUpToDate() {
  return Registry.is("vcs.log.keep.up.to.date",  true) && !PowerSaveMode.isEnabled();
}
 
Example 14
Source Project: consulo   Source File: AnnotationsPreloader.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isEnabled() {
  // TODO: check cores number?
  return Registry.is("vcs.annotations.preload") && !PowerSaveMode.isEnabled();
}
 
Example 15
Source Project: consulo   Source File: DaemonCodeAnalyzerImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
  ApplicationManager.getApplication().assertIsDispatchThread();
  Project project = myProject;
  DaemonCodeAnalyzerImpl dca;
  if (project == null || !project.isInitialized() || project.isDisposed() || PowerSaveMode.isEnabled() || (dca = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project)).myDisposed) {
    return;
  }

  final Collection<FileEditor> activeEditors = dca.getSelectedEditors();
  boolean updateByTimerEnabled = dca.isUpdateByTimerEnabled();
  PassExecutorService
          .log(dca.getUpdateProgress(), null, "Update Runnable. myUpdateByTimerEnabled:", updateByTimerEnabled, " something disposed:", PowerSaveMode.isEnabled() || !myProject.isInitialized(),
               " activeEditors:", activeEditors);
  if (!updateByTimerEnabled) return;

  if (activeEditors.isEmpty()) return;

  if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
    // makes no sense to start from within write action, will cancel anyway
    // we'll restart when the write action finish
    return;
  }
  if (dca.myPsiDocumentManager.hasUncommitedDocuments()) {
    // restart when everything committed
    dca.myPsiDocumentManager.performLaterWhenAllCommitted(this);
    return;
  }
  if (RefResolveService.ENABLED && !RefResolveService.getInstance(myProject).isUpToDate() && RefResolveService.getInstance(myProject).getQueueSize() == 1) {
    return; // if the user have just typed in something, wait until the file is re-resolved
    // (or else it will blink like crazy since unused symbols calculation depends on resolve service)
  }

  Map<FileEditor, HighlightingPass[]> passes = new THashMap<>(activeEditors.size());
  for (FileEditor fileEditor : activeEditors) {
    BackgroundEditorHighlighter highlighter = fileEditor.getBackgroundHighlighter();
    if (highlighter != null) {
      HighlightingPass[] highlightingPasses = highlighter.createPassesForEditor();
      passes.put(fileEditor, highlightingPasses);
    }
  }

  // wait for heavy processing to stop, re-schedule daemon but not too soon
  if (HeavyProcessLatch.INSTANCE.isRunning()) {
    boolean hasPasses = false;
    for (Map.Entry<FileEditor, HighlightingPass[]> entry : passes.entrySet()) {
      HighlightingPass[] filtered = Arrays.stream(entry.getValue()).filter(DumbService::isDumbAware).toArray(HighlightingPass[]::new);
      entry.setValue(filtered);
      hasPasses |= filtered.length != 0;
    }
    if (!hasPasses) {
      HeavyProcessLatch.INSTANCE.executeOutOfHeavyProcess(() -> dca.stopProcess(true, "re-scheduled to execute after heavy processing finished"));
      return;
    }
  }

  // cancel all after calling createPasses() since there are perverts {@link com.intellij.util.xml.ui.DomUIFactoryImpl} who are changing PSI there
  dca.cancelUpdateProgress(true, "Cancel by alarm");
  dca.myUpdateRunnableFuture.cancel(false);
  DaemonProgressIndicator progress = dca.createUpdateProgress(passes.keySet());
  dca.myPassExecutorService.submitPasses(passes, progress);
}
 
Example 16
Source Project: consulo   Source File: TrafficLightRenderer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public AnalyzerStatus getStatus(@Nonnull Editor editor) {
  if (PowerSaveMode.isEnabled()) {
    return new AnalyzerStatus(AllIcons.General.InspectionsPowerSaveMode, "Code analysis is disabled in power save mode", "", () -> createUIController(editor));
  }
  else {
    DaemonCodeAnalyzerStatus status = getDaemonCodeAnalyzerStatus(mySeverityRegistrar);
    List<StatusItem> statusItems = new ArrayList<>();
    Icon mainIcon = null;

    String title = "";
    String details = "";
    boolean isDumb = DumbService.isDumb(myProject);
    if (status.errorAnalyzingFinished) {
      if (isDumb) {
        title = DaemonBundle.message("shallow.analysis.completed");
        details = DaemonBundle.message("shallow.analysis.completed.details");
      }
    }
    else {
      title = DaemonBundle.message("performing.code.analysis");
    }

    int[] errorCount = status.errorCount;
    for (int i = errorCount.length - 1; i >= 0; i--) {
      int count = errorCount[i];
      if (count > 0) {
        HighlightSeverity severity = mySeverityRegistrar.getSeverityByIndex(i);
        String name = StringUtil.toLowerCase(severity.getName());
        if (count > 1) {
          name = StringUtil.pluralize(name);
        }

        Icon icon = mySeverityRegistrar.getRendererIconByIndex(i);
        statusItems.add(new StatusItem(Integer.toString(count), icon, name));

        if (mainIcon == null) {
          mainIcon = icon;
        }
      }
    }

    if (!statusItems.isEmpty()) {
      if (mainIcon == null) {
        mainIcon = AllIcons.General.InspectionsOK;
      }
      AnalyzerStatus result = new AnalyzerStatus(mainIcon, title, "", () -> createUIController(editor)).
              withNavigation().
              withExpandedStatus(statusItems);

      //noinspection ConstantConditions
      return status.errorAnalyzingFinished ? result : result.withAnalyzingType(AnalyzingType.PARTIAL).
              withPasses(ContainerUtil.map(status.passes, p -> new PassWrapper(p.getPresentableName(), p.getProgress(), p.isFinished())));
    }
    if (StringUtil.isNotEmpty(status.reasonWhyDisabled)) {
      return new AnalyzerStatus(AllIcons.General.InspectionsTrafficOff, DaemonBundle.message("no.analysis.performed"), status.reasonWhyDisabled, () -> createUIController(editor))
              .withTextStatus(DaemonBundle.message("iw.status.off"));
    }
    if (StringUtil.isNotEmpty(status.reasonWhySuspended)) {
      return new AnalyzerStatus(AllIcons.General.InspectionsPause, DaemonBundle.message("analysis.suspended"), status.reasonWhySuspended, () -> createUIController(editor)).
              withTextStatus(status.heavyProcessType != null ? status.heavyProcessType.toString() : DaemonBundle.message("iw.status.paused"));
    }
    if (status.errorAnalyzingFinished) {
      return isDumb
             ? new AnalyzerStatus(AllIcons.General.InspectionsPause, title, details, () -> createUIController(editor)).
              withTextStatus(DaemonBundle.message("heavyProcess.type.indexing"))
             : new AnalyzerStatus(AllIcons.General.InspectionsOK, DaemonBundle.message("no.errors.or.warnings.found"), details, () -> createUIController(editor));
    }

    //noinspection ConstantConditions
    return new AnalyzerStatus(AllIcons.General.InspectionsEye, title, details, () -> createUIController(editor)).
            withTextStatus(DaemonBundle.message("iw.status.analyzing")).
            withAnalyzingType(AnalyzingType.EMPTY).
            withPasses(ContainerUtil.map(status.passes, p -> new PassWrapper(p.getPresentableName(), p.getProgress(), p.isFinished())));
  }
}
 
Example 17
Source Project: consulo   Source File: TogglePowerSaveAction.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSelected(AnActionEvent e) {
  return PowerSaveMode.isEnabled();
}
 
Example 18
Source Project: consulo   Source File: TogglePowerSaveAction.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setSelected(AnActionEvent e, boolean state) {
  PowerSaveMode.setEnabled(state);
}