Java Code Examples for com.intellij.openapi.application.Application#get()

The following examples show how to use com.intellij.openapi.application.Application#get() . 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: CompilerTask.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void addMessage(final CompilerMessage message) {
  final CompilerMessageCategory messageCategory = message.getCategory();
  if (CompilerMessageCategory.WARNING.equals(messageCategory)) {
    myWarningCount += 1;
  }
  else if (CompilerMessageCategory.ERROR.equals(messageCategory)) {
    myErrorCount += 1;
    informWolf(message);
  }

  Application application = Application.get();
  if (application.isDispatchThread()) {
    // implicit ui thread
    //noinspection RequiredXAction
    doAddMessage(message);
  }
  else {
    application.invokeLater(() -> {
      if (!myProject.isDisposed()) {
        doAddMessage(message);
      }
    }, ModalityState.NON_MODAL);
  }
}
 
Example 2
Source File: PluginManagerMain.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void notifyPluginsWereUpdated(final String title, final Project project) {
  final ApplicationEx app = (ApplicationEx)Application.get();
  final boolean restartCapable = app.isRestartCapable();
  String message = restartCapable
                   ? IdeBundle.message("message.idea.restart.required", ApplicationNamesInfo.getInstance().getFullProductName())
                   : IdeBundle.message("message.idea.shutdown.required", ApplicationNamesInfo.getInstance().getFullProductName());
  message += "<br><a href=";
  message += restartCapable ? "\"restart\">Restart now" : "\"shutdown\">Shutdown";
  message += "</a>";
  new NotificationGroup("Plugins Lifecycle Group", NotificationDisplayType.STICKY_BALLOON, true)
          .createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, new NotificationListener() {
            @Override
            public void hyperlinkUpdate(@Nonnull Notification notification, @Nonnull HyperlinkEvent event) {
              notification.expire();
              if (restartCapable) {
                app.restart(true);
              }
              else {
                app.exit(true, true);
              }
            }
          }).notify(project);
}
 
Example 3
Source File: PerApplicationInstance.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public V get() {
  V oldValue = myValue;
  if (oldValue == null) {
    synchronized (this) {
      oldValue = myValue;
      if (oldValue == null) {
        Application application = Application.get();
        V newValue = application.getInjectingContainer().getInstance(myTargetClass);
        Disposer.register(application, () -> myValue = null);
        myValue = newValue;
        return newValue;
      }
    }
  }

  return oldValue;
}
 
Example 4
Source File: PluginManagerConfigurable.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void apply() throws ConfigurationException {
  final String applyMessage = myPluginManagerMain.apply();
  if (applyMessage != null) {
    throw new ConfigurationException(applyMessage);
  }

  if (myPluginManagerMain.isRequireShutdown()) {
    final ApplicationEx app = (ApplicationEx)Application.get();

    int response = app.isRestartCapable() ? showRestartIDEADialog() : showShutDownIDEADialog();
    if (response == Messages.YES) {
      app.restart(true);
    }
    else {
      myPluginManagerMain.ignoreChanges();
    }
  }
}
 
Example 5
Source File: AccessRule.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static <T> AsyncResult<T> writeAsync(@RequiredWriteAction @Nonnull ThrowableComputable<T, Throwable> action) {
  ApplicationWithIntentWriteLock application = (ApplicationWithIntentWriteLock)Application.get();
  ExecutorService service = AppExecutorUtil.getAppExecutorService();
  AsyncResult<T> result = AsyncResult.undefined();
  service.execute(() -> {
    application.acquireWriteIntentLock();

    try {
      try {
        result.setDone(application.runWriteActionNoIntentLock(action));
      }
      catch (Throwable throwable) {
        LOG.error(throwable);

        result.rejectWithThrowable(throwable);
      }
    }
    finally {
      application.releaseWriteIntentLock();
    }
  });

  return result;
}
 
