com.intellij.openapi.application.Application Java Examples

The following examples show how to use com.intellij.openapi.application.Application. 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: MockThreadRunner.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private MockThreadRunner(IdeaLightweightExtension extension, long waitTimeSeconds) {
    waitTimeoutSeconds = waitTimeSeconds;
    Application application = extension.getMockApplication();

    BlockingRunAnswer pooledThreadAnswer = new BlockingRunAnswer(pooledThreadsRun);
    when(application.executeOnPooledThread((Runnable) any())).then(pooledThreadAnswer);
    when(application.executeOnPooledThread((Callable<?>) any())).then(pooledThreadAnswer);

    BlockingRunAnswer edtLaterAnswer = new BlockingRunAnswer(edtLaterRun);
    doAnswer(edtLaterAnswer).when(application).invokeLater(any());
    doAnswer(edtLaterAnswer).when(application).invokeLater(any(), (Condition) any());
    doAnswer(edtLaterAnswer).when(application).invokeLater(any(), (ModalityState) any());

    InthreadRunAnswer edtWaitAnswer = new InthreadRunAnswer(edtWaitRun);
    doAnswer(edtWaitAnswer).when(application).invokeAndWait(any());
    doAnswer(edtWaitAnswer).when(application).invokeAndWait(any(), any());
}
 
Example #2
Source File: EditorTypedHandlerBean.java    From consulo with Apache License 2.0 6 votes vote down vote up
public TypedActionHandler getHandler(TypedActionHandler originalHandler) {
  if (myHandler == null) {
    try {
      InjectingContainer container = Application.get().getInjectingContainer();

      InjectingContainerBuilder builder = container.childBuilder();
      // bind original to TypedActionHandler
      builder.bind(TypedActionHandler.class).to(originalHandler);

      myHandler = instantiate(implementationClass, builder.build());
    }
    catch(Exception e) {
      LOG.error(e);
      return null;
    }
  }
  return myHandler;
}
 
Example #3
Source File: ManagePackagesDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void initModel() {
  setDownloadStatus(true);
  final Application application = ApplicationManager.getApplication();
  application.executeOnPooledThread(() -> {
    try {
      myPackagesModel = new PackagesModel(myController.getAllPackages());

      application.invokeLater(() -> {
        myPackages.setModel(myPackagesModel);
        ((MyPackageFilter)myFilter).filter();
        doSelectPackage(mySelectedPackageName);
        setDownloadStatus(false);
      }, ModalityState.any());
    }
    catch (final IOException e) {
      application.invokeLater(() -> {
        if (myMainPanel.isShowing()) {
          Messages.showErrorDialog(myMainPanel, "Error loading package list:" + e.getMessage(), "Packages");
        }
        setDownloadStatus(false);
      }, ModalityState.any());
    }
  });
}
 
Example #4
Source File: AsyncRateLimiter.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void performRequestOnUiThread() {
  final Runnable doRun = () -> {
    if (requestScheduler.isDisposed()) {
      return;
    }
    performRequest();
  };
  final Application app = ApplicationManager.getApplication();
  if (app == null || app.isUnitTestMode()) {
    // This case exists to support unittesting.
    SwingUtilities.invokeLater(doRun);
  }
  else {
    app.invokeLater(doRun);
  }
}
 
Example #5
Source File: GeneralTestEventsProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void addToInvokeLater(final Runnable runnable) {
  final Application application = ApplicationManager.getApplication();
  if (application.isUnitTestMode()) {
    UIUtil.invokeLaterIfNeeded(() -> {
      if (!myProject.isDisposed()) {
        runnable.run();
      }
    });
  }
  else if (application.isHeadlessEnvironment() || SwingUtilities.isEventDispatchThread()) {
    runnable.run();
  }
  else {
    myTransferToEDTQueue.offer(runnable);
  }
}
 
