public EditorsSplitters(
      final FileEditorManagerImpl manager,
      DockManager dockManager,
      boolean createOwnDockableContainer) {
    super(new BorderLayout());
    setOpaque(false);
    myManager = manager;
    myFocusWatcher = new MyFocusWatcher();
    setFocusTraversalPolicy(new MyFocusTraversalPolicy());
    setTransferHandler(new MyTransferHandler());
    clear();

    if (createOwnDockableContainer) {
      DockableEditorTabbedContainer dockable =
          new DockableEditorTabbedContainer(myManager.getProject(), this, false);
      Disposer.register(manager.getProject(), dockable);
      dockManager.register(dockable);
    }

    UISettings.getInstance()
        .addUISettingsListener(
            new UISettingsListener() {
              @Override
              public void uiSettingsChanged(UISettings source) {
                updateBackground();
              }
            },
            manager.getProject());
    updateBackground();
  }
 @Override
 public UpdateInfoTree showUpdateProjectInfo(
     UpdatedFiles updatedFiles,
     String displayActionName,
     ActionInfo actionInfo,
     boolean canceled) {
   if (!myProject.isOpen() || myProject.isDisposed()) return null;
   ContentManager contentManager = getContentManager();
   if (contentManager == null) {
     return null; // content manager is made null during dispose; flag is set later
   }
   final UpdateInfoTree updateInfoTree =
       new UpdateInfoTree(contentManager, myProject, updatedFiles, displayActionName, actionInfo);
   Content content =
       ContentFactory.SERVICE
           .getInstance()
           .createContent(
               updateInfoTree,
               canceled
                   ? VcsBundle.message(
                       "toolwindow.title.update.action.canceled.info", displayActionName)
                   : VcsBundle.message("toolwindow.title.update.action.info", displayActionName),
               true);
   Disposer.register(content, updateInfoTree);
   ContentsUtil.addContent(contentManager, content, true);
   ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.VCS).activate(null);
   updateInfoTree.expandRootChildren();
   return updateInfoTree;
 }
  public LanguageConsoleImpl(
      Project project, String title, LightVirtualFile lightFile, boolean initComponents) {
    myProject = project;
    myTitle = title;
    myVirtualFile = lightFile;
    EditorFactory editorFactory = EditorFactory.getInstance();
    myHistoryFile = new LightVirtualFile(getTitle() + ".history.txt", FileTypes.PLAIN_TEXT, "");
    myEditorDocument = FileDocumentManager.getInstance().getDocument(lightFile);
    reparsePsiFile();
    assert myEditorDocument != null;
    myConsoleEditor = (EditorEx) editorFactory.createEditor(myEditorDocument, myProject);
    myConsoleEditor.addFocusListener(myFocusListener);
    myCurrentEditor = myConsoleEditor;
    myHistoryViewer =
        (EditorEx)
            editorFactory.createViewer(
                ((EditorFactoryImpl) editorFactory).createDocument(true), myProject);
    myUpdateQueue = new MergingUpdateQueue("ConsoleUpdateQueue", 300, true, null);
    Disposer.register(this, myUpdateQueue);

    // action shortcuts are not yet registered
    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              @Override
              public void run() {
                installEditorFactoryListener();
              }
            });

    if (initComponents) {
      initComponents();
    }
  }
  EditorsSplitters(
      final FileEditorManagerImpl manager,
      DockManager dockManager,
      boolean createOwnDockableContainer) {
    super(new BorderLayout());
    myManager = manager;
    myFocusWatcher = new MyFocusWatcher();
    setFocusTraversalPolicy(new MyFocusTraversalPolicy());
    clear();

    if (createOwnDockableContainer) {
      DockableEditorTabbedContainer dockable =
          new DockableEditorTabbedContainer(myManager.getProject(), this, false);
      Disposer.register(manager.getProject(), dockable);
      dockManager.register(dockable);
    }
    KeymapManagerListener keymapListener =
        new KeymapManagerListener() {
          @Override
          public void activeKeymapChanged(Keymap keymap) {
            invalidate();
            repaint();
          }
        };
    KeymapManager.getInstance().addKeymapManagerListener(keymapListener, this);
  }
 public void setTreeBuilder(final AbstractTreeBuilder treeBuilder) {
   if (treeBuilder != null) {
     Disposer.register(this, treeBuilder);
     // needs refactoring for project view first
     //      treeBuilder.setCanYieldUpdate(true);
   }
   myTreeBuilder = treeBuilder;
 }
 protected EditorTextFieldCellRenderer(
     @Nullable Project project,
     @Nullable FileType fileType,
     boolean inheritFontFromLaF,
     @NotNull Disposable parent) {
   myProject = project;
   myFileType = fileType;
   myInheritFontFromLaF = inheritFontFromLaF;
   Disposer.register(parent, this);
 }
  @NotNull
  private RendererComponent getEditorPanel(final JTable table) {
    RendererComponent panel = UIUtil.getClientProperty(table, MY_PANEL_PROPERTY);
    if (panel != null) {
      DelegateColorScheme scheme = (DelegateColorScheme) panel.getEditor().getColorsScheme();
      scheme.setDelegate(EditorColorsManager.getInstance().getGlobalScheme());
      return panel;
    }

    panel = createRendererComponent(myProject, myFileType, myInheritFontFromLaF);
    Disposer.register(this, panel);
    Disposer.register(
        this,
        new Disposable() {
          @Override
          public void dispose() {
            UIUtil.putClientProperty(table, MY_PANEL_PROPERTY, null);
          }
        });

    table.putClientProperty(MY_PANEL_PROPERTY, panel);
    return panel;
  }
 private DiffPanel createPanel(final boolean horizontal) {
   final DiffPanel diffPanel =
       new DiffPanelImpl(null, myProject, false, horizontal) {
         @Override
         protected DiffPanelState createDiffPanelState(@NotNull Disposable parentDisposable) {
           return new FragmentedDiffPanelState(this, myProject, !horizontal, parentDisposable);
         }
       };
   diffPanel.enableToolbar(false);
   diffPanel.removeStatusBar();
   DiffPanelOptions o = ((DiffPanelEx) diffPanel).getOptions();
   o.setRequestFocusOnNewContent(false);
   Disposer.register(this, diffPanel);
   return diffPanel;
 }
