com.intellij.openapi.application.ex.ApplicationEx Java Examples

The following examples show how to use com.intellij.openapi.application.ex.ApplicationEx. 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: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean runActionAndCancelBeforeWrite(@Nonnull ApplicationEx application, @Nonnull Runnable cancellation, @Nonnull Runnable action) {
  if (isWriting(application)) {
    cancellation.run();
    return false;
  }

  ourWACancellations.add(cancellation);
  try {
    if (isWriting(application)) {
      // the listener might not be notified if write action was requested concurrently with listener addition
      cancellation.run();
      return false;
    }
    else {
      action.run();
      return true;
    }
  }
  finally {
    ourWACancellations.remove(cancellation);
  }
}
 
Example #2
Source File: LoadAllVfsStoredContentsAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  ApplicationEx application = ApplicationManagerEx.getApplicationEx();
  String m = "Started loading content";
  LOG.info(m);
  System.out.println(m);
  long start = System.currentTimeMillis();

  count.set(0);
  totalSize.set(0);
  application.runProcessWithProgressSynchronously(() -> {
    PersistentFS vfs = (PersistentFS)application.getComponent(ManagingFS.class);
    VirtualFile[] roots = vfs.getRoots();
    for (VirtualFile root : roots) {
      iterateCached(root);
    }
  }, "Loading", false, null);

  long end = System.currentTimeMillis();
  String message = "Finished loading content of " + count + " files. " + "Total size=" + StringUtil.formatFileSize(totalSize.get()) + ". " + "Elapsed=" + ((end - start) / 1000) + "sec.";
  LOG.info(message);
  System.out.println(message);
}
 
Example #3
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 #4
Source File: RootUIBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void build(@Nonnull Window window) {
  Disposer.register(window, () -> {
    WebApplication application = WebApplication.getInstance();
    if (application == null || !((ApplicationEx)application).isLoaded()) {
      return;
    }

    WriteAction.run(() -> {
      ProjectManager projectManager = ProjectManager.getInstance();

      Project[] openProjects = projectManager.getOpenProjects();

      for (Project openProject : openProjects) {
        projectManager.closeProject(openProject);
      }
    });
  });

  window.setContent(new WebLoadingPanelImpl());

  UIAccess access = UIAccess.current();

  scheduleWelcomeFrame(access, window);
}
 
Example #5
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 #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: WebPostStarter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void main(StatCollector stat, Runnable appInitalizeMark, ApplicationEx app, boolean newConfigFolder, @Nonnull CommandLineArgs args) {
  StartupProgress startupProgress = mySplashRef.get();
  if (startupProgress != null) {
    startupProgress.dispose();
    mySplashRef.set(null);
  }

  appInitalizeMark.run();

  /*AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(() -> {
    System.out.println("Save All");

    Application application = ApplicationManager.getApplication();
    if(application == null || application.isDisposed()) {
      return;
    }

    SwingUtilities.invokeLater(() -> application.saveSettings());
  }, 1, 5, TimeUnit.MINUTES); */
}
 
Example #8
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean runWithWriteActionPriority(@Nonnull Runnable action, @Nonnull ProgressIndicator progressIndicator) {
  ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    throw new IllegalStateException("Must not call from EDT");
  }
  Runnable cancellation = indicatorCancellation(progressIndicator);
  if (isWriting(application)) {
    cancellation.run();
    return false;
  }
  return ProgressManager.getInstance().runProcess(() -> {
    try {
      // add listener inside runProcess to avoid cancelling indicator before even starting the progress
      return runActionAndCancelBeforeWrite(application, cancellation, action);
    }
    catch (ProcessCanceledException ignore) {
      return false;
    }
  }, progressIndicator);
}
 
Example #9
Source File: RefreshQueueImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void execute(@Nonnull RefreshSessionImpl session) {
  if (session.isAsynchronous()) {
    queueSession(session, session.getTransaction());
  }
  else {
    if (myApplication.isWriteThread()) {
      ((TransactionGuardEx)TransactionGuard.getInstance()).assertWriteActionAllowed();
      doScan(session);
      session.fireEvents(session.getEvents(), null);
    }
    else {
      if (((ApplicationEx)myApplication).holdsReadLock()) {
        LOG.error("Do not call synchronous refresh under read lock (except from EDT) - " + "this will cause a deadlock if there are any events to fire.");
        return;
      }
      queueSession(session, TransactionGuard.getInstance().getContextTransaction());
      session.waitFor();
    }
  }
}
 
