Java Code Examples for com.intellij.openapi.util.AsyncResult#undefined()

The following examples show how to use com.intellij.openapi.util.AsyncResult#undefined() . 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: DesktopToolWindowImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public AsyncResult<Void> getReady(@Nonnull final Object requestor) {
  final AsyncResult<Void> result = AsyncResult.undefined();
  myShowing.getReady(this).doWhenDone(() -> {
    ArrayList<FinalizableCommand> cmd = new ArrayList<>();
    cmd.add(new FinalizableCommand(null) {
      @Override
      public void run() {
        IdeFocusManager.getInstance(myToolWindowManager.getProject()).doWhenFocusSettlesDown(() -> {
          if (myContentManager.isDisposed()) return;
          myContentManager.getReady(requestor).notify(result);
        });
      }
    });
    myToolWindowManager.execute(cmd);
  });
  return result;
}
 
Example 2
Source File: DialogWrapper.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@RequiredUIAccess
public AsyncResult<Void> showAsync() {
  UIAccess uiAccess = UIAccess.current();

  AsyncResult<Void> result = AsyncResult.undefined();
  showInternal().doWhenProcessed(() -> {
    if (isOK()) {
      result.setDone();
    }
    else {
      result.setRejected();
    }
  });
  return result;
}
 
Example 3
Source File: LazyUiDisposable.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static AsyncResult<Disposable> findDisposable(Disposable defaultValue, final Key<? extends Disposable> key) {
  if (defaultValue == null) {
    if (ApplicationManager.getApplication() != null) {
      final AsyncResult<Disposable> result = AsyncResult.undefined();
      DataManager.getInstance().getDataContextFromFocus().doWhenDone(context -> {
        Disposable disposable = context.getData(key);
        if (disposable == null) {
          disposable = Disposer.get("ui");
        }
        result.setDone(disposable);
      });
      return result;
    }
    else {
      return null;
    }
  }
  else {
    return AsyncResult.done(defaultValue);
  }
}
 
Example 4
Source File: AccessRule.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static <T> AsyncResult<T> readAsync(@RequiredReadAction @Nonnull ThrowableComputable<T, Throwable> action) {
  AsyncResult<T> result = AsyncResult.undefined();
  Application application = Application.get();
  AppExecutorUtil.getAppExecutorService().execute(() -> {
    try {
      result.setDone(application.runReadAction(action));
    }
    catch (Throwable throwable) {
      LOG.error(throwable);

      result.rejectWithThrowable(throwable);
    }
  });
  return result;
}
 
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: ModuleImportProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Will execute module importing. Will show popup for selecting import providers if more that one, and then show import wizard
 *
 * @param project - null mean its new project creation
 * @return
 */
@RequiredUIAccess
public static <C extends ModuleImportContext> AsyncResult<Pair<C, ModuleImportProvider<C>>> showFileChooser(@Nullable Project project, @Nullable FileChooserDescriptor chooserDescriptor) {
  boolean isModuleImport = project != null;

  FileChooserDescriptor descriptor = ObjectUtil.notNull(chooserDescriptor, createAllImportDescriptor(isModuleImport));

  VirtualFile toSelect = null;
  String lastLocation = PropertiesComponent.getInstance().getValue(LAST_IMPORTED_LOCATION);
  if (lastLocation != null) {
    toSelect = LocalFileSystem.getInstance().refreshAndFindFileByPath(lastLocation);
  }

  AsyncResult<Pair<C, ModuleImportProvider<C>>> result = AsyncResult.undefined();

  AsyncResult<VirtualFile> fileChooseAsync = FileChooser.chooseFile(descriptor, project, toSelect);
  fileChooseAsync.doWhenDone((f) -> {
    PropertiesComponent.getInstance().setValue(LAST_IMPORTED_LOCATION, f.getPath());

    showImportChooser(project, f, AsyncResult.undefined());
  });

  fileChooseAsync.doWhenRejected((Runnable)result::setRejected);

  return result;
}
 
Example 7
Source File: ProjectUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static AsyncResult<Integer> confirmOpenNewProjectAsync(UIAccess uiAccess, boolean isNewProject) {
  final GeneralSettings settings = GeneralSettings.getInstance();
  int confirmOpenNewProject = settings.getConfirmOpenNewProject();
  if (confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK) {
    Alert<Integer> alert = Alert.create();
    alert.asQuestion();
    alert.remember(ProjectNewWindowDoNotAskOption.INSTANCE);
    alert.title(isNewProject ? IdeBundle.message("title.new.project") : IdeBundle.message("title.open.project"));
    alert.text(IdeBundle.message("prompt.open.project.in.new.frame"));

    alert.button(IdeBundle.message("button.existingframe"), () -> GeneralSettings.OPEN_PROJECT_SAME_WINDOW);
    alert.asDefaultButton();

    alert.button(IdeBundle.message("button.newframe"), () -> GeneralSettings.OPEN_PROJECT_NEW_WINDOW);

    alert.button(Alert.CANCEL, Alert.CANCEL);
    alert.asExitButton();

    AsyncResult<Integer> result = AsyncResult.undefined();
    uiAccess.give(() -> alert.showAsync().notify(result));
    return result;
  }

  return AsyncResult.resolved(confirmOpenNewProject);
}
 
