@Override
  public void runWhenProjectIsInitialized(@NotNull final Runnable action) {
    final Application application = ApplicationManager.getApplication();
    if (application == null) return;

    //noinspection SynchronizeOnThis
    synchronized (this) {
      // in tests which simulate project opening, post-startup activities could have been run
      // already.
      // Then we should act as if the project was initialized
      boolean initialized =
          myProject.isInitialized()
              || application.isUnitTestMode() && myPostStartupActivitiesPassed;
      if (!initialized) {
        registerPostStartupActivity(action);
        return;
      }
    }

    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            if (!myProject.isDisposed()) {
              action.run();
            }
          }
        };
    if (application.isDispatchThread() && ModalityState.current() == ModalityState.NON_MODAL) {
      runnable.run();
    } else {
      application.invokeLater(runnable, ModalityState.NON_MODAL);
    }
  }
示例#2
0
  public void doExecute(@NotNull final AnActionEvent event, final Map<String, Object> _params) {
    try {
      FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.rootNode");

      Project project = event.getData(PlatformDataKeys.PROJECT);
      assert project != null;

      RootChooseModel chooseSNodeResult = new RootChooseModel(project, new RootNodeNameIndex());
      ChooseByNamePopup popup =
          MpsPopupFactory.createNodePopupWithParentAction(
              project, chooseSNodeResult, GoToRootNode_Action.this);

      popup.invoke(
          new ChooseByNamePopupComponent.Callback() {
            @Override
            public void onClose() {}

            @Override
            public void elementChosen(Object element) {
              ((NavigationItem) element).navigate(true);
            }
          },
          ModalityState.current(),
          true);
    } catch (Throwable t) {
      if (LOG.isEnabledFor(Level.ERROR)) {
        LOG.error("User's action execute method failed. Action:" + "GoToRootNode", t);
      }
    }
  }
示例#3
0
  public static void addModelImport(
      final Project project,
      final SModule module,
      final SModel model,
      @Nullable BaseAction parentAction) {
    BaseModelModel goToModelModel =
        new BaseModelModel(project) {
          @Override
          public NavigationItem doGetNavigationItem(final SModelReference modelReference) {
            return new AddModelItem(project, model, modelReference, module);
          }

          @Override
          public SModelReference[] find(SearchScope scope) {
            Condition<SModel> cond =
                new Condition<SModel>() {
                  @Override
                  public boolean met(SModel modelDescriptor) {
                    boolean rightStereotype =
                        SModelStereotype.isUserModel(modelDescriptor)
                            || SModelStereotype.isStubModelStereotype(
                                SModelStereotype.getStereotype(modelDescriptor));
                    boolean hasModule = modelDescriptor.getModule() != null;
                    return rightStereotype && hasModule;
                  }
                };
            ConditionalIterable<SModel> iter =
                new ConditionalIterable<SModel>(scope.getModels(), cond);
            List<SModelReference> filteredModelRefs = new ArrayList<SModelReference>();
            for (SModel md : iter) {
              filteredModelRefs.add(md.getReference());
            }
            return filteredModelRefs.toArray(new SModelReference[filteredModelRefs.size()]);
          }

          @Override
          @Nullable
          public String getPromptText() {
            return "Import model:";
          }
        };
    ChooseByNamePopup popup =
        MpsPopupFactory.createPackagePopup(project, goToModelModel, parentAction);

    popup.invoke(
        new ChooseByNamePopupComponent.Callback() {
          @Override
          public void onClose() {
            // if (GoToRootNodeAction.class.equals(myInAction)) myInAction = null;
          }

          @Override
          public void elementChosen(final Object element) {
            ((NavigationItem) element).navigate(true);
          }
        },
        ModalityState.current(),
        true);
  }