Example #10
Source File: ProjectImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected ProjectImpl(@Nonnull Application application, @Nonnull ProjectManager manager, @Nonnull String dirPath, boolean isOptimiseTestLoadSpeed, String projectName, boolean noUIThread) {
  super(application, "Project " + (projectName == null ? dirPath : projectName), ExtensionAreaId.PROJECT);
  myApplication = (ApplicationEx)application;
  myDirPath = dirPath;

  putUserData(CREATION_TIME, System.nanoTime());

  if (myApplication.isUnitTestMode()) {
    putUserData(CREATION_TRACE, DebugUtil.currentStackTrace());
  }

  if (!isDefault()) {
    if (noUIThread) {
      getStateStore().setProjectFilePathNoUI(dirPath);
    }
    else {
      getStateStore().setProjectFilePath(dirPath);
    }
  }

  myOptimiseTestLoadSpeed = isOptimiseTestLoadSpeed;

  myManager = manager;

  myName = projectName;
}
 
Example #11
Source File: DesktopTransactionGuardImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean areAssertionsEnabled() {
  Application app = ApplicationManager.getApplication();
  if (app.isUnitTestMode() && !ourTestingTransactions) {
    return false;
  }
  if (app instanceof ApplicationEx && !((ApplicationEx)app).isLoaded()) {
    return false;
  }
  return Registry.is("ide.require.transaction.for.model.changes", false);
}
 
Example #12
Source File: BaseApplication.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void createLocatorFile() {
  ContainerPathManager containerPathManager = ContainerPathManager.get();
  File locatorFile = new File(containerPathManager.getSystemPath() + "/" + ApplicationEx.LOCATOR_FILE_NAME);
  try {
    byte[] data = containerPathManager.getHomePath().getBytes(CharsetToolkit.UTF8_CHARSET);
    FileUtil.writeToFile(locatorFile, data);
  }
  catch (IOException e) {
    LOG.warn("can't store a location in '" + locatorFile + "'", e);
  }
}
 
Example #13
Source File: RootUIBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void scheduleWelcomeFrame(UIAccess access, Window window) {
  AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
    WebApplication application = WebApplication.getInstance();
    if (application == null || !((ApplicationEx)application).isLoaded()) {
      if (access.isValid()) {
        scheduleWelcomeFrame(access, window);
      }
      return;
    }

    if (access.isValid()) {
      access.give(() -> showWelcomeFrame(application, window));
    }
  }, 1, TimeUnit.SECONDS);
}
 
Example #14
Source File: BaseApplication.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void bootstrapInjectingContainer(@Nonnull InjectingContainerBuilder builder) {
  super.bootstrapInjectingContainer(builder);

  builder.bind(Application.class).to(this);
  builder.bind(ApplicationEx.class).to(this);
  builder.bind(ApplicationEx2.class).to(this);
  builder.bind(ApplicationInfo.class).to(ApplicationInfo::getInstance);
  builder.bind(ContainerPathManager.class).to(ContainerPathManager::get);

  builder.bind(IApplicationStore.class).to(ApplicationStoreImpl.class).forceSingleton();
  builder.bind(ApplicationPathMacroManager.class).to(ApplicationPathMacroManager.class).forceSingleton();

  builder.bind(FileTypeRegistry.class).to(FileTypeManager::getInstance);
}
 
Example #15
Source File: LocatorTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void test() throws Exception {
  File locatorFile = new File(ContainerPathManager.get().getSystemPath() + "/" + ApplicationEx.LOCATOR_FILE_NAME);
  assertTrue(locatorFile.getPath(), locatorFile.canRead());

  String home = FileUtil.loadFile(locatorFile, "UTF-8");
  assertTrue(home, StringUtil.isNotEmpty(home));

  assertEquals(home, ContainerPathManager.get().getHomePath());
}
 