Example #6
Source File: ToolbarUpdater.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateActions(boolean now, final boolean transparentOnly, final boolean forced) {
  final Runnable updateRunnable = new MyUpdateRunnable(this, transparentOnly, forced);
  final Application app = ApplicationManager.getApplication();

  if (now || (app.isUnitTestMode() && app.isDispatchThread())) {
    updateRunnable.run();
  }
  else {
    final IdeFocusManager fm = IdeFocusManager.getInstance(null);

    if (!app.isHeadlessEnvironment()) {
      if (app.isDispatchThread() && myComponent.isShowing()) {
        fm.doWhenFocusSettlesDown(updateRunnable);
      }
      else {
        UiNotifyConnector.doWhenFirstShown(myComponent, () -> fm.doWhenFocusSettlesDown(updateRunnable));
      }
    }
  }
}
 
Example #7
Source File: PantsOpenProjectProvider.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private AddModuleWizard openNewProjectWizard(VirtualFile projectFile) {
  PantsProjectImportProvider provider = new PantsProjectImportProvider();
  AddModuleWizard dialog = new AddModuleWizard(null, projectFile.getPath(), provider);

  ProjectImportBuilder builder = provider.getBuilder();
  builder.setUpdate(false);
  dialog.getWizardContext().setProjectBuilder(builder);

  // dialog can only be shown in a non-headless environment
  Application application = ApplicationManager.getApplication();
  if (application.isHeadlessEnvironment() || dialog.showAndGet()) {
    return dialog;
  }
  else {
    return null;
  }
}
 
Example #8
Source File: DesktopIdeFrameImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void setupCloseAction() {
  myJFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
  myJFrame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(@Nonnull final WindowEvent e) {
      if (isTemporaryDisposed()) return;

      final Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
      if (openProjects.length > 1 || openProjects.length == 1 && TopApplicationMenuUtil.isMacSystemMenu) {
        if (myProject != null && myProject.isOpen()) {
          ProjectUtil.closeAndDispose(myProject);
        }
        ApplicationManager.getApplication().getMessageBus().syncPublisher(AppLifecycleListener.TOPIC).projectFrameClosed();
        WelcomeFrame.showIfNoProjectOpened();
      }
      else {
        Application.get().exit();
      }
    }
  });
}
 
Example #9
Source File: ExtensibleQueryFactory.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected ExtensibleQueryFactory(@NonNls final String epNamespace) {
  myPoint = new NotNullLazyValue<SimpleSmartExtensionPoint<QueryExecutor<Result, Parameters>>>() {
    @Override
    @Nonnull
    protected SimpleSmartExtensionPoint<QueryExecutor<Result, Parameters>> compute() {
      return new SimpleSmartExtensionPoint<QueryExecutor<Result, Parameters>>(new SmartList<QueryExecutor<Result, Parameters>>()){
        @Override
        @Nonnull
        protected ExtensionPoint<QueryExecutor<Result, Parameters>> getExtensionPoint() {
          String epName = ExtensibleQueryFactory.this.getClass().getName();
          int pos = epName.lastIndexOf('.');
          if (pos >= 0) {
            epName = epName.substring(pos+1);
          }
          epName = epNamespace + "." + StringUtil.decapitalize(epName);
          return Application.get().getExtensionPoint(ExtensionPointName.create(epName));
        }
      };
    }
  };
}
 
Example #10
Source File: GeneralToSMTRunnerEventsConvertor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void dispose() {
  super.dispose();
  addToInvokeLater(() -> {

    disconnectListeners();
    if (!myRunningTestsFullNameToProxy.isEmpty()) {
      final Application application = ApplicationManager.getApplication();
      if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) {
        logProblem("Not all events were processed! " + dumpRunningTestsNames());
      }
    }
    myRunningTestsFullNameToProxy.clear();
    mySuitesStack.clear();
  });
}
 
Example #11
Source File: LightFilePointer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void refreshFile() {
  VirtualFile file = myFile;
  if (file != null && file.isValid()) return;
  VirtualFileManager vfManager = VirtualFileManager.getInstance();
  VirtualFile virtualFile = vfManager.findFileByUrl(myUrl);
  if (virtualFile == null && !myRefreshed) {
    myRefreshed = true;
    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread() || !application.isReadAccessAllowed()) {
      virtualFile = vfManager.refreshAndFindFileByUrl(myUrl);
    }
    else {
      application.executeOnPooledThread(() -> vfManager.refreshAndFindFileByUrl(myUrl));
    }
  }

  myFile = virtualFile != null && virtualFile.isValid() ? virtualFile : null;
}
 