Example 8
Source File: WebUIAccessImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public <T> AsyncResult<T> give(@Nonnull Supplier<T> supplier) {
  AsyncResult<T> result = AsyncResult.undefined();
  if (isValid()) {
    myUI.access(() -> {
      try {
        result.setDone(supplier.get());
      }
      catch (Throwable e) {
        LOGGER.error(e);
        result.rejectWithThrowable(e);
      }
    });
  }
  else {
    result.setDone();
  }
  return result;
}
 
Example 9
Source File: AbstractToolBeforeRunTask.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public AsyncResult<Void> execute(UIAccess uiAccess, final DataContext context, final long executionId) {
  AsyncResult<Void> result = AsyncResult.undefined();
  uiAccess.give(() -> {
    boolean runToolResult = ToolAction.runTool(myToolActionId, context, null, executionId, new ProcessAdapter() {
      @Override
      public void processTerminated(ProcessEvent event) {
        if(event.getExitCode() == 0) {
          result.setDone();
        }
        else {
          result.setRejected();
        }
      }
    });

    if(!runToolResult) {
      result.setRejected();
    }
  }).doWhenRejectedWithThrowable(result::rejectWithThrowable);

  return result;
}
 
Example 10
Source File: BaseDataManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public AsyncResult<DataContext> getDataContextFromFocus() {
  AsyncResult<DataContext> context = AsyncResult.undefined();
  IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> context.setDone(getDataContext()), ModalityState.current());
  return context;
}
 
Example 11
Source File: ProjectStructureConfigurable.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncResult<Void> navigateTo(@Nullable final Place place, final boolean requestFocus) {
  if(myProjectStructureDialog == null) {
    return AsyncResult.rejected();
  }
  final Configurable toSelect = (Configurable)place.getPath(CATEGORY);

  if (mySelectedConfigurable != toSelect) {
    if (mySelectedConfigurable instanceof BaseStructureConfigurable) {
      ((BaseStructureConfigurable)mySelectedConfigurable).onStructureUnselected();
    }
    removeSelected();

    if (toSelect != null) {
      myProjectStructureDialog.accept(toSelect);
    }

    setSelectedConfigurable(toSelect);

    if (toSelect instanceof MasterDetailsComponent) {
      final MasterDetailsComponent masterDetails = (MasterDetailsComponent)toSelect;

      masterDetails.setHistory(myHistory);
    }

    if (toSelect instanceof BaseStructureConfigurable) {
      ((BaseStructureConfigurable)toSelect).onStructureSelected();
    }
  }

  final AsyncResult<Void> result = AsyncResult.undefined();
  Place.goFurther(toSelect, place, requestFocus).notifyWhenDone(result);

  if (!myHistory.isNavigatingNow() && mySelectedConfigurable != null) {
    myHistory.pushQueryPlace();
  }

  return result;
}
 
Example 12
Source File: BuildArtifactsBeforeRunTaskProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public AsyncResult<Void> executeTaskAsync(UIAccess uiAccess, DataContext context, RunConfiguration configuration, ExecutionEnvironment env, BuildArtifactsBeforeRunTask task) {
  AsyncResult<Void> result = AsyncResult.undefined();

  final List<Artifact> artifacts = new ArrayList<>();
  AccessRule.read(() -> {
    for (ArtifactPointer pointer : task.getArtifactPointers()) {
      ContainerUtil.addIfNotNull(artifacts, pointer.get());
    }
  });

  final CompileStatusNotification callback = (aborted, errors, warnings, compileContext) -> {
    if(!aborted && errors == 0) {
      result.setDone();
    }
    else {
      result.setRejected();
    }
  };

  final Condition<Compiler> compilerFilter = compiler -> compiler instanceof ArtifactsCompiler || compiler instanceof ArtifactAwareCompiler && ((ArtifactAwareCompiler)compiler).shouldRun(artifacts);

  uiAccess.give(() -> {
    final CompilerManager manager = CompilerManager.getInstance(myProject);
    manager.make(ArtifactCompileScope.createArtifactsScope(myProject, artifacts), compilerFilter, callback);
  }).doWhenRejectedWithThrowable(result::rejectWithThrowable);

  return result;
}
 