示例#4
0
  public static void addModelImportByRoot(
      final Project project,
      final SModule contextModule,
      final SModel model,
      String initialText,
      @Nullable BaseAction parentAction,
      final ModelImportByRootCallback callback) {
    BaseMPSChooseModel goToNodeModel =
        new RootChooseModel(project, new RootNodeNameIndex()) {
          @Override
          public NavigationItem doGetNavigationItem(final NavigationTarget object) {
            return new RootNodeElement(object) {
              @Override
              public void navigate(boolean requestFocus) {
                ModelAccess.assertLegalRead();
                new AddModelItem(
                        project,
                        model,
                        object.getNodeReference().getModelReference(),
                        contextModule)
                    .navigate(requestFocus);
              }
            };
          }

          @Override
          @Nullable
          public String getPromptText() {
            return "Import model that contains root:";
          }
        };
    ChooseByNamePopup popup =
        MpsPopupFactory.createNodePopup(project, goToNodeModel, initialText, parentAction);

    popup.invoke(
        new ChooseByNamePopupComponent.Callback() {
          @Override
          public void onClose() {
            // if (GoToRootNodeAction.class.equals(myInAction)) myInAction = null;
          }

          @Override
          public void elementChosen(final Object element) {
            ModelAccess.instance()
                .runWriteAction(
                    new Runnable() {
                      @Override
                      public void run() {
                        NavigationItem navigationItem = (NavigationItem) element;
                        navigationItem.navigate(true);
                        callback.importForRootAdded(
                            navigationItem.getPresentation().getPresentableText());
                      }
                    });
          }
        },
        ModalityState.current(),
        true);
  }
示例#5
0
  private void doInit(
      final List<SModelReference> options, @Nullable List<SModelReference> nonProjectModels) {
    setModal(true);
    myModels.addAll(options);
    if (nonProjectModels != null) {
      myNonProjectModels.addAll(nonProjectModels);
    }

    DataContext dataContext = DataManager.getInstance().getDataContext();
    final Project project = MPSDataKeys.PROJECT.getData(dataContext);

    BaseModelModel goToModelModel =
        new BaseModelModel(project) {
          public NavigationItem doGetNavigationItem(final SModelReference modelReference) {
            return new BaseModelItem(modelReference) {
              public void navigate(boolean requestFocus) {}
            };
          }

          @Override
          public SModelReference[] find(boolean checkboxState) {
            if (checkboxState) {
              return myNonProjectModels.toArray(new SModelReference[myNonProjectModels.size()]);
            } else {
              return myModels.toArray(new SModelReference[myModels.size()]);
            }
          }

          public SModelReference[] find(IScope scope) {
            throw new UnsupportedOperationException("must not be used");
          }

          @Override
          public boolean loadInitialCheckBoxState() {
            return false;
          }
        };

    myChooser =
        MpsPopupFactory.createPanelForPackage(goToModelModel, !myNonProjectModels.isEmpty());
    myChooser.invoke(
        new Callback() {
          public void elementChosen(Object element) {
            if (!myOkDone) {
              myOkDone = true;
              onOk();
            }
          }
        },
        ModalityState.current(),
        myIsMultipleSelection);
  }
  private static void showDumbModeWarningLaterIfNobodyConsumesEvent(
      final InputEvent e, final AnActionEvent... actionEvents) {
    if (ModalityState.current() == ModalityState.NON_MODAL) {
      ApplicationManager.getApplication()
          .invokeLater(
              new Runnable() {
                public void run() {
                  if (e.isConsumed()) return;

                  ActionUtil.showDumbModeWarning(actionEvents);
                }
              });
    }
  }