Example 6
Source File: ApplicationStarter.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void run(StatCollector stat, Runnable appInitalizeMark, boolean newConfigFolder) {
  try {
    ApplicationEx app = (ApplicationEx)Application.get();
    app.load(ContainerPathManager.get().getOptionsPath());

    if (myPostStarter.needStartInTransaction()) {
      ((TransactionGuardEx)TransactionGuard.getInstance()).performUserActivity(() -> myPostStarter.main(stat, appInitalizeMark, app, newConfigFolder, myArgs));
    }
    else {
      myPostStarter.main(stat, appInitalizeMark, app, newConfigFolder, myArgs);
    }

    myPostStarter = null;

    ourLoaded = true;
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source File: RefreshProgress.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateIndicators(final boolean start) {
  Application application = Application.get();
  UIAccess uiAccess = application.getLastUIAccess();
  // wrapping in invokeLater here reduces the number of events posted to EDT in case of multiple IDE frames
  uiAccess.giveIfNeed(() -> {
    if (application.isDisposed()) return;

    WindowManager windowManager = WindowManager.getInstance();
    if (windowManager == null) return;

    Project[] projects = ProjectManager.getInstance().getOpenProjects();
    if (projects.length == 0) projects = NULL_ARRAY;
    for (Project project : projects) {
      StatusBarEx statusBar = (StatusBarEx)windowManager.getStatusBar(project);
      if (statusBar != null) {
        if (start) {
          statusBar.startRefreshIndication(myMessage);
        }
        else {
          statusBar.stopRefreshIndication();
        }
      }
    }
  });
}
 
Example 8
Source File: Notifications.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void notifyAndHide(@Nonnull final Notification notification, @Nullable Project project) {
  notify(notification);
  Alarm alarm = new Alarm(project == null ? Application.get() : project);
  alarm.addRequest(() -> {
    notification.expire();
    Disposer.dispose(alarm);
  }, 5000);
}
 
Example 9
Source File: MockPsiManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiModificationTracker getModificationTracker() {
  if (myPsiModificationTracker == null) {
    myPsiModificationTracker = new PsiModificationTrackerImpl(Application.get(), myProject);
  }
  return myPsiModificationTracker;
}
 
Example 10
Source File: PlatformOrPluginUpdateChecker.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static AsyncResult<Void> updateAndShowResult() {
  final AsyncResult<Void> result = AsyncResult.undefined();
  final Application app = Application.get();
  final UpdateSettings updateSettings = UpdateSettings.getInstance();
  if (!updateSettings.isEnable()) {
    result.setDone();
    return result;
  }
  app.executeOnPooledThread(() -> checkAndNotifyForUpdates(null, false, null).notify(result));
  return result;
}
 
Example 11
Source File: Extensions.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Deprecated
public static <T> T[] getExtensions(String extensionPointName, @Nullable ComponentManager target) {
  ComponentManager componentManager = target == null ? Application.get() : target;
  ExtensionPoint<T> extensionPoint = componentManager.getExtensionPoint(ExtensionPointName.create(extensionPointName));
  return extensionPoint.getExtensions();
}
 
Example 12
Source File: DesktopCommandProcessorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
protected AsyncResult<Void> invokeLater(@Nonnull Runnable command, @Nonnull Condition<?> expire) {
  DesktopApplicationImpl application = (DesktopApplicationImpl)Application.get();

  ModalityState modalityState = ModalityPerProjectEAPDescriptor.is() ? ModalityState.current() : ModalityState.NON_MODAL;
  return application.getInvokator().invokeLater(command, modalityState, expire);
}
 
Example 13
Source File: CompilerTask.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void closeUI() {
  Application application = Application.get();
  application.invokeLater(() -> {
    final boolean shouldRetainView = myErrorCount > 0 || myWarningCount > 0 && !ProblemsView.getInstance(myProject).isHideWarnings();
    if (shouldRetainView) {
      ProblemsView.getInstance(myProject).selectFirstMessage();
    }
    else {
      ProblemsView.getInstance(myProject).showOrHide(true);
    }
  }, ModalityState.NON_MODAL);
}
 
Example 14
Source File: Notifications.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void doNotify(Notification notification, @Nullable Project project) {
  if (project != null && !project.isDisposed()) {
    project.getMessageBus().syncPublisher(TOPIC).notify(notification);
  } else {
    Application app = Application.get();
    if (!app.isDisposed()) {
      app.getMessageBus().syncPublisher(TOPIC).notify(notification);
    }
  }
}
 
Example 15
Source File: FileTypeExtensionFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
public FileTypeExtensionFactory(@Nonnull final Class<T> interfaceClass, @NonNls @Nonnull final ExtensionPointName<KeyedFactoryEPBean> epName) {
  super(interfaceClass, epName, Application.get());
}
 
Example 16
Source File: PluginManagerConfigurable.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void shutdownOrRestartApp(String title) {
  final ApplicationEx app = (ApplicationEx)Application.get();
  int response = app.isRestartCapable() ? showRestartIDEADialog(title) : showShutDownIDEADialog(title);
  if (response == Messages.YES) app.restart(true);
}
 
Example 17
Source File: MockProject.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Application getApplication() {
  return Application.get();
}
 
Example 18
Source File: BraceHighlightingHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
static void lookForInjectedAndMatchBracesInOtherThread(@Nonnull final Editor editor,
                                                       @Nonnull final Alarm alarm,
                                                       @Nonnull final Processor<BraceHighlightingHandler> processor) {
  ApplicationEx application = (ApplicationEx)Application.get();
  application.assertIsDispatchThread();
  if (!isValidEditor(editor)) return;
  if (!PROCESSED_EDITORS.add(editor)) {
    // Skip processing if that is not really necessary.
    // Assuming to be in EDT here.
    return;
  }
  final int offset = editor.getCaretModel().getOffset();
  final Project project = editor.getProject();
  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (!isValidFile(psiFile)) return;
  application.executeOnPooledThread(() -> {
    if (!application.tryRunReadAction(() -> {
      final PsiFile injected;
      try {
        if (psiFile instanceof PsiBinaryFile || !isValidEditor(editor) || !isValidFile(psiFile)) {
          injected = null;
        }
        else {
          injected = getInjectedFileIfAny(editor, project, offset, psiFile, alarm);
        }
      }
      catch (RuntimeException e) {
        // Reset processing flag in case of unexpected exception.
        application.invokeLater(new DumbAwareRunnable() {
          @Override
          public void run() {
            PROCESSED_EDITORS.remove(editor);
          }
        });
        throw e;
      }
      application.invokeLater(new DumbAwareRunnable() {
        @Override
        public void run() {
          try {
            if (isValidEditor(editor) && isValidFile(injected)) {
              Editor newEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injected);
              BraceHighlightingHandler handler = new BraceHighlightingHandler(project, newEditor, alarm, injected);
              processor.process(handler);
            }
          }
          finally {
            PROCESSED_EDITORS.remove(editor);
          }
        }
      }, ModalityState.stateForComponent(editor.getComponent()));
    })) {
      // write action is queued in AWT. restart after it's finished
      application.invokeLater(() -> {
        PROCESSED_EDITORS.remove(editor);
        lookForInjectedAndMatchBracesInOtherThread(editor, alarm, processor);
      }, ModalityState.stateForComponent(editor.getComponent()));
    }
  });
}
 
Example 19
Source File: BaseRefactoringProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void doRefactoring(@Nonnull final Collection<UsageInfo> usageInfoSet) {
  for (Iterator<UsageInfo> iterator = usageInfoSet.iterator(); iterator.hasNext(); ) {
    UsageInfo usageInfo = iterator.next();
    final PsiElement element = usageInfo.getElement();
    if (element == null || !isToBeChanged(usageInfo)) {
      iterator.remove();
    }
  }

  String commandName = getCommandName();
  LocalHistoryAction action = LocalHistory.getInstance().startAction(commandName);

  final UsageInfo[] writableUsageInfos = usageInfoSet.toArray(UsageInfo.EMPTY_ARRAY);
  try {
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    RefactoringListenerManagerImpl listenerManager = (RefactoringListenerManagerImpl)RefactoringListenerManager.getInstance(myProject);
    myTransaction = listenerManager.startTransaction();
    final Map<RefactoringHelper, Object> preparedData = new LinkedHashMap<>();
    final Runnable prepareHelpersRunnable = () -> {
      for (final RefactoringHelper helper : RefactoringHelper.EP_NAME.getExtensionList()) {
        Object operation = ReadAction.compute(() -> helper.prepareOperation(writableUsageInfos));
        preparedData.put(helper, operation);
      }
    };

    ProgressManager.getInstance().runProcessWithProgressSynchronously(prepareHelpersRunnable, "Prepare ...", false, myProject);

    Runnable performRefactoringRunnable = () -> {
      final String refactoringId = getRefactoringId();
      if (refactoringId != null) {
        RefactoringEventData data = getBeforeData();
        if (data != null) {
          data.addUsages(usageInfoSet);
        }
        myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, data);
      }

      try {
        if (refactoringId != null) {
          UndoableAction action1 = new UndoRefactoringAction(myProject, refactoringId);
          UndoManager.getInstance(myProject).undoableActionPerformed(action1);
        }

        performRefactoring(writableUsageInfos);
      }
      finally {
        if (refactoringId != null) {
          myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, getAfterData(writableUsageInfos));
        }
      }
    };
    ApplicationEx2 app = (ApplicationEx2)Application.get();
    if (Registry.is("run.refactorings.under.progress")) {
      app.runWriteActionWithNonCancellableProgressInDispatchThread(commandName, myProject, null, indicator -> performRefactoringRunnable.run());
    }
    else {
      app.runWriteAction(performRefactoringRunnable);
    }

    DumbService.getInstance(myProject).completeJustSubmittedTasks();

    for (Map.Entry<RefactoringHelper, Object> e : preparedData.entrySet()) {
      //noinspection unchecked
      e.getKey().performOperation(myProject, e.getValue());
    }
    myTransaction.commit();
    if (Registry.is("run.refactorings.under.progress")) {
      app.runWriteActionWithNonCancellableProgressInDispatchThread(commandName, myProject, null, indicator -> performPsiSpoilingRefactoring());
    }
    else {
      app.runWriteAction(this::performPsiSpoilingRefactoring);
    }
  }
  finally {
    action.finish();
  }

  int count = writableUsageInfos.length;
  if (count > 0) {
    StatusBarUtil.setStatusBarInfo(myProject, RefactoringBundle.message("statusBar.refactoring.result", count));
  }
  else {
    if (!isPreviewUsages(writableUsageInfos)) {
      StatusBarUtil.setStatusBarInfo(myProject, RefactoringBundle.message("statusBar.noUsages"));
    }
  }
}
 
Example 20
Source File: JobLauncher.java    From consulo with Apache License 2.0 2 votes vote down vote up
/**
 * Schedules concurrent execution of #thingProcessor over each element of #things and waits for completion
 * With checkCanceled in each thread delegated to our current progress
 *
 * @param things         data to process concurrently
 * @param progress       progress indicator
 * @param thingProcessor to be invoked concurrently on each element from the collection
 * @return false if tasks have been canceled,
 * or at least one processor returned false,
 * or threw an exception,
 * or we were unable to start read action in at least one thread
 * @throws ProcessCanceledException if at least one task has thrown ProcessCanceledException
 */
public <T> boolean invokeConcurrentlyUnderProgress(@Nonnull List<? extends T> things, ProgressIndicator progress, @Nonnull Processor<? super T> thingProcessor) throws ProcessCanceledException {
  ApplicationEx app = (ApplicationEx)Application.get();
  return invokeConcurrentlyUnderProgress(things, progress, app.isReadAccessAllowed(), app.isInImpatientReader(), thingProcessor);
}