use of com.intellij.openapi.application.ModalityState in project intellij-community by JetBrains.
the class MvcConsole method executeProcessImpl.
private void executeProcessImpl(final MyProcessInConsole pic, boolean toFocus) {
final Module module = pic.module;
final GeneralCommandLine commandLine = pic.commandLine;
final String[] input = pic.input;
final boolean closeOnDone = pic.closeOnDone;
final Runnable onDone = pic.onDone;
assert module.getProject() == myProject;
myExecuting = true;
// Module creation was cancelled
if (module.isDisposed())
return;
final ModalityState modalityState = ModalityState.current();
final boolean modalContext = modalityState != ModalityState.NON_MODAL;
if (!modalContext && pic.showConsole) {
show(null, toFocus);
}
FileDocumentManager.getInstance().saveAllDocuments();
myConsole.print(commandLine.getCommandLineString(), ConsoleViewContentType.SYSTEM_OUTPUT);
final OSProcessHandler handler;
try {
handler = new OSProcessHandler(commandLine);
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed") OutputStreamWriter writer = new OutputStreamWriter(handler.getProcess().getOutputStream());
for (String s : input) {
writer.write(s);
}
writer.flush();
final Ref<Boolean> gotError = new Ref<>(false);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key key) {
if (key == ProcessOutputTypes.STDERR)
gotError.set(true);
LOG.debug("got text: " + event.getText());
}
@Override
public void processTerminated(ProcessEvent event) {
final int exitCode = event.getExitCode();
if (exitCode == 0 && !gotError.get().booleanValue()) {
ApplicationManager.getApplication().invokeLater(() -> {
if (myProject.isDisposed() || !closeOnDone)
return;
myToolWindow.hide(null);
}, modalityState);
}
}
});
} catch (final Exception e) {
ApplicationManager.getApplication().invokeLater(() -> {
Messages.showErrorDialog(e.getMessage(), "Cannot Start Process");
try {
if (onDone != null && !module.isDisposed())
onDone.run();
} catch (Exception e1) {
LOG.error(e1);
}
}, modalityState);
return;
}
pic.setHandler(handler);
myKillAction.setHandler(handler);
final MvcFramework framework = MvcFramework.getInstance(module);
myToolWindow.setIcon(framework == null ? JetgroovyIcons.Groovy.Groovy_13x13 : framework.getToolWindowIcon());
myContent.setDisplayName((framework == null ? "" : framework.getDisplayName() + ":") + "Executing...");
myConsole.scrollToEnd();
myConsole.attachToProcess(handler);
ApplicationManager.getApplication().executeOnPooledThread(() -> {
handler.startNotify();
handler.waitFor();
ApplicationManager.getApplication().invokeLater(() -> {
if (myProject.isDisposed())
return;
module.putUserData(UPDATING_BY_CONSOLE_PROCESS, true);
LocalFileSystem.getInstance().refresh(false);
module.putUserData(UPDATING_BY_CONSOLE_PROCESS, null);
try {
if (onDone != null && !module.isDisposed())
onDone.run();
} catch (Exception e) {
LOG.error(e);
}
myConsole.print("\n", ConsoleViewContentType.NORMAL_OUTPUT);
myKillAction.setHandler(null);
myContent.setDisplayName("");
myExecuting = false;
final MyProcessInConsole pic1 = myProcessQueue.poll();
if (pic1 != null) {
executeProcessImpl(pic1, false);
}
}, modalityState);
});
}
use of com.intellij.openapi.application.ModalityState in project intellij-community by JetBrains.
the class TreeFileChooserDialog method createCenterPanel.
@Override
protected JComponent createCenterPanel() {
final DefaultTreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode());
myTree = new Tree(model);
final ProjectAbstractTreeStructureBase treeStructure = new AbstractProjectTreeStructure(myProject) {
@Override
public boolean isFlattenPackages() {
return false;
}
@Override
public boolean isShowMembers() {
return false;
}
@Override
public boolean isHideEmptyMiddlePackages() {
return true;
}
@Override
public Object[] getChildElements(final Object element) {
return filterFiles(super.getChildElements(element));
}
@Override
public boolean isAbbreviatePackageNames() {
return false;
}
@Override
public boolean isShowLibraryContents() {
return myShowLibraryContents;
}
@Override
public boolean isShowModules() {
return false;
}
@Override
public List<TreeStructureProvider> getProviders() {
return myDisableStructureProviders ? null : super.getProviders();
}
};
myBuilder = new ProjectTreeBuilder(myProject, myTree, model, AlphaComparator.INSTANCE, treeStructure);
myTree.setRootVisible(false);
myTree.expandRow(0);
myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
myTree.setCellRenderer(new NodeRenderer());
UIUtil.setLineStyleAngled(myTree);
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
scrollPane.setPreferredSize(JBUI.size(500, 300));
myTree.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyCode()) {
doOKAction();
}
}
});
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent e) {
final TreePath path = myTree.getPathForLocation(e.getX(), e.getY());
if (path != null && myTree.isPathSelected(path)) {
doOKAction();
return true;
}
return false;
}
}.installOn(myTree);
myTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(final TreeSelectionEvent e) {
handleSelectionChanged();
}
});
new TreeSpeedSearch(myTree);
myTabbedPane = new TabbedPaneWrapper(getDisposable());
final JPanel dummyPanel = new JPanel(new BorderLayout());
String name = null;
if (myInitialFile != null) {
name = myInitialFile.getName();
}
PsiElement context = myInitialFile == null ? null : myInitialFile;
myGotoByNamePanel = new ChooseByNamePanel(myProject, new MyGotoFileModel(), name, true, context) {
@Override
protected void close(final boolean isOk) {
super.close(isOk);
if (isOk) {
doOKAction();
} else {
doCancelAction();
}
}
@Override
protected void initUI(final ChooseByNamePopupComponent.Callback callback, final ModalityState modalityState, boolean allowMultipleSelection) {
super.initUI(callback, modalityState, allowMultipleSelection);
dummyPanel.add(myGotoByNamePanel.getPanel(), BorderLayout.CENTER);
//IdeFocusTraversalPolicy.getPreferredFocusedComponent(myGotoByNamePanel.getPanel()).requestFocus();
if (mySelectSearchByNameTab) {
myTabbedPane.setSelectedIndex(1);
}
}
@Override
protected void showTextFieldPanel() {
}
@Override
protected void chosenElementMightChange() {
handleSelectionChanged();
}
};
myTabbedPane.addTab(IdeBundle.message("tab.chooser.project"), scrollPane);
myTabbedPane.addTab(IdeBundle.message("tab.chooser.search.by.name"), dummyPanel);
SwingUtilities.invokeLater(() -> myGotoByNamePanel.invoke(new MyCallback(), ModalityState.stateForComponent(getRootPane()), false));
myTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
handleSelectionChanged();
}
});
return myTabbedPane.getComponent();
}
use of com.intellij.openapi.application.ModalityState in project intellij-community by JetBrains.
the class DownloadableLibraryPropertiesEditor method edit.
protected void edit() {
final ModalityState current = ModalityState.current();
myDescription.fetchVersions(new DownloadableFileSetVersions.FileSetVersionsCallback<FrameworkLibraryVersion>() {
@Override
public void onSuccess(@NotNull final List<? extends FrameworkLibraryVersion> versions) {
ApplicationManager.getApplication().invokeLater(() -> {
String pathForDownloaded = "";
final VirtualFile existingRootDirectory = myEditorComponent.getExistingRootDirectory();
if (existingRootDirectory != null) {
pathForDownloaded = existingRootDirectory.getPath();
} else {
final VirtualFile baseDir = myEditorComponent.getBaseDirectory();
if (baseDir != null) {
pathForDownloaded = baseDir.getPath() + "/lib";
}
}
final LibraryDownloadSettings initialSettings = new LibraryDownloadSettings(getCurrentVersion(versions), myLibraryType, LibrariesContainer.LibraryLevel.PROJECT, pathForDownloaded);
final LibraryDownloadSettings settings = DownloadingOptionsDialog.showDialog(getMainPanel(), initialSettings, versions, false);
if (settings != null) {
final NewLibraryEditor editor = settings.download(getMainPanel(), null);
if (editor != null) {
final LibraryEditorBase target = (LibraryEditorBase) myEditorComponent.getLibraryEditor();
target.removeAllRoots();
myEditorComponent.renameLibrary(editor.getName());
target.setType(myLibraryType);
editor.applyTo(target);
myEditorComponent.updateRootsTree();
myCurrentVersionString = settings.getVersion().getVersionString();
setModified();
}
}
}, current);
}
});
}
use of com.intellij.openapi.application.ModalityState in project intellij-community by JetBrains.
the class DocumentationManager method doFetchDocInfo.
private ActionCallback doFetchDocInfo(final DocumentationComponent component, final DocumentationCollector provider, final boolean cancelRequests, final boolean clearHistory) {
final ActionCallback callback = new ActionCallback();
myLastAction = callback;
boolean wasEmpty = component.isEmpty();
component.startWait();
if (cancelRequests) {
myUpdateDocAlarm.cancelAllRequests();
}
if (wasEmpty) {
component.setText(CodeInsightBundle.message("javadoc.fetching.progress"), null, clearHistory);
final AbstractPopup jbPopup = (AbstractPopup) getDocInfoHint();
if (jbPopup != null) {
jbPopup.setDimensionServiceKey(null);
}
}
ModalityState modality = ModalityState.defaultModalityState();
myUpdateDocAlarm.addRequest(() -> {
if (myProject.isDisposed())
return;
LOG.debug("Started fetching documentation...");
final Throwable[] ex = new Throwable[1];
String text = null;
try {
text = provider.getDocumentation();
} catch (Throwable e) {
LOG.info(e);
ex[0] = e;
}
if (ex[0] != null) {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> {
String message = ex[0] instanceof IndexNotReadyException ? "Documentation is not available until indices are built." : CodeInsightBundle.message("javadoc.external.fetch.error.message");
component.setText(message, null, true);
callback.setDone();
});
return;
}
LOG.debug("Documentation fetched successfully:\n", text);
final PsiElement element = ApplicationManager.getApplication().runReadAction(new Computable<PsiElement>() {
@Override
@Nullable
public PsiElement compute() {
return provider.getElement();
}
});
if (element == null) {
LOG.debug("Element for which documentation was requested is not available anymore");
return;
}
final String documentationText = text;
PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted(() -> {
if (!element.isValid()) {
LOG.debug("Element for which documentation was requested is not valid");
callback.setDone();
return;
}
if (documentationText == null) {
component.setText(CodeInsightBundle.message("no.documentation.found"), element, true, clearHistory);
} else if (documentationText.isEmpty()) {
component.setText(component.getText(), element, true, clearHistory);
} else {
component.setData(element, documentationText, clearHistory, provider.getEffectiveExternalUrl(), provider.getRef());
}
final AbstractPopup jbPopup = (AbstractPopup) getDocInfoHint();
if (jbPopup == null) {
callback.setDone();
return;
}
jbPopup.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE);
jbPopup.setCaption(getTitle(element, false));
// Set panel name so that it is announced by readers when it gets the focus
AccessibleContextUtil.setName(component, getTitle(element, false));
callback.setDone();
}, modality);
}, 10);
return callback;
}
use of com.intellij.openapi.application.ModalityState in project intellij-community by JetBrains.
the class FindDialog method findSettingsChanged.
private void findSettingsChanged() {
if (haveResultsPreview()) {
final ModalityState state = ModalityState.current();
// skip initial changes
if (state == ModalityState.NON_MODAL)
return;
finishPreviousPreviewSearch();
mySearchRescheduleOnCancellationsAlarm.cancelAllRequests();
final FindModel findModel = myHelper.getModel().clone();
applyTo(findModel, false);
ValidationInfo result = getValidationInfo(findModel);
final ProgressIndicatorBase progressIndicatorWhenSearchStarted = new ProgressIndicatorBase();
myResultsPreviewSearchProgress = progressIndicatorWhenSearchStarted;
final DefaultTableModel model = new DefaultTableModel() {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// 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() < findModel.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 = findModel;
model.addColumn("Usages");
myResultsPreviewTable.setModel(model);
if (result != null) {
myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow"));
myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE);
return;
}
myResultsPreviewTable.getColumnModel().getColumn(0).setCellRenderer(new UsageTableCellRenderer(false, true));
myResultsPreviewTable.getEmptyText().setText("Searching...");
myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE);
final Component component = myInputComboBox.getEditor().getEditorComponent();
// (UsagePreviewPanel.highlight)
if (component instanceof EditorTextField) {
final Document document = ((EditorTextField) component).getDocument();
if (document != null) {
PsiDocumentManager.getInstance(myProject).commitDocument(document);
}
}
final AtomicInteger resultsCount = new AtomicInteger();
final AtomicInteger resultsFilesCount = new AtomicInteger();
ProgressIndicatorUtils.scheduleWithWriteActionPriority(myResultsPreviewSearchProgress, new ReadTask() {
@Nullable
@Override
public Continuation performInReadAction(@NotNull ProgressIndicator indicator) throws ProcessCanceledException {
final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(FindSettings.getInstance().isShowResultsInSeparateView(), findModel);
final boolean showPanelIfOnlyOneUsage = !FindSettings.getInstance().isSkipResultsWithOneUsage();
final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, showPanelIfOnlyOneUsage, presentation);
Ref<VirtualFile> lastUsageFileRef = new Ref<>();
FindInProjectUtil.findUsages(findModel, 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 });
}, state);
return resultsCount.incrementAndGet() < ShowUsagesAction.USAGES_PAGE_SIZE;
}, processPresentation, filesToScanInitially);
boolean succeeded = !progressIndicatorWhenSearchStarted.isCanceled();
if (succeeded) {
return new Continuation(() -> {
if (progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress && !myResultsPreviewSearchProgress.isCanceled()) {
int occurrences = resultsCount.get();
int filesWithOccurrences = resultsFilesCount.get();
if (occurrences == 0)
myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow"));
boolean foundAllUsages = occurrences < ShowUsagesAction.USAGES_PAGE_SIZE;
myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE + " (" + (foundAllUsages ? Integer.valueOf(occurrences) : occurrences + "+") + UIBundle.message("message.matches", occurrences) + " in " + (foundAllUsages ? Integer.valueOf(filesWithOccurrences) : filesWithOccurrences + "+") + UIBundle.message("message.files", filesWithOccurrences) + ")");
}
}, state);
}
return null;
}
@Override
public void onCanceled(@NotNull ProgressIndicator indicator) {
if (isShowing() && progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress) {
scheduleResultsUpdate();
}
}
});
}
}
Aggregations