下面列出了com.intellij.psi.PsiStatement#com.intellij.openapi.progress.Task 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Compiles the project and runs the task only if there are no compilation errors.
*/
private static void runAfterCompilationCheck(ProjectInfo projectInfo, Task task) {
ApplicationManager.getApplication().invokeLater(() -> {
List<PsiClass> classes = projectInfo.getClasses();
if (!classes.isEmpty()) {
VirtualFile[] virtualFiles = classes.stream()
.map(classObject -> classObject.getContainingFile().getVirtualFile()).toArray(VirtualFile[]::new);
Project project = projectInfo.getProject();
CompilerManager compilerManager = CompilerManager.getInstance(project);
CompileStatusNotification callback = (aborted, errors, warnings, compileContext) -> {
if (errors == 0 && !aborted) {
ProgressManager.getInstance().run(task);
} else {
task.onCancel();
AbstractRefactoringPanel.showCompilationErrorNotification(project);
}
};
CompileScope compileScope = compilerManager.createFilesCompileScope(virtualFiles);
compilerManager.make(compileScope, callback);
} else {
ProgressManager.getInstance().run(task);
}
});
}
protected ContentDiffRequest createDifference(final FileDifferenceModel m) {
final Ref<ContentDiffRequest> requestRef = new Ref<>();
new Task.Modal(myProject, message("message.processing.revisions"), false) {
public void run(@Nonnull final ProgressIndicator i) {
ApplicationManager.getApplication().runReadAction(() -> {
RevisionProcessingProgressAdapter p = new RevisionProcessingProgressAdapter(i);
p.processingLeftRevision();
DiffContent left = m.getLeftDiffContent(p);
p.processingRightRevision();
DiffContent right = m.getRightDiffContent(p);
requestRef.set(new SimpleDiffRequest(m.getTitle(), left, right, m.getLeftTitle(p), m.getRightTitle(p)));
});
}
}.queue();
return requestRef.get();
}
@Override
public JComponent getSearchComponent() {
myLogFilterCombo.setModel(new DefaultComboBoxModel(myFilters.toArray(new LogFilter[myFilters.size()])));
resetLogFilter();
myLogFilterCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final LogFilter filter = (LogFilter)myLogFilterCombo.getSelectedItem();
final Task.Backgroundable task = new Task.Backgroundable(myProject, APPLYING_FILTER_TITLE) {
@Override
public void run(@Nonnull ProgressIndicator indicator) {
myModel.selectFilter(filter);
}
};
ProgressManager.getInstance().run(task);
}
});
myTextFilterWrapper.removeAll();
myTextFilterWrapper.add(getTextFilterComponent());
return mySearchComponent;
}
public ZipAndQueue(final Project project, final int interval, final String title, final Runnable runnable) {
final int correctedInterval = interval <= 0 ? 300 : interval;
myZipperUpdater = new ZipperUpdater(correctedInterval, project);
myQueue = new BackgroundTaskQueue(project, title);
myInZipper = new Runnable() {
@Override
public void run() {
myQueue.run(myInvokedOnQueue);
}
};
myInvokedOnQueue = new Task.Backgroundable(project, title, false, BackgroundFromStartOption.getInstance()) {
@Override
public void run(@Nonnull ProgressIndicator indicator) {
runnable.run();
}
};
Disposer.register(project, new Disposable() {
@Override
public void dispose() {
myZipperUpdater.stop();
}
});
}
@Override
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
TreePath selPath = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
Question question = (Question) node.getUserObject();
if (!isOneOpen(node)) {
return;
} else if ("lock".equals(question.getStatus())) {
MessageUtils.showMsg(toolWindow.getContentManager().getComponent(), MessageType.INFO, "info", "no permissions");
throw new ExpandVetoException(event);
}
ProgressManager.getInstance().run(new Task.Backgroundable(project,"leetcode.editor.tree",false) {
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
loadData(question,node,selPath,tree,toolWindow);
}
});
throw new ExpandVetoException(event);
}
@Override
public void setSelected(AnActionEvent anActionEvent, boolean b) {
JTree tree = WindowFactory.getDataContext(anActionEvent.getProject()).getData(DataKeys.LEETCODE_PROJECTS_TREE);
Question question = ViewManager.getTreeQuestion(tree, anActionEvent.getProject());
if (question == null) {
return;
}
ProgressManager.getInstance().run(new Task.Backgroundable(anActionEvent.getProject(),"leetcode.editor.favorite",false) {
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
if (b) {
FavoriteManager.addQuestionToFavorite(tag, question, anActionEvent.getProject());
} else {
FavoriteManager.removeQuestionFromFavorite(tag, question, anActionEvent.getProject());
}
}
});
}
@Override
public void setSelected(AnActionEvent anActionEvent, boolean b) {
tag.setSelect(b);
JTree tree = WindowFactory.getDataContext(anActionEvent.getProject()).getData(DataKeys.LEETCODE_PROJECTS_TREE);
if (tree == null) {
return;
}
if (againLoad) {
ProgressManager.getInstance().run(new Task.Backgroundable(anActionEvent.getProject(), "leetcode.editor." + tag.getName(), false) {
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
if (b) {
ViewManager.loadServiceData(tree, anActionEvent.getProject(), tag.getType());
} else {
ViewManager.loadServiceData(tree, anActionEvent.getProject());
}
}
});
} else {
ViewManager.update(tree);
}
}
private void waitForConnection() {
ProgressManager.getInstance()
.run(
new Task.Backgroundable(project, "Connecting To Debugger", /* canBeCanceled= */ false) {
@Override
public void run(ProgressIndicator indicator) {
indicator.setText("Waiting for connection...");
boolean success = transport.waitForConnection();
if (!success) {
reportError("Failed to connect to the debugger");
transport.close();
getSession().stop();
return;
}
init();
}
});
}
public void renewCoverageData(@Nonnull final CoverageSuitesBundle suite, @Nonnull final CoverageDataManager dataManager) {
final Runnable request = createRenewRequest(suite, dataManager);
if (request != null) {
if (myProject.isDisposed()) return;
ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Loading coverage data...", false) {
@Override
public void run(@Nonnull ProgressIndicator indicator) {
request.run();
}
@RequiredUIAccess
@Override
public void onSuccess() {
final CoverageView coverageView = CoverageViewManager.getInstance(myProject).getToolwindow(suite);
if (coverageView != null) {
coverageView.updateParentTitle();
}
}
});
}
}
public void saveWorkspace(final Project project, final String workspaceRootPath, final boolean syncFiles, final Runnable onSuccess) {
final ServerContext serverContext = currentServerContext;
final Workspace oldWorkspace = this.oldWorkspace;
final Workspace newWorkspace = new Workspace(server, name, computer, owner, comment, mappings);
// Using IntelliJ's background framework here so the user can choose to wait or continue working
final Task.Backgroundable backgroundTask = new Task.Backgroundable(project,
TfPluginBundle.message(TfPluginBundle.KEY_WORKSPACE_DIALOG_PROGRESS_TITLE),
true, PerformInBackgroundOption.DEAF) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
saveWorkspaceInternal(serverContext, oldWorkspace, newWorkspace, indicator, project,
workspaceRootPath, syncFiles, onSuccess);
}
};
backgroundTask.queue();
}
/**
* Update the auth info for each context selected
*/
public void updatePasswords() {
final ListSelectionModel selectionModel = getTableSelectionModel();
if (!selectionModel.isSelectionEmpty()) {
if (Messages.showYesNoDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_DIALOG_UPDATE_MSG), TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_DIALOG_UPDATE_TITLE), Messages.getQuestionIcon()) == Messages.YES) {
final List<ServerContext> contexts = tableModel.getSelectedContexts();
final Task.Backgroundable updateAuthTask = new Task.Backgroundable(project, TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_UPDATING)) {
@Override
public void run(final ProgressIndicator indicator) {
logger.info("Updating passwords for user. Selected: " + contexts.size());
ServerContextManager.getInstance().updateServerContextsAuthInfo(contexts);
populateContextTable();
}
};
updateAuthTask.queue();
}
} else {
Messages.showWarningDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_NO_ROWS_SELECTED), TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_DIALOG_UPDATE_TITLE));
}
}
@Override
public void startBackgroundTask(@Nonnull final MMDPrintPanel source, @Nonnull final String taskName, @Nonnull final Runnable task) {
final Task.Backgroundable backgroundTask = new Task.Backgroundable(this.project, taskName) {
@Override
public void run(@Nonnull final ProgressIndicator indicator) {
try {
indicator.setIndeterminate(true);
task.run();
IdeaUtils.showPopup(String.format("%s has been sent to the printer", taskName), MessageType.INFO);
} catch (Exception ex) {
LOGGER.error("Print error", ex);
IdeaUtils.showPopup("Print error! See the log!", MessageType.ERROR);
} finally {
indicator.stop();
}
}
};
ProgressManager.getInstance().run(backgroundTask);
}
@Override
public ModuleWizardStep[] createSteps(WizardContext context) {
/**
* Newer export version project sdk can be automatically discovered and configured.
*/
AtomicBoolean isSdkConfigured = new AtomicBoolean(true);
String message = PantsBundle.message("pants.default.sdk.config.progress");
ProgressManager.getInstance().run(new Task.Modal(context.getProject(), message, !CAN_BE_CANCELLED) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
if (isSdkConfigured.get()) {
isSdkConfigured.set(isJvmProject(context.getProjectFileDirectory()));
}
}
});
if (isSdkConfigured.get()) {
return super.createSteps(context);
}
return ArrayUtil.append(super.createSteps(context), new ProjectJdkStep(context));
}
public void execute(ClassEntity targetClass) {
this.targetClass = targetClass;
ProgressManager.getInstance().run(new Task.Backgroundable(project, "GsonFormat") {
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
progressIndicator.setIndeterminate(true);
long currentTimeMillis = System.currentTimeMillis();
execute();
progressIndicator.setIndeterminate(false);
progressIndicator.setFraction(1.0);
StringBuffer sb = new StringBuffer();
sb.append("GsonFormat [" + (System.currentTimeMillis() - currentTimeMillis) + " ms]\n");
// sb.append("generate class : ( "+generateClassList.size()+" )\n");
// for (String item: generateClassList) {
// sb.append(" at "+item+"\n");
// }
// sb.append(" \n");
// NotificationCenter.info(sb.toString());
Toast.make(project, MessageType.INFO, sb.toString());
}
});
}
/**
* this method will called from webservice thread
*/
private static void syncProjectStep2(@Nonnull final Project project,
@Nullable final Sdk sdk,
@Nullable UnityOpenFilePostHandlerRequest requestor,
final boolean runValidator,
UnitySetDefines unitySetDefines)
{
Task.Backgroundable.queue(project, "Sync Project", indicator ->
{
AccessToken accessToken = HeavyProcessLatch.INSTANCE.processStarted("unity sync project");
try
{
importAfterDefines(project, sdk, runValidator, indicator, requestor, unitySetDefines);
}
finally
{
accessToken.finish();
}
});
}
@Override
protected void perform(@NotNull Project project, @NotNull List<VirtualFile> gitRoots,
@NotNull VirtualFile defaultRoot) {
GitPushTagsDialog dialog = new GitPushTagsDialog(project, gitRoots, defaultRoot);
dialog.show();
if (dialog.isOK()) {
final Optional<TagsPushSpec> pushSpec = dialog.getPushSpec();
if (pushSpec.isPresent()) {
Task.Backgroundable task = new Task.Backgroundable(project, ResBundle.message("message.pushing"), false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
GtPushResult result = GitTagsPusher.create(getProject(), indicator).push(pushSpec.get());
handleResult(getProject(), result);
}
};
GitVcs.runInBackground(task);
}
}
}
private void runGeneration() {
ProgressManager.getInstance().run(new Task.Backgroundable(project, MESSAGE_GENERATING_SERVICE, false) {
public void run(@NotNull ProgressIndicator progressIndicator) {
try {
getGenerator().generate(progressIndicator);
} catch (Exception e) {
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
onActionFailure(error);
}
});
return;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
onActionSuccess(GenerateActions.GENERATE_SUCCESS);
}
});
}
});
}
private void performFileOperation() {
project.save();
FileDocumentManager.getInstance().saveAllDocuments();
ProjectManagerEx.getInstanceEx().blockReloadingProjectOnExternalChanges();
ProgressManager.getInstance().run(new Task.Backgroundable(project, MESSAGE_GENERATING_SERVICE, false) {
public void run(@NotNull ProgressIndicator progressIndicator) {
getGenerator().makeFilePerformance(progressIndicator);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
onActionSuccess(GenerateActions.FILE_OPERATION_SUCCESS);
}
});
}
});
}
public void actionPerformed(AnActionEvent e) {
final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
if (project == null) {
return;
}
Deployable server = WebDeploymentDataKeys.DEPLOYABLE.getData(e.getDataContext());
if(server == null || !PublishConfig.getInstance(project).isDefault(server)) {
return;
}
new Task.Backgroundable(project, "Symfony: Downloading Files", false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
Symfony2ProjectComponent.getLogger().info("Running webDeployment dev download");
RemoteWebServerUtil.collectRemoteFiles(project);
}
}.queue();
}
@Override
public void execute() {
ProgressManager.getInstance()
.run(
new Task.Modal(project, "Disconnecting...", false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
log.info(
"Disconnecting current connection: " + connectionHandler.getConnectionID());
indicator.setIndeterminate(true);
try {
connectionHandler.disconnect();
} finally {
indicator.stop();
}
}
});
}
public void unshelveSilentlyAsynchronously(@Nonnull final Project project,
@Nonnull final List<ShelvedChangeList> selectedChangeLists,
@Nonnull final List<ShelvedChange> selectedChanges,
@Nonnull final List<ShelvedBinaryFile> selectedBinaryChanges,
@Nullable final LocalChangeList forcePredefinedOneChangelist) {
ProgressManager.getInstance().run(new Task.Backgroundable(project, VcsBundle.message("unshelve.changes.progress.title"), true) {
@Override
public void run(@Nonnull ProgressIndicator indicator) {
for (ShelvedChangeList changeList : selectedChangeLists) {
List<ShelvedChange> changesForChangelist = ContainerUtil.newArrayList(ContainerUtil.intersection(changeList.getChanges(myProject), selectedChanges));
List<ShelvedBinaryFile> binariesForChangelist =
ContainerUtil.newArrayList(ContainerUtil.intersection(changeList.getBinaryFiles(), selectedBinaryChanges));
boolean shouldUnshelveAllList = changesForChangelist.isEmpty() && binariesForChangelist.isEmpty();
unshelveChangeList(changeList, shouldUnshelveAllList ? null : changesForChangelist, shouldUnshelveAllList ? null : binariesForChangelist,
forcePredefinedOneChangelist != null ? forcePredefinedOneChangelist : getChangeListUnshelveTo(changeList), true);
}
}
});
}
private void schedulePostExecutionActions(final OSProcessHandler result, final String title) {
final ProgressManager manager = ProgressManager.getInstance();
ApplicationManager.getApplication()
.invokeLater(
() -> {
manager.run(
new Task.Backgroundable(mProject, title, true) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
try {
result.waitFor();
} finally {
indicator.cancel();
}
BuckToolWindow buckToolWindow =
BuckUIManager.getInstance(mProject).getBuckToolWindow();
if (!buckToolWindow.isRunToolWindowVisible()) {
buckToolWindow.showRunToolWindow();
}
}
});
});
}
public static void processDuplicates(@Nonnull final PsiElement callElement,
@Nonnull final PsiElement generatedMethod,
@Nonnull final List<PsiElement> scope,
@Nonnull final SimpleDuplicatesFinder finder,
@Nonnull final Editor editor,
@Nonnull final Consumer<Pair<SimpleMatch, PsiElement>> replacer) {
finder.setReplacement(callElement);
if (ApplicationManager.getApplication().isUnitTestMode()) {
replaceDuplicates(callElement, editor, replacer, finder.findDuplicates(scope, generatedMethod));
return;
}
final Project project = callElement.getProject();
ProgressManager.getInstance().run(new Task.Backgroundable(project, RefactoringBundle.message("searching.for.duplicates"), true) {
public void run(@Nonnull ProgressIndicator indicator) {
if (myProject == null || myProject.isDisposed()) return;
final List<SimpleMatch> duplicates = ApplicationManager.getApplication().runReadAction(new Computable<List<SimpleMatch>>() {
@Override
public List<SimpleMatch> compute() {
return finder.findDuplicates(scope, generatedMethod);
}
});
ApplicationManager.getApplication().invokeLater(() -> replaceDuplicates(callElement, editor, replacer, duplicates));
}
});
}
public static void runAfterCompilationCheck(Task.Backgroundable afterCompilationBackgroundable,
Project project, ProjectInfo projectInfo) {
final Task.Backgroundable compilationBackgroundable = new Task.Backgroundable(project, IntelliJDeodorantBundle.message("project.compiling.indicator.text"), true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
runAfterCompilationCheck(projectInfo, afterCompilationBackgroundable);
}
};
ProgressManager.getInstance().run(compilationBackgroundable);
}
/**
* Calculates suggestions for whole project.
*/
private void calculateRefactorings() {
Project project = scope.getProject();
ProjectInfo projectInfo = new ProjectInfo(scopeChooserCombo.getScope(), false);
final Task.Backgroundable backgroundable = new Task.Backgroundable(project,
IntelliJDeodorantBundle.message(detectIndicatorStatusTextKey), true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
ApplicationManager.getApplication().runReadAction(() -> {
List<RefactoringType.AbstractCandidateRefactoringGroup> candidates =
refactoringType.getRefactoringOpportunities(projectInfo, indicator);
if (candidates == null) {
showCompilationErrorNotification(getProject());
candidates = new ArrayList<>();
}
logFound(project, candidates.size());
candidates.sort(Comparator.comparing(o -> o.getCandidates().get(0).getSourceClass().getQualifiedName()));
model.setCandidateRefactoringGroups(candidates);
ApplicationManager.getApplication().invokeLater(() -> showRefactoringsTable());
});
}
@Override
public void onCancel() {
showRefreshingProposal();
}
};
runAfterCompilationCheck(backgroundable, scope.getProject(), projectInfo);
}
@Nonnull
private static CallbackData createInteractive(@Nonnull Project project,
@Nonnull InvokeAfterUpdateMode mode,
@Nonnull Runnable afterUpdate,
String title,
@Nullable ModalityState state) {
Task task = mode.isSynchronous()
? new Waiter(project, afterUpdate, title, mode.isCancellable())
: new FictiveBackgroundable(project, afterUpdate, title, mode.isCancellable(), state);
Runnable callback = () -> {
logUpdateFinished(project, mode);
setDone(task);
};
return new CallbackData(callback, () -> ProgressManager.getInstance().run(task));
}
/**
* Calculates suggestions for whole project.
*/
private void calculateRefactorings() {
Project project = scope.getProject();
ProjectInfo projectInfo = new ProjectInfo(scopeChooserCombo.getScope(), false);
final Task.Backgroundable backgroundable = new Task.Backgroundable(project,
IntelliJDeodorantBundle.message("long.method.detect.indicator.status"), true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
ApplicationManager.getApplication().runReadAction(() -> {
Set<ASTSliceGroup> candidates = getExtractMethodRefactoringOpportunities(projectInfo, indicator);
final List<ExtractMethodCandidateGroup> extractMethodCandidateGroups = candidates.stream().filter(Objects::nonNull)
.map(sliceGroup ->
sliceGroup.getCandidates().stream()
.filter(c -> canBeExtracted(c))
.collect(toSet()))
.filter(set -> !set.isEmpty())
.map(ExtractMethodCandidateGroup::new)
.sorted(Comparator.comparing(ExtractMethodCandidateGroup::getDescription))
.collect(toList());
treeTableModel.setCandidateRefactoringGroups(extractMethodCandidateGroups);
ApplicationManager.getApplication().invokeLater(() -> showRefactoringsTable());
IntelliJDeodorantCounterCollector.getInstance().refactoringFound(project, "extract.method", extractMethodCandidateGroups.size());
});
}
@Override
public void onCancel() {
showEmptyPanel();
}
};
runAfterCompilationCheck(backgroundable, scope.getProject(), projectInfo);
}
private void calculateRefactorings() {
Project project = scope.getProject();
ProjectInfo projectInfo = new ProjectInfo(scopeChooserCombo.getScope(), true);
Set<String> classNamesToBeExamined = new HashSet<>();
PsiUtils.extractFiles(project).stream()
.filter(file -> scopeChooserCombo.getScope().contains(file))
.forEach(list ->
Arrays.stream(list.getClasses()).map(PsiClass::getQualifiedName).forEach(classNamesToBeExamined::add));
final Task.Backgroundable backgroundable = new Task.Backgroundable(project, IntelliJDeodorantBundle.message("feature.envy.detect.indicator.status"), true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
ApplicationManager.getApplication().runReadAction(() -> {
List<MoveMethodCandidateRefactoring> candidates = JDeodorantFacade.getMoveMethodRefactoringOpportunities(projectInfo, indicator, classNamesToBeExamined);
final List<MoveMethodRefactoring> references = candidates.stream().filter(Objects::nonNull)
.map(x ->
new MoveMethodRefactoring(x.getSourceMethodDeclaration(),
x.getTargetClass().getClassObject().getPsiClass(),
x.getDistinctSourceDependencies(),
x.getDistinctTargetDependencies()))
.collect(Collectors.toList());
refactorings.clear();
refactorings.addAll(new ArrayList<>(references));
model.updateTable(refactorings);
scrollPane.setVisible(true);
scrollPane.setViewportView(table);
enableButtonsOnConditions();
IntelliJDeodorantCounterCollector.getInstance().refactoringFound(project, "move.method", references.size());
});
}
@Override
public void onCancel() {
showEmptyPanel();
}
};
AbstractRefactoringPanel.runAfterCompilationCheck(backgroundable, project, projectInfo);
}
@Override
public void mouseClicked(MouseEvent e) {
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if (selPath != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
Question question = (Question) node.getUserObject();
if ("lock".equals(question.getStatus())) {
return;
}
if (question.isLeaf()) {
if (e.getButton() == 3) { //鼠标右键
final ActionManager actionManager = ActionManager.getInstance();
final ActionGroup actionGroup = (ActionGroup) actionManager.getAction("leetcode.NavigatorActionsMenu");
if (actionGroup != null) {
actionManager.createActionPopupMenu("", actionGroup).getComponent().show(e.getComponent(), e.getX(), e.getY());
}
} else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
ProgressManager.getInstance().run(new Task.Backgroundable(project,"leetcode.editor.openCode",false) {
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
CodeManager.openCode(question, project);
}
});
}
}
}
}
@Nullable
public static UsageView showInUsageView(@Nullable PsiElement sourceElement,
@Nonnull PsiElement[] targets,
@Nonnull String title,
@Nonnull final Project project) {
if (targets.length == 0) return null;
final UsageViewPresentation presentation = new UsageViewPresentation();
presentation.setCodeUsagesString(title);
presentation.setTabName(title);
presentation.setTabText(title);
UsageTarget[] usageTargets = sourceElement == null ? UsageTarget.EMPTY_ARRAY : new UsageTarget[]{new PsiElement2UsageTargetAdapter(sourceElement)};
PsiElement[] primary = sourceElement == null ? PsiElement.EMPTY_ARRAY : new PsiElement[]{sourceElement};
UsageView view = UsageViewManager.getInstance(project).showUsages(usageTargets, Usage.EMPTY_ARRAY, presentation);
SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(project);
List<SmartPsiElementPointer> pointers = ContainerUtil.map(targets, smartPointerManager::createSmartPsiElementPointer);
// usage view will load document/AST so still referencing all these PSI elements might lead to out of memory
//noinspection UnusedAssignment
targets = PsiElement.EMPTY_ARRAY;
ProgressManager.getInstance().run(new Task.Backgroundable(project, "Updating Usage View ...") {
@Override
public void run(@Nonnull ProgressIndicator indicator) {
for (final SmartPsiElementPointer pointer : pointers) {
if (((UsageViewImpl)view).isDisposed()) break;
ApplicationManager.getApplication().runReadAction(() -> {
final PsiElement target = pointer.getElement();
if (target != null) {
view.appendUsage(UsageInfoToUsageConverter.convert(primary, new UsageInfo(target)));
}
});
}
UIUtil.invokeLaterIfNeeded(((UsageViewImpl)view)::expandAll);
}
});
return view;
}