static {
   if (System.getProperty("is.popup.test") != null
       || (ApplicationManagerEx.getApplicationEx() != null
           && ApplicationManagerEx.getApplicationEx().isUnitTestMode())) {
     Toolkit.getDefaultToolkit().addAWTEventListener(ourInstance, MouseEvent.MOUSE_PRESSED);
     KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(ourInstance);
   }
 }
  public EntryPoint acquire(@NotNull Target target, @NotNull Parameters configuration)
      throws Exception {
    ApplicationManagerEx.getApplicationEx().assertTimeConsuming();

    Ref<RunningInfo> ref = Ref.create(null);
    Pair<Target, Parameters> key = Pair.create(target, configuration);
    if (!getExistingInfo(ref, key)) {
      startProcess(target, configuration, key);
      if (ref.isNull()) {
        try {
          //noinspection SynchronizationOnLocalVariableOrMethodParameter
          synchronized (ref) {
            while (ref.isNull()) {
              ref.wait(1000);
              ProgressManager.checkCanceled();
            }
          }
        } catch (InterruptedException e) {
          ProgressManager.checkCanceled();
        }
      }
    }
    if (ref.isNull())
      throw new RuntimeException("Unable to acquire remote proxy for: " + getName(target));
    RunningInfo info = ref.get();
    if (info.handler == null) {
      String message = info.name;
      if (message != null && message.startsWith("ERROR: transport error 202:")) {
        message =
            "Unable to start java process in debug mode: -Xdebug parameters are already in use.";
      }
      throw new ExecutionException(message);
    }
    return acquire(info);
  }
  private boolean tryToReloadApplication() {
    try {
      final Application app = ApplicationManager.getApplication();

      if (app.isDisposed()) return false;
      final HashSet<Pair<VirtualFile, StateStorage>> causes =
          new HashSet<Pair<VirtualFile, StateStorage>>(myChangedApplicationFiles);
      if (causes.isEmpty()) return true;

      final boolean[] reloadOk = {false};
      final LinkedHashSet<String> components = new LinkedHashSet<String>();

      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    reloadOk[0] =
                        ((ApplicationImpl) app).getStateStore().reload(causes, components);
                  } catch (StateStorageException e) {
                    Messages.showWarningDialog(
                        ProjectBundle.message("project.reload.failed", e.getMessage()),
                        ProjectBundle.message("project.reload.failed.title"));
                  } catch (IOException e) {
                    Messages.showWarningDialog(
                        ProjectBundle.message("project.reload.failed", e.getMessage()),
                        ProjectBundle.message("project.reload.failed.title"));
                  }
                }
              });

      if (!reloadOk[0] && !components.isEmpty()) {
        String message = "Application components were changed externally and cannot be reloaded:\n";
        for (String component : components) {
          message += component + "\n";
        }

        final boolean canRestart = ApplicationManager.getApplication().isRestartCapable();
        message += "Would you like to " + (canRestart ? "restart " : "shutdown ");
        message += ApplicationNamesInfo.getInstance().getProductName() + "?";

        if (Messages.showYesNoDialog(
                message, "Application Configuration Reload", Messages.getQuestionIcon())
            == Messages.YES) {
          for (Pair<VirtualFile, StateStorage> cause : causes) {
            StateStorage stateStorage = cause.getSecond();
            if (stateStorage instanceof XmlElementStorage) {
              ((XmlElementStorage) stateStorage).disableSaving();
            }
          }
          ApplicationManagerEx.getApplicationEx().restart(true);
        }
      }

      return reloadOk[0];
    } finally {
      myChangedApplicationFiles.clear();
    }
  }
 private void execAsync(Runnable process, TaskInfo task, Frame frame) {
   ApplicationManagerEx.getApplicationEx()
       .runProcessWithProgressSynchronously(
           process,
           task.getTitle(),
           task.isCancellable(),
           project,
           SwingUtilities.getRootPane(frame));
 }
  private static void assertAfterCommit(
      Document document,
      final PsiFile file,
      String oldPsiText,
      FileElement myTreeElementBeingReparsedSoItWontBeCollected) {
    if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() != document.getTextLength()) {
      final String documentText = document.getText();
      if (ApplicationManagerEx.getApplicationEx().isInternal()) {
        String fileText = file.getText();
        LOG.error(
            "commitDocument left PSI inconsistent; file len="
                + myTreeElementBeingReparsedSoItWontBeCollected.getTextLength()
                + "; doc len="
                + document.getTextLength()
                + "; doc.getText() == file.getText(): "
                + Comparing.equal(fileText, documentText)
                + ";\n file psi text="
                + fileText
                + ";\n doc text="
                + documentText
                + ";\n old psi file text="
                + oldPsiText);
      } else {
        LOG.error("commitDocument left PSI inconsistent: " + file);
      }

      file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE);
      try {
        BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
        final DiffLog diffLog =
            blockSupport.reparseRange(
                file, 0, documentText.length(), 0, documentText, new ProgressIndicatorBase());
        CodeStyleManager.getInstance(file.getProject())
            .performActionWithFormatterDisabled(
                new Runnable() {
                  @Override
                  public void run() {
                    synchronized (PsiLock.LOCK) {
                      doActualPsiChange(file, diffLog);
                    }
                  }
                });

        if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength()
            != document.getTextLength()) {
          LOG.error("PSI is broken beyond repair in: " + file);
        }
      } finally {
        file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
      }
    }
  }