示例#7
0
  public static void addLanguageImport(
      final Project project,
      final SModule contextModule,
      final SModel model,
      @Nullable BaseAction parentAction,
      @Nullable final Runnable onClose) {
    BaseLanguageModel goToLanguageModel =
        new BaseLanguageModel(project) {
          @Override
          public NavigationItem doGetNavigationItem(SModuleReference ref) {
            return new AddLanguageItem(project, ref, contextModule, model);
          }

          @Override
          public SModuleReference[] find(SearchScope scope) {
            ArrayList<SModuleReference> res = new ArrayList<SModuleReference>();
            for (SModule m : scope.getModules()) {
              if (!(m instanceof Language)) continue;
              res.add(m.getModuleReference());
            }
            return res.toArray(new SModuleReference[res.size()]);
          }

          @Nullable
          @Override
          public String getPromptText() {
            return "Import language:";
          }
        };
    ChooseByNamePopup popup =
        MpsPopupFactory.createPackagePopup(project, goToLanguageModel, parentAction);

    popup.invoke(
        new ChooseByNamePopupComponent.Callback() {
          @Override
          public void onClose() {
            // if (GoToRootNodeAction.class.equals(myInAction)) myInAction = null;
            if (onClose != null) {
              onClose.run();
            }
          }

          @Override
          public void elementChosen(Object element) {
            ((NavigationItem) element).navigate(true);
          }
        },
        ModalityState.current(),
        true);
  }
  @CalledInAwt
  @NotNull
  public static ProgressIndicator executeOnPooledThread(
      @NotNull final Consumer<ProgressIndicator> task, @NotNull Disposable parent) {
    final ModalityState modalityState = ModalityState.current();
    final ProgressIndicator indicator =
        new EmptyProgressIndicator() {
          @NotNull
          @Override
          public ModalityState getModalityState() {
            return modalityState;
          }
        };
    indicator.start();

    final Disposable disposable =
        new Disposable() {
          @Override
          public void dispose() {
            if (indicator.isRunning()) indicator.cancel();
          }
        };
    Disposer.register(parent, disposable);

    ApplicationManager.getApplication()
        .executeOnPooledThread(
            new Runnable() {
              @Override
              public void run() {
                ProgressManager.getInstance()
                    .executeProcessUnderProgress(
                        new Runnable() {
                          @Override
                          public void run() {
                            try {
                              task.consume(indicator);
                            } finally {
                              indicator.stop();
                              Disposer.dispose(disposable);
                            }
                          }
                        },
                        indicator);
              }
            });

    return indicator;
  }
示例#9
0
  public void doExecute(AnActionEvent e, Map<String, Object> _params) {
    final Project project = e.getData(PlatformDataKeys.PROJECT);
    assert project != null;

    FeatureUsageTracker.getInstance().triggerFeatureUsed("goto.model");
    // PsiDocumentManager.getInstance(project).commitAllDocuments();

    BaseModelModel goToModelModel =
        new BaseModelModel(project) {
          public NavigationItem doGetNavigationItem(final SModelReference modelReference) {
            return new BaseModelItem(modelReference) {
              public void navigate(boolean requestFocus) {
                ProjectPane projectPane = ProjectPane.getInstance(project);
                SModelDescriptor md =
                    SModelRepository.getInstance().getModelDescriptor(modelReference);
                projectPane.selectModel(md, true);
              }
            };
          }

          public SModelReference[] find(IScope scope) {
            Condition<SModelDescriptor> cond =
                new Condition<SModelDescriptor>() {
                  public boolean met(SModelDescriptor modelDescriptor) {
                    boolean rightStereotype =
                        SModelStereotype.isUserModel(modelDescriptor)
                            || SModelStereotype.isStubModelStereotype(
                                modelDescriptor.getStereotype());
                    boolean hasModule = modelDescriptor.getModule() != null;
                    return rightStereotype && hasModule;
                  }
                };
            ConditionalIterable<SModelDescriptor> iter =
                new ConditionalIterable<SModelDescriptor>(scope.getModelDescriptors(), cond);
            List<SModelReference> result = new ArrayList<SModelReference>();
            for (SModelDescriptor md : iter) {
              result.add(md.getSModelReference());
            }
            return result.toArray(new SModelReference[result.size()]);
          }
        };
    ChooseByNamePopup popup = MpsPopupFactory.createPackagePopup(project, goToModelModel);
    popup.setShowListForEmptyPattern(true);
    popup.invoke(new NavigateCallback(), ModalityState.current(), true);
  }
