use of com.intellij.openapi.progress.util.ProgressIndicatorBase in project intellij-community by JetBrains.
the class ProgressIndicatorTest method testWrapperIndicatorGotCanceledTooWhenInnerIndicatorHas.
public void testWrapperIndicatorGotCanceledTooWhenInnerIndicatorHas() {
final ProgressIndicator progress = new ProgressIndicatorBase() {
@Override
protected boolean isCancelable() {
return true;
}
};
try {
ProgressManager.getInstance().executeProcessUnderProgress(() -> {
assertFalse(CoreProgressManager.threadsUnderCanceledIndicator.contains(Thread.currentThread()));
assertTrue(!progress.isCanceled());
progress.cancel();
assertTrue(CoreProgressManager.threadsUnderCanceledIndicator.contains(Thread.currentThread()));
assertTrue(progress.isCanceled());
while (true) {
// wait for PCE
ProgressManager.checkCanceled();
}
}, ProgressWrapper.wrap(progress));
fail("PCE must have been thrown");
} catch (ProcessCanceledException ignored) {
}
}
use of com.intellij.openapi.progress.util.ProgressIndicatorBase in project intellij-community by JetBrains.
the class FindPopupPanel method findSettingsChanged.
private void findSettingsChanged() {
if (isShowing()) {
ScrollingUtil.ensureSelectionExists(myResultsPreviewTable);
}
final ModalityState state = ModalityState.current();
finishPreviousPreviewSearch();
mySearchRescheduleOnCancellationsAlarm.cancelAllRequests();
applyTo(myHelper.getModel(), false);
myHelper.updateFindSettings();
FindModel findInProjectModel = FindManager.getInstance(myProject).getFindInProjectModel();
FindModel copy = new FindModel();
copy.copyFrom(findInProjectModel);
findInProjectModel.copyFrom(myHelper.getModel());
//todo check if we really need to do it now
((FindManagerImpl) FindManager.getInstance(myProject)).changeGlobalSettings(myHelper.getModel());
FindSettings findSettings = FindSettings.getInstance();
myScopeUI.applyTo(findSettings, mySelectedScope);
findSettings.setFileMask(myHelper.getModel().getFileFilter());
ValidationInfo result = getValidationInfo(myHelper.getModel());
final ProgressIndicatorBase progressIndicatorWhenSearchStarted = new ProgressIndicatorBase();
myResultsPreviewSearchProgress = progressIndicatorWhenSearchStarted;
final DefaultTableModel model = new DefaultTableModel() {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
model.addColumn("Usages");
// Use previously shown usage files as hint for faster search and better usage preview performance if pattern length increased
final LinkedHashSet<VirtualFile> filesToScanInitially = new LinkedHashSet<>();
if (myHelper.myPreviousModel != null && myHelper.myPreviousModel.getStringToFind().length() < myHelper.getModel().getStringToFind().length()) {
final DefaultTableModel previousModel = (DefaultTableModel) myResultsPreviewTable.getModel();
for (int i = 0, len = previousModel.getRowCount(); i < len; ++i) {
final UsageInfo2UsageAdapter usage = (UsageInfo2UsageAdapter) previousModel.getValueAt(i, 0);
final VirtualFile file = usage.getFile();
if (file != null)
filesToScanInitially.add(file);
}
}
myHelper.myPreviousModel = myHelper.getModel().clone();
myCodePreviewComponent.setVisible(false);
mySearchTextArea.setInfoText(null);
myResultsPreviewTable.setModel(model);
if (result != null) {
myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow") + " (" + result.message + ")");
return;
}
myResultsPreviewTable.getColumnModel().getColumn(0).setCellRenderer(new FindDialog.UsageTableCellRenderer(myCbFileFilter.isSelected(), false));
myResultsPreviewTable.getEmptyText().setText("Searching...");
final AtomicInteger resultsCount = new AtomicInteger();
final AtomicInteger resultsFilesCount = new AtomicInteger();
ProgressIndicatorUtils.scheduleWithWriteActionPriority(myResultsPreviewSearchProgress, new ReadTask() {
@Override
public void computeInReadAction(@NotNull ProgressIndicator indicator) {
final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(findSettings.isShowResultsInSeparateView(), /*findModel*/
myHelper.getModel().clone());
final boolean showPanelIfOnlyOneUsage = !findSettings.isSkipResultsWithOneUsage();
final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, showPanelIfOnlyOneUsage, presentation);
Ref<VirtualFile> lastUsageFileRef = new Ref<>();
FindInProjectUtil.findUsages(myHelper.getModel().clone(), myProject, info -> {
final Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info);
usage.getPresentation().getIcon();
VirtualFile file = lastUsageFileRef.get();
VirtualFile usageFile = info.getVirtualFile();
if (file == null || !file.equals(usageFile)) {
resultsFilesCount.incrementAndGet();
lastUsageFileRef.set(usageFile);
}
ApplicationManager.getApplication().invokeLater(() -> {
model.addRow(new Object[] { usage });
myCodePreviewComponent.setVisible(true);
if (model.getRowCount() == 1 && myResultsPreviewTable.getModel() == model) {
myResultsPreviewTable.setRowSelectionInterval(0, 0);
}
}, state);
return resultsCount.incrementAndGet() < ShowUsagesAction.USAGES_PAGE_SIZE;
}, processPresentation, filesToScanInitially);
boolean succeeded = !progressIndicatorWhenSearchStarted.isCanceled();
if (succeeded) {
ApplicationManager.getApplication().invokeLater(() -> {
if (progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress && !myResultsPreviewSearchProgress.isCanceled()) {
int occurrences = resultsCount.get();
int filesWithOccurrences = resultsFilesCount.get();
if (occurrences == 0)
myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow"));
myCodePreviewComponent.setVisible(occurrences > 0);
StringBuilder info = new StringBuilder();
if (occurrences > 0) {
info.append(Math.min(ShowUsagesAction.USAGES_PAGE_SIZE, occurrences));
boolean foundAllUsages = occurrences < ShowUsagesAction.USAGES_PAGE_SIZE;
if (!foundAllUsages) {
info.append("+");
}
info.append(UIBundle.message("message.matches", occurrences));
info.append(" in ");
info.append(filesWithOccurrences);
if (!foundAllUsages) {
info.append("+");
}
info.append(UIBundle.message("message.files", filesWithOccurrences));
}
mySearchTextArea.setInfoText(info.toString());
}
}, state);
}
}
@Override
public void onCanceled(@NotNull ProgressIndicator indicator) {
if (isShowing() && progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress) {
scheduleResultsUpdate();
}
}
});
}
use of com.intellij.openapi.progress.util.ProgressIndicatorBase in project intellij-community by JetBrains.
the class InspectionApplication method run.
private void run() {
File tmpDir = null;
try {
myProjectPath = myProjectPath.replace(File.separatorChar, '/');
VirtualFile vfsProject = LocalFileSystem.getInstance().findFileByPath(myProjectPath);
if (vfsProject == null) {
logError(InspectionsBundle.message("inspection.application.file.cannot.be.found", myProjectPath));
printHelp();
}
logMessage(1, InspectionsBundle.message("inspection.application.opening.project"));
final ConversionService conversionService = ConversionService.getInstance();
if (conversionService.convertSilently(myProjectPath, createConversionListener()).openingIsCanceled()) {
gracefulExit();
return;
}
myProject = ProjectUtil.openOrImport(myProjectPath, null, false);
if (myProject == null) {
logError("Unable to open project");
gracefulExit();
return;
}
ApplicationManager.getApplication().runWriteAction(() -> VirtualFileManager.getInstance().refreshWithoutFileWatcher(false));
PatchProjectUtil.patchProject(myProject);
logMessageLn(1, InspectionsBundle.message("inspection.done"));
logMessage(1, InspectionsBundle.message("inspection.application.initializing.project"));
InspectionProfileImpl inspectionProfile = loadInspectionProfile();
if (inspectionProfile == null)
return;
final InspectionManagerEx im = (InspectionManagerEx) InspectionManager.getInstance(myProject);
im.createNewGlobalContext(true).setExternalProfile(inspectionProfile);
im.setProfile(inspectionProfile.getName());
final AnalysisScope scope;
if (mySourceDirectory == null) {
final String scopeName = System.getProperty("idea.analyze.scope");
final NamedScope namedScope = scopeName != null ? NamedScopesHolder.getScope(myProject, scopeName) : null;
scope = namedScope != null ? new AnalysisScope(GlobalSearchScopesCore.filterScope(myProject, namedScope), myProject) : new AnalysisScope(myProject);
} else {
mySourceDirectory = mySourceDirectory.replace(File.separatorChar, '/');
VirtualFile vfsDir = LocalFileSystem.getInstance().findFileByPath(mySourceDirectory);
if (vfsDir == null) {
logError(InspectionsBundle.message("inspection.application.directory.cannot.be.found", mySourceDirectory));
printHelp();
}
PsiDirectory psiDirectory = PsiManager.getInstance(myProject).findDirectory(vfsDir);
scope = new AnalysisScope(psiDirectory);
}
logMessageLn(1, InspectionsBundle.message("inspection.done"));
if (!myRunWithEditorSettings) {
logMessageLn(1, InspectionsBundle.message("inspection.application.chosen.profile.log.message", inspectionProfile.getName()));
}
InspectionsReportConverter reportConverter = getReportConverter(myOutputFormat);
if (reportConverter == null && myOutputFormat != null && myOutputFormat.endsWith(".xsl")) {
// xslt converter
reportConverter = new XSLTReportConverter(myOutputFormat);
}
final String resultsDataPath;
if (// use default xml converter(if null( or don't store default xml report in tmp dir
(reportConverter == null || !reportConverter.useTmpDirForRawData()) && myOutPath != null) {
// and don't use STDOUT stream
resultsDataPath = myOutPath;
} else {
try {
tmpDir = FileUtil.createTempDirectory("inspections", "data");
resultsDataPath = tmpDir.getPath();
} catch (IOException e) {
LOG.error(e);
System.err.println("Cannot create tmp directory.");
System.exit(1);
return;
}
}
final List<File> inspectionsResults = new ArrayList<>();
ProgressManager.getInstance().runProcess(() -> {
if (!GlobalInspectionContextUtil.canRunInspections(myProject, false)) {
gracefulExit();
return;
}
im.createNewGlobalContext(true).launchInspectionsOffline(scope, resultsDataPath, myRunGlobalToolsOnly, inspectionsResults);
logMessageLn(1, "\n" + InspectionsBundle.message("inspection.capitalized.done") + "\n");
if (!myErrorCodeRequired) {
closeProject();
}
}, new ProgressIndicatorBase() {
private String lastPrefix = "";
private int myLastPercent = -1;
@Override
public void setText(String text) {
if (myVerboseLevel == 0)
return;
if (myVerboseLevel == 1) {
String prefix = getPrefix(text);
if (prefix == null)
return;
if (prefix.equals(lastPrefix)) {
logMessage(1, ".");
return;
}
lastPrefix = prefix;
logMessageLn(1, "");
logMessageLn(1, prefix);
return;
}
if (myVerboseLevel == 3) {
if (!isIndeterminate() && getFraction() > 0) {
final int percent = (int) (getFraction() * 100);
if (myLastPercent == percent)
return;
String prefix = getPrefix(text);
myLastPercent = percent;
String msg = (prefix != null ? prefix : InspectionsBundle.message("inspection.display.name")) + " " + percent + "%";
logMessageLn(2, msg);
}
return;
}
logMessageLn(2, text);
}
});
final String descriptionsFile = resultsDataPath + File.separatorChar + DESCRIPTIONS + XML_EXTENSION;
describeInspections(descriptionsFile, myRunWithEditorSettings ? null : inspectionProfile.getName(), inspectionProfile);
inspectionsResults.add(new File(descriptionsFile));
// convert report
if (reportConverter != null) {
try {
reportConverter.convert(resultsDataPath, myOutPath, im.createNewGlobalContext(true).getTools(), inspectionsResults);
} catch (InspectionsReportConverter.ConversionException e) {
logError("\n" + e.getMessage());
printHelp();
}
}
} catch (IOException e) {
LOG.error(e);
logError(e.getMessage());
printHelp();
} catch (Throwable e) {
LOG.error(e);
logError(e.getMessage());
gracefulExit();
} finally {
// delete tmp dir
if (tmpDir != null) {
FileUtil.delete(tmpDir);
}
}
}
use of com.intellij.openapi.progress.util.ProgressIndicatorBase in project intellij by bazelbuild.
the class DelegatingSwitchToHeaderOrSourceProvider method getItemsWithTimeout.
/**
* Runs the getter under a progress indicator that cancels itself after a certain timeout (assumes
* that the getter will check for cancellation cooperatively).
*
* @param getter computes the GotoRelatedItems.
* @return a list of items computed, or Optional.empty if timed out.
*/
private Optional<List<? extends GotoRelatedItem>> getItemsWithTimeout(ThrowableComputable<List<? extends GotoRelatedItem>, RuntimeException> getter) {
try {
ProgressIndicator indicator = new ProgressIndicatorBase();
ProgressIndicator wrappedIndicator = new WatchdogIndicator(indicator, TIMEOUT_MS, TimeUnit.MILLISECONDS);
// DataContexts which may be used in one of the GotoRelatedProvider#getItems overloads.
return Optional.of(ProgressManager.getInstance().runProcess(() -> ReadAction.compute(getter), wrappedIndicator));
} catch (ProcessCanceledException e) {
return Optional.empty();
}
}
use of com.intellij.openapi.progress.util.ProgressIndicatorBase in project intellij-community by JetBrains.
the class SliceNode method getChildren.
@Override
@NotNull
public Collection<SliceNode> getChildren() {
ProgressIndicator current = ProgressManager.getInstance().getProgressIndicator();
ProgressIndicator indicator = current == null ? new ProgressIndicatorBase() : current;
if (current == null) {
indicator.start();
}
Ref<Collection<SliceNode>> nodes = Ref.create();
ProgressManager.getInstance().executeProcessUnderProgress(() -> nodes.set(getChildrenUnderProgress(ProgressManager.getInstance().getProgressIndicator())), indicator);
if (current == null) {
indicator.stop();
}
return nodes.get();
}
Aggregations