Пример #9
0
      private MyFocusCommand(DialogWrapper wrapper) {
        myWrapper = getDialogWrapper();
        setToInvalidateRequestors(false);

        Disposer.register(
            wrapper.getDisposable(),
            new Disposable() {
              @Override
              public void dispose() {
                if (!myTypeAheadDone.isProcessed()) {
                  myTypeAheadDone.setDone();
                }

                flushEvents();
              }
            });
      }
  public FlatWelcomeFrame() {
    final JRootPane rootPane = getRootPane();
    myScreen = new FlatWelcomeScreen();

    final IdeGlassPaneImpl glassPane =
        new IdeGlassPaneImpl(rootPane) {
          @Override
          public void addNotify() {
            super.addNotify();
            rootPane.remove(getProxyComponent());
            //noinspection SSBasedInspection
            SwingUtilities.invokeLater(
                new Runnable() {
                  public void run() {
                    JBProtocolCommand.handleCurrentCommand();
                  }
                });
          }
        };

    setGlassPane(glassPane);
    glassPane.setVisible(false);
    // setUndecorated(true);
    setContentPane(myScreen.getWelcomePanel());
    setTitle("Welcome to " + ApplicationNamesInfo.getInstance().getFullProductName());
    AppUIUtil.updateWindowIcon(this);
    final int width =
        RecentProjectsManager.getInstance().getRecentProjectsActions(false).length == 0 ? 666 : 777;
    setSize(JBUI.size(width, 460));
    setResizable(false);
    // int x = bounds.x + (bounds.width - getWidth()) / 2;
    // int y = bounds.y + (bounds.height - getHeight()) / 2;
    Point location = DimensionService.getInstance().getLocation(WelcomeFrame.DIMENSION_KEY, null);
    Rectangle screenBounds =
        ScreenUtil.getScreenRectangle(location != null ? location : new Point(0, 0));
    setLocation(
        new Point(
            screenBounds.x + (screenBounds.width - getWidth()) / 2,
            screenBounds.y + (screenBounds.height - getHeight()) / 3));

    // setLocation(x, y);
    ProjectManager.getInstance()
        .addProjectManagerListener(
            new ProjectManagerAdapter() {
              @Override
              public void projectOpened(Project project) {
                dispose();
              }
            });

    myBalloonLayout = new BalloonLayoutImpl(rootPane, JBUI.insets(8));

    WelcomeFrame.setupCloseAction(this);
    MnemonicHelper.init(this);
    Disposer.register(
        ApplicationManager.getApplication(),
        new Disposable() {
          @Override
          public void dispose() {
            FlatWelcomeFrame.this.dispose();
          }
        });
  }
  public FileStructurePopup(
      StructureViewModel structureViewModel,
      @Nullable Editor editor,
      Project project,
      @NotNull final Disposable auxDisposable,
      final boolean applySortAndFilter) {
    myProject = project;
    myEditor = editor;

    // Stop code analyzer to speedup EDT
    final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(myProject);
    if (analyzer != null) {
      myDaemonUpdateEnabled = ((DaemonCodeAnalyzerImpl) analyzer).isUpdateByTimerEnabled();
      analyzer.setUpdateByTimerEnabled(false);
    } else {
      myDaemonUpdateEnabled = false;
    }

    IdeFocusManager.getInstance(myProject).typeAheadUntil(myTreeHasBuilt);
    myBaseTreeModel = structureViewModel;
    Disposer.register(this, auxDisposable);
    if (applySortAndFilter) {
      myTreeActionsOwner = new TreeStructureActionsOwner(myBaseTreeModel);
      myTreeModel = new TreeModelWrapper(structureViewModel, myTreeActionsOwner);
    } else {
      myTreeActionsOwner = null;
      myTreeModel = structureViewModel;
    }

    myTreeStructure =
        new SmartTreeStructure(project, myTreeModel) {
          public void rebuildTree() {
            if (ApplicationManager.getApplication().isUnitTestMode() || !myPopup.isDisposed()) {
              super.rebuildTree();
            }
          }

          public boolean isToBuildChildrenInBackground(final Object element) {
            return getRootElement() == element;
          }

          protected TreeElementWrapper createTree() {
            return new StructureViewComponent.StructureViewTreeElementWrapper(
                myProject, myModel.getRoot(), myModel);
          }

          @Override
          public String toString() {
            return "structure view tree structure(model=" + myTreeModel + ")";
          }
        };

    myTree =
        new FileStructureTree(
            myTreeStructure.getRootElement(), Registry.is("fast.tree.expand.in.structure.view"));

    myTree.setCellRenderer(
        new NodeRenderer() {
          @Override
          protected void doAppend(
              @NotNull @Nls String fragment,
              @NotNull SimpleTextAttributes attributes,
              boolean isMainText,
              boolean selected) {
            SpeedSearchUtil.appendFragmentsForSpeedSearch(
                myTree, fragment, attributes, selected, this);
          }

          @Override
          public void doAppend(
              @NotNull String fragment,
              @NotNull SimpleTextAttributes attributes,
              boolean selected) {
            SpeedSearchUtil.appendFragmentsForSpeedSearch(
                myTree, fragment, attributes, selected, this);
          }

          @Override
          public void doAppend(String fragment, boolean selected) {
            SpeedSearchUtil.appendFragmentsForSpeedSearch(
                myTree, fragment, SimpleTextAttributes.REGULAR_ATTRIBUTES, selected, this);
          }
        });

    mySpeedSearch = new MyTreeSpeedSearch();
    mySpeedSearch.setComparator(new SpeedSearchComparator(false, true));

    final FileStructurePopupFilter filter = new FileStructurePopupFilter();
    myFilteringStructure =
        new FilteringTreeStructure(
            filter, myTreeStructure, ApplicationManager.getApplication().isUnitTestMode());
    myAbstractTreeBuilder =
        new FilteringTreeBuilder(myTree, filter, myFilteringStructure, null) {
          @Override
          public void initRootNode() {}

          @Override
          protected boolean validateNode(Object child) {
            return StructureViewComponent.isValid(child);
          }

          @Override
          public void revalidateTree() {
            // myTree.revalidate();
            // myTree.repaint();
          }

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

    myTreeExpander = new DefaultTreeExpander(myTree);

    // myAbstractTreeBuilder.getUi().setPassthroughMode(true);
    myAbstractTreeBuilder.getUi().getUpdater().setDelay(1);
    myInitialPsiElement = getCurrentElement(getPsiFile(myProject));
    // myAbstractTreeBuilder.setCanYieldUpdate(true);
    Disposer.register(this, myAbstractTreeBuilder);
  }
  public void show() {
    // final long time = System.currentTimeMillis();
    JComponent panel = createCenterPanel();
    new MnemonicHelper().register(panel);
    boolean shouldSetWidth =
        DimensionService.getInstance().getSize(getDimensionServiceKey(), myProject) == null;
    myPopup =
        JBPopupFactory.getInstance()
            .createComponentPopupBuilder(panel, null)
            .setTitle(myTitle)
            .setResizable(true)
            .setModalContext(false)
            .setFocusable(true)
            .setMovable(true)
            .setBelongsToGlobalPopupStack(true)
            // .setCancelOnClickOutside(false) //for debug and snapshots
            .setCancelKeyEnabled(false)
            .setDimensionServiceKey(null, getDimensionServiceKey(), false)
            .setCancelCallback(
                new Computable<Boolean>() {
                  @Override
                  public Boolean compute() {
                    DimensionService.getInstance()
                        .setLocation(
                            getDimensionServiceKey(), myPopup.getLocationOnScreen(), myProject);
                    return true;
                  }
                })
            .createPopup();

    myTree.addTreeSelectionListener(
        new TreeSelectionListener() {
          @Override
          public void valueChanged(TreeSelectionEvent e) {
            if (myPopup.isVisible()) {
              final PopupUpdateProcessor updateProcessor =
                  myPopup.getUserData(PopupUpdateProcessor.class);
              if (updateProcessor != null) {
                final AbstractTreeNode node = getSelectedNode();
                updateProcessor.updatePopup(node);
              }
            }
          }
        });
    Disposer.register(myPopup, this);
    Disposer.register(
        myPopup,
        new Disposable() {
          @Override
          public void dispose() {
            if (!myTreeHasBuilt.isDone()) {
              myTreeHasBuilt.setRejected();
            }
          }
        });
    myTree.getEmptyText().setText("Loading...");
    final Point location =
        DimensionService.getInstance().getLocation(getDimensionServiceKey(), myProject);
    if (location != null) {
      myPopup.showInScreenCoordinates(myEditor.getContentComponent(), location);
    } else {
      myPopup.showCenteredInCurrentWindow(myProject);
    }

    ((AbstractPopup) myPopup).setShowHints(true);
    if (shouldSetWidth) {
      myPopup.setSize(new Dimension(myPreferredWidth + 10, myPopup.getSize().height));
    }

    IdeFocusManager.getInstance(myProject).requestFocus(myTree, true);
    ApplicationManager.getApplication()
        .executeOnPooledThread(
            new Runnable() {
              @Override
              public void run() {
                final AccessToken token =
                    ApplicationManager.getApplication().acquireReadActionLock();
                try {
                  myFilteringStructure.rebuild();
                } finally {
                  token.finish();
                }

                SwingUtilities.invokeLater(
                    new Runnable() {
                      @Override
                      public void run() {
                        myAbstractTreeBuilder
                            .queueUpdate()
                            .doWhenDone(
                                new Runnable() {
                                  @Override
                                  public void run() {
                                    myTreeHasBuilt.setDone();
                                    //noinspection SSBasedInspection
                                    SwingUtilities.invokeLater(
                                        new Runnable() {
                                          @Override
                                          public void run() {
                                            selectPsiElement(myInitialPsiElement);
                                          }
                                        });
                                  }
                                });
                      }
                    });
                installUpdater();
              }
            });
  }
  EditorTabbedContainer(final EditorWindow window, Project project, final int tabPlacement) {
    myWindow = window;
    myProject = project;
    final ActionManager actionManager = ActionManager.getInstance();
    myTabs = new JBEditorTabs(project, actionManager, IdeFocusManager.getInstance(project), this);
    myTabs
        .setDataProvider(new MyDataProvider())
        .setPopupGroup(
            new Getter<ActionGroup>() {
              public ActionGroup get() {
                return (ActionGroup)
                    CustomActionsSchema.getInstance()
                        .getCorrectedAction(IdeActions.GROUP_EDITOR_TAB_POPUP);
              }
            },
            ActionPlaces.EDITOR_TAB_POPUP,
            false)
        .setNavigationActionsEnabled(false)
        .addTabMouseListener(new TabMouseListener())
        .getPresentation()
        .setTabDraggingEnabled(true)
        .setUiDecorator(
            new UiDecorator() {
              @NotNull
              public UiDecoration getDecoration() {
                return new UiDecoration(
                    null,
                    new Insets(
                        TabsUtil.TAB_VERTICAL_PADDING, 10, TabsUtil.TAB_VERTICAL_PADDING, 10));
              }
            })
        .setTabLabelActionsMouseDeadzone(TimedDeadzone.NULL)
        .setGhostsAlwaysVisible(true)
        .setTabLabelActionsAutoHide(false)
        .setActiveTabFillIn(
            EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground())
        .setPaintFocus(false)
        .getJBTabs()
        .addListener(
            new TabsListener.Adapter() {
              public void selectionChanged(final TabInfo oldSelection, final TabInfo newSelection) {
                final FileEditorManager editorManager = FileEditorManager.getInstance(myProject);
                final FileEditor oldEditor =
                    oldSelection != null
                        ? editorManager.getSelectedEditor((VirtualFile) oldSelection.getObject())
                        : null;
                if (oldEditor != null) {
                  oldEditor.deselectNotify();
                }

                final FileEditor newEditor =
                    editorManager.getSelectedEditor((VirtualFile) newSelection.getObject());
                if (newEditor != null) {
                  newEditor.selectNotify();
                }
              }
            })
        .setAdditionalSwitchProviderWhenOriginal(new MySwitchProvider())
        .setSelectionChangeHandler(
            new JBTabs.SelectionChangeHandler() {
              @Override
              public ActionCallback execute(
                  TabInfo info, boolean requestFocus, final ActiveRunnable doChangeSelection) {
                final ActionCallback result = new ActionCallback();
                CommandProcessor.getInstance()
                    .executeCommand(
                        myProject,
                        new Runnable() {
                          @Override
                          public void run() {
                            ((IdeDocumentHistoryImpl) IdeDocumentHistory.getInstance(myProject))
                                .onSelectionChanged();
                            result.notify(doChangeSelection.run());
                          }
                        },
                        "EditorChange",
                        null);
                return result;
              }
            })
        .getPresentation()
        .setRequestFocusOnLastFocusedComponent(true);

    setTabPlacement(UISettings.getInstance().EDITOR_TAB_PLACEMENT);

    updateTabBorder();

    ((ToolWindowManagerEx) ToolWindowManager.getInstance(myProject))
        .addToolWindowManagerListener(
            new ToolWindowManagerAdapter() {
              public void stateChanged() {
                updateTabBorder();
              }

              public void toolWindowRegistered(@NotNull final String id) {
                updateTabBorder();
              }
            });

    UISettings.getInstance()
        .addUISettingsListener(
            new UISettingsListener() {
              public void uiSettingsChanged(UISettings source) {
                updateTabBorder();
              }
            },
            this);

    Disposer.register(project, this);
  }
Пример #14
0
 protected <T extends Disposable> T disposeOnTearDown(final T disposable) {
   Disposer.register(myTestRootDisposable, disposable);
   return disposable;
 }
Пример #15
0
  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) {
      }
    }
  }