Beispiel #6
0
 public void tearDown() {
   Assert.assertFalse(TEST_OBJECT.getShutDown());
   ApplicationManagerEx.getApplicationEx()
       .addApplicationListener(
           new ApplicationAdapter() {
             @Override
             public void applicationExiting() {
               if (!(Extension_Test.TEST_OBJECT.getShutDown())) {
                 throw new RuntimeException("!TestObject.shutDown");
               }
             }
           });
 }
  public void cancel(InputEvent e) {
    if (isDisposed()) return;

    if (myPopup != null) {
      if (!canClose()) {
        return;
      }
      storeDimensionSize(myContent.getSize());
      if (myUseDimServiceForXYLocation) {
        final JRootPane root = myComponent.getRootPane();
        if (root != null) {
          final Container popupWindow = root.getParent();
          if (popupWindow != null && popupWindow.isShowing()) {
            storeLocation(popupWindow.getLocationOnScreen());
          }
        }
      }

      if (e instanceof MouseEvent) {
        IdeEventQueue.getInstance().blockNextEvents(((MouseEvent) e));
      }

      myPopup.hide(false);

      if (ApplicationManagerEx.getApplicationEx() != null) {
        StackingPopupDispatcher.getInstance().onPopupHidden(this);
      }

      if (myInStack) {
        myFocusTrackback.setForcedRestore(!myOk && myFocusable);
        myFocusTrackback.restoreFocus();
      }

      disposePopup();

      if (myListeners != null) {
        for (JBPopupListener each : myListeners) {
          each.onClosed(new LightweightWindowEvent(this, myOk));
        }
      }
    }

    Disposer.dispose(this, false);
  }
  @NotNull
  @Override
  public ListPopup createConfirmation(
      String title,
      final String yesText,
      String noText,
      final Runnable onYes,
      final Runnable onNo,
      int defaultOptionIndex) {

    final BaseListPopupStep<String> step =
        new BaseListPopupStep<String>(title, new String[] {yesText, noText}) {
          @Override
          public PopupStep onChosen(String selectedValue, final boolean finalChoice) {
            if (selectedValue.equals(yesText)) {
              onYes.run();
            } else {
              onNo.run();
            }
            return FINAL_CHOICE;
          }

          @Override
          public void canceled() {
            onNo.run();
          }

          @Override
          public boolean isMnemonicsNavigationEnabled() {
            return true;
          }
        };
    step.setDefaultOptionIndex(defaultOptionIndex);

    final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
    return app == null || !app.isUnitTestMode()
        ? new ListPopupImpl(step)
        : new MockConfirmation(step, yesText);
  }
  // if {@code things} are too few to be processed in the real pool, returns TRUE if processed
  // successfully, FALSE if not
  // returns null if things need to be processed in the real pool
  private static <T> Boolean processImmediatelyIfTooFew(
      @NotNull final List<T> things,
      @NotNull final ProgressIndicator progress,
      boolean runInReadAction,
      @NotNull final Processor<? super T> thingProcessor) {
    // commit can be invoked from within write action
    // if (runInReadAction && ApplicationManager.getApplication().isWriteAccessAllowed()) {
    //  throw new RuntimeException("Must not run invokeConcurrentlyUnderProgress() from under write
    // action because of imminent deadlock");
    // }
    if (things.isEmpty()) return true;

    if (things.size() <= 1 || JobSchedulerImpl.CORES_COUNT <= CORES_FORK_THRESHOLD) {
      final AtomicBoolean result = new AtomicBoolean(true);
      Runnable runnable =
          () ->
              ProgressManager.getInstance()
                  .executeProcessUnderProgress(
                      () -> {
                        //noinspection ForLoopReplaceableByForEach
                        for (int i = 0; i < things.size(); i++) {
                          T thing = things.get(i);
                          if (!thingProcessor.process(thing)) {
                            result.set(false);
                            break;
                          }
                        }
                      },
                      progress);
      if (runInReadAction) {
        if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(runnable)) return false;
      } else {
        runnable.run();
      }
      return result.get();
    }
    return null;
  }
 private void assertIsDispatchThread() {
   ApplicationManagerEx.getApplicationEx().assertIsDispatchThread(myEditor.getComponent());
 }
  protected void runOverFiles(
      @NotNull final Project project, @NotNull final List<VirtualFile> dartFiles) {
    if (dartFiles.isEmpty()) {
      Messages.showInfoMessage(
          project,
          DartBundle.message("dart.sort.members.files.no.dart.files"),
          DartBundle.message("dart.sort.members.action.name"));
      return;
    }

    if (Messages.showOkCancelDialog(
            project,
            DartBundle.message("dart.sort.members.files.dialog.question", dartFiles.size()),
            DartBundle.message("dart.sort.members.action.name"),
            null)
        != Messages.OK) {
      return;
    }

    final Map<VirtualFile, SourceFileEdit> fileToFileEditMap = Maps.newHashMap();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            double fraction = 0.0;
            for (final VirtualFile virtualFile : dartFiles) {
              fraction += 1.0;
              final ProgressIndicator indicator =
                  ProgressManager.getInstance().getProgressIndicator();
              if (indicator != null) {
                indicator.checkCanceled();
                indicator.setFraction(fraction / dartFiles.size());
                indicator.setText2(FileUtil.toSystemDependentName(virtualFile.getPath()));
              }

              final String path = virtualFile.getPath();
              final SourceFileEdit fileEdit =
                  DartAnalysisServerService.getInstance().edit_sortMembers(path);
              if (fileEdit != null) {
                fileToFileEditMap.put(virtualFile, fileEdit);
              }
            }
          }
        };

    DartAnalysisServerService.getInstance().updateFilesContent();

    final boolean ok =
        ApplicationManagerEx.getApplicationEx()
            .runProcessWithProgressSynchronously(
                runnable, DartBundle.message("dart.sort.members.action.name"), true, project);

    if (ok) {
      final Runnable onSuccessRunnable =
          new Runnable() {
            @Override
            public void run() {
              CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);

              for (Map.Entry<VirtualFile, SourceFileEdit> entry : fileToFileEditMap.entrySet()) {
                final VirtualFile file = entry.getKey();
                final Document document = FileDocumentManager.getInstance().getDocument(file);
                final SourceFileEdit fileEdit = entry.getValue();
                if (document != null) {
                  AssistUtils.applySourceEdits(document, fileEdit.getEdits());
                }
              }
            }
          };

      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  CommandProcessor.getInstance()
                      .executeCommand(
                          project,
                          onSuccessRunnable,
                          DartBundle.message("dart.sort.members.action.name"),
                          null);
                }
              });
    }
  }
 private static boolean isInternal() {
   return ApplicationManagerEx.getApplicationEx().isInternal();
 }
  @Nullable("returns runnable to execute under write action in AWT to finish the commit")
  private Processor<Document> doCommit(
      @NotNull final Document document,
      @NotNull final PsiFile file,
      @NotNull ProgressIndicator indicator,
      final boolean synchronously,
      @NotNull PsiDocumentManager documentManager) {
    ((PsiDocumentManagerImpl) documentManager).clearTreeHardRef(document);
    final TextBlock textBlock = TextBlock.get(file);
    if (textBlock.isEmpty()) return null;
    final long startPsiModificationTimeStamp = file.getModificationStamp();
    final long startDocModificationTimeStamp = document.getModificationStamp();
    final FileElement myTreeElementBeingReparsedSoItWontBeCollected =
        ((PsiFileImpl) file).calcTreeElement();
    if (textBlock.isEmpty())
      return null; // if tree was just loaded above textBlock will be cleared by contentsLoaded
    final CharSequence chars = document.getCharsSequence();
    final Boolean data = document.getUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY);
    if (data != null) {
      document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
      file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, data);
    }
    final String oldPsiText =
        ApplicationManagerEx.getApplicationEx().isInternal()
                && !ApplicationManagerEx.getApplicationEx().isUnitTestMode()
            ? myTreeElementBeingReparsedSoItWontBeCollected.getText()
            : null;
    int startOffset;
    int endOffset;
    int lengthShift;
    if (file.getViewProvider().supportsIncrementalReparse(file.getLanguage())) {
      startOffset = textBlock.getStartOffset();
      int psiEndOffset = textBlock.getPsiEndOffset();
      endOffset = psiEndOffset;
      lengthShift = textBlock.getTextEndOffset() - psiEndOffset;
    } else {
      startOffset = 0;
      endOffset = document.getTextLength();
      lengthShift =
          document.getTextLength() - myTreeElementBeingReparsedSoItWontBeCollected.getTextLength();
    }
    assertBeforeCommit(
        document,
        file,
        textBlock,
        chars,
        oldPsiText,
        myTreeElementBeingReparsedSoItWontBeCollected);
    BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
    final DiffLog diffLog =
        blockSupport.reparseRange(file, startOffset, endOffset, lengthShift, chars, indicator);

    return new Processor<Document>() {
      @Override
      public boolean process(Document document) {
        ApplicationManager.getApplication().assertWriteAccessAllowed();
        log(
            "Finishing",
            document,
            synchronously,
            document.getModificationStamp(),
            startDocModificationTimeStamp);
        // if (file.getModificationStamp() != startPsiModificationTimeStamp) return; // optimistic
        // locking failed
        if (document.getModificationStamp() != startDocModificationTimeStamp) {
          return false; // optimistic locking failed
        }

        try {
          textBlock.performAtomically(
              new Runnable() {
                @Override
                public void run() {
                  CodeStyleManager.getInstance(file.getProject())
                      .performActionWithFormatterDisabled(
                          new Runnable() {
                            @Override
                            public void run() {
                              synchronized (PsiLock.LOCK) {
                                doActualPsiChange(file, diffLog);
                              }
                            }
                          });
                }
              });

          assertAfterCommit(
              document, file, oldPsiText, myTreeElementBeingReparsedSoItWontBeCollected);
        } finally {
          textBlock.clear();
          SmartPointerManagerImpl.synchronizePointers(file);
        }

        return true;
      }
    };
  }
  // returns finish commit Runnable (to be invoked later in EDT), or null on failure
  private Runnable commitUnderProgress(
      @NotNull final Document document,
      @NotNull final Project project,
      final PsiFile excludeFile,
      @NotNull final ProgressIndicator indicator,
      final boolean synchronously,
      @NotNull final Object reason) {
    final List<Processor<Document>> finishRunnables = new SmartList<Processor<Document>>();
    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            if (project.isDisposed()) return;
            final PsiDocumentManagerImpl documentManager =
                (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(project);
            final FileViewProvider viewProvider = documentManager.getCachedViewProvider(document);
            if (viewProvider == null) return;
            final List<PsiFile> psiFiles = viewProvider.getAllFiles();
            for (PsiFile file : psiFiles) {
              if (file.isValid() && file != excludeFile) {
                Processor<Document> finishRunnable =
                    doCommit(document, file, indicator, synchronously, documentManager);
                if (finishRunnable != null) {
                  finishRunnables.add(finishRunnable);
                }
              }
            }
          }
        };
    if (synchronously) {
      ApplicationManager.getApplication().assertWriteAccessAllowed();
      runnable.run();
    } else {
      if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(runnable)) {
        log(
            "Could not start readaction",
            document,
            synchronously,
            ApplicationManager.getApplication().isReadAccessAllowed(),
            Thread.currentThread());
        return null;
      }
    }

    boolean canceled = indicator.isCanceled();
    if (synchronously) {
      assert !canceled;
    }
    if (canceled || !indicator.isRunning()) {
      assert !synchronously;
      return null;
    }
    if (!synchronously
        && !changeCommitStage(
            document,
            CommitStage.QUEUED_TO_COMMIT,
            CommitStage.WAITING_FOR_PSI_APPLY,
            synchronously)) {
      return null;
    }

    Runnable finishRunnable =
        new Runnable() {
          @Override
          public void run() {
            if (project.isDisposed()) return;

            PsiDocumentManagerImpl documentManager =
                (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(project);

            CommitStage stage = getCommitStage(document);
            log("Finish", document, synchronously, project);
            if (stage
                != (synchronously
                    ? CommitStage.ABOUT_TO_BE_SYNC_COMMITTED
                    : CommitStage.WAITING_FOR_PSI_APPLY)) {
              return; // there must be a synchronous commit sneaked in between queued commit and
                      // finish commit, or just document changed meanwhile
            }

            boolean success = false;
            try {
              success =
                  documentManager.finishCommit(document, finishRunnables, synchronously, reason);
              log(
                  "Finished",
                  document,
                  synchronously,
                  success,
                  Arrays.asList(documentManager.getUncommittedDocuments()));
              if (synchronously) {
                assert success;
              }
            } finally {
              if (success) {
                success =
                    synchronously
                        || changeCommitStage(
                            document,
                            CommitStage.WAITING_FOR_PSI_APPLY,
                            CommitStage.COMMITTED,
                            false);
              }
            }
            List<Document> unc = Arrays.asList(documentManager.getUncommittedDocuments());
            log("after call finish commit", document, synchronously, unc, success);
            if (synchronously || success) {
              assert !unc.contains(document) : unc;
            }
            if (!success) {
              // add document back to the queue
              boolean addedBack = queueCommit(project, document, "Re-added back");
              assert addedBack;
            }
          }
        };
    return finishRunnable;
  }
 private static WindowManagerEx getWndManager() {
   return ApplicationManagerEx.getApplicationEx() != null ? WindowManagerEx.getInstanceEx() : null;
 }