Example #16
Source File: PathMacroManagerTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Before
public final void setupApplication() throws Exception {
  // in fact the test accesses extension points so it rather should be converted to a platform one
  assumeNotNull(ApplicationManager.getApplication());

  context = new JUnit4Mockery();
  context.setImposteriser(ClassImposteriser.INSTANCE);
  myApplication = context.mock(ApplicationEx.class, "application");

  context.checking(new Expectations() {
    {
      allowing(myApplication).isUnitTestMode();
      will(returnValue(false));

      // some tests leave invokeLater()'s after them
      allowing(myApplication).invokeLater(with(any(Runnable.class)), with(any(ModalityState.class)));

      allowing(myApplication).runReadAction(with(any(Runnable.class)));
      will(new Action() {
        @Override
        public void describeTo(final Description description) {
          description.appendText("runs runnable");
        }

        @Override
        @javax.annotation.Nullable
        public Object invoke(final Invocation invocation) throws Throwable {
          ((Runnable)invocation.getParameter(0)).run();
          return null;
        }
      });
    }
  });
}
 
Example #17
Source File: LatteIdeHelper.java    From intellij-latte with MIT License 5 votes vote down vote up
public static boolean holdsReadLock() {
    Application app = ApplicationManager.getApplication();
    try {
        return ((ApplicationEx)app).holdsReadLock();
    } catch (IllegalStateException e) {
        return false;
    }
}
 
Example #18
Source File: ProjectSettingsForm.java    From EclipseCodeFormatter with Apache License 2.0 5 votes vote down vote up
public ListPopup createConfirmation(String title, final String yesText, String noText, final Runnable onYes, final Runnable onNo, int defaultOptionIndex) {

		final BaseListPopupStep<String> step = new BaseListPopupStep<String>(title, new String[]{yesText, noText}) {
			@Override
			public PopupStep onChosen(String selectedValue, final boolean finalChoice) {
				if (selectedValue.equals(yesText)) {
					onYes.run();
				} else {
					onNo.run();
				}
				return FINAL_CHOICE;
			}

			@Override
			public void canceled() {
			}

			@Override
			public boolean isMnemonicsNavigationEnabled() {
				return true;
			}
		};
		step.setDefaultOptionIndex(defaultOptionIndex);

		final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
		return app == null || !app.isUnitTestMode() ? new ListPopupImpl(step) : new MockConfirmation(step, yesText);
	}
 
Example #19
Source File: DesktopApplicationPostStarter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@RequiredUIAccess
public void main(StatCollector stat, Runnable appInitializeMark, ApplicationEx app, boolean newConfigFolder, @Nonnull CommandLineArgs args) {
  SystemDock.getInstance().updateMenu();

  // if OS has dock, RecentProjectsManager will be already created, but not all OS have dock, so, we trigger creation here to ensure that RecentProjectsManager app listener will be added
  RecentProjectsManager.getInstance();

  // Event queue should not be changed during initialization of application components.
  // It also cannot be changed before initialization of application components because IdeEventQueue uses other
  // application components. So it is proper to perform replacement only here.
  DesktopWindowManagerImpl windowManager = (DesktopWindowManagerImpl)WindowManager.getInstance();
  IdeEventQueue.getInstance().setWindowManager(windowManager);

  RecentProjectsManagerBase recentProjectsManager = RecentProjectsManagerBase.getInstanceEx();

  appInitializeMark.run();

  stat.dump("Startup statistics", LOG::info);

  PluginLoadStatistics.get().dumpPluginClassStatistics(LOG::info);

  app.invokeAndWait(() -> {
    StartupProgress desktopSplash = mySplashRef.get();
    if (desktopSplash != null) {
      desktopSplash.dispose();
      mySplashRef.set(null);  // Allow GC collect the splash window
    }
  }, ModalityState.NON_MODAL);

  if (newConfigFolder && !ApplicationProperties.isInSandbox()) {
    FirstStartCustomizeUtil.show(true);
  }

  boolean willOpenProject = recentProjectsManager.willReopenProjectOnStart() && !args.isNoRecentProjects();

  AppLifecycleListener lifecyclePublisher = app.getMessageBus().syncPublisher(AppLifecycleListener.TOPIC);
  lifecyclePublisher.appFrameCreated(args, willOpenProject);

  if (recentProjectsManager.willReopenProjectOnStart() && !args.isNoRecentProjects()) {
    windowManager.showFrame();
  }
  else {
    WelcomeFrameManager.getInstance().showFrame();
  }

  app.invokeLater(() -> {
    if (!args.isNoRecentProjects()) {
      AsyncResult<Project> projectFromCommandLine = AsyncResult.rejected();

      if (myApplicationStarter.isPerformProjectLoad()) {
        projectFromCommandLine = CommandLineProcessor.processExternalCommandLine(args, null);
      }

      projectFromCommandLine.doWhenRejected(recentProjectsManager::doReopenLastProject);
    }

    SwingUtilities.invokeLater(() -> reportPluginError(myPluginsInitializeInfo));

    UsageTrigger.trigger("consulo.app.started");
  }, ModalityState.NON_MODAL);
}
 