示例#10
0
  public void doExecute(AnActionEvent e, Map<String, Object> _params) {
    final Project project = e.getData(PlatformDataKeys.PROJECT);
    assert project != null;

    ChooseByNamePopup popup;

    if (!myUseCache) {
      BaseNodeModel baseNodeModel =
          new BaseNodeModel(project) {
            public SNode[] find(IScope scope) {
              final List<SNode> nodes = new ArrayList<SNode>();
              Iterable<SModelDescriptor> modelDescriptors = scope.getModelDescriptors();
              for (SModelDescriptor modelDescriptor : modelDescriptors) {
                if (!SModelStereotype.isUserModel(modelDescriptor)) continue;
                for (SNode node : modelDescriptor.getSModel().roots()) {
                  nodes.add(node);
                }
              }
              return nodes.toArray(new SNode[0]);
            }

            public boolean willOpenEditor() {
              return true;
            }
          };
      popup = MpsPopupFactory.createNodePopup(project, baseNodeModel);
    } else {
      MPSChooseSNodeDescriptor chooseSNodeResult =
          new MPSChooseSNodeDescriptor(project, new RootNodeNameIndex());
      popup = MpsPopupFactory.createNodePopup(project, chooseSNodeResult);
    }

    popup.invoke(
        new ChooseByNamePopupComponent.Callback() {
          public void onClose() {}

          public void elementChosen(Object element) {
            ((NavigationItem) element).navigate(true);
          }
        },
        ModalityState.current(),
        true);
  }