Beispiel #16
0
    @Override
    @SuppressWarnings("deprecation")
    public void show() {
      myFocusTrackback = new FocusTrackback(getDialogWrapper(), getParent(), true);

      final DialogWrapper dialogWrapper = getDialogWrapper();
      boolean isAutoAdjustable = dialogWrapper.isAutoAdjustable();
      Point location = null;
      if (isAutoAdjustable) {
        pack();

        Dimension packedSize = getSize();
        Dimension minSize = getMinimumSize();
        setSize(
            Math.max(packedSize.width, minSize.width), Math.max(packedSize.height, minSize.height));

        setSize(
            (int) (getWidth() * dialogWrapper.getHorizontalStretch()),
            (int) (getHeight() * dialogWrapper.getVerticalStretch()));

        // Restore dialog's size and location

        myDimensionServiceKey = dialogWrapper.getDimensionKey();

        if (myDimensionServiceKey != null) {
          final Project projectGuess =
              CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(this));
          location =
              DimensionService.getInstance().getLocation(myDimensionServiceKey, projectGuess);
          Dimension size =
              DimensionService.getInstance().getSize(myDimensionServiceKey, projectGuess);
          if (size != null) {
            myInitialSize = new Dimension(size);
            _setSizeForLocation(myInitialSize.width, myInitialSize.height, location);
          }
        }

        if (myInitialSize == null) {
          myInitialSize = getSize();
        }
      }

      if (location == null) {
        location = dialogWrapper.getInitialLocation();
      }

      if (location != null) {
        setLocation(location);
      } else {
        setLocationRelativeTo(getOwner());
      }

      if (isAutoAdjustable) {
        final Rectangle bounds = getBounds();
        ScreenUtil.fitToScreen(bounds);
        setBounds(bounds);
      }
      addWindowListener(
          new WindowAdapter() {
            @Override
            public void windowActivated(WindowEvent e) {
              final DialogWrapper wrapper = getDialogWrapper();
              if (wrapper != null && myFocusTrackback != null) {
                myFocusTrackback.cleanParentWindow();
                myFocusTrackback.registerFocusComponent(
                    new FocusTrackback.ComponentQuery() {
                      @Override
                      public Component getComponent() {
                        return wrapper.getPreferredFocusedComponent();
                      }
                    });
              }
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
              if (!isModal()) {
                final Ref<IdeFocusManager> focusManager = new Ref<IdeFocusManager>(null);
                Project project = getProject();
                if (project != null && !project.isDisposed()) {
                  focusManager.set(getFocusManager());
                  focusManager
                      .get()
                      .doWhenFocusSettlesDown(
                          new Runnable() {
                            @Override
                            public void run() {
                              disposeFocusTrackbackIfNoChildWindowFocused(focusManager.get());
                            }
                          });
                } else {
                  disposeFocusTrackbackIfNoChildWindowFocused(focusManager.get());
                }
              }
            }

            @Override
            public void windowOpened(WindowEvent e) {
              if (!SystemInfo.isMacOSLion) return;
              Window window = e.getWindow();
              if (window instanceof Dialog) {
                ID _native = MacUtil.findWindowForTitle(((Dialog) window).getTitle());
                if (_native != null && _native.intValue() > 0) {
                  // see MacMainFrameDecorator
                  // NSCollectionBehaviorFullScreenAuxiliary = 1 << 8
                  Foundation.invoke(_native, "setCollectionBehavior:", 1 << 8);
                }
              }
            }
          });

      if (Registry.is("actionSystem.fixLostTyping")) {
        final IdeEventQueue queue = IdeEventQueue.getInstance();
        if (queue != null) {
          queue.getKeyEventDispatcher().resetState();
        }

        // if (myProject != null) {
        //   Project project = myProject.get();
        // if (project != null && !project.isDisposed() && project.isInitialized()) {
        // // IdeFocusManager.findInstanceByComponent(this).requestFocus(new
        // MyFocusCommand(dialogWrapper), true);
        // }
        // }
      }

      if (SystemInfo.isMac
          && myProject != null
          && Registry.is("ide.mac.fix.dialog.showing")
          && !dialogWrapper.isModalProgress()) {
        final IdeFrame frame = WindowManager.getInstance().getIdeFrame(myProject.get());
        AppIcon.getInstance().requestFocus(frame);
      }

      setBackground(UIUtil.getPanelBackground());

      final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
      if (app != null && !app.isLoaded() && Splash.BOUNDS != null) {
        final Point loc = getLocation();
        loc.y = Splash.BOUNDS.y + Splash.BOUNDS.height;
        setLocation(loc);
      }
      super.show();
    }
 private static void assertReadAccess() {
   ApplicationManagerEx.getApplicationEx().assertReadAccessAllowed();
 }
  protected void runOverFiles(
      @NotNull final Project project, @NotNull final List<VirtualFile> dartFiles) {
    if (dartFiles.isEmpty()) {
      Messages.showInfoMessage(
          project,
          DartBundle.message("dart.style.files.no.dart.files"),
          DartBundle.message("dart.style.action.name"));
      return;
    }

    if (Messages.showOkCancelDialog(
            project,
            DartBundle.message("dart.style.files.dialog.question", dartFiles.size()),
            DartBundle.message("dart.style.action.name"),
            null)
        != Messages.OK) {
      return;
    }

    final Map<VirtualFile, String> fileToNewContentMap = new THashMap<VirtualFile, String>();
    final int lineLength = getRightMargin(project);

    final Runnable runnable =
        () -> {
          double fraction = 0.0;
          for (final VirtualFile virtualFile : dartFiles) {
            fraction += 1.0;
            final ProgressIndicator indicator =
                ProgressManager.getInstance().getProgressIndicator();
            if (indicator != null) {
              indicator.checkCanceled();
              indicator.setFraction(fraction / dartFiles.size());
              indicator.setText2(FileUtil.toSystemDependentName(virtualFile.getPath()));
            }

            final DartAnalysisServerService.FormatResult formatResult =
                DartAnalysisServerService.getInstance().edit_format(virtualFile, 0, 0, lineLength);
            if (formatResult != null
                && formatResult.getEdits() != null
                && formatResult.getEdits().size() == 1) {
              final String replacement =
                  StringUtil.convertLineSeparators(formatResult.getEdits().get(0).getReplacement());
              fileToNewContentMap.put(virtualFile, replacement);
            }
          }
        };

    DartAnalysisServerService.getInstance().updateFilesContent();

    final boolean ok =
        ApplicationManagerEx.getApplicationEx()
            .runProcessWithProgressSynchronously(
                runnable, DartBundle.message("dart.style.action.name"), true, project);

    if (ok) {
      final Runnable onSuccessRunnable =
          () -> {
            CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);

            for (Map.Entry<VirtualFile, String> entry : fileToNewContentMap.entrySet()) {
              final VirtualFile file = entry.getKey();
              final Document document = FileDocumentManager.getInstance().getDocument(file);
              final String newContent = entry.getValue();

              if (document != null && newContent != null) {
                document.setText(newContent);
              }
            }
          };

      ApplicationManager.getApplication()
          .runWriteAction(
              () ->
                  CommandProcessor.getInstance()
                      .executeCommand(
                          project,
                          onSuccessRunnable,
                          DartBundle.message("dart.style.action.name"),
                          null));
    }
  }
  public ApplicationImpl(
      boolean isInternal,
      boolean isUnitTestMode,
      boolean isHeadless,
      boolean isCommandLine,
      @NotNull String appName,
      Splash splash) {
    super(null);

    ApplicationManagerEx.setApplication(
        this, myLastDisposable); // reset back to null only when all components already disposed

    getPicoContainer().registerComponentInstance(Application.class, this);

    CommonBundle.assertKeyIsFound = isUnitTestMode;
    AWTExceptionHandler.register(); // do not crash AWT on exceptions
    if ((isInternal || isUnitTestMode)
        && !Comparing.equal("off", System.getProperty("idea.disposer.debug"))) {
      Disposer.setDebugMode(true);
    }
    myStartTime = System.currentTimeMillis();
    mySplash = splash;
    myName = appName;

    PluginsFacade.INSTANCE =
        new PluginsFacade() {
          public IdeaPluginDescriptor getPlugin(PluginId id) {
            return PluginManager.getPlugin(id);
          }

          public IdeaPluginDescriptor[] getPlugins() {
            return PluginManager.getPlugins();
          }
        };

    myIsInternal = isInternal;
    myTestModeFlag = isUnitTestMode;
    myHeadlessMode = isHeadless;
    myCommandLineMode = isCommandLine;

    myDoNotSave = myTestModeFlag || myHeadlessMode;

    loadApplicationComponents();

    if (myTestModeFlag) {
      registerShutdownHook();
    }

    if (!isUnitTestMode && !isHeadless) {
      Disposer.register(this, Disposer.newDisposable(), "ui");

      StartupUtil.addExternalInstanceListener(
          new Consumer<List<String>>() {
            @Override
            public void consume(final List<String> args) {
              invokeLater(
                  new Runnable() {
                    @Override
                    public void run() {
                      final Project project = CommandLineProcessor.processExternalCommandLine(args);
                      final IdeFrame frame;
                      if (project != null) {
                        frame = WindowManager.getInstance().getIdeFrame(project);
                      } else {
                        frame = WindowManager.getInstance().getAllFrames()[0];
                      }
                      ((IdeFrameImpl) frame).requestFocus();
                    }
                  });
            }
          });
    }

    final String s = System.getProperty("jb.restart.code");
    if (s != null) {
      try {
        myRestartCode = Integer.parseInt(s);
      } catch (NumberFormatException ignore) {
      }
    }

    registerFont("/fonts/Inconsolata.ttf");
  }
    public void showPreview(@Nullable ResourceItem element) {
      CardLayout layout = (CardLayout) myPreviewPanel.getLayout();

      if (element == null || element.getGroup().getType() == ResourceType.ID) {
        layout.show(myPreviewPanel, NONE);
        return;
      }

      try {
        VirtualFile file = element.getFile();
        if (file == null) {
          String value = element.getPreviewString();
          if (value == null) {
            java.util.List<ResourceElement> resources = element.getPreviewResources();

            if (resources == null) {
              long time = System.currentTimeMillis();
              resources =
                  myManager.findValueResources(
                      element.getGroup().getType().getName(), element.toString());
              if (ApplicationManagerEx.getApplicationEx().isInternal()) {
                System.out.println("Time: " + (System.currentTimeMillis() - time)); // XXX
              }

              int size = resources.size();
              if (size == 1) {
                value = getResourceElementValue(resources.get(0));
                element.setPreviewString(value);
              } else if (size > 1) {
                resources = new ArrayList<ResourceElement>(resources);
                Collections.sort(
                    resources,
                    new Comparator<ResourceElement>() {
                      @Override
                      public int compare(ResourceElement element1, ResourceElement element2) {
                        PsiDirectory directory1 =
                            element1.getXmlTag().getContainingFile().getParent();
                        PsiDirectory directory2 =
                            element2.getXmlTag().getContainingFile().getParent();

                        if (directory1 == null && directory2 == null) {
                          return 0;
                        }
                        if (directory2 == null) {
                          return 1;
                        }
                        if (directory1 == null) {
                          return -1;
                        }

                        return directory1.getName().compareTo(directory2.getName());
                      }
                    });

                DefaultComboBoxModel model = new DefaultComboBoxModel();
                String defaultSelection = null;
                for (int i = 0; i < size; i++) {
                  ResourceElement resource = resources.get(i);
                  PsiDirectory directory = resource.getXmlTag().getContainingFile().getParent();
                  String name = directory == null ? "unknown-" + i : directory.getName();
                  model.addElement(name);
                  if (defaultSelection == null && "values".equalsIgnoreCase(name)) {
                    defaultSelection = name;
                  }
                }
                element.setPreviewResources(resources, model, defaultSelection);

                showComboPreview(element);
                return;
              } else {
                layout.show(myPreviewPanel, NONE);
                return;
              }
            } else {
              showComboPreview(element);
              return;
            }
          }
          if (value == null) {
            layout.show(myPreviewPanel, NONE);
            return;
          }

          myTextArea.setText(value);
          layout.show(myPreviewPanel, TEXT);
        } else if (ImageFileTypeManager.getInstance().isImage(file)) {
          Icon icon = element.getPreviewIcon();
          if (icon == null) {
            icon = new SizedIcon(100, 100, new ImageIcon(file.getPath()));
            element.setPreviewIcon(icon);
          }
          myImageComponent.setIcon(icon);
          layout.show(myPreviewPanel, IMAGE);
        } else if (file.getFileType() == XmlFileType.INSTANCE) {
          String value = element.getPreviewString();
          if (value == null) {
            value = new String(file.contentsToByteArray());
            element.setPreviewString(value);
          }
          myTextArea.setText(value);
          myTextArea.setEditable(false);
          layout.show(myPreviewPanel, TEXT);
        } else {
          layout.show(myPreviewPanel, NONE);
        }
      } catch (IOException e) {
        layout.show(myPreviewPanel, NONE);
      }
    }
  public static boolean isSendAllowed() {
    if (ApplicationManagerEx.getApplicationEx().isInternal()) return true; // todo remove

    return isSendAllowed(UsageStatisticsPersistenceComponent.getInstance());
  }
  public ApplicationImpl(
      boolean isInternal,
      boolean isUnitTestMode,
      boolean isHeadless,
      boolean isCommandLine,
      @NotNull String appName) {
    super(null);

    getPicoContainer().registerComponentInstance(Application.class, this);

    CommonBundle.assertKeyIsFound = isUnitTestMode;

    if ((isInternal || isUnitTestMode)
        && !Comparing.equal("off", System.getProperty("idea.disposer.debug"))) {
      Disposer.setDebugMode(true);
    }
    myStartTime = System.currentTimeMillis();
    myName = appName;
    ApplicationManagerEx.setApplication(this);

    PluginsFacade.INSTANCE =
        new PluginsFacade() {
          public IdeaPluginDescriptor getPlugin(PluginId id) {
            return PluginManager.getPlugin(id);
          }

          public IdeaPluginDescriptor[] getPlugins() {
            return PluginManager.getPlugins();
          }
        };

    if (!isUnitTestMode && !isHeadless) {
      Toolkit.getDefaultToolkit().getSystemEventQueue().push(IdeEventQueue.getInstance());
      if (Patches.SUN_BUG_ID_6209673) {
        RepaintManager.setCurrentManager(new IdeRepaintManager());
      }
      IconLoader.activate();
    }

    myIsInternal = isInternal;
    myTestModeFlag = isUnitTestMode;
    myHeadlessMode = isHeadless;
    myCommandLineMode = isCommandLine;

    loadApplicationComponents();

    if (myTestModeFlag) {
      registerShutdownHook();
    }

    if (!isUnitTestMode && !isHeadless) {
      Disposer.register(this, Disposer.newDisposable(), "ui");

      StartupUtil.addExternalInstanceListener(
          new Consumer<List<String>>() {
            @Override
            public void consume(final List<String> args) {
              invokeLater(
                  new Runnable() {
                    @Override
                    public void run() {
                      final Project project = CommandLineProcessor.processExternalCommandLine(args);
                      final IdeFrame frame;
                      if (project != null) {
                        frame = WindowManager.getInstance().getIdeFrame(project);
                      } else {
                        frame = WindowManager.getInstance().getAllFrames()[0];
                      }
                      ((IdeFrameImpl) frame).requestFocus();
                    }
                  });
            }
          });
    }

    final String s = System.getProperty("jb.restart.code");
    if (s != null) {
      try {
        myRestartCode = Integer.parseInt(s);
      } catch (NumberFormatException ignore) {
      }
    }
  }
 protected boolean beforeShow() {
   if (ApplicationManagerEx.getApplicationEx() == null) return true;
   StackingPopupDispatcher.getInstance().onPopupShown(this, myInStack);
   return true;
 }
 private static void assertIsDispatchThreadForEditor() {
   ApplicationManagerEx.getApplicationEx().assertIsDispatchThread();
 }
  public void show(Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) {
    if (ApplicationManagerEx.getApplicationEx() != null
        && ApplicationManager.getApplication().isHeadlessEnvironment()) return;
    if (isDisposed()) {
      throw new IllegalStateException(
          "Popup was already disposed. Recreate a new instance to show again");
    }

    assert ApplicationManager.getApplication().isDispatchThread();

    addActivity();

    final boolean shouldShow = beforeShow();
    if (!shouldShow) {
      removeActivity();
      return;
    }

    prepareToShow();

    if (myInStack) {
      myFocusTrackback = new FocusTrackback(this, owner, true);
      myFocusTrackback.setMustBeShown(true);
    }

    Dimension sizeToSet = null;

    if (myDimensionServiceKey != null) {
      sizeToSet = DimensionService.getInstance().getSize(myDimensionServiceKey, myProject);
    }

    if (myForcedSize != null) {
      sizeToSet = myForcedSize;
    }

    if (myMinSize == null) {
      myMinSize = myContent.getMinimumSize();
    }

    if (sizeToSet == null) {
      sizeToSet = myContent.getPreferredSize();
    }

    if (sizeToSet != null) {
      sizeToSet.width = Math.max(sizeToSet.width, myMinSize.width);
      sizeToSet.height = Math.max(sizeToSet.height, myMinSize.height);

      myContent.setSize(sizeToSet);
      myContent.setPreferredSize(sizeToSet);
    }

    Point xy = new Point(aScreenX, aScreenY);
    boolean adjustXY = true;
    if (myDimensionServiceKey != null) {
      final Point storedLocation =
          DimensionService.getInstance().getLocation(myDimensionServiceKey, myProject);
      if (storedLocation != null) {
        xy = storedLocation;
        adjustXY = false;
      }
    }

    if (adjustXY) {
      final Insets insets = myContent.getInsets();
      if (insets != null) {
        xy.x -= insets.left;
        xy.y -= insets.top;
      }
    }

    if (considerForcedXY && myForcedLocation != null) {
      xy = myForcedLocation;
    }

    if (myLocateByContent) {
      final Dimension captionSize = myHeaderPanel.getPreferredSize();
      xy.y -= captionSize.height;
    }

    Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize());
    Insets insets = myPopupBorder.getBorderInsets(myContent);
    if (insets != null) {
      targetBounds.x += insets.left;
      targetBounds.y += insets.top;
    }

    Rectangle original = new Rectangle(targetBounds);
    if (myLocateWithinScreen) {
      ScreenUtil.moveRectangleToFitTheScreen(targetBounds);
    }

    if (myMouseOutCanceller != null) {
      myMouseOutCanceller.myEverEntered = targetBounds.equals(original);
    }

    myOwner = IdeFrameImpl.findNearestModalComponent(owner);
    if (myOwner == null) {
      myOwner = owner;
    }

    myRequestorComponent = owner;

    boolean forcedDialog = (SystemInfo.isMac && !(myOwner instanceof IdeFrame)) || myMayBeParent;

    PopupComponent.Factory factory = getFactory(myForcedHeavyweight || myResizable, forcedDialog);
    myNativePopup = factory.isNativePopup();
    myPopup = factory.getPopup(myOwner, myContent, targetBounds.x, targetBounds.y);

    if (myResizable) {
      final JRootPane root = myContent.getRootPane();
      final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root);
      root.setGlassPane(glass);

      final ResizeComponentListener resizeListener = new ResizeComponentListener(this, glass);
      glass.addMousePreprocessor(resizeListener, this);
      glass.addMouseMotionPreprocessor(resizeListener, this);
    }

    if (myCaption != null && myMovable) {
      final MoveComponentListener moveListener =
          new MoveComponentListener(myCaption) {
            public void mousePressed(final MouseEvent e) {
              super.mousePressed(e);
              if (e.isConsumed()) return;

              if (UIUtil.isCloseClick(e)) {
                if (myCaption.isWithinPanel(e)) {
                  cancel();
                }
              }
            }
          };
      ListenerUtil.addMouseListener(myCaption, moveListener);
      ListenerUtil.addMouseMotionListener(myCaption, moveListener);
      final MyContentPanel saved = myContent;
      Disposer.register(
          this,
          new Disposable() {
            public void dispose() {
              ListenerUtil.removeMouseListener(saved, moveListener);
              ListenerUtil.removeMouseMotionListener(saved, moveListener);
            }
          });
    }

    for (JBPopupListener listener : myListeners) {
      listener.beforeShown(new LightweightWindowEvent(this));
    }

    myPopup.setRequestFocus(myRequestFocus);
    myPopup.show();

    final Window window = SwingUtilities.getWindowAncestor(myContent);

    myWindowListener = new MyWindowListener();
    window.addWindowListener(myWindowListener);

    if (myFocusable) {
      window.setFocusableWindowState(true);
      window.setFocusable(true);
    }

    myWindow = updateMaskAndAlpha(window);

    if (myWindow instanceof JWindow) {
      ((JWindow) myWindow).getRootPane().putClientProperty(KEY, this);
    }

    if (myWindow != null) {
      // dialogwrapper-based popups do this internally through peer,
      // for other popups like jdialog-based we should exclude them manually, but
      // we still have to be able to use IdeFrame as parent
      if (!myMayBeParent && !(myWindow instanceof Frame)) {
        WindowManager.getInstance().doNotSuggestAsParent(myWindow);
      }
    }

    final Runnable afterShow =
        new Runnable() {
          public void run() {
            if (myPreferredFocusedComponent != null && myInStack && myFocusable) {
              myFocusTrackback.registerFocusComponent(myPreferredFocusedComponent);
            }

            removeActivity();

            afterShow();
          }
        };

    if (myRequestFocus) {
      getFocusManager()
          .requestFocus(
              new FocusCommand() {
                @Override
                public ActionCallback run() {
                  if (isDisposed()) {
                    removeActivity();
                    return new ActionCallback.Done();
                  }

                  _requestFocus();

                  final ActionCallback result = new ActionCallback();

                  final Runnable afterShowRunnable =
                      new Runnable() {
                        @Override
                        public void run() {
                          afterShow.run();
                          result.setDone();
                        }
                      };
                  if (myNativePopup) {
                    final FocusRequestor furtherRequestor = getFocusManager().getFurtherRequestor();
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          @Override
                          public void run() {
                            if (isDisposed()) {
                              result.setRejected();
                              return;
                            }

                            furtherRequestor
                                .requestFocus(
                                    new FocusCommand() {
                                      @Override
                                      public ActionCallback run() {
                                        if (isDisposed()) {
                                          return new ActionCallback.Rejected();
                                        }

                                        _requestFocus();

                                        afterShowRunnable.run();

                                        return new ActionCallback.Done();
                                      }
                                    },
                                    true)
                                .notify(result)
                                .doWhenProcessed(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        removeActivity();
                                      }
                                    });
                          }
                        });
                  } else {
                    afterShowRunnable.run();
                  }

                  return result;
                }
              },
              true)
          .doWhenRejected(
              new Runnable() {
                @Override
                public void run() {
                  afterShow.run();
                }
              });
    } else {
      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              if (isDisposed()) {
                removeActivity();
                return;
              }

              afterShow.run();
            }
          });
    }
  }
    private void doRun() {
      if (myUpdateProgress.isCanceled()) return;

      log(myUpdateProgress, myPass, "Started. ");

      for (ScheduledPass successor : mySuccessorsOnSubmit) {
        int predecessorsToRun = successor.myRunningPredecessorsCount.decrementAndGet();
        if (predecessorsToRun == 0) {
          submit(successor);
        }
      }

      ProgressManager.getInstance()
          .executeProcessUnderProgress(
              () -> {
                boolean success =
                    ApplicationManagerEx.getApplicationEx()
                        .tryRunReadAction(
                            () -> {
                              try {
                                if (DumbService.getInstance(myProject).isDumb()
                                    && !DumbService.isDumbAware(myPass)) {
                                  return;
                                }

                                if (!myUpdateProgress.isCanceled() && !myProject.isDisposed()) {
                                  myPass.collectInformation(myUpdateProgress);
                                }
                              } catch (ProcessCanceledException e) {
                                log(myUpdateProgress, myPass, "Canceled ");

                                if (!myUpdateProgress.isCanceled()) {
                                  myUpdateProgress.cancel(
                                      e); // in case when some smart asses throw PCE just for fun
                                }
                              } catch (RuntimeException | Error e) {
                                myUpdateProgress.cancel(e);
                                LOG.error(e);
                                throw e;
                              }
                            });

                if (!success) {
                  myUpdateProgress.cancel();
                }
              },
              myUpdateProgress);

      log(myUpdateProgress, myPass, "Finished. ");

      if (!myUpdateProgress.isCanceled()) {
        applyInformationToEditorsLater(
            myFileEditor, myPass, myUpdateProgress, myThreadsToStartCountdown);
        for (ScheduledPass successor : mySuccessorsOnCompletion) {
          int predecessorsToRun = successor.myRunningPredecessorsCount.decrementAndGet();
          if (predecessorsToRun == 0) {
            submit(successor);
          }
        }
      }
    }
  @Override
  public void startRunInjectors(@NotNull final Document hostDocument, final boolean synchronously) {
    if (myProject.isDisposed()) return;
    if (!synchronously && ApplicationManager.getApplication().isWriteAccessAllowed()) return;
    // use cached to avoid recreate PSI in alien project
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    final PsiFile hostPsiFile = documentManager.getCachedPsiFile(hostDocument);
    if (hostPsiFile == null) return;

    final ConcurrentList<DocumentWindow> injected =
        InjectedLanguageUtil.getCachedInjectedDocuments(hostPsiFile);
    if (injected.isEmpty()) return;

    if (myProgress.isCanceled()) {
      myProgress = new DaemonProgressIndicator();
    }
    final Set<DocumentWindow> newDocuments = Collections.synchronizedSet(new THashSet<>());
    final Processor<DocumentWindow> commitProcessor =
        documentWindow -> {
          if (myProject.isDisposed()) return false;
          ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
          if (indicator != null && indicator.isCanceled()) return false;
          if (documentManager.isUncommited(hostDocument) || !hostPsiFile.isValid())
            return false; // will be committed later

          // it is here where the reparse happens and old file contents replaced
          InjectedLanguageUtil.enumerate(
              documentWindow,
              hostPsiFile,
              (injectedPsi, places) -> {
                DocumentWindow newDocument =
                    (DocumentWindow) injectedPsi.getViewProvider().getDocument();
                if (newDocument != null) {
                  PsiDocumentManagerBase.checkConsistency(injectedPsi, newDocument);
                  newDocuments.add(newDocument);
                }
              });
          return true;
        };
    final Runnable commitInjectionsRunnable =
        () -> {
          if (myProgress.isCanceled()) return;
          JobLauncher.getInstance()
              .invokeConcurrentlyUnderProgress(
                  new ArrayList<>(injected), myProgress, true, commitProcessor);

          synchronized (ourInjectionPsiLock) {
            injected.clear();
            injected.addAll(newDocuments);
          }
        };

    if (synchronously) {
      if (Thread.holdsLock(PsiLock.LOCK)) {
        // hack for the case when docCommit was called from within PSI modification, e.g. in
        // formatter.
        // we can't spawn threads to do injections there, otherwise a deadlock is imminent
        ContainerUtil.process(new ArrayList<>(injected), commitProcessor);
      } else {
        commitInjectionsRunnable.run();
      }
    } else {
      JobLauncher.getInstance()
          .submitToJobThread(
              () ->
                  ApplicationManagerEx.getApplicationEx()
                      .tryRunReadAction(commitInjectionsRunnable),
              null);
    }
  }