下面列出了org.junit.jupiter.api.extension.ExtendWith#com.intellij.openapi.progress.ProgressIndicator 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Nonnull
public static Map<String, List<ProblemDescriptor>> inspectEx(@Nonnull final List<LocalInspectionToolWrapper> toolWrappers,
@Nonnull final PsiFile file,
@Nonnull final InspectionManager iManager,
final boolean isOnTheFly,
boolean failFastOnAcquireReadAction,
@Nonnull final ProgressIndicator indicator) {
if (toolWrappers.isEmpty()) return Collections.emptyMap();
TextRange range = file.getTextRange();
List<Divider.DividedElements> allDivided = new ArrayList<>();
Divider.divideInsideAndOutsideAllRoots(file, range, range, Conditions.alwaysTrue(), new CommonProcessors.CollectProcessor<>(allDivided));
List<PsiElement> elements = ContainerUtil.concat(
(List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> ContainerUtil.concat(d.inside, d.outside, d.parents)));
return inspectElements(toolWrappers, file, iManager, isOnTheFly, failFastOnAcquireReadAction, indicator, elements,
calcElementDialectIds(elements));
}
@RequiredUIAccess
private void setupSdk(Sdk newSdk, Consumer<Sdk> callback) {
UIAccess uiAccess = UIAccess.current();
new Task.ConditionalModal(null, "Setuping SDK...", false, PerformInBackgroundOption.DEAF) {
@Override
public void run(@Nonnull ProgressIndicator indicator) {
SdkType sdkType = (SdkType)newSdk.getSdkType();
sdkType.setupSdkPaths(newSdk);
uiAccess.give(() -> {
if (newSdk.getVersionString() == null) {
String home = newSdk.getHomePath();
Messages.showMessageDialog(ProjectBundle.message("sdk.java.corrupt.error", home), ProjectBundle.message("sdk.java.corrupt.title"), Messages.getErrorIcon());
}
doAdd(newSdk, callback);
});
}
}.queue();
}
private static void openDefinition(@Nullable PsiMember unit, AnalysisScope scope) {
new Task.Backgroundable(scope.getProject(), "Search Definition") {
private PsiElement result;
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
result = unit;
}
@Override
public void onSuccess() {
if (result != null) {
EditorHelper.openInEditor(result);
}
}
}.queue();
}
public void init41(@Nullable ProgressIndicator indicator) {
boolean finished = false;
try {
//ProjectManagerImpl.initProject(path, this, true, null, null);
Method method = ReflectionUtil
.getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, Project.class,
ProgressIndicator.class);
assert (method != null);
try {
method.invoke(null, path, this, true, null, null);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
finished = true;
}
finally {
if (!finished) {
TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
}
}
}
@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();
}
}
});
}
private void wrapInReadActionAndIndicator(@Nonnull final Runnable process) {
Runnable toRun = runInReadAction ? () -> {
if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(process)) {
failedSubTasks.add(this);
doComplete(throwable);
}
} : process;
ProgressIndicator existing = ProgressManager.getInstance().getProgressIndicator();
if (existing == progressIndicator) {
// we are already wrapped in an indicator - most probably because we came here from helper which steals children tasks
toRun.run();
}
else {
ProgressManager.getInstance().executeProcessUnderProgress(toRun, progressIndicator);
}
}
public void init41(@Nullable ProgressIndicator indicator) {
boolean finished = false;
try {
//ProjectManagerImpl.initProject(path, this, true, null, null);
Method method = ReflectionUtil
.getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, Project.class,
ProgressIndicator.class);
assert (method != null);
try {
method.invoke(null, path, this, true, null, null);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
finished = true;
}
finally {
if (!finished) {
TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
}
}
}
/**
* Run handler in the current thread.
*
* @param handler a handler to run
* @param indicator a progress manager
* @param setIndeterminateFlag if true handler is configured as indeterminate
* @param operationName
*/
public void runInCurrentThread(
final BuckCommandHandler handler,
final ProgressIndicator indicator,
final boolean setIndeterminateFlag,
@Nullable final String operationName) {
runInCurrentThread(handler, new Runnable() {
public void run() {
if (indicator != null) {
indicator.setText(operationName);
indicator.setText2("");
if (setIndeterminateFlag) {
indicator.setIndeterminate(true);
}
}
}
});
}
@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 void ensureInitializationCompleted(Project project, ProgressIndicator indicator) {
final int id = getProjectId(project);
synchronized (myAsyncScanLock) {
while (myInitInProgress.containsKey(id)) {
if (!project.isOpen() || project.isDisposed() || (indicator != null && indicator.isCanceled())) {
// makes no sense to continue waiting
break;
}
try {
myAsyncScanLock.wait(500);
}
catch (InterruptedException ignored) {
break;
}
}
}
}
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);
}
});
}
});
}
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
if (ActorManager.runNopolLocally && !ActorManager.nopolIsRunning) {
ActorManager.launchNopol();
}
Timeout timeout = new Timeout(scala.concurrent.duration.Duration.fromNanos(20*1000000000));// nano = 10^9
EventSender.send(EventSender.Event.REPAIR_ATTEMPT);
try {
ConfigActor configActor = new ConfigActorImpl(nopolContext, Files.readAllBytes(Paths.get(outputZip)));
this.future = Patterns.ask(ActorManager.remoteActor, configActor, timeout);
if (Plugin.enableFancyRobot) {
ApplicationManager.getApplication().invokeLater(runnerFancyRobot);
}
this.response = Await.result(future, timeout.duration());
} catch (Exception e) {
onError(e);
}
}
public static void reparseProjectFiles(@NotNull final Project project) {
Task.Backgroundable task = new Task.Backgroundable(project, HaxeBundle.message("haxe.project.reparsing"), false) {
public void run(@NotNull ProgressIndicator indicator) {
final Collection<VirtualFile> haxeFiles = new ArrayList<VirtualFile>();
final VirtualFile baseDir = project.getBaseDir();
if (baseDir != null) {
FileBasedIndex.getInstance().iterateIndexableFiles(new ContentIterator() {
public boolean processFile(VirtualFile file) {
if (HaxeFileType.HAXE_FILE_TYPE == file.getFileType()) {
haxeFiles.add(file);
}
return true;
}
}, project, indicator);
}
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
FileContentUtil.reparseFiles(project, haxeFiles, !project.isDefault());
}
}, ModalityState.NON_MODAL);
}
};
ProgressManager.getInstance().run(task);
}
static void log(ProgressIndicator progressIndicator, TextEditorHighlightingPass pass, @NonNls @Nonnull Object... info) {
if (LOG.isDebugEnabled()) {
CharSequence docText = pass == null || pass.getDocument() == null ? "" : ": '" + StringUtil.first(pass.getDocument().getCharsSequence(), 10, true) + "'";
synchronized (PassExecutorService.class) {
String infos = StringUtil.join(info, Functions.TO_STRING(), " ");
String message = StringUtil.repeatSymbol(' ', getThreadNum() * 4) +
" " +
pass +
" " +
infos +
"; progress=" +
(progressIndicator == null ? null : progressIndicator.hashCode()) +
" " +
(progressIndicator == null ? "?" : progressIndicator.isCanceled() ? "X" : "V") +
docText;
LOG.debug(message);
//System.out.println(message);
}
}
}
private static Module createAssemblyUnityScriptModuleFirstPass(Project project,
ModifiableModuleModel newModel,
Sdk unityBundle,
MultiMap<Module, VirtualFile> virtualFilesByModule,
ProgressIndicator progressIndicator,
UnityProjectImportContext context)
{
if(isVersionHigherOrEqual(unityBundle, "2018.2"))
{
Module module = newModel.findModuleByName(ASSEMBLY_UNITYSCRIPT_FIRSTPASS);
if(module != null)
{
newModel.disposeModule(module);
}
return null;
}
else
{
return createAndSetupModule(ASSEMBLY_UNITYSCRIPT_FIRSTPASS, project, newModel, FIRST_PASS_PATHS, unityBundle, null, "unity3d-unityscript-child", JavaScriptFileType.INSTANCE,
virtualFilesByModule, progressIndicator, context);
}
}
public static BooleanRunnable reparse(@Nonnull PsiFile injectedPsiFile,
@Nonnull DocumentWindow injectedDocument,
@Nonnull PsiFile hostPsiFile,
@Nonnull Document hostDocument,
@Nonnull FileViewProvider hostViewProvider,
@Nonnull ProgressIndicator indicator,
@Nonnull ASTNode oldRoot,
@Nonnull ASTNode newRoot,
@Nonnull PsiDocumentManagerBase documentManager) {
LanguageVersion languageVersion = injectedPsiFile.getLanguageVersion();
InjectedFileViewProvider provider = (InjectedFileViewProvider)injectedPsiFile.getViewProvider();
VirtualFile oldInjectedVFile = provider.getVirtualFile();
VirtualFile hostVirtualFile = hostViewProvider.getVirtualFile();
BooleanRunnable runnable = InjectionRegistrarImpl
.reparse(languageVersion, (DocumentWindowImpl)injectedDocument, injectedPsiFile, (VirtualFileWindow)oldInjectedVFile, hostVirtualFile, hostPsiFile, (DocumentEx)hostDocument, indicator, oldRoot,
newRoot, documentManager);
if (runnable == null) {
EditorWindowImpl.disposeEditorFor(injectedDocument);
}
return runnable;
}
@Override
public final void doCollectInformation(@Nonnull final ProgressIndicator progress) {
if (!(progress instanceof DaemonProgressIndicator)) {
throw new IncorrectOperationException("Highlighting must be run under DaemonProgressIndicator, but got: " + progress);
}
myFinished = false;
if (myFile != null) {
myHighlightingSession = HighlightingSessionImpl.getOrCreateHighlightingSession(myFile, (DaemonProgressIndicator)progress, getColorsScheme());
}
try {
collectInformationWithProgress(progress);
}
finally {
if (myFile != null) {
sessionFinished();
}
}
}
private static ReadTask.Continuation runUnderProgress(@Nonnull final ProgressIndicator progressIndicator, @Nonnull final ReadTask task) {
return ProgressManager.getInstance().runProcess(() -> {
try {
return task.runBackgroundProcess(progressIndicator);
}
catch (ProcessCanceledException ignore) {
return null;
}
}, progressIndicator);
}
@Nonnull
private static FairDiffIterable optimizeLineChunks(@Nonnull List<Line> lines1,
@Nonnull List<Line> lines2,
@Nonnull FairDiffIterable iterable,
@Nonnull ProgressIndicator indicator) {
return new ChunkOptimizer.LineChunkOptimizer(lines1, lines2, iterable, indicator).build();
}
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);
}
@Nullable
private FileContent doTake(ProgressIndicator indicator) {
FileContent result = null;
boolean waitForContentsToBeLoaded = false;
while (result == null) {
indicator.checkCanceled();
final int remainingContentsToLoad = myContentsToLoad.get();
result = pollLoadedContent(waitForContentsToBeLoaded && remainingContentsToLoad > 0);
if (result == null) { // no loaded contents by other threads
if (remainingContentsToLoad == 0) return null; // no items to load
if (!loadNextContent()) { // attempt to eagerly load content failed
// last remaining contents are loaded by other threads, use timed poll for results
waitForContentsToBeLoaded = true;
}
}
}
long loadedBytesInQueueNow = myLoadedBytesInQueue.addAndGet(-result.getLength());
if (loadedBytesInQueueNow < MAX_SIZE_OF_BYTES_IN_QUEUE) {
// nudge content preloader to proceed
synchronized (ourProceedWithLoadingLock) {
// we actually ask only content loading thread to proceed, so there should not be much difference with plain notify
ourProceedWithLoadingLock.notifyAll();
}
}
return result;
}
private void reportHistory(final FilePath filePath, @Nullable final VcsRevisionNumber startRevisionNumber,
final VcsKey vcsKey,
final VcsBackgroundableActions resultingActionKey,
final BackgroundableActionEnabledHandler handler,
final VcsAppendableHistorySessionPartner cachedPartner, final boolean canUseLastRevisionCheck) {
ProgressManager.getInstance().run(new Task.Backgroundable(myProject, VcsBundle.message("loading.file.history.progress"), true) {
public void run(@Nonnull ProgressIndicator indicator) {
indicator.setText(VcsUtil.getPathForProgressPresentation(filePath.getIOFile()));
indicator.setIndeterminate(true);
try {
VcsAbstractHistorySession cachedSession;
if (canUseLastRevisionCheck &&
myCachesHistory &&
(cachedSession = getSessionFromCacheWithLastRevisionCheck(filePath, vcsKey)) != null) {
cachedPartner.reportCreatedEmptySession(cachedSession);
} else if (myDelegate instanceof VcsHistoryProviderEx) {
((VcsHistoryProviderEx)myDelegate).reportAppendableHistory(filePath, startRevisionNumber, cachedPartner);
}
else {
myDelegate.reportAppendableHistory(filePath, cachedPartner);
}
}
catch (VcsException e) {
cachedPartner.reportException(e);
}
finally {
cachedPartner.finished();
ApplicationManager.getApplication().invokeLater(() -> handler.completed(resultingActionKey), ModalityState.NON_MODAL);
}
}
});
}
/**
* Opens definition of method and highlights statements, which should be extracted.
*
* @param sourceMethod method from which code is proposed to be extracted into separate method.
* @param scope scope of the current project.
* @param slice computation slice.
*/
private static void openDefinition(@Nullable PsiMethod sourceMethod, AnalysisScope scope, ASTSlice slice) {
new Task.Backgroundable(scope.getProject(), "Search Definition") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
}
@Override
public void onSuccess() {
if (sourceMethod != null) {
Set<SmartPsiElementPointer<PsiElement>> statements = slice.getSliceStatements();
PsiStatement psiStatement = (PsiStatement) statements.iterator().next().getElement();
if (psiStatement != null && psiStatement.isValid()) {
EditorHelper.openInEditor(psiStatement);
Editor editor = FileEditorManager.getInstance(sourceMethod.getProject()).getSelectedTextEditor();
if (editor != null) {
TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
editor.getMarkupModel().removeAllHighlighters();
statements.stream()
.filter(statement -> statement.getElement() != null)
.forEach(statement ->
editor.getMarkupModel().addRangeHighlighter(statement.getElement().getTextRange().getStartOffset(),
statement.getElement().getTextRange().getEndOffset(), HighlighterLayer.SELECTION,
attributes, HighlighterTargetArea.EXACT_RANGE));
}
}
}
}
}.queue();
}
@Override
public void run(ContinuationContext context) {
final ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
pi.setText(getName());
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
//
}
pi.setText("");
}
public List<AbstractCandidateRefactoringGroup> getRefactoringOpportunities(ProjectInfo projectInfo, ProgressIndicator indicator) {
Set<?> notAbstractRefactoringOpportunities = getNotAbstractRefactoringOpportunities(projectInfo, indicator);
if (notAbstractRefactoringOpportunities == null) {
return null;
}
List<AbstractCandidateRefactoringGroup> result = new ArrayList<>();
for (Object candidate : notAbstractRefactoringOpportunities) {
result.add(newAbstractCandidateRefactoringGroup(candidate));
}
return result;
}
public LineFragmentSplitter(@Nonnull CharSequence text1,
@Nonnull CharSequence text2,
@Nonnull List<InlineChunk> words1,
@Nonnull List<InlineChunk> words2,
@Nonnull FairDiffIterable iterable,
@Nonnull ProgressIndicator indicator) {
myText1 = text1;
myText2 = text2;
myWords1 = words1;
myWords2 = words2;
myIterable = iterable;
myIndicator = indicator;
}
@Override
public final void run(@NotNull final ProgressIndicator indicator) {
indicator.setText(FETCHING_FILE_CONTENT);
indicator.setFraction(0.0);
String fileName = codeInfo.getAbsoluteFileName();
fileContents = searchUtils.getContentsForFile(fileName);
//Setting contents so that we can use that for Open in New Tab
codeInfo.setContents(fileContents);
indicator.setFraction(1.0);
}
public static void checkContentRevision(@javax.annotation.Nullable Project project,
@Nonnull ContentRevision rev,
@Nonnull UserDataHolder context,
@Nonnull ProgressIndicator indicator) throws DiffRequestProducerException {
if (rev.getFile().isDirectory()) {
throw new DiffRequestProducerException("Can't show diff for directory");
}
}
@Nonnull
public static FairDiffIterable comparePunctuation(@Nonnull CharSequence text1,
@Nonnull CharSequence text2,
@Nonnull ProgressIndicator indicator) {
indicator.checkCanceled();
CharOffsets chars1 = getPunctuationChars(text1);
CharOffsets chars2 = getPunctuationChars(text2);
FairDiffIterable nonSpaceChanges = diff(chars1.characters, chars2.characters, indicator);
return transfer(chars1, chars2, text1, text2, nonSpaceChanges, indicator);
}
@Override
public Future<?> startThread(final ProgressIndicator progressIndicator, Runnable runnable) {
ProgressManager.getInstance().runProcess(runnable, progressIndicator);
FutureResult<Object> result = new FutureResult<>();
result.set(true);
return result;
}