com.intellij.openapi.application.TransactionGuard Java Examples

The following examples show how to use com.intellij.openapi.application.TransactionGuard. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LaterInvocator.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void enterModal(@Nonnull Object modalEntity, @Nonnull ModalityStateEx appendedState) {
  LOG.assertTrue(isDispatchThread(), "enterModal() should be invoked in event-dispatch thread");

  if (LOG.isDebugEnabled()) {
    LOG.debug("enterModal:" + modalEntity);
  }

  ourModalityStateMulticaster.getMulticaster().beforeModalityStateChanged(true);

  ourModalEntities.add(modalEntity);
  ourModalityStack.push(appendedState);

  TransactionGuardEx guard = ApplicationStarter.isLoaded() ? (TransactionGuardEx)TransactionGuard.getInstance() : null;
  if (guard != null) {
    guard.enteredModality(appendedState);
  }

  reincludeSkippedItems();
  requestFlush();
}
 
Example #2
Source File: WidgetEditToolbar.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final AnAction action = ActionManager.getInstance().getAction("Flutter.ExtractWidget");
  if (action != null) {
    TransactionGuard.submitTransaction(project, () -> {
      final Editor editor = getCurrentEditor();
      if (editor == null) {
        // It is a race condition if we hit this. Gracefully assume
        // the action has just been canceled.
        return;
      }
      final JComponent editorComponent = editor.getComponent();
      final DataContext editorContext = DataManager.getInstance().getDataContext(editorComponent);
      final AnActionEvent editorEvent = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, editorContext);

      action.actionPerformed(editorEvent);
    });
  }
}
 
Example #3
Source File: WidgetEditToolbar.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final AnAction action = ActionManager.getInstance().getAction("Flutter.ExtractWidget");
  if (action != null) {
    TransactionGuard.submitTransaction(project, () -> {
      final Editor editor = getCurrentEditor();
      if (editor == null) {
        // It is a race condition if we hit this. Gracefully assume
        // the action has just been canceled.
        return;
      }
      final JComponent editorComponent = editor.getComponent();
      final DataContext editorContext = DataManager.getInstance().getDataContext(editorComponent);
      final AnActionEvent editorEvent = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, editorContext);

      action.actionPerformed(editorEvent);
    });
  }
}
 
Example #4
Source File: WidgetEditToolbar.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final AnAction action = ActionManager.getInstance().getAction("ExtractMethod");
  if (action != null) {
    final FlutterOutline outline = getWidgetOutline();
    if (outline != null) {
      TransactionGuard.submitTransaction(project, () -> {
        final Editor editor = getCurrentEditor();
        if (editor == null) {
          // It is a race condition if we hit this. Gracefully assume
          // the action has just been canceled.
          return;
        }
        final OutlineOffsetConverter converter = new OutlineOffsetConverter(project, activeFile.getValue());
        final int offset = converter.getConvertedOutlineOffset(outline);
        editor.getCaretModel().moveToOffset(offset);

        final JComponent editorComponent = editor.getComponent();
        final DataContext editorContext = DataManager.getInstance().getDataContext(editorComponent);
        final AnActionEvent editorEvent = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, editorContext);

        action.actionPerformed(editorEvent);
      });
    }
  }
}
 
Example #5
Source File: CopyPasteDelegator.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean performDefaultPaste(final DataContext dataContext) {
  final boolean[] isCopied = new boolean[1];
  final PsiElement[] elements = PsiCopyPasteManager.getInstance().getElements(isCopied);
  if (elements == null) return false;

  DumbService.getInstance(myProject).setAlternativeResolveEnabled(true);
  try {
    final Module module = dataContext.getData(LangDataKeys.MODULE);
    PsiElement target = getPasteTarget(dataContext, module);
    if (isCopied[0]) {
      TransactionGuard.getInstance().submitTransactionAndWait(() -> pasteAfterCopy(elements, module, target, true));
    }
    else if (MoveHandler.canMove(elements, target)) {
      TransactionGuard.getInstance().submitTransactionAndWait(() -> pasteAfterCut(dataContext, elements, target));
    }
    else {
      return false;
    }
  }
  finally {
    DumbService.getInstance(myProject).setAlternativeResolveEnabled(false);
    updateView();
  }
  return true;
}
 
