private static void prefetchProjectFiles(Project project) { if (!Blaze.isBlazeProject(project)) { return; } BlazeProjectData projectData = getBlazeProjectData(project); ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet(); if (projectViewSet == null) { return; } long start = System.currentTimeMillis(); ListenableFuture<?> future = PrefetchService.getInstance().prefetchProjectFiles(project, projectViewSet, projectData); TransactionGuard.submitTransaction( project, () -> { DumbService.getInstance(project).queueTask(new PrefetchTask(future, start)); }); }
private void refactor(String currentStepText, String newStepText, TransactionId contextTransaction, CompileContext context, RefactorStatusCallback refactorStatusCallback) { refactorStatusCallback.onStatusChange("Refactoring..."); Module module = GaugeUtil.moduleForPsiElement(file); TransactionGuard.getInstance().submitTransaction(() -> { }, contextTransaction, () -> { Api.PerformRefactoringResponse response = null; FileDocumentManager.getInstance().saveAllDocuments(); FileDocumentManager.getInstance().saveDocumentAsIs(editor.getDocument()); GaugeService gaugeService = Gauge.getGaugeService(module, true); try { response = gaugeService.getGaugeConnection().sendPerformRefactoringRequest(currentStepText, newStepText); } catch (Exception e) { refactorStatusCallback.onFinish(new RefactoringStatus(false, String.format("Could not execute refactor command: %s", e.toString()))); return; } new UndoHandler(response.getFilesChangedList(), module.getProject(), "Refactoring").handle(); if (!response.getSuccess()) { showMessage(response, context, refactorStatusCallback); return; } refactorStatusCallback.onFinish(new RefactoringStatus(true)); }); }
/** * Updates route list. The method starts task that call 'rake routes' and parses result after complete. * After routes are parsed, Routes panel is updated. * * @return True if update task is started, false if new task is not started because routes update is in progress. */ public boolean updateRouteList() { if (isUpdating()) return false; setState(UPDATING); // Save all documents to make sure that requestMethods will be collected using actual files. TransactionGuard.submitTransaction(ApplicationManager.getApplication(), () -> { FileDocumentManager.getInstance().saveAllDocuments(); // Start background task. (new UpdateRoutesTask()).queue(); }); return true; }
public static void performActionDumbAware(AnAction action, AnActionEvent e) { Runnable runnable = new Runnable() { @Override public void run() { try { action.actionPerformed(e); } catch (IndexNotReadyException e1) { showDumbModeWarning(e); } } @Override public String toString() { return action + " of " + action.getClass(); } }; if (action.startInTransaction()) { TransactionGuard.getInstance().submitTransactionAndWait(runnable); } else { runnable.run(); } }
public void run(boolean newConfigFolder) { try { ApplicationEx app = ApplicationManagerEx.getApplicationEx(); app.load(PathManager.getOptionsPath()); if (myPostStarter.needStartInTransaction()) { ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> myPostStarter.main(newConfigFolder, myArgs)); } else { myPostStarter.main(newConfigFolder, myArgs); } myPostStarter = null; ourLoaded = true; } catch (Exception e) { throw new RuntimeException(e); } }
public static void afterItemInsertion(final CompletionProgressIndicator indicator, final Runnable laterRunnable) { if (laterRunnable != null) { ActionTracker tracker = new ActionTracker(indicator.getEditor(), indicator); Runnable wrapper = () -> { if (!indicator.getProject().isDisposed() && !tracker.hasAnythingHappened()) { laterRunnable.run(); } indicator.disposeIndicator(); }; if (ApplicationManager.getApplication().isUnitTestMode()) { wrapper.run(); } else { TransactionGuard.getInstance().submitTransactionLater(indicator, wrapper); } } else { indicator.disposeIndicator(); } }
static boolean chooseActionAndInvoke(@Nonnull PsiFile hostFile, @Nullable final Editor hostEditor, @Nonnull final IntentionAction action, @Nonnull String text, @Nonnull final Project project) { FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.quickFix"); ((FeatureUsageTrackerImpl)FeatureUsageTracker.getInstance()).getFixesStats().registerInvocation(); PsiDocumentManager.getInstance(project).commitAllDocuments(); Pair<PsiFile, Editor> pair = chooseFileForAction(hostFile, hostEditor, action); if (pair == null) return false; CommandProcessor.getInstance() .executeCommand(project, () -> TransactionGuard.getInstance().submitTransactionAndWait(() -> invokeIntention(action, pair.second, pair.first)), text, null); return true; }
private static void reloadPsi(final VirtualFile file, final Project project) { final FileManagerImpl fileManager = (FileManagerImpl)((PsiManagerEx)PsiManager.getInstance(project)).getFileManager(); if (fileManager.findCachedViewProvider(file) != null) { Runnable runnable = new Runnable() { @Override public void run() { WriteAction.run(new ThrowableRunnable<RuntimeException>() { @Override public void run() throws RuntimeException { fileManager.forceReload(file); } }); } }; if (ApplicationManager.getApplication().isDispatchThread()) { runnable.run(); } else { TransactionGuard.submitTransaction(project, runnable); } } }
public PsiDocumentManagerImpl(@Nonnull final Project project, @Nonnull PsiManager psiManager, @Nonnull EditorFactory editorFactory, @Nonnull MessageBus bus, @NonNls @Nonnull final DocumentCommitProcessor documentCommitThread) { super(project, psiManager, bus, documentCommitThread); myDocumentCommitThread = documentCommitThread; editorFactory.getEventMulticaster().addDocumentListener(this, project); MessageBusConnection connection = bus.connect(); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() { @Override public void fileContentLoaded(@Nonnull final VirtualFile virtualFile, @Nonnull Document document) { PsiFile psiFile = ReadAction.compute(() -> myProject.isDisposed() || !virtualFile.isValid() ? null : getCachedPsiFile(virtualFile)); fireDocumentCreated(document, psiFile); } }); connection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() { @Override public void updateFinished(@Nonnull Document doc) { documentCommitThread.commitAsynchronously(project, doc, "Bulk update finished", TransactionGuard.getInstance().getContextTransaction()); } }); Disposer.register(project, () -> ((DocumentCommitThread)myDocumentCommitThread).cancelTasksOnProjectDispose(project)); }
public static void openOptionOrPerformAction(@Nonnull Object element, final String enteredText, @Nullable final Project project, Component component, @Nullable AnActionEvent e) { if (element instanceof OptionDescription) { final String configurableId = ((OptionDescription)element).getConfigurableId(); TransactionGuard.getInstance().submitTransactionLater(project != null ? project : ApplicationManager.getApplication(), new Runnable() { @Override public void run() { ShowSettingsUtilImpl.showSettingsDialog(project, configurableId, enteredText); } }); } else { performAction(element, component, e); } }
private void doDrop(TreeNode targetNode, PsiElement[] sourceElements) { final PsiElement targetElement = getPsiElement(targetNode); if (targetElement == null) return; if (DumbService.isDumb(myProject)) { Messages.showMessageDialog(myProject, "Copy refactoring is not available while indexing is in progress", "Indexing", null); return; } final PsiDirectory psiDirectory; if (targetElement instanceof PsiDirectoryContainer) { final PsiDirectoryContainer directoryContainer = (PsiDirectoryContainer)targetElement; final PsiDirectory[] psiDirectories = directoryContainer.getDirectories(); psiDirectory = psiDirectories.length != 0 ? psiDirectories[0] : null; } else if (targetElement instanceof PsiDirectory) { psiDirectory = (PsiDirectory)targetElement; } else { final PsiFile containingFile = targetElement.getContainingFile(); LOG.assertTrue(containingFile != null); psiDirectory = containingFile.getContainingDirectory(); } TransactionGuard.getInstance().submitTransactionAndWait(() -> CopyHandler.doCopy(sourceElements, psiDirectory)); }
protected void restartAnalysis(final Project project, final AnalysisScope scope) { TransactionGuard guard = TransactionGuard.getInstance(); TransactionId id = guard.getContextTransaction(); DumbService.getInstance(project).smartInvokeLater(() -> TransactionGuard.getInstance().submitTransaction(project, id, () -> { if(DumbService.isDumb(project)) { restartAnalysis(project, scope); } else { analyze(project, scope); } })); }
@Nullable private static Project openProject(@NotNull String projectPath) { final Project[] project = {null}; ApplicationManager.getApplication().invokeAndWait(() -> { TransactionGuard.getInstance().submitTransactionAndWait(() -> project[0] = ProjectUtil.openProject(projectPath, null, true)); requestFocus(project[0]); }); return project[0]; }
private static void rebuildSymbols(Project project) { TransactionGuard.getInstance() .submitTransactionLater( project, () -> ApplicationManager.getApplication().runReadAction(() -> doRebuildSymbols(project))); }
private static void rebuildSymbols(Project project, OCWorkspace workspace) { TransactionGuard.submitTransaction( project, () -> ApplicationManager.getApplication() .runReadAction( () -> OCWorkspaceModificationTrackersCompatUtils.getTrackers(project) .getBuildSettingsChangesTracker() .incModificationCount())); }
void compileAndRefactor(String currentStepText, String newStepText, @Nullable RefactorStatusCallback refactorStatusCallback) { refactorStatusCallback.onStatusChange("Compiling..."); TransactionId contextTransaction = TransactionGuard.getInstance().getContextTransaction(); CompilerManager.getInstance(project).make((aborted, errors, warnings, context) -> { if (errors > 0) { refactorStatusCallback.onFinish(new RefactoringStatus(false, "Please fix all errors before refactoring.")); return; } refactor(currentStepText, newStepText, contextTransaction, context, refactorStatusCallback); }); }
@Nonnull private HyperlinkListener createGotToOptionsListener(@Nonnull final UsageTarget[] targets) { return new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { if (e.getDescription().equals(FIND_OPTIONS_HREF_TARGET)) { TransactionGuard.getInstance().submitTransactionAndWait(() -> FindManager.getInstance(myProject).showSettingsAndFindUsages(targets)); } } }; }
@Nonnull private HyperlinkListener createSearchInProjectListener() { return new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { if (e.getDescription().equals(SEARCH_IN_PROJECT_HREF_TARGET)) { PsiElement psiElement = getPsiElement(mySearchFor); if (psiElement != null) { TransactionGuard.getInstance().submitTransactionAndWait( () -> FindManager.getInstance(myProject).findUsagesInScope(psiElement, GlobalSearchScope.projectScope(myProject))); } } } }; }
public void saveDocument(@Nonnull final Document document, final boolean explicit) { ApplicationManager.getApplication().assertIsDispatchThread(); ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); if (!myUnsavedDocuments.contains(document)) return; try { doSaveDocument(document, explicit); } catch (IOException e) { handleErrorsOnSave(Collections.singletonMap(document, e)); } catch (SaveVetoException ignored) { } }
private static Processor<VirtualFile> createChangeCharsetProcessor() { return file -> { if (!(file instanceof VirtualFileSystemEntry)) return false; Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file); if (cachedDocument == null) return true; ProgressManager.progress("Reloading files...", file.getPresentableUrl()); TransactionGuard.submitTransaction(ApplicationManager.getApplication(), () -> clearAndReload(file)); return true; }; }
private void reloadAllFilesUnder(@Nullable final VirtualFile root) { tryStartReloadWithProgress(() -> processSubFiles(root, file -> { if (!(file instanceof VirtualFileSystemEntry)) return true; Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file); if (cachedDocument != null) { ProgressManager.progress("Reloading file...", file.getPresentableUrl()); TransactionGuard.submitTransaction(myProject, () -> reload(file)); } // for not loaded files deep under project, reset encoding to give them chance re-detect the right one later else if (file.isCharsetSet() && !file.equals(root)) { file.setCharset(null); } return true; })); }
private boolean askUser() { final boolean[] isOk = new boolean[1]; TransactionGuard.getInstance().submitTransactionAndWait(() -> { String actionText = getActionName(myUndoableGroup.getCommandName()); if (actionText.length() > 80) { actionText = actionText.substring(0, 80) + "... "; } isOk[0] = Messages.showOkCancelDialog(myManager.getProject(), actionText + "?", getActionName(), Messages.getQuestionIcon()) == Messages.OK; }); return isOk[0]; }
/** Inserts, removes or replaces the given text at the given offset */ private void editDocumentSafely(final int offset, final int length, @Nullable final String text) { TransactionGuard.submitTransaction(myEditor.getDisposable(), () -> { Project project = myEditor.getProject(); Document document = myEditor.getDocument(); if (!FileDocumentManager.getInstance().requestWriting(document, project)) { return; } CommandProcessor.getInstance().executeCommand(project, () -> WriteAction.run(() -> { document.startGuardedBlockChecking(); try { if (text == null) { // remove document.deleteString(offset, offset + length); } else if (length == 0) { // insert document.insertString(offset, text); } else { document.replaceString(offset, offset + length, text); } } catch (ReadOnlyFragmentModificationException e) { EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e); } finally { document.stopGuardedBlockChecking(); } }), "", document, UndoConfirmationPolicy.DEFAULT, document); }); }
@Override public void mouseDragged(@Nonnull MouseEvent e) { if (myDraggedRange != null || myGutterComponent.myDnDInProgress) return; // on Mac we receive events even if drag-n-drop is in progress validateMousePointer(e); ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> runMouseDraggedCommand(e)); EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) { myGutterComponent.mouseDragged(e); } for (EditorMouseMotionListener listener : myMouseMotionListeners) { listener.mouseDragged(event); } }
@Override protected void exportDone(@Nonnull final JComponent source, @Nullable Transferable data, int action) { if (data == null) return; final Component last = DnDManager.getInstance().getLastDropHandler(); if (last != null && !(last instanceof EditorComponentImpl) && !(last instanceof EditorGutterComponentImpl)) return; final EditorImpl editor = getEditor(source); if (action == MOVE && !editor.isViewer() && editor.myDraggedRange != null) { ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> removeDraggedOutFragment(editor)); } editor.clearDnDContext(); }
private void doScheduledRefresh() { TransactionGuard.submitTransaction(this, () -> { if (canSyncOrSave()) { refreshOpenFiles(); } maybeRefresh(ModalityState.NON_MODAL); }); }
@Override public void setModalityProgress(ProgressIndicator modalityProgress) { LOG.assertTrue(!isRunning()); myModalityProgress = modalityProgress; ModalityState currentModality = ApplicationManager.getApplication().getCurrentModalityState(); myModalityState = myModalityProgress != null ? ((ModalityStateEx)currentModality).appendProgress(myModalityProgress) : currentModality; if (modalityProgress != null) { ((TransactionGuardImpl)TransactionGuard.getInstance()).enteredModality(myModalityState); } }
private void assertWriteAccess() { if (myAssertThreading) { final Application application = ApplicationManager.getApplication(); if (application != null) { application.assertWriteAccessAllowed(); VirtualFile file = FileDocumentManager.getInstance().getFile(this); if (file != null && file.isInLocalFileSystem()) { ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); } } } }
@Override @RequiredDispatchThread protected void fireFileUnchanged() { // later to avoid saving inside document change event processing. TransactionGuard.getInstance().submitTransactionLater(getProject(), () -> { FileDocumentManager.getInstance().saveDocument(myDocument); List<Range> ranges = getRanges(); if (ranges == null || ranges.isEmpty()) { // file was modified, and now it's not -> dirty local change myVcsDirtyScopeManager.fileDirty(myVirtualFile); } }); }
public static void runTransactionWithEverythingCommitted(@Nonnull final Project project, @Nonnull final Runnable runnable) { TransactionGuard guard = TransactionGuard.getInstance(); TransactionId id = guard.getContextTransaction(); final PsiDocumentManager pdm = PsiDocumentManager.getInstance(project); pdm.performLaterWhenAllCommitted(() -> guard.submitTransaction(project, id, () -> { if (pdm.hasUncommitedDocuments()) { // no luck, will try later runTransactionWithEverythingCommitted(project, runnable); } else { runnable.run(); } })); }
@Override public void focusGained(Editor editor) { myCurrentEditor = (EditorEx)editor; if (GeneralSettings.getInstance().isSaveOnFrameDeactivation()) { TransactionGuard.submitTransaction(LanguageConsoleImpl.this, () -> FileDocumentManager.getInstance().saveAllDocuments()); // PY-12487 } }
private void appendMoreUsages(Editor editor, @Nonnull RelativePoint popupPosition, @Nonnull FindUsagesHandler handler, int maxUsages, @Nonnull FindUsagesOptions options) { TransactionGuard.submitTransaction(handler.getProject(), () -> showElementUsages(editor, popupPosition, handler, maxUsages + getUsagesPageSize(), options)); }
public static void performAction(Object element, @Nullable final Component component, @Nullable final AnActionEvent e) { // element could be AnAction (SearchEverywhere) final AnAction action = element instanceof AnAction ? (AnAction)element : ((GotoActionModel.ActionWrapper)element).getAction(); if (action != null) { TransactionGuard.getInstance().submitTransactionLater(ApplicationManager.getApplication(), new Runnable() { @Override public void run() { if (component == null) return; Presentation presentation = action.getTemplatePresentation().clone(); DataContext context = DataManager.getInstance().getDataContext(component); AnActionEvent event = new AnActionEvent(e == null ? null : e.getInputEvent(), context, ActionPlaces.ACTION_SEARCH, presentation, ActionManager.getInstance(), e == null ? 0 : e.getModifiers()); if (ActionUtil.lastUpdateAndCheckDumb(action, event, false)) { if (action instanceof ActionGroup && ((ActionGroup)action).getChildren(event).length > 0) { ListPopup popup = JBPopupFactory.getInstance() .createActionGroupPopup(presentation.getText(), (ActionGroup)action, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false); if (component.isShowing()) { popup.showInBestPositionFor(context); } else { popup.showInFocusCenter(); } } else { ActionUtil.performActionDumbAware(action, event); } } } }); } }
private void doDrop(TreeNode targetNode, PsiElement[] sourceElements, final boolean externalDrop) { final PsiElement targetElement = getPsiElement(targetNode); if (targetElement == null) return; if (DumbService.isDumb(myProject)) { Messages.showMessageDialog(myProject, "Move refactoring is not available while indexing is in progress", "Indexing", null); return; } final Module module = getModule(targetNode); final DataContext dataContext = DataManager.getInstance().getDataContext(myTree); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); if (!targetElement.isValid()) return; for (PsiElement sourceElement : sourceElements) { if (!sourceElement.isValid()) return; } DataContext context = new DataContext() { @Override @Nullable public Object getData(@NonNls Key dataId) { if (LangDataKeys.TARGET_MODULE == dataId) { if (module != null) return module; } if (LangDataKeys.TARGET_PSI_ELEMENT == dataId) { return targetElement; } else { return externalDrop ? null : dataContext.getData(dataId); } } }; TransactionGuard.getInstance().submitTransactionAndWait(() -> getActionHandler().invoke(myProject, sourceElements, context)); }
protected void customizeUsagesView(@Nonnull final UsageViewDescriptor viewDescriptor, @Nonnull final UsageView usageView) { Runnable refactoringRunnable = () -> { Set<UsageInfo> usagesToRefactor = UsageViewUtil.getNotExcludedUsageInfos(usageView); final UsageInfo[] infos = usagesToRefactor.toArray(UsageInfo.EMPTY_ARRAY); TransactionGuard.getInstance().submitTransactionAndWait(() -> { if (ensureElementsWritable(infos, viewDescriptor)) { execute(infos); } }); }; String canNotMakeString = RefactoringBundle.message("usageView.need.reRun"); addDoRefactoringAction(usageView, refactoringRunnable, canNotMakeString); }
private void optimizeImportsOnTheFlyLater(@NotNull final ProgressIndicator progress) { if((myHasRedundantImports || myHasMissortedImports) && !progress.isCanceled()) { // schedule optimise action at the time of session disposal, which is after all applyInformation() calls Disposable invokeFixLater = () -> { // later because should invoke when highlighting is finished TransactionGuard.getInstance().submitTransactionLater(myProject, () -> { if(!myFile.isValid() || !myFile.isWritable()) { return; } IntentionAction optimizeImportsFix = QuickFixFactory.getInstance().createOptimizeImportsFix(true); if(optimizeImportsFix.isAvailable(myProject, null, myFile)) { optimizeImportsFix.invoke(myProject, null, myFile); } }); }; try { Disposer.register((DaemonProgressIndicator) progress, invokeFixLater); } catch(Exception ignored) { // suppress "parent already has been disposed" exception here } if(progress.isCanceled()) { Disposer.dispose(invokeFixLater); Disposer.dispose((DaemonProgressIndicator) progress); progress.checkCanceled(); } } }
public void openSettings() { TransactionGuard.getInstance().submitTransactionLater(() -> { }, () -> ShowSettingsUtil.getInstance().showSettingsDialog(guiInstance.getProject(), "Stack-InTheFlow")); }
public static void submitTransactionAndWait(Runnable runnable) { TransactionGuard.getInstance().submitTransactionAndWait(runnable); }
public static void submitTransaction(Disposable disposable, Runnable runnable) { TransactionGuard.submitTransaction(disposable, runnable); }
@Override public void show() { TransactionGuard.getInstance().submitTransactionAndWait(super::show); }