Example 13
Source File: ChooseComponentsToExportDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredUIAccess
public static AsyncResult<String> chooseSettingsFile(String oldPath, Component parent, final String title, final String description) {
  FileChooserDescriptor chooserDescriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor();
  chooserDescriptor.setDescription(description);
  chooserDescriptor.setHideIgnored(false);
  chooserDescriptor.setTitle(title);

  VirtualFile initialDir;
  if (oldPath != null) {
    final File oldFile = new File(oldPath);
    initialDir = LocalFileSystem.getInstance().findFileByIoFile(oldFile);
    if (initialDir == null && oldFile.getParentFile() != null) {
      initialDir = LocalFileSystem.getInstance().findFileByIoFile(oldFile.getParentFile());
    }
  }
  else {
    initialDir = null;
  }
  final AsyncResult<String> result = AsyncResult.undefined();
  AsyncResult<VirtualFile[]> fileAsyncResult = FileChooser.chooseFiles(chooserDescriptor, null, parent, initialDir);
  fileAsyncResult.doWhenDone(files -> {
    VirtualFile file = files[0];
    if (file.isDirectory()) {
      result.setDone(file.getPath() + '/' + new File(DEFAULT_PATH).getName());
    }
    else {
      result.setDone(file.getPath());
    }
  });
  fileAsyncResult.doWhenRejected((Runnable)result::setRejected);
  return result;
}
 
Example 14
Source File: WebPathChooserDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Nonnull
@Override
public AsyncResult<VirtualFile[]> chooseAsync(@Nullable Project project, @Nonnull VirtualFile[] toSelect) {
  AsyncResult<VirtualFile[]> result = AsyncResult.undefined();
  DialogImpl dialog = new DialogImpl(project, myDescriptor, result);
  dialog.showAsync();
  return result;
}
 
Example 15
Source File: FileChooser.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Shows file/folder open dialog, allows user to choose file/folder and then passes result to callback in EDT.
 *
 * @param descriptor file chooser descriptor
 * @param project    project
 * @param parent     parent component
 * @param toSelect   file to preselect
 */
@Nonnull
@RequiredUIAccess
public static AsyncResult<VirtualFile> chooseFile(@Nonnull final FileChooserDescriptor descriptor, @Nullable Project project, @Nullable Component parent, @Nullable VirtualFile toSelect) {
  LOG.assertTrue(!descriptor.isChooseMultiple());
  AsyncResult<VirtualFile> result = AsyncResult.undefined();

  AsyncResult<VirtualFile[]> filesAsync = chooseFiles(descriptor, project, parent, toSelect);
  filesAsync.doWhenDone((f) -> result.setDone(f[0]));
  filesAsync.doWhenRejected((Runnable)result::setRejected);
  return result;
}
 
Example 16
Source File: WinPathChooserDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredUIAccess
@Nonnull
@Override
public AsyncResult<VirtualFile[]> chooseAsync(@Nullable VirtualFile toSelect) {
  if (toSelect != null && toSelect.getParent() != null) {

    String directoryName;
    String fileName = null;
    if (toSelect.isDirectory()) {
      directoryName = toSelect.getCanonicalPath();
    }
    else {
      directoryName = toSelect.getParent().getCanonicalPath();
      fileName = toSelect.getPath();
    }
    myFileDialog.setDirectory(directoryName);
    myFileDialog.setFile(fileName);
  }


  myFileDialog.setFilenameFilter((dir, name) -> {
    File file = new File(dir, name);
    return myFileChooserDescriptor.isFileSelectable(fileToVirtualFile(file));
  });

  myFileDialog.setMultipleMode(myFileChooserDescriptor.isChooseMultiple());

  AsyncResult<VirtualFile[]> result = AsyncResult.undefined();
  SwingUtilities.invokeLater(() -> {
    final CommandProcessorEx commandProcessor = ApplicationManager.getApplication() != null ? (CommandProcessorEx)CommandProcessor.getInstance() : null;
    final boolean appStarted = commandProcessor != null;

    if (appStarted) {
      commandProcessor.enterModal();
      LaterInvocator.enterModal(myFileDialog);
    }

    Component parent = myParent.get();
    try {
      myFileDialog.setVisible(true);
    }
    finally {
      if (appStarted) {
        commandProcessor.leaveModal();
        LaterInvocator.leaveModal(myFileDialog);
        if (parent != null) parent.requestFocus();
      }
    }

    File[] files = myFileDialog.getFiles();
    List<VirtualFile> virtualFileList = getChosenFiles(Stream.of(files));
    virtualFiles = virtualFileList.toArray(VirtualFile.EMPTY_ARRAY);

    if (!virtualFileList.isEmpty()) {
      try {
        if (virtualFileList.size() == 1) {
          myFileChooserDescriptor.isFileSelectable(virtualFileList.get(0));
        }
        myFileChooserDescriptor.validateSelectedFiles(virtualFiles);
      }
      catch (Exception e) {
        if (parent == null) {
          Messages.showErrorDialog(myProject, e.getMessage(), myTitle);
        }
        else {
          Messages.showErrorDialog(parent, e.getMessage(), myTitle);
        }

        result.setRejected();
        return;
      }

      if (!ArrayUtil.isEmpty(files)) {
        result.setDone(VfsUtil.toVirtualFileArray(virtualFileList));
      }
      else {
        result.setRejected();
      }
    }
  });
  return result;
}
 