Example #6
Source File: ProjectViewDropTarget.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void doDrop(@Nonnull TreePath target, PsiElement[] sources) {
  final PsiElement targetElement = getPsiElement(target);
  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, targetElement);
    psiDirectory = containingFile.getContainingDirectory();
  }
  TransactionGuard.getInstance().submitTransactionAndWait(() -> CopyHandler.doCopy(sources, psiDirectory));
}
 
Example #7
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initPre41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //registerComponents();
    Method method = ReflectionUtil.getDeclaredMethod(ProjectImpl.class, "registerComponents");
    assert (method != null);
    try {
      method.invoke(this);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    getStateStore().setPath(path, true, null);
    super.init(indicator);
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #8
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)));
    }
  }
}
 
Example #9
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initPre41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //registerComponents();
    Method method = ReflectionUtil.getDeclaredMethod(ProjectImpl.class, "registerComponents");
    assert (method != null);
    try {
      method.invoke(this);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    getStateStore().setPath(path, true, null);
    super.init(indicator);
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #10
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)));
    }
  }
}
 
Example #11
Source File: WidgetEditToolbar.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final AnAction action = ActionManager.getInstance().getAction("ExtractMethod");
  if (action != null) {
    final FlutterOutline outline = getWidgetOutline();
    if (outline != null) {
      TransactionGuard.submitTransaction(project, () -> {
        final Editor editor = getCurrentEditor();
        if (editor == null) {
          // It is a race condition if we hit this. Gracefully assume
          // the action has just been canceled.
          return;
        }
        final OutlineOffsetConverter converter = new OutlineOffsetConverter(project, activeFile.getValue());
        final int offset = converter.getConvertedOutlineOffset(outline);
        editor.getCaretModel().moveToOffset(offset);

        final JComponent editorComponent = editor.getComponent();
        final DataContext editorContext = DataManager.getInstance().getDataContext(editorComponent);
        final AnActionEvent editorEvent = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, editorContext);

        action.actionPerformed(editorEvent);
      });
    }
  }
}
 
Example #12
Source File: GotoActionAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void openOptionOrPerformAction(Object element, String enteredText, @Nullable Project project, Component component, @JdkConstants.InputEventMask int modifiers) {
  if (element instanceof OptionDescription) {
    OptionDescription optionDescription = (OptionDescription)element;
    String configurableId = optionDescription.getConfigurableId();
    Disposable disposable = project != null ? project : ApplicationManager.getApplication();
    TransactionGuard guard = TransactionGuard.getInstance();
    if (optionDescription.hasExternalEditor()) {
      guard.submitTransactionLater(disposable, () -> optionDescription.invokeInternalEditor());
    }
    else {
      guard.submitTransactionLater(disposable, () -> ShowSettingsUtil.getInstance().showSettingsDialog(project, configurableId, enteredText));
    }
  }
  else {
    ApplicationManager.getApplication().invokeLater(() -> IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> performAction(element, component, null, modifiers, null)));
  }
}
 
Example #13
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
public 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 (isTestingMode()) {
      wrapper.run();
    }
    else {
      TransactionGuard.getInstance().submitTransactionLater(indicator, wrapper);
    }
  }
  else {
    indicator.disposeIndicator();
  }
}
 
Example #14
Source File: BaseRefactoringProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
  usageView.setRerunAction(new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
      doRun();
    }
  });
}
 
Example #15
Source File: ActionUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example #16
Source File: RoutesManager.java    From railways with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: GaugeRefactorHandler.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
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));
    });
}
 