Example #20
Source File: DialogWrapperPeerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void show() {
  final DialogWrapper dialogWrapper = getDialogWrapper();
  boolean isAutoAdjustable = dialogWrapper.isAutoAdjustable();
  Point location = null;
  if (isAutoAdjustable) {
    pack();

    Dimension packedSize = getSize();
    Dimension minSize = getMinimumSize();
    setSize(Math.max(packedSize.width, minSize.width), Math.max(packedSize.height, minSize.height));

    setSize((int)(getWidth() * dialogWrapper.getHorizontalStretch()), (int)(getHeight() * dialogWrapper.getVerticalStretch()));

    // Restore dialog's size and location

    myDimensionServiceKey = dialogWrapper.getDimensionKey();

    if (myDimensionServiceKey != null) {
      final Project projectGuess = DataManager.getInstance().getDataContext((Component)this).getData(CommonDataKeys.PROJECT);
      location = getWindowStateService(projectGuess).getLocation(myDimensionServiceKey);
      Dimension size = getWindowStateService(projectGuess).getSize(myDimensionServiceKey);
      if (size != null) {
        myInitialSize = new Dimension(size);
        _setSizeForLocation(myInitialSize.width, myInitialSize.height, location);
      }
    }

    if (myInitialSize == null) {
      myInitialSize = getSize();
    }
  }

  if (location == null) {
    location = dialogWrapper.getInitialLocation();
  }

  if (location != null) {
    setLocation(location);
  }
  else {
    setLocationRelativeTo(getOwner());
  }

  if (isAutoAdjustable) {
    final Rectangle bounds = getBounds();
    ScreenUtil.fitToScreen(bounds);
    setBounds(bounds);
  }

  if (Registry.is("actionSystem.fixLostTyping")) {
    final IdeEventQueue queue = IdeEventQueue.getInstance();
    if (queue != null) {
      queue.getKeyEventDispatcher().resetState();
    }

  }

  // Workaround for switching workspaces on dialog show
  if (SystemInfo.isMac && myProject != null && Registry.is("ide.mac.fix.dialog.showing") && !dialogWrapper.isModalProgress()) {
    final IdeFrame frame = WindowManager.getInstance().getIdeFrame(myProject.get());
    AppIcon.getInstance().requestFocus(frame);
  }

  setBackground(UIUtil.getPanelBackground());

  final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
  if (app != null && !app.isLoaded() && DesktopSplash.BOUNDS != null) {
    final Point loc = getLocation();
    loc.y = DesktopSplash.BOUNDS.y + DesktopSplash.BOUNDS.height;
    setLocation(loc);
  }
  super.show();
}
 