示例#11
0
  private void doInit(final List<SNode> options) {
    setModal(true);
    myNodes.addAll(options);

    DataContext dataContext = DataManager.getInstance().getDataContext();
    final Project project = MPSDataKeys.PROJECT.getData(dataContext);

    BaseNodeModel goToNodeModel =
        new BaseNodeModel(project) {
          public NavigationItem doGetNavigationItem(final SNode node) {
            return new BaseNodeItem(node) {
              public void navigate(boolean requestFocus) {}
            };
          }

          @Override
          public SNode[] find(boolean checkboxState) {
            return myNodes.toArray(new SNode[myNodes.size()]);
          }

          public SNode[] find(IScope scope) {
            throw new UnsupportedOperationException("must not be used");
          }

          @Override
          public boolean loadInitialCheckBoxState() {
            return false;
          }
        };

    myChooser = MpsPopupFactory.createPanelForNode(goToNodeModel, false);
    myChooser.invoke(
        new Callback() {
          public void elementChosen(Object element) {
            if (!myOkDone) {
              myOkDone = true;
              onOk();
            }
          }
        },
        ModalityState.current(),
        false);
  }
    @Override
    public void itemSelected(LookupEvent event) {
      LookupElement item = event.getItem();
      if (item == null) return;

      char c = event.getCompletionChar();
      if (myCheckCompletionChar && !LookupEvent.isSpecialCompletionChar(c)) {
        return;
      }

      final Project project = myContext.getProject();
      if (project == null) {
        return;
      }

      Runnable runnable =
          () ->
              new WriteCommandAction(project) {
                @Override
                protected void run(@NotNull com.intellij.openapi.application.Result result)
                    throws Throwable {
                  Editor editor = myContext.getEditor();
                  if (editor != null) {
                    TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
                    if (templateState != null) {
                      templateState.considerNextTabOnLookupItemSelected(item);
                    }
                  }
                }
              }.execute();
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        runnable.run();
      } else {
        ApplicationManager.getApplication()
            .invokeLater(runnable, ModalityState.current(), project.getDisposed());
      }
    }
  public void doExecute(AnActionEvent e, Map<String, Object> _params) {
    final Project project = e.getData(PlatformDataKeys.PROJECT);
    assert project != null;

    // FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.popup.class");
    // PsiDocumentManager.getInstance(project).commitAllDocuments();

    BaseModuleModel goToModuleModel =
        new BaseModuleModel(project, "module") {
          public NavigationItem doGetNavigationItem(final ModuleReference ref) {
            return new BaseModuleItem(ref) {
              public void navigate(boolean requestFocus) {
                IProjectPane projectPane = ProjectPane.getInstance(project);
                IModule module = MPSModuleRepository.getInstance().getModule(ref);
                projectPane.selectModule(module, true);
              }
            };
          }

          public ModuleReference[] find(IScope scope) {
            List<ModuleReference> modules = new ArrayList<ModuleReference>();
            for (IModule module : scope.getVisibleModules()) {
              if (!(module instanceof Solution
                  || module instanceof Language
                  || module instanceof DevKit)) continue;
              modules.add(module.getModuleReference());
            }
            return modules.toArray(new ModuleReference[modules.size()]);
          }
        };
    ChooseByNamePopupMPS popup =
        ChooseByNamePopupMPS.createPopup(
            project, goToModuleModel, DefaultMatcherFactory.createAllMatcher(goToModuleModel));

    popup.invoke(new NavigateCallback(), ModalityState.current(), true);
  }
  @CalledInAwt
  @NotNull
  public static ProgressIndicator executeAndTryWait(
      @NotNull final Function<ProgressIndicator, Runnable> backgroundTask,
      @Nullable final Runnable onSlowAction,
      final int waitMillis,
      final boolean forceEDT) {
    final ModalityState modality = ModalityState.current();
    final ProgressIndicator indicator =
        new EmptyProgressIndicator() {
          @NotNull
          @Override
          public ModalityState getModalityState() {
            return modality;
          }
        };

    final Semaphore semaphore = new Semaphore(0);
    final AtomicReference<Runnable> resultRef = new AtomicReference<Runnable>();

    if (forceEDT) {
      try {
        Runnable callback = backgroundTask.fun(indicator);
        finish(callback, indicator);
      } catch (ProcessCanceledException ignore) {
      } catch (Throwable t) {
        LOG.error(t);
      }
    } else {
      ApplicationManager.getApplication()
          .executeOnPooledThread(
              new Runnable() {
                @Override
                public void run() {
                  ProgressManager.getInstance()
                      .executeProcessUnderProgress(
                          new Runnable() {
                            @Override
                            public void run() {
                              final Runnable callback = backgroundTask.fun(indicator);

                              if (indicator.isCanceled()) {
                                semaphore.release();
                                return;
                              }

                              if (!resultRef.compareAndSet(null, callback)) {
                                ApplicationManager.getApplication()
                                    .invokeLater(
                                        new Runnable() {
                                          @Override
                                          public void run() {
                                            finish(callback, indicator);
                                          }
                                        },
                                        modality);
                              }
                              semaphore.release();
                            }
                          },
                          indicator);
                }
              });

      try {
        semaphore.tryAcquire(waitMillis, TimeUnit.MILLISECONDS);
      } catch (InterruptedException ignore) {
      }
      if (!resultRef.compareAndSet(null, TOO_SLOW_OPERATION)) {
        // update presentation in the same thread to reduce blinking, caused by 'invokeLater' and
        // fast background operation
        finish(resultRef.get(), indicator);
      } else {
        if (onSlowAction != null) onSlowAction.run();
      }
    }

    return indicator;
  }
 private static boolean isInFrame() {
   return ModalityState.current().equals(ModalityState.NON_MODAL);
 }
  public void actionPerformed(final AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    if (project == null) return;
    if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;
    final Change[] changes = e.getData(VcsDataKeys.CHANGES);
    if (changes == null) return;

    final boolean needsConvertion = checkIfThereAreFakeRevisions(project, changes);
    final List<Change> changesInList = e.getData(VcsDataKeys.CHANGES_IN_LIST_KEY);

    // this trick is essential since we are under some conditions to refresh changes;
    // but we can only rely on callback after refresh
    final Runnable performer =
        new Runnable() {
          public void run() {
            Change[] convertedChanges;
            if (needsConvertion) {
              convertedChanges = loadFakeRevisions(project, changes);
            } else {
              convertedChanges = changes;
            }

            if (convertedChanges == null || convertedChanges.length == 0) {
              return;
            }

            List<Change> changesInListCopy = changesInList;

            int index = 0;
            if (convertedChanges.length == 1) {
              final Change selectedChange = convertedChanges[0];
              ChangeList changeList =
                  ((ChangeListManagerImpl) ChangeListManager.getInstance(project))
                      .getIdentityChangeList(selectedChange);
              if (changeList != null) {
                if (changesInListCopy == null) {
                  changesInListCopy = new ArrayList<Change>(changeList.getChanges());
                  Collections.sort(
                      changesInListCopy,
                      new Comparator<Change>() {
                        public int compare(final Change o1, final Change o2) {
                          return ChangesUtil.getFilePath(o1)
                              .getName()
                              .compareToIgnoreCase(ChangesUtil.getFilePath(o2).getName());
                        }
                      });
                }
                convertedChanges = changesInListCopy.toArray(new Change[changesInListCopy.size()]);
                index =
                    Math.max(0, ContainerUtil.indexOfIdentity(changesInListCopy, selectedChange));
              }
            }

            showDiffForChange(convertedChanges, index, project);
          }
        };

    if (needsConvertion) {
      ChangeListManager.getInstance(project)
          .invokeAfterUpdate(
              performer,
              InvokeAfterUpdateMode.BACKGROUND_CANCELLABLE,
              ourText,
              ModalityState.current());
    } else {
      performer.run();
    }
  }
 protected ModalityState getModalityState() {
   return ModalityState.current();
 }