Example 17
Source File: CompileStepBeforeRun.java    From consulo with Apache License 2.0 4 votes vote down vote up
static AsyncResult<Void> doMake(UIAccess uiAccess, final Project myProject, final RunConfiguration configuration, final boolean ignoreErrors) {
  if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
    return AsyncResult.rejected();
  }

  if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase)configuration).excludeCompileBeforeLaunchOption()) {
    return AsyncResult.resolved();
  }

  final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption)configuration;
  AsyncResult<Void> result = AsyncResult.undefined();
  try {
    final CompileStatusNotification callback = (aborted, errors, warnings, compileContext) -> {
      if ((errors == 0 || ignoreErrors) && !aborted) {
        result.setDone();
      }
      else {
        result.setRejected();
      }
    };

    TransactionGuard.submitTransaction(myProject, () -> {
      CompileScope scope;
      final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
      if (Comparing.equal(Boolean.TRUE.toString(), System.getProperty(MAKE_PROJECT_ON_RUN_KEY))) {
        // user explicitly requested whole-project make
        scope = compilerManager.createProjectCompileScope();
      }
      else {
        final Module[] modules = runConfiguration.getModules();
        if (modules.length > 0) {
          for (Module module : modules) {
            if (module == null) {
              LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + runConfiguration.getClass().getName());
            }
          }
          scope = compilerManager.createModulesCompileScope(modules, true);
        }
        else {
          scope = compilerManager.createProjectCompileScope();
        }
      }

      if (!myProject.isDisposed()) {
        compilerManager.make(scope, callback);
      }
      else {
        result.setRejected();
      }
    });
  }
  catch (Exception e) {
    result.rejectWithThrowable(e);
  }

  return result;
}
 
Example 18
Source File: PooledAsyncResult.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static <V> AsyncResult<V> create(@Nonnull Supplier<AsyncResult<V>> callable) {
  AsyncResult<V> result = AsyncResult.undefined();
  AppExecutorUtil.getAppExecutorService().execute(() -> callable.get().notify(result));
  return result;
}
 
Example 19
Source File: CallChain.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public AsyncResult<NewValue> tossAsync() {
  AsyncResult<NewValue> result = AsyncResult.undefined();
  toss(result::setDone);
  return result;
}
 
Example 20
Source File: RunConfigurationBeforeRunProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public AsyncResult<Void> executeTaskAsync(UIAccess uiAccess, DataContext context, RunConfiguration configuration, ExecutionEnvironment env, RunConfigurableBeforeRunTask task) {
  RunnerAndConfigurationSettings settings = task.getSettings();
  if (settings == null) {
    return AsyncResult.rejected();
  }
  final Executor executor = DefaultRunExecutor.getRunExecutorInstance();
  String executorId = executor.getId();
  final ProgramRunner runner = ProgramRunnerUtil.getRunner(executorId, settings);
  if (runner == null) return AsyncResult.rejected();
  final ExecutionEnvironment environment = new ExecutionEnvironment(executor, runner, settings, myProject);
  environment.setExecutionId(env.getExecutionId());
  if (!ExecutionTargetManager.canRun(settings, env.getExecutionTarget())) {
    return AsyncResult.rejected();
  }

  if (!runner.canRun(executorId, environment.getRunProfile())) {
    return AsyncResult.rejected();
  }
  else {
    AsyncResult<Void> result = AsyncResult.undefined();

    uiAccess.give(() -> {
      try {
        runner.execute(environment, descriptor -> {
          ProcessHandler processHandler = descriptor != null ? descriptor.getProcessHandler() : null;
          if (processHandler != null) {
            processHandler.addProcessListener(new ProcessAdapter() {
              @Override
              public void processTerminated(ProcessEvent event) {
                if(event.getExitCode() == 0) {
                  result.setDone();
                }
                else {
                  result.setRejected();
                }
              }
            });
          }
        });
      }
      catch (ExecutionException e) {
        result.setRejected();
        LOG.error(e);
      }
    }).doWhenRejectedWithThrowable(result::rejectWithThrowable);

    return result;
  }
}