Example #12
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 #13
Source File: InstalledPackagesPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void refreshLatestVersions(@Nonnull final PackageManagementService packageManagementService) {
  final Application application = ApplicationManager.getApplication();
  application.executeOnPooledThread(() -> {
    if (packageManagementService == myPackageManagementService) {
      try {
        List<RepoPackage> packages = packageManagementService.reloadAllPackages();
        final Map<String, RepoPackage> packageMap = buildNameToPackageMap(packages);
        application.invokeLater(() -> {
          for (int i = 0; i != myPackagesTableModel.getRowCount(); ++i) {
            final InstalledPackage pyPackage = (InstalledPackage)myPackagesTableModel.getValueAt(i, 0);
            final RepoPackage repoPackage = packageMap.get(pyPackage.getName());
            myPackagesTableModel.setValueAt(repoPackage == null ? null : repoPackage.getLatestVersion(), i, 2);
          }
          myPackagesTable.setPaintBusy(false);
        }, ModalityState.stateForComponent(myPackagesTable));
      }
      catch (IOException ignored) {
        myPackagesTable.setPaintBusy(false);
      }
    }
  });
}
 
Example #14
Source File: ActionTracer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public JComponent getComponent() {
  if (myComponent == null) {
    myText = new JTextArea();
    final JBScrollPane log = new JBScrollPane(myText);
    final AnAction clear = new AnAction("Clear", "Clear log", AllIcons.General.Reset) {
      @Override
      public void actionPerformed(AnActionEvent e) {
        myText.setText(null);
      }
    };
    myComponent = new JPanel(new BorderLayout());
    final DefaultActionGroup group = new DefaultActionGroup();
    group.add(clear);
    myComponent.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true).getComponent(), BorderLayout.NORTH);
    myComponent.add(log);

    myListenerDisposable = Disposable.newDisposable();
    Application.get().getMessageBus().connect(myListenerDisposable).subscribe(AnActionListener.TOPIC, this);
  }

  return myComponent;
}
 
Example #15
Source File: HttpRequests.java    From leetcode-editor with Apache License 2.0 6 votes vote down vote up
private static <T> T process(RequestBuilderImpl builder, RequestProcessor<T> processor) throws IOException {
    Application app = ApplicationManager.getApplication();
    LOG.assertTrue(app == null || app.isUnitTestMode() || app.isHeadlessEnvironment() || !app.isReadAccessAllowed(),
            "Network shouldn't be accessed in EDT or inside read action");

    ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
    if (contextLoader != null && shouldOverrideContextClassLoader()) {
        // hack-around for class loader lock in sun.net.www.protocol.http.NegotiateAuthentication (IDEA-131621)
        try (URLClassLoader cl = new URLClassLoader(new URL[0], contextLoader)) {
            Thread.currentThread().setContextClassLoader(cl);
            return doProcess(builder, processor);
        }
        finally {
            Thread.currentThread().setContextClassLoader(contextLoader);
        }
    }
    else {
        return doProcess(builder, processor);
    }
}
 
Example #16
Source File: EditorActionHandlerBean.java    From consulo with Apache License 2.0 6 votes vote down vote up
public EditorActionHandler getHandler(EditorActionHandler originalHandler) {
  if (myHandler == null) {
    try {
      InjectingContainer container = Application.get().getInjectingContainer();

      InjectingContainerBuilder builder = container.childBuilder();
      // bind original to EditorActionHandler
      builder.bind(EditorActionHandler.class).to(originalHandler);

      myHandler = instantiate(implementationClass, builder.build());
    }
    catch(Exception e) {
      LOG.error(e);
      return null;
    }
  }
  return myHandler;
}
 
Example #17
Source File: TestUtils.java    From intellij with Apache License 2.0 6 votes vote down vote up
public static void createMockApplication(Disposable parentDisposable) {
  final BlazeMockApplication instance = new BlazeMockApplication(parentDisposable);

  // If there was no previous application,
  // ApplicationManager leaves the MockApplication in place, which can break future tests.
  Application oldApplication = ApplicationManager.getApplication();
  if (oldApplication == null) {
    Disposer.register(
        parentDisposable,
        () -> {
          new ApplicationManager() {
            {
              ourApplication = null;
            }
          };
        });
  }

  ApplicationManager.setApplication(instance, FileTypeManager::getInstance, parentDisposable);
  instance.registerService(EncodingManager.class, EncodingManagerImpl.class);
}
 