Example #18
Source File: ApplicationStarter.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void run(StatCollector stat, Runnable appInitalizeMark, boolean newConfigFolder) {
  try {
    ApplicationEx app = (ApplicationEx)Application.get();
    app.load(ContainerPathManager.get().getOptionsPath());

    if (myPostStarter.needStartInTransaction()) {
      ((TransactionGuardEx)TransactionGuard.getInstance()).performUserActivity(() -> myPostStarter.main(stat, appInitalizeMark, app, newConfigFolder, myArgs));
    }
    else {
      myPostStarter.main(stat, appInitalizeMark, app, newConfigFolder, myArgs);
    }

    myPostStarter = null;

    ourLoaded = true;
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #19
Source File: AutoSwitcher.java    From JHelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void addSelectedConfigurationListener() {
	RunManagerImpl.getInstanceImpl(project).addRunManagerListener(new RunManagerListener() {
		@Override
		public void runConfigurationSelected(RunnerAndConfigurationSettings selectedConfiguration) {
			if (selectedConfiguration == null) {
				return;
			}
			RunConfiguration configuration = selectedConfiguration.getConfiguration();
			if (busy || !(configuration instanceof TaskConfiguration)) {
				return;
			}
			busy = true;
			String pathToClassFile = ((TaskConfiguration) configuration).getCppPath();
			VirtualFile toOpen = project.getBaseDir().findFileByRelativePath(pathToClassFile);
			if (toOpen != null) {
				TransactionGuard.getInstance().submitTransactionAndWait(() -> FileEditorManager.getInstance(project).openFile(
						toOpen,
						true
				));
			}
			busy = false;
		}
	});
}
 
Example #20
Source File: BlazeTypeScriptConfigServiceImpl.java    From intellij with Apache License 2.0 6 votes vote down vote up
private void restartServiceIfConfigsChanged() {
  if (!restartTypeScriptService.getValue()) {
    return;
  }
  int pathHash = Arrays.hashCode(configs.keySet().stream().map(VirtualFile::getPath).toArray());
  long contentTimestamp =
      configs.values().stream()
          .map(TypeScriptConfig::getDependencies)
          .flatMap(Collection::stream)
          .map(VfsUtil::virtualToIoFile)
          .map(File::lastModified)
          .max(Comparator.naturalOrder())
          .orElse(0L);
  int newConfigsHash = Objects.hash(pathHash, contentTimestamp);
  if (configsHash.getAndSet(newConfigsHash) != newConfigsHash) {
    TransactionGuard.getInstance()
        .submitTransactionLater(
            project, () -> TypeScriptCompilerService.restartServices(project, false));
  }
}
 
Example #21
Source File: ExecutionPointHighlighter.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void show(final @Nonnull XSourcePosition position, final boolean notTopFrame, @Nullable final GutterIconRenderer gutterIconRenderer) {
  updateRequested.set(false);
  TransactionGuard.submitTransaction(myProject, () -> {
    updateRequested.set(false);

    mySourcePosition = position;

    clearDescriptor();
    myOpenFileDescriptor = XSourcePositionImpl.createOpenFileDescriptor(myProject, position);
    if (!XDebuggerSettingManagerImpl.getInstanceImpl().getGeneralSettings().isScrollToCenter()) {
      myOpenFileDescriptor.setScrollType(notTopFrame ? ScrollType.CENTER : ScrollType.MAKE_VISIBLE);
    }
    //see IDEA-125645 and IDEA-63459
    //myOpenFileDescriptor.setUseCurrentWindow(true);

    myGutterIconRenderer = gutterIconRenderer;
    myNotTopFrame = notTopFrame;

    doShow(true);
  });
}
 
Example #22
Source File: BlazeCWorkspace.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Notifies the workspace of changes in inputs to the resolve configuration. See {@link
 * com.jetbrains.cidr.lang.workspace.OCWorkspaceListener.OCWorkspaceEvent}.
 */
private void incModificationTrackers() {
  TransactionGuard.submitTransaction(
      project,
      () -> {
        if (project.isDisposed()) {
          return;
        }
        OCWorkspaceEventImpl event =
            new OCWorkspaceEventImpl(
                /* resolveConfigurationsChanged= */ true,
                /* sourceFilesChanged= */ true,
                /* compilerSettingsChanged= */ true);
        ((OCWorkspaceModificationTrackersImpl)
                OCWorkspace.getInstance(project).getModificationTrackers())
            .fireWorkspaceChanged(event);
      });
}
 
Example #23
Source File: PendingWebTestContext.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public void resolve(
    ExecutionEnvironment env, BlazeCommandRunConfiguration config, Runnable rerun) {
  DataContext dataContext = env.getDataContext();
  if (dataContext == null) {
    return;
  }
  JBPopup popup =
      JBPopupFactory.getInstance()
          .createPopupChooserBuilder(wrapperTests)
          .setTitle("Choose Web Test to Run")
          .setMovable(false)
          .setResizable(false)
          .setRequestFocus(true)
          .setCancelOnWindowDeactivation(false)
          .setItemChosenCallback(
              (wrapperTest) -> updateContextAndRerun(config, wrapperTest, rerun))
          .createPopup();
  TransactionGuard.getInstance()
      .submitTransactionAndWait(() -> popup.showInBestPositionFor(dataContext));
}
 
Example #24
Source File: DesktopEditorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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 DesktopEditorImpl editor = getEditor(source);
  if (action == MOVE && !editor.isViewer() && editor.myDraggedRange != null) {
    ((TransactionGuardEx)TransactionGuard.getInstance()).performUserActivity(() -> removeDraggedOutFragment(editor));
  }

  editor.clearDnDContext();
}
 
Example #25
Source File: EncodingProjectManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
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;
  }));
}
 