Пример #16
0
  private void buildInInlineIndicator(@NotNull final InlineProgressIndicator inline) {
    removeAll();
    setLayout(new InlineLayout());
    add(myRefreshAndInfoPanel);

    final JPanel inlinePanel = new JPanel(new BorderLayout());

    inline.getComponent().setBorder(new EmptyBorder(1, 0, 0, 2));
    final JComponent inlineComponent = inline.getComponent();
    inlineComponent.setOpaque(false);
    inlinePanel.add(inlineComponent, BorderLayout.CENTER);

    // myProgressIcon.setBorder(new IdeStatusBarImpl.MacStatusBarWidgetBorder());
    inlinePanel.add(myProgressIcon, BorderLayout.WEST);

    inline.updateProgressNow();
    inlinePanel.setOpaque(false);

    add(inlinePanel);

    myRefreshAndInfoPanel.revalidate();
    myRefreshAndInfoPanel.repaint();

    if (UISettings.getInstance().PRESENTATION_MODE) {
      final JRootPane pane = myInfoPanel.getRootPane();
      final RelativePoint point = new RelativePoint(pane, new Point(pane.getWidth() - 250, 60));
      final PresentationModeProgressPanel panel = new PresentationModeProgressPanel(inline);
      final MyInlineProgressIndicator delegate =
          new MyInlineProgressIndicator(true, inline.getInfo(), inline) {
            @Override
            protected void updateProgress() {
              super.updateProgress();
              panel.update();
            }
          };

      Disposer.register(inline, delegate);

      JBPopupFactory.getInstance()
          .createBalloonBuilder(panel.getRootPanel())
          .setFadeoutTime(0)
          .setFillColor(Gray.TRANSPARENT)
          .setShowCallout(false)
          .setBorderColor(Gray.TRANSPARENT)
          .setBorderInsets(new Insets(0, 0, 0, 0))
          .setAnimationCycle(0)
          .setCloseButtonEnabled(false)
          .setHideOnClickOutside(false)
          .setDisposable(inline)
          .setHideOnFrameResize(false)
          .setHideOnKeyOutside(false)
          .setBlockClicksThroughBalloon(true)
          .setHideOnAction(false)
          .createBalloon()
          .show(
              new PositionTracker<Balloon>(pane) {
                @Override
                public RelativePoint recalculateLocation(Balloon object) {
                  final EditorComponentImpl editorComponent =
                      UIUtil.findComponentOfType(pane, EditorComponentImpl.class);
                  if (editorComponent != null) {
                    return new RelativePoint(
                        editorComponent.getParent().getParent(),
                        new Point(
                            editorComponent.getParent().getParent().getWidth() - 150,
                            editorComponent.getParent().getParent().getHeight() - 70));
                  }
                  return point;
                }
              },
              Balloon.Position.above);
    }
  }
 public void navigate(int injectedOffset) {
   if (myAction.isShowInBalloon()) {
     final JComponent component = myAction.createBalloonComponent(myNewFile);
     if (component != null) {
       final Balloon balloon =
           JBPopupFactory.getInstance()
               .createBalloonBuilder(component)
               .setShadow(true)
               .setAnimationCycle(0)
               .setHideOnClickOutside(true)
               .setHideOnKeyOutside(true)
               .setHideOnAction(false)
               .setFillColor(UIUtil.getControlColor())
               .createBalloon();
       new AnAction() {
         @Override
         public void actionPerformed(AnActionEvent e) {
           balloon.hide();
         }
       }.registerCustomShortcutSet(CommonShortcuts.ESCAPE, component);
       Disposer.register(myNewFile.getProject(), balloon);
       final Balloon.Position position = QuickEditAction.getBalloonPosition(myEditor);
       RelativePoint point = JBPopupFactory.getInstance().guessBestPopupLocation(myEditor);
       if (position == Balloon.Position.above) {
         final Point p = point.getPoint();
         point =
             new RelativePoint(
                 point.getComponent(), new Point(p.x, p.y - myEditor.getLineHeight()));
       }
       balloon.show(point, position);
     }
   } else {
     final FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(myProject);
     final FileEditor[] editors = fileEditorManager.getEditors(myNewVirtualFile);
     if (editors.length == 0) {
       final EditorWindow curWindow = fileEditorManager.getCurrentWindow();
       mySplittedWindow =
           curWindow.split(SwingConstants.HORIZONTAL, false, myNewVirtualFile, true);
     }
     Editor editor =
         fileEditorManager.openTextEditor(
             new OpenFileDescriptor(myProject, myNewVirtualFile, injectedOffset), true);
     // fold missing values
     if (editor != null) {
       editor.putUserData(QuickEditAction.QUICK_EDIT_HANDLER, this);
       final FoldingModel foldingModel = editor.getFoldingModel();
       foldingModel.runBatchFoldingOperation(
           () -> {
             for (RangeMarker o :
                 ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
               String replacement = o.getUserData(REPLACEMENT_KEY);
               if (StringUtil.isEmpty(replacement)) continue;
               FoldRegion region =
                   foldingModel.addFoldRegion(o.getStartOffset(), o.getEndOffset(), replacement);
               if (region != null) region.setExpanded(false);
             }
           });
     }
     SwingUtilities.invokeLater(
         () -> myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE));
   }
 }
  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 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 prepareToShow() {
    final MouseAdapter mouseAdapter =
        new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            Point point = (Point) e.getPoint().clone();
            SwingUtilities.convertPointToScreen(point, e.getComponent());

            final Dimension dimension = myContent.getSize();
            dimension.height +=
                myResizable && isToDrawMacCorner() ? ourMacCorner.getHeight(myContent) : 4;
            dimension.width += 4;
            Point locationOnScreen = myContent.getLocationOnScreen();
            final Rectangle bounds =
                new Rectangle(new Point(locationOnScreen.x - 2, locationOnScreen.y - 2), dimension);
            if (!bounds.contains(point)) {
              cancel();
            }
          }
        };
    myContent.addMouseListener(mouseAdapter);
    Disposer.register(
        this,
        new Disposable() {
          public void dispose() {
            myContent.removeMouseListener(mouseAdapter);
          }
        });

    myContent.registerKeyboardAction(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (myCancelKeyEnabled) {
              cancel();
            }
          }
        },
        KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
        JComponent.WHEN_IN_FOCUSED_WINDOW);

    mySearchKeyListener = new SpeedSearchKeyListener();
    myContent.addKeyListener(mySearchKeyListener);

    if (myCancelOnMouseOutCallback != null || myCancelOnWindow) {
      myMouseOutCanceller = new Canceller();
      Toolkit.getDefaultToolkit()
          .addAWTEventListener(
              myMouseOutCanceller,
              AWTEvent.MOUSE_EVENT_MASK
                  | WindowEvent.WINDOW_ACTIVATED
                  | AWTEvent.MOUSE_MOTION_EVENT_MASK);
    }

    myFocusWatcher =
        new ChildFocusWatcher(myContent) {
          protected void onFocusGained(final FocusEvent event) {
            setWindowActive(true);
          }

          protected void onFocusLost(final FocusEvent event) {
            setWindowActive(false);
          }
        };

    mySpeedSearchPatternField = new JTextField();
    if (SystemInfo.isMac) {
      Font f = mySpeedSearchPatternField.getFont();
      mySpeedSearchPatternField.setFont(f.deriveFont(f.getStyle(), f.getSize() - 2));
    }
  }
  public StructureViewComponent(
      final FileEditor editor,
      final StructureViewModel structureViewModel,
      final Project project,
      final boolean showRootNode) {
    super(true, true);

    myProject = project;
    myFileEditor = editor;
    myTreeModel = structureViewModel;
    myTreeModelWrapper = new TreeModelWrapper(myTreeModel, this);

    SmartTreeStructure treeStructure =
        new SmartTreeStructure(project, myTreeModelWrapper) {
          public void rebuildTree() {
            if (!isDisposed()) {
              super.rebuildTree();
            }
          }

          public boolean isToBuildChildrenInBackground(final Object element) {
            return getRootElement() == element;
          }

          protected TreeElementWrapper createTree() {
            return new StructureViewTreeElementWrapper(myProject, myModel.getRoot(), myModel);
          }

          @Override
          public String toString() {
            return "structure view tree structure(model=" + myTreeModel + ")";
          }
        };

    final DefaultTreeModel model =
        new DefaultTreeModel(new DefaultMutableTreeNode(treeStructure.getRootElement()));
    myTree = new Tree(model);
    myTree.setRootVisible(showRootNode);
    myTree.setShowsRootHandles(true);

    myAbstractTreeBuilder =
        new StructureTreeBuilder(
            project,
            myTree,
            (DefaultTreeModel) myTree.getModel(),
            treeStructure,
            myTreeModelWrapper) {
          @Override
          protected boolean validateNode(Object child) {
            return isValid(child);
          }
        };
    Disposer.register(this, myAbstractTreeBuilder);
    Disposer.register(
        myAbstractTreeBuilder,
        new Disposable() {
          public void dispose() {
            storeState();
          }
        });

    setContent(ScrollPaneFactory.createScrollPane(myAbstractTreeBuilder.getTree()));

    myAbstractTreeBuilder.getTree().setCellRenderer(new NodeRenderer());

    myAutoScrollToSourceHandler = new MyAutoScrollToSourceHandler();
    myAutoScrollFromSourceHandler = new MyAutoScrollFromSourceHandler(myProject, this);

    JComponent toolbarComponent =
        ActionManager.getInstance()
            .createActionToolbar(ActionPlaces.STRUCTURE_VIEW_TOOLBAR, createActionGroup(), true)
            .getComponent();
    setToolbar(toolbarComponent);

    installTree();

    myCopyPasteDelegator =
        new CopyPasteDelegator(myProject, getTree()) {
          @NotNull
          protected PsiElement[] getSelectedElements() {
            return getSelectedPsiElements();
          }
        };
  }