protected void doOKAction() { final LogicalPosition currentPosition = myEditor.getCaretModel().getLogicalPosition(); int lineNumber = getLineNumber(currentPosition.line + 1); if (isInternal() && myOffsetField.getText().length() > 0) { try { final int offset = Integer.parseInt(myOffsetField.getText()); if (offset < myEditor.getDocument().getTextLength()) { myEditor.getCaretModel().removeSecondaryCarets(); myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER); myEditor.getSelectionModel().removeSelection(); IdeFocusManager.getGlobalInstance().requestFocus(myEditor.getContentComponent(), true); super.doOKAction(); } return; } catch (NumberFormatException e) { return; } } if (lineNumber < 0) return; int columnNumber = getColumnNumber(currentPosition.column); myEditor.getCaretModel().removeSecondaryCarets(); myEditor .getCaretModel() .moveToLogicalPosition( new LogicalPosition(Math.max(0, lineNumber - 1), Math.max(0, columnNumber - 1))); myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER); myEditor.getSelectionModel().removeSelection(); IdeFocusManager.getGlobalInstance().requestFocus(myEditor.getContentComponent(), true); super.doOKAction(); }
private void recalculateMaxValues() { myIdxLeft = widestEditor(myLeftEditors); final Editor leftEditor = myLeftEditors.get(myIdxLeft); final int wholeWidth = leftEditor.getContentComponent().getWidth(); final Rectangle va = leftEditor.getScrollingModel().getVisibleArea(); final int visibleLeft = leftEditor.xyToVisualPosition(new Point(va.width, 0)).column; myMaxColumnsLeft = (int) (visibleLeft * ((double) wholeWidth / va.getWidth())); myIdxRight = widestEditor(myRightEditors); final Editor rightEditor = myRightEditors.get(myIdxRight); final int wholeWidthRight = rightEditor.getContentComponent().getWidth(); final Rectangle vaRight = rightEditor.getScrollingModel().getVisibleArea(); final int visibleRight = rightEditor.xyToVisualPosition(new Point(va.width, 0)).column; myMaxColumnsRight = (int) (visibleRight * ((double) wholeWidthRight / vaRight.getWidth())); myByLeft = !(myMaxColumnsLeft <= visibleLeft); if (!myByLeft) { // check right editor if (myLeftScroll.getVisibleAmount() != visibleRight) { myLeftScroll.setVisibleAmount(visibleRight); } myLeftScroll.setMaximum(myMaxColumnsRight); } else { if (myLeftScroll.getVisibleAmount() != visibleLeft) { myLeftScroll.setVisibleAmount(visibleLeft); } myLeftScroll.setMaximum(myMaxColumnsLeft); } }
public ParticleContainer(Editor editor) { parent = editor.getContentComponent(); parent.add(this); this.setBounds(parent.getBounds()); setVisible(true); parent.addComponentListener(this); }
public static void showInfoTooltip( @NotNull final HighlightInfo info, final Editor editor, final int defaultOffset, final int currentWidth) { if (info.toolTip == null || info.getSeverity() == HighlightSeverity.INFORMATION) return; Rectangle visibleArea = editor.getScrollingModel().getVisibleArea(); int endOffset = info.highlighter.getEndOffset(); int startOffset = info.highlighter.getStartOffset(); Point top = editor.logicalPositionToXY(editor.offsetToLogicalPosition(startOffset)); Point bottom = editor.logicalPositionToXY(editor.offsetToLogicalPosition(endOffset)); Point bestPoint = new Point(top.x, bottom.y + editor.getLineHeight()); if (!visibleArea.contains(bestPoint)) { bestPoint = editor.logicalPositionToXY(editor.offsetToLogicalPosition(defaultOffset)); } Point p = SwingUtilities.convertPoint( editor.getContentComponent(), bestPoint, editor.getComponent().getRootPane().getLayeredPane()); TooltipController.getInstance() .showTooltip(editor, p, info.toolTip, currentWidth, false, DAEMON_INFO_GROUP); }
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) { if (editor == null) return; // final PsiFile psiFile = // PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); if (psiFile == null) return; CommandProcessor.getInstance() .executeCommand( project, () -> { final CodeInsightActionHandler handler = getHandler(); final Runnable action = () -> { if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return; handler.invoke(project, editor, psiFile); }; if (handler.startInWriteAction()) { ApplicationManager.getApplication().runWriteAction(action); } else { action.run(); } }, getCommandName(), DocCommandGroupId.noneGroupId(editor.getDocument())); }
@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); } }
private HighlightersSet installHighlighterSet(Info info, Editor editor) { final JComponent internalComponent = editor.getContentComponent(); internalComponent.addKeyListener(myEditorKeyListener); editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener); final Cursor cursor = internalComponent.getCursor(); internalComponent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); myFileEditorManager.addFileEditorManagerListener(myFileEditorManagerListener); List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>(); TextAttributes attributes = myEditorColorsManager .getGlobalScheme() .getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR); for (TextRange range : info.getRanges()) { TextAttributes attr = patchAttributesColor(attributes, range, editor); final RangeHighlighter highlighter = editor .getMarkupModel() .addRangeHighlighter( range.getStartOffset(), range.getEndOffset(), HighlighterLayer.SELECTION + 1, attr, HighlighterTargetArea.EXACT_RANGE); highlighters.add(highlighter); } return new HighlightersSet(highlighters, editor, cursor, info); }
@Override public void editorReleased(@NotNull EditorFactoryEvent editorFactoryEvent) { Editor editor = editorFactoryEvent.getEditor(); JComponent contentComponent = editor.getContentComponent(); editorsList.remove(editor); contentComponent.setBorder(null); }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PsiMethod method = findMethod(file, editor.getCaretModel().getOffset()); if (method == null) return; if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return; invokeHandler(project, editor, method); }
@Override public void run() { final Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor(); if (editor != null) { editor.getContentComponent().revalidate(); editor.getContentComponent().repaint(); } }
/** ******************** EditorFactoryListener ******************** */ @Override public void editorCreated(@NotNull EditorFactoryEvent editorFactoryEvent) { Editor editor = editorFactoryEvent.getEditor(); JComponent contentComponent = editor.getContentComponent(); editorsList.add(editor); contentComponent.setBorder(new BackgroundImageBorder()); loadImage(editor); }
public void uninstall() { for (RangeHighlighter highlighter : myHighlighters) { highlighter.dispose(); } Component internalComponent = myHighlighterView.getContentComponent(); internalComponent.setCursor(myStoredCursor); internalComponent.removeKeyListener(myEditorKeyListener); myHighlighterView.getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener); myFileEditorManager.removeFileEditorManagerListener(myFileEditorManagerListener); }
public void showInBestPositionFor(@NotNull Editor editor) { assert editor.getComponent().isShowing() : "Editor must be showing on the screen"; DataContext context = ((EditorEx) editor).getDataContext(); Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(context); if (dominantArea != null && !myRequestFocus) { final JLayeredPane layeredPane = editor.getContentComponent().getRootPane().getLayeredPane(); show(relativePointWithDominantRectangle(layeredPane, dominantArea)); } else { show(JBPopupFactory.getInstance().guessBestPopupLocation(editor)); } }
private void addCommentActionToEditor( Editor editor, String filePath, ChangeInfo changeInfo, String revisionId, Comment.Side commentSide) { if (editor == null) return; DefaultActionGroup group = new DefaultActionGroup(); final AddCommentAction addCommentAction = addCommentActionBuilder .create(this, changeInfo, revisionId, editor, filePath, commentSide) .withText("Add Comment") .withIcon(AllIcons.Toolwindows.ToolWindowMessages) .get(); addCommentAction.registerCustomShortcutSet( CustomShortcutSet.fromString("C"), editor.getContentComponent()); group.add(addCommentAction); PopupHandler.installUnknownPopupHandler( editor.getContentComponent(), group, ActionManager.getInstance()); }
@NotNull @Override public RelativePoint guessBestPopupLocation(@NotNull Editor editor) { Point p = getVisibleBestPopupLocation(editor); if (p == null) { final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea(); p = new Point( (visibleArea.x + visibleArea.width) / 2, (visibleArea.y + visibleArea.height) / 2); } return new RelativePoint(editor.getContentComponent(), p); }
@NotNull private static DataContext createEditorContext(@NotNull Editor editor) { Object e = editor; Object hostEditor = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor; Map<String, Object> map = ContainerUtil.newHashMap( Pair.create(CommonDataKeys.HOST_EDITOR.getName(), hostEditor), Pair.createNonNull(CommonDataKeys.EDITOR.getName(), e)); DataContext parent = DataManager.getInstance().getDataContext(editor.getContentComponent()); return SimpleDataContext.getSimpleContext(map, parent); }
public CompletionProgressIndicator( final Editor editor, CompletionParameters parameters, CodeCompletionHandlerBase handler, Semaphore freezeSemaphore, final OffsetMap offsetMap, boolean hasModifiers) { myEditor = editor; myParameters = parameters; myHandler = handler; myFreezeSemaphore = freezeSemaphore; myOffsetMap = offsetMap; myLookup = (LookupImpl) parameters.getLookup(); myLookup.setArranger(new CompletionLookupArranger(parameters, this)); myLookup.addLookupListener(myLookupListener); myLookup.setCalculating(true); myLookupManagerListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getNewValue() != null) { LOG.error( "An attempt to change the lookup during completion, phase = " + CompletionServiceImpl.getCompletionPhase()); } } }; LookupManager.getInstance(getProject()).addPropertyChangeListener(myLookupManagerListener); myQueue = new MergingUpdateQueue( "completion lookup progress", 200, true, myEditor.getContentComponent()); myQueue.setPassThrough(false); ApplicationManager.getApplication().assertIsDispatchThread(); addMapToDispose(offsetMap); if (ApplicationManager.getApplication().isUnitTestMode()) { return; } if (!myLookup.isShown()) { scheduleAdvertising(); } if (hasModifiers) { trackModifiers(); } }
private boolean navigateInAnyFileEditor(Project project, boolean focusEditor) { List<FileEditor> editors = FileEditorManager.getInstance(project).openEditor(this, focusEditor); for (FileEditor editor : editors) { if (editor instanceof TextEditor) { Editor e = ((TextEditor) editor).getEditor(); unfoldCurrentLine(e); if (focusEditor) { IdeFocusManager.getInstance(myProject).requestFocus(e.getContentComponent(), true); } } } return !editors.isEmpty(); }
private int widestEditor(final List<Editor> editors) { int maxWidth = 0; int idxMax = 0; for (int i = 0; i < editors.size(); i++) { Editor editor = editors.get(i); final int wholeWidth = editor.getContentComponent().getWidth(); if (wholeWidth > maxWidth) { maxWidth = wholeWidth; idxMax = i; } } return idxMax; }
@Nullable public RelativePoint getHyperlinkLocation(HyperlinkInfo info) { Editor editor = myLogEditor.getValue(); Project project = editor.getProject(); RangeHighlighter range = myHyperlinkSupport.getValue().findHyperlinkRange(info); Window window = NotificationsManagerImpl.findWindowForBalloon(project); if (range != null && window != null) { Point point = editor.visualPositionToXY(editor.offsetToVisualPosition(range.getStartOffset())); return new RelativePoint( window, SwingUtilities.convertPoint(editor.getContentComponent(), point, window)); } return null; }
public static void performTypingAction(Editor editor, char c) { EditorActionManager actionManager = EditorActionManager.getInstance(); if (c == BACKSPACE_FAKE_CHAR) { executeAction(editor, IdeActions.ACTION_EDITOR_BACKSPACE); } else if (c == SMART_ENTER_FAKE_CHAR) { executeAction(editor, IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT); } else if (c == SMART_LINE_SPLIT_CHAR) { executeAction(editor, IdeActions.ACTION_EDITOR_SPLIT); } else if (c == '\n') { executeAction(editor, IdeActions.ACTION_EDITOR_ENTER); } else { TypedAction action = actionManager.getTypedAction(); action.actionPerformed( editor, c, DataManager.getInstance().getDataContext(editor.getContentComponent())); } }
public void setDiffRequest(DiffRequest data) { myDiffRequest = data; if (data.getHints().contains(DiffTool.HINT_DO_NOT_IGNORE_WHITESPACES)) { setComparisonPolicy(ComparisonPolicy.DEFAULT, false); } myDataProvider.putData(myDiffRequest.getGenericData()); DiffContent content1 = data.getContents()[0]; DiffContent content2 = data.getContents()[1]; setContents(content1, content2); setTitles(data); setWindowTitle(myOwnerWindow, data.getWindowTitle()); myPanel.setToolbarActions(createToolbar()); data.customizeToolbar(myPanel.resetToolbar()); myPanel.registerToolbarActions(); initEditorSettings(getEditor1()); initEditorSettings(getEditor2()); final JComponent oldBottomComponent = myPanel.getBottomComponent(); if (oldBottomComponent instanceof Disposable) { Disposer.dispose((Disposable) oldBottomComponent); } final JComponent newBottomComponent = data.getBottomComponent(); myPanel.setBottomComponent(newBottomComponent); if (myIsRequestFocus) { IdeFocusManager fm = IdeFocusManager.getInstance(myProject); boolean isEditor1Focused = getEditor1() != null && fm.getFocusedDescendantFor(getEditor1().getComponent()) != null; boolean isEditor2Focused = myData.getContent2() != null && getEditor2() != null && fm.getFocusedDescendantFor(getEditor2().getComponent()) != null; if (isEditor1Focused || isEditor2Focused) { Editor e = isEditor2Focused ? getEditor2() : getEditor1(); if (e != null) { fm.requestFocus(e.getContentComponent(), true); } } myPanel.requestScrollEditors(); } }
private void loadImage(Editor editor) { JComponent contentComponent = editor.getContentComponent(); Border border = contentComponent.getBorder(); if (border instanceof BackgroundImageBorder) { BackgroundImageBorder backgroundImageBorder = (BackgroundImageBorder) border; if (imagesList.size() > 1) { int i = random.nextInt(imagesList.size()); ImageHolder imageHolder = imagesList.get(i); backgroundImageBorder.setImageHolder(imageHolder); } else if (imagesList.size() == 1) { backgroundImageBorder.setImageHolder(imagesList.get(0)); } else { backgroundImageBorder.setImageHolder(null); } contentComponent.repaint(); } }
@Override public void doApplyInformationToEditor() { Application application = ApplicationManager.getApplication(); application.assertIsDispatchThread(); if (!application.isUnitTestMode() && !myEditor.getContentComponent().hasFocus()) return; List<HighlightInfo> visibleHighlights = getVisibleHighlights(myStartOffset, myEndOffset, myProject, myEditor); int caretOffset = myEditor.getCaretModel().getOffset(); for (int i = visibleHighlights.size() - 1; i >= 0; i--) { HighlightInfo info = visibleHighlights.get(i); if (info.startOffset <= caretOffset && showAddImportHint(info)) return; } for (HighlightInfo visibleHighlight : visibleHighlights) { if (visibleHighlight.startOffset > caretOffset && showAddImportHint(visibleHighlight)) return; } }
@Override protected void processKeyEvent(@NotNull final KeyEvent e) { final char keyChar = e.getKeyChar(); if (keyChar == KeyEvent.VK_ENTER || keyChar == KeyEvent.VK_TAB) { IdeFocusManager.getInstance(myProject) .requestFocus(myEditor.getContentComponent(), true) .doWhenDone( new Runnable() { @Override public void run() { IdeEventQueue.getInstance().getKeyEventDispatcher().dispatchKeyEvent(e); } }); return; } super.processKeyEvent(e); }
public static void navigateToFailedPlaceholder( @NotNull final StudyState studyState, @NotNull final Task task, @NotNull final VirtualFile taskDir, @NotNull final Project project) { TaskFile selectedTaskFile = studyState.getTaskFile(); Editor editor = studyState.getEditor(); TaskFile taskFileToNavigate = selectedTaskFile; VirtualFile fileToNavigate = studyState.getVirtualFile(); final StudyTaskManager taskManager = StudyTaskManager.getInstance(project); if (!taskManager.hasFailedAnswerPlaceholders(selectedTaskFile)) { for (Map.Entry<String, TaskFile> entry : task.getTaskFiles().entrySet()) { String name = entry.getKey(); TaskFile taskFile = entry.getValue(); if (taskManager.hasFailedAnswerPlaceholders(taskFile)) { taskFileToNavigate = taskFile; VirtualFile virtualFile = taskDir.findChild(name); if (virtualFile == null) { continue; } FileEditor fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile); if (fileEditor instanceof StudyEditor) { StudyEditor studyEditor = (StudyEditor) fileEditor; editor = studyEditor.getEditor(); } fileToNavigate = virtualFile; break; } } } if (fileToNavigate != null) { FileEditorManager.getInstance(project).openFile(fileToNavigate, true); } final Editor editorToNavigate = editor; ApplicationManager.getApplication() .invokeLater( () -> IdeFocusManager.getInstance(project) .requestFocus(editorToNavigate.getContentComponent(), true)); StudyNavigator.navigateToFirstFailedAnswerPlaceholder(editor, taskFileToNavigate); }
public boolean showLookup() { ApplicationManager.getApplication().assertIsDispatchThread(); checkValid(); LOG.assertTrue(!myShown); myShown = true; myStampShown = System.currentTimeMillis(); if (ApplicationManager.getApplication().isUnitTestMode()) return true; if (!myEditor.getContentComponent().isShowing()) { hide(); return false; } myAdComponent.showRandomText(); myUi = new LookupUi(this, myAdComponent, myList, myProject); myUi.setCalculating(myCalculating); Point p = myUi.calculatePosition().getLocation(); try { HintManagerImpl.getInstanceImpl() .showEditorHint( this, myEditor, p, HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false, HintManagerImpl.createHintHint(myEditor, p, this, HintManager.UNDER) .setAwtTooltip(false)); } catch (Exception e) { LOG.error(e); } if (!isVisible() || !myList.isShowing()) { hide(); return false; } DaemonCodeAnalyzer.getInstance(myProject).disableUpdateByTimer(this); return true; }
@Override public RelativePoint recalculateLocation(final Balloon object) { FindResult cursor = mySearchResults.getCursor(); if (cursor == null) return null; final TextRange cur = cursor; int startOffset = cur.getStartOffset(); int endOffset = cur.getEndOffset(); if (startOffset >= myEditor.getDocument().getTextLength()) { if (!object.isDisposed()) { requestBalloonHiding(object); } return null; } if (!SearchResults.insideVisibleArea(myEditor, cur)) { requestBalloonHiding(object); VisibleAreaListener visibleAreaListener = new VisibleAreaListener() { @Override public void visibleAreaChanged(VisibleAreaEvent e) { if (SearchResults.insideVisibleArea(myEditor, cur)) { showReplacementPreview(); final VisibleAreaListener visibleAreaListener = this; final boolean remove = myVisibleAreaListenersToRemove.remove(visibleAreaListener); if (remove) { myEditor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener); } } } }; myEditor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); myVisibleAreaListenersToRemove.add(visibleAreaListener); } Point startPoint = myEditor.visualPositionToXY(myEditor.offsetToVisualPosition(startOffset)); Point endPoint = myEditor.visualPositionToXY(myEditor.offsetToVisualPosition(endOffset)); Point point = new Point((startPoint.x + endPoint.x) / 2, startPoint.y); return new RelativePoint(myEditor.getContentComponent(), point); }
private Editor createLogEditor() { Project project = myProjectModel.getProject(); final Editor editor = ConsoleViewUtil.setupConsoleEditor(project, false, false); myProjectModel .getProject() .getMessageBus() .connect() .subscribe( ProjectManager.TOPIC, new ProjectManagerAdapter() { @Override public void projectClosed(Project project) { if (project == myProjectModel.getProject()) { EditorFactory.getInstance().releaseEditor(editor); } } }); ((EditorMarkupModel) editor.getMarkupModel()).setErrorStripeVisible(true); final ClearLogAction clearLog = new ClearLogAction(this); clearLog.registerCustomShortcutSet( ActionManager.getInstance().getAction(IdeActions.CONSOLE_CLEAR_ALL).getShortcutSet(), editor.getContentComponent()); editor.addEditorMouseListener( new EditorPopupHandler() { public void invokePopup(final EditorMouseEvent event) { final ActionManager actionManager = ActionManager.getInstance(); final ActionPopupMenu menu = actionManager.createActionPopupMenu( ActionPlaces.EDITOR_POPUP, createPopupActions(actionManager, clearLog)); final MouseEvent mouseEvent = event.getMouseEvent(); menu.getComponent() .show(mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent.getY()); } }); return editor; }
private static void addCompletionChar( Project project, CompletionAssertions.WatchingInsertionContext context, LookupElement item, Editor editor, CompletionProgressIndicator indicator, char completionChar) { int tailOffset = context.getTailOffset(); if (tailOffset < 0) { LOG.info( "tailOffset<0 after inserting " + item + " of " + item.getClass() + "; invalidated at: " + context.invalidateTrace + "\n--------"); } else { editor.getCaretModel().moveToOffset(tailOffset); } if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) { final Language language = PsiUtilBase.getLanguageInEditor(editor, project); if (language != null) { for (SmartEnterProcessor processor : SmartEnterProcessors.INSTANCE.forKey(language)) { if (processor.processAfterCompletion(editor, indicator.getParameters().getOriginalFile())) break; } } } else if (!editor .getCaretModel() .supportsMultipleCarets()) { // this will be done outside of runForEach caret context DataContext dataContext = DataManager.getInstance().getDataContext(editor.getContentComponent()); EditorActionManager.getInstance() .getTypedAction() .getHandler() .execute(editor, completionChar, dataContext); } }