示例#18
0
 public void addRequest(@NotNull Runnable request, int delayMillis) {
   _addRequest(
       request,
       delayMillis,
       myThreadToUse == ThreadToUse.SWING_THREAD ? ModalityState.current() : null);
 }
  private void runLayoutCodeProcess(
      final Runnable readAction, final Runnable writeAction, final boolean globalAction) {
    final ProgressWindow progressWindow = new ProgressWindow(true, myProject);
    progressWindow.setTitle(myCommandName);
    progressWindow.setText(myProgressText);

    final ModalityState modalityState = ModalityState.current();

    final Runnable process =
        new Runnable() {
          @Override
          public void run() {
            ApplicationManager.getApplication().runReadAction(readAction);
          }
        };

    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            try {
              ProgressManager.getInstance().runProcess(process, progressWindow);
            } catch (ProcessCanceledException e) {
              return;
            } catch (IndexNotReadyException e) {
              return;
            }

            final Runnable writeRunnable =
                new Runnable() {
                  @Override
                  public void run() {
                    CommandProcessor.getInstance()
                        .executeCommand(
                            myProject,
                            new Runnable() {
                              @Override
                              public void run() {
                                if (globalAction)
                                  CommandProcessor.getInstance()
                                      .markCurrentCommandAsGlobal(myProject);
                                try {
                                  writeAction.run();

                                  if (myPostRunnable != null) {
                                    ApplicationManager.getApplication().invokeLater(myPostRunnable);
                                  }
                                } catch (IndexNotReadyException ignored) {
                                }
                              }
                            },
                            myCommandName,
                            null);
                  }
                };

            if (ApplicationManager.getApplication().isUnitTestMode()) {
              writeRunnable.run();
            } else {
              ApplicationManager.getApplication()
                  .invokeLater(writeRunnable, modalityState, myProject.getDisposed());
            }
          }
        };

    if (ApplicationManager.getApplication().isUnitTestMode()) {
      runnable.run();
    } else {
      ApplicationManager.getApplication().executeOnPooledThread(runnable);
    }
  }