Example #21
Source File: ReplaceInProjectManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
private boolean replaceUsages(@Nonnull ReplaceContext replaceContext, @Nonnull Collection<Usage> usages) {
  if (!ensureUsagesWritable(replaceContext, usages)) {
    return true;
  }

  int[] replacedCount = {0};
  final boolean[] success = {true};

  success[0] &= ((ApplicationEx)ApplicationManager.getApplication())
          .runWriteActionWithCancellableProgressInDispatchThread(FindBundle.message("find.replace.all.confirmation.title"), myProject, null, indicator -> {
            indicator.setIndeterminate(false);
            int processed = 0;
            VirtualFile lastFile = null;

            for (final Usage usage : usages) {
              ++processed;
              indicator.checkCanceled();
              indicator.setFraction((float)processed / usages.size());

              if (usage instanceof UsageInFile) {
                VirtualFile virtualFile = ((UsageInFile)usage).getFile();
                if (virtualFile != null && !virtualFile.equals(lastFile)) {
                  indicator.setText2(virtualFile.getPresentableUrl());
                  lastFile = virtualFile;
                }
              }

              ProgressManager.getInstance().executeNonCancelableSection(() -> {
                try {
                  if (replaceUsage(usage, replaceContext.getFindModel(), replaceContext.getExcludedSetCached(), false)) {
                    replacedCount[0]++;
                  }
                }
                catch (FindManager.MalformedReplacementStringException ex) {
                  markAsMalformedReplacement(replaceContext, usage);
                  success[0] = false;
                }
              });
            }
          });

  replaceContext.getUsageView().removeUsagesBulk(usages);
  reportNumberReplacedOccurrences(myProject, replacedCount[0]);
  return success[0];
}
 
Example #22
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 #23
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 #24
Source File: ApplicationPostStarter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void main(StatCollector stat, Runnable appInitalizeMark, ApplicationEx app, boolean newConfigFolder, @Nonnull CommandLineArgs args) {
}
 
Example #25
Source File: Invoker.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @param task    a task to execute on the valid thread
 * @param promise an object to control task processing
 * @param attempt an attempt to run the specified task
 */
private void invokeSafely(@Nonnull Runnable task, @Nonnull AsyncPromise<?> promise, int attempt) {
  try {
    if (canInvoke(task, promise)) {
      if (getApplication() == null) {
        task.run(); // is not interruptible in tests without application
      }
      else if (useReadAction != ThreeState.YES || isDispatchThread()) {
        ProgressManager.getInstance().runProcess(task, indicator(promise));
      }
      else if (getApplication().isReadAccessAllowed()) {
        if (((ApplicationEx)getApplication()).isWriteActionPending()) {
          offerRestart(task, promise, attempt);
          return;
        }
        ProgressManager.getInstance().runProcess(task, indicator(promise));
      }
      else {
        // try to execute a task until it stops throwing ProcessCanceledException
        while (!ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(task, indicator(promise))) {
          if (!is("invoker.can.yield.to.pending.write.actions")) {
            offerRestart(task, promise, attempt);
            return;
          }
          if (!canInvoke(task, promise)) return; // stop execution of obsolete task
          ProgressIndicatorUtils.yieldToPendingWriteActions();
          if (!canRestart(task, promise, attempt)) return;
          LOG.debug("Task is restarted");
          attempt++;
        }
      }
      promise.setResult(null);
    }
  }
  catch (ProcessCanceledException | IndexNotReadyException exception) {
    offerRestart(task, promise, attempt);
  }
  catch (Throwable throwable) {
    try {
      LOG.error(throwable);
    }
    finally {
      promise.setError(throwable);
    }
  }
  finally {
    count.decrementAndGet();
  }
}
 
Example #26
Source File: TabbedPaneWrapper.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void assertIsDispatchThread() {
  final ApplicationEx application = ApplicationManagerEx.getApplicationEx();
  if (application != null){
    application.assertIsDispatchThread(myTabbedPane.getComponent());
  }
}
 
Example #27
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean isWriting(ApplicationEx application) {
  return application.isWriteActionPending() || application.isWriteActionInProgress();
}
 
Example #28
Source File: LightPlatformTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public final void runBare() throws Throwable {
  if (!shouldRunTest()) {
    return;
  }

  final Throwable[] throwables = new Throwable[1];

  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      try {
        ourTestThread = Thread.currentThread();
        startRunAndTear();
      }
      catch (Throwable throwable) {
        throwables[0] = throwable;
      }
      finally {
        ourTestThread = null;
        try {
          Application application = ApplicationManager.getApplication();
          if (application instanceof ApplicationEx) {
            PlatformTestCase.cleanupApplicationCaches(ourProject);
          }
          resetAllFields();
        }
        catch (Throwable e) {
          e.printStackTrace();
        }
      }
    }
  });

  if (throwables[0] != null) {
    throw throwables[0];
  }

  // just to make sure all deferred Runnables to finish
  UIUtil.invokeAndWaitIfNeeded(EmptyRunnable.getInstance());
}
 
Example #29
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);
}