Example #18
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 #19
Source File: ChooseLibrariesDialogBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void collectChildren(Object element, final List<Object> result) {
  if (element instanceof Application) {
    Collections.addAll(result, ProjectManager.getInstance().getOpenProjects());
    final LibraryTablesRegistrar instance = LibraryTablesRegistrar.getInstance();
    result.add(instance.getLibraryTable()); //1
    result.addAll(instance.getCustomLibraryTables()); //2
  }
  else if (element instanceof Project) {
    Collections.addAll(result, ModuleManager.getInstance((Project)element).getModules());
    result.add(LibraryTablesRegistrar.getInstance().getLibraryTable((Project)element));
  }
  else if (element instanceof LibraryTable) {
    Collections.addAll(result, ((LibraryTable)element).getLibraries());
  }
  else if (element instanceof Module) {
    for (OrderEntry entry : ModuleRootManager.getInstance((Module)element).getOrderEntries()) {
      if (entry instanceof LibraryOrderEntry) {
        final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry;
        if (LibraryTableImplUtil.MODULE_LEVEL.equals(libraryOrderEntry.getLibraryLevel())) {
          final Library library = libraryOrderEntry.getLibrary();
          result.add(library);
        }
      }
    }
  }
}
 
Example #20
Source File: PostprocessReformattingAspect.java    From consulo with Apache License 2.0 5 votes vote down vote up
public <T> T postponeFormattingInside(@Nonnull Computable<T> computable) {
  Application application = ApplicationManager.getApplication();
  application.assertIsDispatchThread();
  try {
    incrementPostponedCounter();
    return computable.compute();
  }
  finally {
    decrementPostponedCounter();
  }
}
 
Example #21
Source File: HaxeCompilerCompletionContributor.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
/**
 * Save the file contents to disk so that the compiler has the correct data to work with.
 */
private void saveEditsToDisk(VirtualFile file) {
  final Document doc = FileDocumentManager.getInstance().getDocument(file);
  if (FileDocumentManager.getInstance().isDocumentUnsaved(doc)) {
    final Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread()) {
      LOG.debug("Saving buffer to disk...");
      FileDocumentManager.getInstance().saveDocumentAsIs(doc);
    } else {
      LOG.debug("Not on dispatch thread and document is unsaved.");
    }
  }
}
 
Example #22
Source File: PsiReferenceProviderBean.java    From consulo with Apache License 2.0 5 votes vote down vote up
public PsiReferenceProvider instantiate() {
  try {
    return (PsiReferenceProvider)instantiate(className, Application.get().getInjectingContainer());
  }
  catch (ClassNotFoundException e) {
    LOG.error(e);
  }
  return null;
}
 
Example #23
Source File: CoreCommandProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void executeCommand(@Nullable Project project,
                            @Nonnull Runnable command,
                            @Nullable String name,
                            @Nullable Object groupId,
                            @Nonnull UndoConfirmationPolicy confirmationPolicy,
                            boolean shouldRecordCommandForActiveDocument,
                            @Nullable Document document) {
  Application application = ApplicationManager.getApplication();
  application.assertIsDispatchThread();
  if (project != null && project.isDisposed()) {
    CommandLog.LOG.error("Project " + project + " already disposed");
    return;
  }

  if (CommandLog.LOG.isDebugEnabled()) {
    CommandLog.LOG.debug("executeCommand: " + command + ", name = " + name + ", groupId = " + groupId +
                         ", in command = " + (myCurrentCommand != null) +
                         ", in transparent action = " + isUndoTransparentActionInProgress());
  }

  if (myCurrentCommand != null) {
    command.run();
    return;
  }
  Throwable throwable = null;
  try {
    myCurrentCommand = new CommandDescriptor(command, project, name, groupId, confirmationPolicy, shouldRecordCommandForActiveDocument, document);
    fireCommandStarted();
    command.run();
  }
  catch (Throwable th) {
    throwable = th;
  }
  finally {
    finishCommand(myCurrentCommand, throwable);
  }
}
 
