@Override @Nullable public Object getData(DataProvider dataProvider) { Project project = MPSCommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); if (project == null) { IdeFrame[] frames = WindowManager.getInstance().getAllFrames(); return frames.length == 0 ? null : frames[0]; } return WindowManager.getInstance().getFrame(project); }
/** * Returns the currently selected file, based on which VcsBranch or StatusBar components will * identify the current repository root. */ @Nullable public static VirtualFile getSelectedFile(@NotNull Project project) { StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); final FileEditor fileEditor = StatusBarUtil.getCurrentFileEditor(project, statusBar); VirtualFile result = null; if (fileEditor != null) { if (fileEditor instanceof TextEditor) { Document document = ((TextEditor) fileEditor).getEditor().getDocument(); result = FileDocumentManager.getInstance().getFile(document); } else if (fileEditor instanceof ImageFileEditor) { result = ((ImageFileEditor) fileEditor).getImageEditor().getFile(); } } if (result == null) { final FileEditorManager manager = FileEditorManager.getInstance(project); if (manager != null) { Editor editor = manager.getSelectedTextEditor(); if (editor != null) { result = FileDocumentManager.getInstance().getFile(editor.getDocument()); } } } return result; }
@NotNull @Override public RelativePoint guessBestPopupLocation(@NotNull DataContext dataContext) { Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext); JComponent focusOwner = component instanceof JComponent ? (JComponent) component : null; if (focusOwner == null) { Project project = PlatformDataKeys.PROJECT.getData(dataContext); IdeFrameImpl frame = project == null ? null : ((WindowManagerEx) WindowManager.getInstance()).getFrame(project); focusOwner = frame == null ? null : frame.getRootPane(); if (focusOwner == null) { throw new IllegalArgumentException("focusOwner cannot be null"); } } final Point point = PlatformDataKeys.CONTEXT_MENU_POINT.getData(dataContext); if (point != null) { return new RelativePoint(focusOwner, point); } Editor editor = PlatformDataKeys.EDITOR.getData(dataContext); if (editor != null && focusOwner == editor.getContentComponent()) { return guessBestPopupLocation(editor); } else { return guessBestPopupLocation(focusOwner); } }
public static void requestFocus(Project project, final boolean useRobot) { JFrame frame = WindowManager.getInstance().getFrame(project); // the only reliable way I found to bring it to the top boolean aot = frame.isAlwaysOnTop(); frame.setAlwaysOnTop(true); frame.setAlwaysOnTop(aot); int frameState = frame.getExtendedState(); if ((frameState & Frame.ICONIFIED) == Frame.ICONIFIED) { // restore the frame if it is minimized frame.setExtendedState(frameState ^ Frame.ICONIFIED); } frame.toFront(); frame.requestFocus(); if (useRobot && runningOnWindows7()) { try { // remember the last location of mouse final Point oldMouseLocation = MouseInfo.getPointerInfo().getLocation(); // simulate a mouse click on title bar of window Robot robot = new Robot(); robot.mouseMove(frame.getX(), frame.getY()); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); // move mouse to old location robot.mouseMove((int) oldMouseLocation.getX(), (int) oldMouseLocation.getY()); } catch (Exception ex) { // just ignore exception, or you can handle it as you want } finally { frame.setAlwaysOnTop(false); } } }
protected void performHighlighting() { boolean clearHighlights = HighlightUsagesHandler.isClearHighlights(myEditor); EditorColorsManager manager = EditorColorsManager.getInstance(); TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES); HighlightUsagesHandler.highlightRanges( HighlightManager.getInstance(myEditor.getProject()), myEditor, attributes, clearHighlights, myReadUsages); HighlightUsagesHandler.highlightRanges( HighlightManager.getInstance(myEditor.getProject()), myEditor, writeAttributes, clearHighlights, myWriteUsages); if (!clearHighlights) { WindowManager.getInstance().getStatusBar(myEditor.getProject()).setInfo(myStatusText); HighlightHandlerBase.setupFindModel(myEditor.getProject()); // enable f3 navigation } if (myHintText != null) { HintManager.getInstance().showInformationHint(myEditor, myHintText); } }
@Override public void compilationFinished( boolean aborted, int errors, int warnings, CompileContext compileContext) { if (errors < 1) { // get the current time lastCompileTime = Calendar.getInstance(); StatusBar statusBar = WindowManager.getInstance() .getStatusBar(ProjectManager.getInstance().getOpenProjects()[0]); JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder( "Build ready to be sent to TestFlight, <a href='open'>Click Here</a> to open TestFlightUploader and send it.", MessageType.INFO, new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { ToolWindowManager.getInstance(ProjectManager.getInstance().getOpenProjects()[0]) .getToolWindow("TF Uploader") .show(null); } } }) .setFadeoutTime(4000) .createBalloon() .show(RelativePoint.getNorthEastOf(statusBar.getComponent()), Balloon.Position.atRight); } }
@Override public boolean isAvailable() { if (myRobot != null) { myRobot.createScreenCapture(new Rectangle(0, 0, 1, 1)); return WindowManager.getInstance().isAlphaModeSupported(); } return false; }
private static void setStatusBarText(Project project, String message) { if (project != null) { final StatusBarEx statusBar = (StatusBarEx) WindowManager.getInstance().getStatusBar(project); if (statusBar != null) { statusBar.setInfo(message); } } }
public static void reportNumberReplacedOccurrences(Project project, int occurrences) { if (occurrences != 0) { final StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); if (statusBar != null) { statusBar.setInfo(FindBundle.message("0.occurrences.replaced", occurrences)); } } }
public static boolean hasBackgroundProcesses(@NotNull Project project) { final IdeFrame frame = ((WindowManagerEx) WindowManager.getInstance()).findFrameFor(project); final StatusBarEx statusBar = frame == null ? null : (StatusBarEx) frame.getStatusBar(); if (statusBar != null) { final List<Pair<TaskInfo, ProgressIndicator>> processes = statusBar.getBackgroundProcesses(); if (!processes.isEmpty()) return true; } return false; }
public boolean isFocused() { IdeFocusManager fm = IdeFocusManager.getInstance(myProject); Component component = fm.getFocusedDescendantFor(myToolWindow.getComponent()); if (component != null) return true; Component owner = fm.getLastFocusedFor(WindowManager.getInstance().getIdeFrame(myProject)); return owner != null && SwingUtilities.isDescendingFrom(owner, myToolWindow.getComponent()); }
public void showInFocusCenter() { final Component focused = getWndManager().getFocusedComponent(myProject); if (focused != null) { showInCenterOf(focused); } else { final JFrame frame = WindowManager.getInstance().getFrame(myProject); showInCenterOf(frame.getRootPane()); } }
private static void replaceDuplicate( final Project project, final Map<PsiMember, List<Match>> duplicates, final Set<PsiMember> methods) { final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); if (progressIndicator != null && progressIndicator.isCanceled()) return; final Runnable replaceRunnable = () -> { LocalHistoryAction a = LocalHistory.getInstance().startAction(REFACTORING_NAME); try { for (final PsiMember member : methods) { final List<Match> matches = duplicates.get(member); if (matches == null) continue; final int duplicatesNo = matches.size(); WindowManager.getInstance() .getStatusBar(project) .setInfo(getStatusMessage(duplicatesNo)); CommandProcessor.getInstance() .executeCommand( project, () -> PostprocessReformattingAspect.getInstance(project) .postponeFormattingInside( () -> { final MatchProvider matchProvider = member instanceof PsiMethod ? new MethodDuplicatesMatchProvider( (PsiMethod) member, matches) : new ConstantMatchProvider(member, project, matches); DuplicatesImpl.invoke(project, matchProvider); }), REFACTORING_NAME, REFACTORING_NAME); WindowManager.getInstance().getStatusBar(project).setInfo(""); } } finally { a.finish(); } }; ApplicationManager.getApplication().invokeLater(replaceRunnable, ModalityState.NON_MODAL); }
protected DialogWrapperPeerImpl( @NotNull DialogWrapper wrapper, @Nullable Project project, boolean canBeParent, @NotNull DialogWrapper.IdeModalityType ideModalityType) { myWrapper = wrapper; myTypeAheadCallback = myWrapper.isTypeAheadEnabled() ? new ActionCallback() : null; myWindowManager = null; Application application = ApplicationManager.getApplication(); if (application != null && application.hasComponent(WindowManager.class)) { myWindowManager = (WindowManagerEx) WindowManager.getInstance(); } Window window = null; if (myWindowManager != null) { if (project == null) { //noinspection deprecation project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); } myProject = project; window = myWindowManager.suggestParentWindow(project); if (window == null) { Window focusedWindow = myWindowManager.getMostRecentFocusedWindow(); if (focusedWindow instanceof IdeFrameImpl) { window = focusedWindow; } } if (window == null) { IdeFrame[] frames = myWindowManager.getAllProjectFrames(); for (IdeFrame frame : frames) { if (frame instanceof IdeFrameImpl && ((IdeFrameImpl) frame).isActive()) { window = (IdeFrameImpl) frame; break; } } } } Window owner; if (window != null) { owner = window; } else { if (!isHeadless()) { owner = JOptionPane.getRootFrame(); } else { owner = null; } } createDialog(owner, canBeParent, ideModalityType); }
protected boolean isPreviewUsages(UsageInfo[] usages) { if (myForceShowPreview) return true; if (super.isPreviewUsages(usages)) return true; if (UsageViewUtil.hasNonCodeUsages(usages)) { WindowManager.getInstance() .getStatusBar(myProject) .setInfo( RefactoringBundle.message( "occurrences.found.in.comments.strings.and.non.java.files")); return true; } return false; }
@Override public Dialog show() { Dialog picker = super.show(); myTimer.start(); // it seems like it's the lowest value for opacity for mouse events to be processed correctly WindowManager.getInstance().setAlphaModeRatio(picker, SystemInfo.isMac ? 0.95f : 0.99f); if (SystemInfo.isJavaVersionAtLeast("1.7")) { Area area = new Area(new Rectangle(0, 0, DIALOG_SIZE, DIALOG_SIZE)); area.subtract(new Area(new Rectangle(SIZE / 2 - 1, SIZE / 2 - 1, 3, 3))); picker.setShape(area); } return picker; }
@Override public boolean runProcessWithProgressSynchronously( @NotNull final Task task, @Nullable final JComponent parentComponent) { final long start = System.currentTimeMillis(); final boolean result = super.runProcessWithProgressSynchronously(task, parentComponent); if (result) { final long end = System.currentTimeMillis(); final Task.NotificationInfo notificationInfo = task.notifyFinished(); long time = end - start; if (notificationInfo != null && time > 5000) { // show notification only if process took more than 5 secs final JFrame frame = WindowManager.getInstance().getFrame(task.getProject()); if (frame != null && !frame.hasFocus()) { systemNotify(notificationInfo); } } } return result; }
/** * @param parent parent component which is used to calculate heavy weight window ancestor. <code> * parent</code> cannot be <code>null</code> and must be showing. */ protected DialogWrapperPeerImpl( @NotNull DialogWrapper wrapper, @NotNull Component parent, boolean canBeParent) { myWrapper = wrapper; if (!parent.isShowing() && parent != JOptionPane.getRootFrame()) { throw new IllegalArgumentException("parent must be showing: " + parent); } myWindowManager = null; Application application = ApplicationManager.getApplication(); if (application != null && application.hasComponent(WindowManager.class)) { myWindowManager = (WindowManagerEx) WindowManager.getInstance(); } Window owner = parent instanceof Window ? (Window) parent : (Window) SwingUtilities.getAncestorOfClass(Window.class, parent); if (!(owner instanceof Dialog) && !(owner instanceof Frame)) { owner = JOptionPane.getRootFrame(); } createDialog(owner, canBeParent); }
public DialogWrapperPeerImpl( @NotNull final DialogWrapper wrapper, final Window owner, final boolean canBeParent, final DialogWrapper.IdeModalityType ideModalityType) { myWrapper = wrapper; myWindowManager = null; Application application = ApplicationManager.getApplication(); if (application != null && application.hasComponent(WindowManager.class)) { myWindowManager = (WindowManagerEx) WindowManager.getInstance(); } createDialog(owner, canBeParent); if (!isHeadless()) { Dialog.ModalityType modalityType = DialogWrapper.IdeModalityType.IDE.toAwtModality(); if (Registry.is("ide.perProjectModality")) { modalityType = ideModalityType.toAwtModality(); } myDialog.setModalityType(modalityType); } }
public static void focusProjectWindow(final Project p, boolean executeIfAppInactive) { FocusCommand cmd = new FocusCommand() { @NotNull @Override public ActionCallback run() { JFrame f = WindowManager.getInstance().getFrame(p); if (f != null) { f.toFront(); // f.requestFocus(); } return ActionCallback.DONE; } }; if (executeIfAppInactive) { AppIcon.getInstance().requestFocus((IdeFrame) WindowManager.getInstance().getFrame(p)); cmd.run(); } else { IdeFocusManager.getInstance(p).requestFocus(cmd, true); } }
private boolean inSecondStrokeInProgressState() { KeyEvent e = myContext.getInputEvent(); // when any key is released, we stop waiting for the second stroke if (KeyEvent.KEY_RELEASED == e.getID()) { myFirstKeyStroke = null; setState(KeyState.STATE_INIT); Project project = PlatformDataKeys.PROJECT.getData(myContext.getDataContext()); StatusBar.Info.set(null, project); return false; } KeyStroke originalKeyStroke = KeyStroke.getKeyStrokeForEvent(e); KeyStroke keyStroke = getKeyStrokeWithoutMouseModifiers(originalKeyStroke); updateCurrentContext( myContext.getFoundComponent(), new KeyboardShortcut(myFirstKeyStroke, keyStroke), myContext.isModalContext()); // consume the wrong second stroke and keep on waiting if (myContext.getActions().isEmpty()) { return true; } // finally user had managed to enter the second keystroke, so let it be processed Project project = PlatformDataKeys.PROJECT.getData(myContext.getDataContext()); StatusBarEx statusBar = (StatusBarEx) WindowManager.getInstance().getStatusBar(project); if (processAction(e, myActionProcessor)) { if (statusBar != null) { statusBar.setInfo(null); } return true; } else { return false; } }
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(); } }); } }
/** Updates frame's status bar: insert/overwrite mode, caret position */ private void updateStatusBar() { final StatusBarEx statusBar = (StatusBarEx) WindowManager.getInstance().getStatusBar(myProject); if (statusBar == null) return; statusBar.updateWidgets(); // TODO: do we need this?! }
private void replaceWithPrompt(final ReplaceContext replaceContext) { final List<Usage> _usages = replaceContext.getUsageView().getSortedUsages(); if (hasReadOnlyUsages(_usages)) { WindowManager.getInstance() .getStatusBar(myProject) .setInfo(FindBundle.message("find.replace.occurrences.found.in.read.only.files.status")); return; } final Usage[] usages = _usages.toArray(new Usage[_usages.size()]); // usageView.expandAll(); for (int i = 0; i < usages.length; ++i) { final Usage usage = usages[i]; final UsageInfo usageInfo = ((UsageInfo2UsageAdapter) usage).getUsageInfo(); final PsiElement elt = usageInfo.getElement(); if (elt == null) continue; final PsiFile psiFile = elt.getContainingFile(); if (!psiFile.isWritable()) continue; Runnable selectOnEditorRunnable = new Runnable() { @Override public void run() { final VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile != null && ApplicationManager.getApplication() .runReadAction( new Computable<Boolean>() { @Override public Boolean compute() { return virtualFile.isValid() ? Boolean.TRUE : Boolean.FALSE; } }) .booleanValue()) { if (usage.isValid()) { usage.highlightInEditor(); replaceContext.getUsageView().selectUsages(new Usage[] {usage}); } } } }; CommandProcessor.getInstance() .executeCommand( myProject, selectOnEditorRunnable, FindBundle.message("find.replace.select.on.editor.command"), null); String title = FindBundle.message("find.replace.found.usage.title", i + 1, usages.length); int result; try { replaceUsage( usage, replaceContext.getFindModel(), replaceContext.getExcludedSetCached(), true); result = FindManager.getInstance(myProject) .showPromptDialog(replaceContext.getFindModel(), title); } catch (FindManager.MalformedReplacementStringException e) { markAsMalformedReplacement(replaceContext, usage); result = FindManager.getInstance(myProject) .showMalformedReplacementPrompt(replaceContext.getFindModel(), title, e); } if (result == FindManager.PromptResult.CANCEL) { return; } if (result == FindManager.PromptResult.SKIP) { continue; } final int currentNumber = i; if (result == FindManager.PromptResult.OK) { final Ref<Boolean> success = Ref.create(); Runnable runnable = new Runnable() { @Override public void run() { success.set(replaceUsageAndRemoveFromView(usage, replaceContext)); } }; CommandProcessor.getInstance() .executeCommand(myProject, runnable, FindBundle.message("find.replace.command"), null); if (closeUsageViewIfEmpty(replaceContext.getUsageView(), success.get())) { return; } } if (result == FindManager.PromptResult.ALL_IN_THIS_FILE) { final int[] nextNumber = new int[1]; Runnable runnable = new Runnable() { @Override public void run() { int j = currentNumber; boolean success = true; for (; j < usages.length; j++) { final Usage usage = usages[j]; final UsageInfo usageInfo = ((UsageInfo2UsageAdapter) usage).getUsageInfo(); final PsiElement elt = usageInfo.getElement(); if (elt == null) continue; PsiFile otherPsiFile = elt.getContainingFile(); if (!otherPsiFile.equals(psiFile)) { break; } if (!replaceUsageAndRemoveFromView(usage, replaceContext)) { success = false; } } closeUsageViewIfEmpty(replaceContext.getUsageView(), success); nextNumber[0] = j; } }; CommandProcessor.getInstance() .executeCommand(myProject, runnable, FindBundle.message("find.replace.command"), null); //noinspection AssignmentToForLoopParameter i = nextNumber[0] - 1; } if (result == FindManager.PromptResult.ALL_FILES) { CommandProcessor.getInstance() .executeCommand( myProject, new Runnable() { @Override public void run() { final boolean success = replaceUsages(replaceContext, _usages); closeUsageViewIfEmpty(replaceContext.getUsageView(), success); } }, FindBundle.message("find.replace.command"), null); break; } } }
@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(); }
@Override protected IdeFrame getIdeFrame(Project project) { return WindowManager.getInstance().getIdeFrame(project); }
protected Settings showRefactoringDialog( Project project, final Editor editor, PsiClass parentClass, PsiExpression expr, PsiType type, PsiExpression[] occurrences, PsiElement anchorElement, PsiElement anchorElementIfAll) { final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expr != null ? expr : anchorElement, PsiMethod.class); PsiLocalVariable localVariable = null; if (expr instanceof PsiReferenceExpression) { PsiElement ref = ((PsiReferenceExpression) expr).resolve(); if (ref instanceof PsiLocalVariable) { localVariable = (PsiLocalVariable) ref; } } else if (anchorElement instanceof PsiLocalVariable) { localVariable = (PsiLocalVariable) anchorElement; } String enteredName = null; boolean replaceAllOccurrences = true; final AbstractInplaceIntroducer activeIntroducer = AbstractInplaceIntroducer.getActiveIntroducer(editor); if (activeIntroducer != null) { activeIntroducer.stopIntroduce(editor); expr = (PsiExpression) activeIntroducer.getExpr(); localVariable = (PsiLocalVariable) activeIntroducer.getLocalVariable(); occurrences = (PsiExpression[]) activeIntroducer.getOccurrences(); enteredName = activeIntroducer.getInputName(); replaceAllOccurrences = activeIntroducer.isReplaceAllOccurrences(); type = ((InplaceIntroduceConstantPopup) activeIntroducer).getType(); } for (PsiExpression occurrence : occurrences) { if (RefactoringUtil.isAssignmentLHS(occurrence)) { String message = RefactoringBundle.getCannotRefactorMessage("Selected expression is used for write"); CommonRefactoringUtil.showErrorHint( project, editor, message, REFACTORING_NAME, getHelpID()); highlightError(project, editor, occurrence); return null; } } if (localVariable == null) { final PsiElement errorElement = isStaticFinalInitializer(expr); if (errorElement != null) { String message = RefactoringBundle.getCannotRefactorMessage( RefactoringBundle.message("selected.expression.cannot.be.a.constant.initializer")); CommonRefactoringUtil.showErrorHint( project, editor, message, REFACTORING_NAME, getHelpID()); highlightError(project, editor, errorElement); return null; } } else { final PsiExpression initializer = localVariable.getInitializer(); if (initializer == null) { String message = RefactoringBundle.getCannotRefactorMessage( RefactoringBundle.message( "variable.does.not.have.an.initializer", localVariable.getName())); CommonRefactoringUtil.showErrorHint( project, editor, message, REFACTORING_NAME, getHelpID()); return null; } final PsiElement errorElement = isStaticFinalInitializer(initializer); if (errorElement != null) { String message = RefactoringBundle.getCannotRefactorMessage( RefactoringBundle.message( "initializer.for.variable.cannot.be.a.constant.initializer", localVariable.getName())); CommonRefactoringUtil.showErrorHint( project, editor, message, REFACTORING_NAME, getHelpID()); highlightError(project, editor, errorElement); return null; } } final TypeSelectorManagerImpl typeSelectorManager = new TypeSelectorManagerImpl(project, type, containingMethod, expr, occurrences); if (editor != null && editor.getSettings().isVariableInplaceRenameEnabled() && (expr == null || expr.isPhysical()) && activeIntroducer == null) { myInplaceIntroduceConstantPopup = new InplaceIntroduceConstantPopup( project, editor, parentClass, expr, localVariable, occurrences, typeSelectorManager, anchorElement, anchorElementIfAll, expr != null ? createOccurrenceManager(expr, parentClass) : null); if (myInplaceIntroduceConstantPopup.startInplaceIntroduceTemplate()) { return null; } } final IntroduceConstantDialog dialog = new IntroduceConstantDialog( project, parentClass, expr, localVariable, localVariable != null, occurrences, getParentClass(), typeSelectorManager, enteredName); dialog.setReplaceAllOccurrences(replaceAllOccurrences); if (!dialog.showAndGet()) { if (occurrences.length > 1) { WindowManager.getInstance() .getStatusBar(project) .setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting")); } return null; } return new Settings( dialog.getEnteredName(), expr, occurrences, dialog.isReplaceAllOccurrences(), true, true, InitializationPlace.IN_FIELD_DECLARATION, dialog.getFieldVisibility(), localVariable, dialog.getSelectedType(), dialog.isDeleteVariable(), dialog.getDestinationClass(), dialog.isAnnotateAsNonNls(), dialog.introduceEnumConstant()); }
private static Component notNullOrDefaultParent(Component parent) { return parent != null ? parent : WindowManager.getInstance().getFrame(saros.getProject()); }
public static void navigate(final Project project, final FileUsageList usagesList) { if (usagesList == null) { WindowManager.getInstance().getStatusBar(project).setInfo("No navigation resolved"); } else { if (usagesList.files.size() == 1 && usagesList.files.get(0).usageList.size() == 1) { final FileUsage fileUsage = usagesList.files.get(0); final OurUsage ourUsage = fileUsage.usageList.get(0); doNavigate(fileUsage, ourUsage, project); } else { final List<OurUsage> ourUsages = new ArrayList<OurUsage>(5); for (FileUsage fileUsage : usagesList.files) { for (OurUsage usage : fileUsage.usageList) { ourUsages.add(usage); } } final JList list = new JList( new AbstractListModel() { public int getSize() { return ourUsages.size(); } public Object getElementAt(int index) { return ourUsages.get(index); } }); list.setCellRenderer( new DefaultListCellRenderer() { public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final OurUsage usage = ((OurUsage) value); String text = usage.getContextText() + " in " + usage.fileUsage.getFileLocaton(); return super.getListCellRendererComponent( list, text, index, isSelected, cellHasFocus); } }); DataContext dataContext = DataManager.getInstance().getDataContext(); PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list); builder .setTitle("Select Target") .setItemChoosenCallback( new Runnable() { public void run() { int selectedIndex = list.getSelectedIndex(); if (selectedIndex == -1) return; final OurUsage selectedUsage = (OurUsage) list.getSelectedValue(); for (FileUsage fileUsage : usagesList.files) { for (OurUsage usage : fileUsage.usageList) { if (selectedUsage == usage) { doNavigate(fileUsage, usage, project); break; } } } } }) .createPopup() .showInBestPositionFor(dataContext); } } }
public Frame getFrame() { return WindowManager.getInstance().getFrame(myProject); }