Example #26
Source File: ActionMenuItem.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * We have to make this method public to allow BegMenuItemUI to invoke it.
 */
@Override
public void fireActionPerformed(final ActionEvent event) {
  TransactionGuard.submitTransaction(ApplicationManager.getApplication(), new Runnable() {
    @Override
    public void run() {
      ActionMenuItem.super.fireActionPerformed(event);
    }
  });
}
 
Example #27
Source File: UndoRedo.java    From consulo with Apache License 2.0 5 votes vote down vote up
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];
}
 
Example #28
Source File: EncodingProjectManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
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;
  };
}
 
Example #29
Source File: DesktopEditorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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);
  ((TransactionGuardEx)TransactionGuard.getInstance()).performUserActivity(() -> runMouseDraggedCommand(e));
  EditorMouseEvent event = new EditorMouseEvent(DesktopEditorImpl.this, e, getMouseEventArea(e));
  if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) {
    myGutterComponent.mouseDragged(e);
  }

  for (EditorMouseMotionListener listener : myMouseMotionListeners) {
    listener.mouseDragged(event);
    if (isReleased) return;
  }
}
 
Example #30
Source File: OnEventCreateFix.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(Project project, Editor editor, PsiFile file)
    throws IncorrectOperationException {
  final AtomicReference<PsiMethod> eventMethodRef = new AtomicReference<>();
  final Runnable generateOnEvent =
      () ->
          OnEventGenerateAction.createHandler(
                  (context, eventProject) -> event, eventMethodRef::set)
              .invoke(project, editor, file);
  final Runnable updateArgumentList =
      () ->
          Optional.ofNullable(eventMethodRef.get())
              .map(
                  eventMethod ->
                      AddArgumentFix.createArgumentList(
                          methodCall,
                          clsName,
                          eventMethod.getName(),
                          JavaPsiFacade.getInstance(project).getElementFactory()))
              .ifPresent(argumentList -> methodCall.getArgumentList().replace(argumentList));
  final Runnable action =
      () -> {
        TransactionGuard.getInstance().submitTransactionAndWait(generateOnEvent);
        WriteCommandAction.runWriteCommandAction(project, updateArgumentList);
        ComponentGenerateUtils.updateLayoutComponent(layoutCls);
        LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_FIX_EVENT_HANDLER + ".new");
      };
  final Application application = ApplicationManager.getApplication();
  if (application.isUnitTestMode()) {
    action.run();
  } else {
    application.invokeLater(action);
  }
}