Example #24
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Inject
public FileDocumentManagerImpl(Application application, ProjectManager projectManager) {
  ((ProjectManagerEx)projectManager).registerCloseProjectVeto(new MyProjectCloseHandler());

  myBus = application.getMessageBus();
  InvocationHandler handler = (proxy, method, args) -> {
    multiCast(method, args);
    return null;
  };

  ClassLoader loader = FileDocumentManagerListener.class.getClassLoader();
  myMultiCaster = (FileDocumentManagerListener)Proxy.newProxyInstance(loader, new Class[]{FileDocumentManagerListener.class}, handler);
}
 
Example #25
Source File: GeneralHighlightingPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void cancelAndRestartDaemonLater(@Nonnull ProgressIndicator progress, @Nonnull final Project project) throws ProcessCanceledException {
  RESTART_REQUESTS.incrementAndGet();
  progress.cancel();
  Application application = ApplicationManager.getApplication();
  int delay = application.isUnitTestMode() ? 0 : RESTART_DAEMON_RANDOM.nextInt(100);
  EdtExecutorService.getScheduledExecutorInstance().schedule(() -> {
    RESTART_REQUESTS.decrementAndGet();
    if (!project.isDisposed()) {
      DaemonCodeAnalyzer.getInstance(project).restart();
    }
  }, delay, TimeUnit.MILLISECONDS);
  throw new ProcessCanceledException();
}
 
Example #26
Source File: PluginsAdvertiserHolder.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void initialize(@Nonnull Consumer<List<PluginDescriptor>> consumer) {
  UpdateSettings updateSettings = UpdateSettings.getInstance();
  if (!updateSettings.isEnable()) {
    return;
  }

  if (ourLoadedPluginDescriptors != null) {
    Application.get().executeOnPooledThread(() -> consumer.accept(ourLoadedPluginDescriptors));
    return;
  }

  Application.get().executeOnPooledThread(() -> {
    List<PluginDescriptor> pluginDescriptors = Collections.emptyList();
    try {
      pluginDescriptors = RepositoryHelper.loadPluginsFromRepository(null, updateSettings.getChannel());
    }
    catch (Exception ignored) {
    }

    if(Application.get().isDisposed()) {
      return;
    }

    update(pluginDescriptors);

    if (pluginDescriptors.isEmpty()) {
      return;
    }

    consumer.accept(pluginDescriptors);
  });
}
 
Example #27
Source File: InstalledPluginsState.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static InstalledPluginsState getInstance() {
  Application application = ApplicationManager.getApplication();
  if (application == null) {
    throw new IllegalArgumentException("app is not loaded");
  }
  return ServiceManager.getService(InstalledPluginsState.class);
}
 
Example #28
Source File: EdtExecutorServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@Nonnull Runnable command) {
  Application application = ApplicationManager.getApplication();
  if (application == null) {
    SwingUtilities.invokeLater(command);
  }
  else {
    execute(command, application.getAnyModalityState());
  }
}
 
Example #29
Source File: RecentProjectsManagerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected RecentProjectsManagerBase(@Nonnull Application application) {
  MessageBusConnection connection = application.getMessageBus().connect();
  connection.subscribe(AppLifecycleListener.TOPIC, new MyAppLifecycleListener());
  if (!application.isHeadlessEnvironment()) {
    connection.subscribe(ProjectManager.TOPIC, new MyProjectListener());
  }
}
 
Example #30
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unused") // ECJ compiler for some reason thinks handlerService == null is always false
private static boolean executeCommandClientSide(Command command, Document document) {
    Application workbench = ApplicationManager.getApplication();
    if (workbench == null) {
        return false;
    }
    URI context = LSPIJUtils.toUri(document);
    AnAction parameterizedCommand = createEclipseCoreCommand(command, context, workbench);
    if (parameterizedCommand == null) {
        return false;
    }
    DataContext dataContext = createDataContext(command, context, workbench);
    ActionUtil.invokeAction(parameterizedCommand, dataContext, ActionPlaces.UNKNOWN, null, null);
    return true;
}