/** * @param editor * @param idDialog * @param dialog * @param title */ public static void setDialogVisible( @Nullable Editor editor, String idDialog, JDialog dialog, String title) { Point location = null; if (editor != null) { Point caretLocation = editor.visualPositionToXY(editor.getCaretModel().getVisualPosition()); SwingUtilities.convertPointToScreen(caretLocation, editor.getComponent()); String[] position = UtilsPreferences.getDialogPosition(idDialog).split("x"); if (!(position[0].equals("0") && position[1].equals("0"))) { location = new Point(Integer.parseInt(position[0]), Integer.parseInt(position[1])); } } if (location == null) { // Center to screen dialog.setLocationRelativeTo(null); } else { dialog.setLocation(location.x, location.y); } dialog.setTitle(title); dialog.pack(); dialog.setVisible(true); }
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); }
TextEditorComponent( @NotNull final Project project, @NotNull final VirtualFile file, @NotNull final TextEditorImpl textEditor) { super(new BorderLayout(), textEditor); myProject = project; myFile = file; myTextEditor = textEditor; myDocument = FileDocumentManager.getInstance().getDocument(myFile); LOG.assertTrue(myDocument != null); myDocumentListener = new MyDocumentListener(); myDocument.addDocumentListener(myDocumentListener); myEditorMouseListener = new MyEditorMouseListener(); myEditorPropertyChangeListener = new MyEditorPropertyChangeListener(); myConnection = project.getMessageBus().connect(); myConnection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener()); myVirtualFileListener = new MyVirtualFileListener(); myFile.getFileSystem().addVirtualFileListener(myVirtualFileListener); myEditor = createEditor(); add(myEditor.getComponent(), BorderLayout.CENTER); myModified = isModifiedImpl(); myValid = isEditorValidImpl(); LOG.assertTrue(myValid); }
@Override public boolean isEnabled(Editor editor, DataContext dataContext) { Project project = PlatformDataKeys.PROJECT.getData( DataManager.getInstance().getDataContext(editor.getComponent())); return project != null; }
@Override public void execute(Editor editor, DataContext dataContext) { Project project = PlatformDataKeys.PROJECT.getData( DataManager.getInstance().getDataContext(editor.getComponent())); FindUtil.replace(project, editor); }
public boolean isEnabled(@NotNull final Project project, final AnActionEvent event) { if (!myHandler.isEnabled(project)) return false; Editor editor = event.getData(PlatformDataKeys.EDITOR); if (editor == null) return false; InputEvent inputEvent = event.getInputEvent(); if (inputEvent instanceof MouseEvent && inputEvent.isAltDown()) { MouseEvent mouseEvent = (MouseEvent) inputEvent; Component component = SwingUtilities.getDeepestComponentAt( mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent.getY()); if (SwingUtilities.isDescendingFrom(component, editor.getComponent())) { MouseEvent convertedEvent = SwingUtilities.convertMouseEvent(mouseEvent.getComponent(), mouseEvent, component); EditorMouseEventArea area = editor.getMouseEventArea(convertedEvent); if (area != EditorMouseEventArea.EDITING_AREA) { return false; } } } else { if (StringUtil.isEmptyOrSpaces(editor.getSelectionModel().getSelectedText())) { return false; } } return true; }
private void adjustPositionForLookup(@NotNull Lookup lookup) { if (!myHint.isVisible() || myEditor.isDisposed()) { Disposer.dispose(this); return; } IdeTooltip tooltip = myHint.getCurrentIdeTooltip(); if (tooltip != null) { JRootPane root = myEditor.getComponent().getRootPane(); if (root != null) { Point p = tooltip.getShowingPoint().getPoint(root.getLayeredPane()); if (lookup.isPositionedAboveCaret()) { if (Position.above == tooltip.getPreferredPosition()) { myHint.pack(); myHint.updatePosition(Position.below); myHint.updateLocation(p.x, p.y + tooltip.getPositionChangeY()); } } else { if (Position.below == tooltip.getPreferredPosition()) { myHint.pack(); myHint.updatePosition(Position.above); myHint.updateLocation(p.x, p.y - tooltip.getPositionChangeY()); } } } } }
public BytecodeToolWindow(Project project, ToolWindow toolWindow) { super(new BorderLayout()); myProject = project; this.toolWindow = toolWindow; myEditor = EditorFactory.getInstance() .createEditor( EditorFactory.getInstance().createDocument(""), project, JavaFileType.INSTANCE, true); add(myEditor.getComponent()); JPanel optionPanel = new JPanel(new BorderLayout()); add(optionPanel, BorderLayout.NORTH); /*TODO: try to extract default parameter from compiler options*/ enableInline = new JCheckBox("Enable inline"); optionPanel.add(enableInline, BorderLayout.WEST); new InfinitePeriodicalTask( UPDATE_DELAY, Alarm.ThreadToUse.SWING_THREAD, this, new Computable<LongRunningReadTask>() { @Override public LongRunningReadTask compute() { return new UpdateBytecodeToolWindowTask(); } }) .start(); setText(DEFAULT_TEXT); }
private Content getOrCreateConsoleContent(final ContentManager contentManager) { final String displayName = VcsBundle.message("vcs.console.toolwindow.display.name"); Content content = contentManager.findContent(displayName); if (content == null) { releaseEditor(); final EditorFactory editorFactory = EditorFactory.getInstance(); final Editor editor = editorFactory.createViewer(editorFactory.createDocument(""), myProject); EditorSettings editorSettings = editor.getSettings(); editorSettings.setLineMarkerAreaShown(false); editorSettings.setIndentGuidesShown(false); editorSettings.setLineNumbersShown(false); editorSettings.setFoldingOutlineShown(false); ((EditorEx) editor).getScrollPane().setBorder(null); myEditorAdapter = new EditorAdapter(editor, myProject, false); final JPanel panel = new JPanel(new BorderLayout()); panel.add(editor.getComponent(), BorderLayout.CENTER); content = ContentFactory.SERVICE.getInstance().createContent(panel, displayName, true); contentManager.addContent(content); for (Pair<String, TextAttributes> pair : myPendingOutput) { myEditorAdapter.appendString(pair.first, pair.second); } myPendingOutput.clear(); } return content; }
private static void showParameterHint( final PsiElement element, final Editor editor, final Object[] descriptors, final Project project, @Nullable PsiElement highlighted, final int elementStart, final ParameterInfoHandler handler, final boolean requestFocus) { if (ParameterInfoController.isAlreadyShown(editor, elementStart)) return; if (editor.isDisposed() || !editor.getComponent().isVisible()) return; final ParameterInfoComponent component = new ParameterInfoComponent(descriptors, editor, handler, requestFocus); component.setParameterOwner(element); component.setRequestFocus(requestFocus); if (highlighted != null) { component.setHighlightedParameter(highlighted); } component.update(); // to have correct preferred size final LightweightHint hint = new LightweightHint(component); hint.setSelectingHint(true); final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); final ShowParameterInfoHandler.BestLocationPointProvider provider = new MyBestLocationPointProvider(editor); final Pair<Point, Short> pos = provider.getBestPointPosition(hint, element, elementStart, true, HintManager.UNDER); PsiDocumentManager.getInstance(project) .performLaterWhenAllCommitted( () -> { if (editor.isDisposed() || DumbService.isDumb(project)) return; final Document document = editor.getDocument(); if (document.getTextLength() < elementStart) return; HintHint hintHint = HintManagerImpl.createHintHint(editor, pos.getFirst(), hint, pos.getSecond()); hintHint.setExplicitClose(true); hintHint.setRequestFocus(requestFocus); Editor editorToShow = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor; // is case of injection we need to calculate position for EditorWindow // also we need to show the hint in the main editor because of intention bulb hintManager.showEditorHint( hint, editorToShow, pos.getFirst(), HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false, hintHint); new ParameterInfoController(project, editor, elementStart, hint, handler, provider); }); }
/** @return Point in layered pane coordinate system */ static Pair<Point, Short> chooseBestHintPosition( Project project, Editor editor, int line, int col, LightweightHint hint, boolean awtTooltip, short preferredPosition) { HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); Dimension hintSize = hint.getComponent().getPreferredSize(); JComponent editorComponent = editor.getComponent(); JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane(); Point p1; Point p2; boolean isLookupShown = LookupManager.getInstance(project).getActiveLookup() != null; if (isLookupShown) { p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER); p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE); } else { LogicalPosition pos = new LogicalPosition(line, col); p1 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.UNDER); p2 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.ABOVE); } if (!awtTooltip) { p1.x = Math.min(p1.x, layeredPane.getWidth() - hintSize.width); p1.x = Math.max(p1.x, 0); p2.x = Math.min(p2.x, layeredPane.getWidth() - hintSize.width); p2.x = Math.max(p2.x, 0); } boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight(); boolean p2Ok = p2.y >= 0; if (isLookupShown) { if (p1Ok) return new Pair<Point, Short>(p1, HintManager.UNDER); if (p2Ok) return new Pair<Point, Short>(p2, HintManager.ABOVE); } else { if (preferredPosition != HintManager.DEFAULT) { if (preferredPosition == HintManager.ABOVE) { if (p2Ok) return new Pair<Point, Short>(p2, HintManager.ABOVE); } else if (preferredPosition == HintManager.UNDER) { if (p1Ok) return new Pair<Point, Short>(p1, HintManager.UNDER); } } if (p1Ok) return new Pair<Point, Short>(p1, HintManager.UNDER); if (p2Ok) return new Pair<Point, Short>(p2, HintManager.ABOVE); } int underSpace = layeredPane.getHeight() - p1.y; int aboveSpace = p2.y; return aboveSpace > underSpace ? new Pair<Point, Short>(new Point(p2.x, 0), HintManager.UNDER) : new Pair<Point, Short>(p1, HintManager.ABOVE); }
protected JComponent createEditorContent() { JPanel result = new JPanel(new BorderLayout()); Splitter p; result.add(BorderLayout.CENTER, p = new Splitter(true, 0.5f)); p.setFirstComponent(super.createEditorContent()); replaceCriteriaEdit = createEditor(searchContext, mySavedEditorText != null ? mySavedEditorText : ""); JPanel replace = new JPanel(new BorderLayout()); replace.add(BorderLayout.NORTH, new JLabel(SSRBundle.message("replacement.template.label"))); replace.add(BorderLayout.CENTER, replaceCriteriaEdit.getComponent()); replaceCriteriaEdit.getComponent().setMinimumSize(new Dimension(150, 100)); p.setSecondComponent(replace); return result; }
@Override public void commandStarted(CommandEvent event) { for (Editor editor : EditorFactory.getInstance().getAllEditors()) { if (editor.getComponent().isShowing()) { myEditorsVisibleOnCommandStart.add(editor); } ((ScrollingModelImpl) editor.getScrollingModel()).finishAnimation(); myCurrentCommandStart = System.currentTimeMillis(); } }
/** * Emulates pressing <code>Enter</code> at current caret position. * * @param editor target editor * @param project target project * @param shifts two-elements array which is expected to be filled with the following info: 1. The * first element holds added lines number; 2. The second element holds added symbols number; */ private static void emulateEnter( @NotNull final Editor editor, @NotNull Project project, int[] shifts) { final DataContext dataContext = prepareContext(editor.getComponent(), project); int caretOffset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); SelectionModel selectionModel = editor.getSelectionModel(); int startSelectionOffset = 0; int endSelectionOffset = 0; boolean restoreSelection = selectionModel.hasSelection(); if (restoreSelection) { startSelectionOffset = selectionModel.getSelectionStart(); endSelectionOffset = selectionModel.getSelectionEnd(); selectionModel.removeSelection(); } int textLengthBeforeWrap = document.getTextLength(); int lineCountBeforeWrap = document.getLineCount(); DataManager.getInstance() .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, true); CommandProcessor commandProcessor = CommandProcessor.getInstance(); try { Runnable command = new Runnable() { @Override public void run() { EditorActionManager.getInstance() .getActionHandler(IdeActions.ACTION_EDITOR_ENTER) .execute(editor, dataContext); } }; if (commandProcessor.getCurrentCommand() == null) { commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null); } else { command.run(); } } finally { DataManager.getInstance() .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, null); } int symbolsDiff = document.getTextLength() - textLengthBeforeWrap; if (restoreSelection) { int newSelectionStart = startSelectionOffset; int newSelectionEnd = endSelectionOffset; if (startSelectionOffset >= caretOffset) { newSelectionStart += symbolsDiff; } if (endSelectionOffset >= caretOffset) { newSelectionEnd += symbolsDiff; } selectionModel.setSelection(newSelectionStart, newSelectionEnd); } shifts[0] = document.getLineCount() - lineCountBeforeWrap; shifts[1] = symbolsDiff; }
ParameterInfoComponent( Object[] objects, Editor editor, @NotNull ParameterInfoHandler handler, boolean requestFocus) { super(new BorderLayout()); myRequestFocus = requestFocus; if (!ApplicationManager.getApplication().isUnitTestMode()) { JComponent editorComponent = editor.getComponent(); JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane(); myWidthLimit = layeredPane.getWidth(); } NORMAL_FONT = UIUtil.getLabelFont(); BOLD_FONT = NORMAL_FONT.deriveFont(Font.BOLD); myObjects = objects; setBackground(BACKGROUND_COLOR); myHandler = handler; myPanels = new OneElementComponent[myObjects.length]; final JPanel panel = new JPanel(new GridBagLayout()); for (int i = 0; i < myObjects.length; i++) { myPanels[i] = new OneElementComponent(); panel.add( myPanels[i], new GridBagConstraints( 0, i, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); } if (myRequestFocus) { AccessibleContextUtil.setName( this, "Parameter Info. Press TAB to navigate through each element. Press ESC to close."); } final JScrollPane pane = ScrollPaneFactory.createScrollPane(panel); pane.setBorder(null); pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(pane, BorderLayout.CENTER); myCurrentParameterIndex = -1; }
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 addAlarmRequest() { Runnable request = () -> { if (!myDisposed && !myProject.isDisposed()) { PsiDocumentManager.getInstance(myProject) .performLaterWhenAllCommitted( () -> DumbService.getInstance(myProject) .withAlternativeResolveEnabled(this::updateComponent)); } }; myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent())); }
public Editor addCommitLog(String title, Editor commitLog) { boolean notExist = !_commitLogs.contains(commitLog); LOG.assertTrue(notExist); //noinspection ConstantConditions if (notExist) { DefaultActionGroup actions = new DefaultActionGroup(); actions.add(new CopyContentAction(commitLog)); addTab( title, commitLog.getComponent(), true, false, false, true, actions, COMMIT_LOG_HELP_ID); _commitLogs.add(commitLog); } return commitLog; }
private static PsiAnnotation createNewAnnotation( final Project project, final Editor editor, final PsiElement container, @Nullable final PsiAnnotation annotation, final String id) { if (annotation != null) { final String currentSuppressedId = "\"" + id + "\""; if (!annotation.getText().contains("{")) { final PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes(); if (attributes.length == 1) { final String suppressedWarnings = attributes[0].getText(); if (suppressedWarnings.contains(currentSuppressedId)) return null; return JavaPsiFacade.getInstance(project) .getElementFactory() .createAnnotationFromText( "@" + SuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME + "({" + suppressedWarnings + ", " + currentSuppressedId + "})", container); } } else { final int curlyBraceIndex = annotation.getText().lastIndexOf("}"); if (curlyBraceIndex > 0) { final String oldSuppressWarning = annotation.getText().substring(0, curlyBraceIndex); if (oldSuppressWarning.contains(currentSuppressedId)) return null; return JavaPsiFacade.getInstance(project) .getElementFactory() .createAnnotationFromText( oldSuppressWarning + ", " + currentSuppressedId + "})", container); } else if (!ApplicationManager.getApplication().isUnitTestMode() && editor != null) { Messages.showErrorDialog( editor.getComponent(), InspectionsBundle.message( "suppress.inspection.annotation.syntax.error", annotation.getText())); } } } else { return JavaPsiFacade.getInstance(project) .getElementFactory() .createAnnotationFromText( "@" + SuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME + "(\"" + id + "\")", container); } return null; }
@NotNull private DataContext getContext() { Editor editor = getEditor(); DataContext parent = DataManager.getInstance().getDataContext((Component) myStatusBar); return SimpleDataContext.getSimpleContext( CommonDataKeys.VIRTUAL_FILE.getName(), getSelectedFile(), SimpleDataContext.getSimpleContext( CommonDataKeys.PROJECT.getName(), getProject(), SimpleDataContext.getSimpleContext( PlatformDataKeys.CONTEXT_COMPONENT.getName(), editor == null ? null : editor.getComponent(), parent))); }
@Nullable public static LightweightHint showEditorFragmentHint( Editor editor, TextRange range, boolean showFolding, boolean hideByAnyKey) { JComponent editorComponent = editor.getComponent(); final JRootPane rootPane = editorComponent.getRootPane(); if (rootPane == null) return null; JLayeredPane layeredPane = rootPane.getLayeredPane(); int x = -2; int y = 0; Point point = SwingUtilities.convertPoint(editorComponent, x, y, layeredPane); return showEditorFragmentHintAt( editor, range, point.x, point.y, true, showFolding, hideByAnyKey); }
public Editor addOutput(Editor output) { LOG.assertTrue(myOutput == null); if (myOutput == null) { addTab( CvsBundle.message("tab.title.cvs.output"), output.getComponent(), false, false, false, true, null, "cvs.cvsOutput"); myOutput = output; } return myOutput; }
private void updateComponent() { if (!myHint.isVisible()) { Disposer.dispose(this); return; } final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); CharSequence chars = myEditor.getDocument().getCharsSequence(); boolean noDelimiter = myHandler instanceof ParameterInfoHandlerWithTabActionSupport && ((ParameterInfoHandlerWithTabActionSupport) myHandler) .getActualParameterDelimiterType() == TokenType.WHITE_SPACE; int caretOffset = myEditor.getCaretModel().getOffset(); final int offset = noDelimiter ? caretOffset : CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1; final UpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file); final Object elementForUpdating = myHandler.findElementForUpdatingParameterInfo(context); if (elementForUpdating != null) { myHandler.updateParameterInfo(elementForUpdating, context); if (!myDisposed && myHint.isVisible() && !myEditor.isDisposed() && myEditor.getComponent().getRootPane() != null) { myComponent.update(); IdeTooltip tooltip = myHint.getCurrentIdeTooltip(); short position = tooltip != null ? toShort(tooltip.getPreferredPosition()) : HintManager.UNDER; Pair<Point, Short> pos = myProvider.getBestPointPosition( myHint, elementForUpdating instanceof PsiElement ? (PsiElement) elementForUpdating : null, caretOffset, true, position); HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond()); } } else { context.removeHint(); } }
@Override public void update(AnActionEvent e) { if (myUpdating) { return; } VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE); VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY); if (files != null && files.length > 1) { virtualFile = null; } if (virtualFile != null) { Navigatable navigatable = e.getData(PlatformDataKeys.NAVIGATABLE); if (navigatable instanceof OpenFileDescriptor) { // prefer source to the class file virtualFile = ((OpenFileDescriptor) navigatable).getFile(); } } if (virtualFile != null && !virtualFile.isInLocalFileSystem()) { virtualFile = null; } Editor editor = e.getData(PlatformDataKeys.EDITOR); boolean enabled = encodingActionsPair.areActionsEnabled( null, editor, editor == null ? null : editor.getComponent(), virtualFile, getEventProject(e)); removeAll(); if (enabled) { addAll(encodingActionsPair.createActionGroup()); } myUpdating = true; try { e.getPresentation().setText("File encoding"); // updating the enabled state of the action can trigger the menuSelected handler, which // updates the action group again e.getPresentation().setEnabled(enabled); } finally { myUpdating = false; } }
private void updateChangesForDocument(@NotNull final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); if (DaemonListeners.isUnderIgnoredAction(null) || myProject.isDisposed()) return; List<Pair<PsiElement, Boolean>> toUpdate = changedElements.get(document); if (toUpdate == null) { // The document has been changed, but psi hasn't // We may still need to rehighlight the file if there were changes inside highlighted ranges. if (UpdateHighlightersUtil.isWhitespaceOptimizationAllowed(document)) return; // don't create PSI for files in other projects PsiElement file = PsiDocumentManager.getInstance(myProject).getCachedPsiFile(document); if (file == null) return; toUpdate = Collections.singletonList(Pair.create(file, true)); } Application application = ApplicationManager.getApplication(); final Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor(); if (editor != null && !application.isUnitTestMode()) { application.invokeLater( () -> { if (!editor.isDisposed()) { EditorMarkupModel markupModel = (EditorMarkupModel) editor.getMarkupModel(); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); TrafficLightRenderer.setOrRefreshErrorStripeRenderer( markupModel, myProject, editor.getDocument(), file); } }, ModalityState.stateForComponent(editor.getComponent()), myProject.getDisposed()); } for (Pair<PsiElement, Boolean> changedElement : toUpdate) { PsiElement element = changedElement.getFirst(); Boolean whiteSpaceOptimizationAllowed = changedElement.getSecond(); updateByChange(element, document, whiteSpaceOptimizationAllowed); } changedElements.remove(document); }
private void showHint( @NotNull String text, @Nullable final Editor editor, @NotNull final RelativePoint popupPosition, @NotNull FindUsagesHandler handler, int maxUsages, @NotNull FindUsagesOptions options) { JComponent label = createHintComponent( text, handler, popupPosition, editor, HIDE_HINTS_ACTION, maxUsages, options); if (editor == null || editor.isDisposed() || !editor.getComponent().isShowing()) { HintManager.getInstance() .showHint( label, popupPosition, HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING, 0); } else { HintManager.getInstance().showInformationHint(editor, label); } }
private Editor createEditor() { EditorFactory editorFactory = EditorFactory.getInstance(); Document doc = myFile == null ? editorFactory.createDocument(myTemplate == null ? "" : myTemplate.getText()) : PsiDocumentManager.getInstance(myFile.getProject()).getDocument(myFile); Editor editor = myProject == null ? editorFactory.createEditor(doc) : editorFactory.createEditor(doc, myProject); EditorSettings editorSettings = editor.getSettings(); editorSettings.setVirtualSpace(false); editorSettings.setLineMarkerAreaShown(false); editorSettings.setIndentGuidesShown(false); editorSettings.setLineNumbersShown(false); editorSettings.setFoldingOutlineShown(false); editorSettings.setAdditionalColumnsCount(3); editorSettings.setAdditionalLinesCount(3); EditorColorsScheme scheme = editor.getColorsScheme(); scheme.setColor(EditorColors.CARET_ROW_COLOR, null); editor .getDocument() .addDocumentListener( new DocumentAdapter() { @Override public void documentChanged(DocumentEvent e) { onTextChanged(); } }); ((EditorEx) editor).setHighlighter(createHighlighter()); mySplitter.setFirstComponent(editor.getComponent()); return editor; }
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { final StrutsFacet strutsFacet = StrutsFacet.getInstance(file); assert strutsFacet != null; final Set<StrutsFileSet> strutsFileSets = strutsFacet.getConfiguration().getFileSets(); final BaseListPopupStep<StrutsFileSet> step = new BaseListPopupStep<StrutsFileSet>( StrutsBundle.message("annotators.fileset.fix.choose.fileset"), new ArrayList<StrutsFileSet>(strutsFileSets)) { public Icon getIconFor(final StrutsFileSet aValue) { return StrutsIcons.STRUTS_CONFIG_FILE; } public PopupStep onChosen( final StrutsFileSet selectedValue, final boolean finalChoice) { selectedValue.addFile(file.getVirtualFile()); ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { ProjectRootManagerEx.getInstanceEx(project) .makeRootsChange(EmptyRunnable.getInstance(), false, true); } }); // re-highlight (remove annotation) DaemonCodeAnalyzer.getInstance(project).restart(); return super.onChosen(selectedValue, finalChoice); } }; JBPopupFactory.getInstance() .createListPopup(step) .showInBestPositionFor(DataManager.getInstance().getDataContext(editor.getComponent())); }
public ImplementationViewComponent(PsiElement[] elements, final int index) { super(new BorderLayout()); final Project project = elements.length > 0 ? elements[0].getProject() : null; EditorFactory factory = EditorFactory.getInstance(); Document doc = factory.createDocument(""); doc.setReadOnly(true); myEditor = factory.createEditor(doc, project); ((EditorEx) myEditor).setBackgroundColor(EditorFragmentComponent.getBackgroundColor(myEditor)); final EditorSettings settings = myEditor.getSettings(); settings.setAdditionalLinesCount(1); settings.setAdditionalColumnsCount(1); settings.setLineMarkerAreaShown(false); settings.setIndentGuidesShown(false); settings.setLineNumbersShown(false); settings.setFoldingOutlineShown(false); myBinarySwitch = new CardLayout(); myViewingPanel = new JPanel(myBinarySwitch); myEditor.setBorder(null); ((EditorEx) myEditor).getScrollPane().setViewportBorder(JBScrollPane.createIndentBorder()); myViewingPanel.add(myEditor.getComponent(), TEXT_PAGE_KEY); myBinaryPanel = new JPanel(new BorderLayout()); myViewingPanel.add(myBinaryPanel, BINARY_PAGE_KEY); add(myViewingPanel, BorderLayout.CENTER); myToolbar = createToolbar(); myLocationLabel = new JLabel(); myCountLabel = new JLabel(); final JPanel header = new JPanel(new BorderLayout(2, 0)); header.setBorder( BorderFactory.createCompoundBorder( IdeBorderFactory.createBorder(SideBorder.BOTTOM), IdeBorderFactory.createEmptyBorder(0, 0, 0, 5))); final JPanel toolbarPanel = new JPanel(new GridBagLayout()); final GridBagConstraints gc = new GridBagConstraints( GridBagConstraints.RELATIVE, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 2, 0, 0), 0, 0); toolbarPanel.add(myToolbar.getComponent(), gc); setPreferredSize(new Dimension(600, 400)); update( elements, new PairFunction<PsiElement[], List<FileDescriptor>, Boolean>() { @Override public Boolean fun( final PsiElement[] psiElements, final List<FileDescriptor> fileDescriptors) { if (psiElements.length == 0) return false; myElements = psiElements; myIndex = index < myElements.length ? index : 0; PsiFile psiFile = getContainingFile(myElements[myIndex]); VirtualFile virtualFile = psiFile.getVirtualFile(); EditorHighlighter highlighter; if (virtualFile != null) highlighter = HighlighterFactory.createHighlighter(project, virtualFile); else { String fileName = psiFile.getName(); // some artificial psi file, lets do best we can highlighter = HighlighterFactory.createHighlighter(project, fileName); } ((EditorEx) myEditor).setHighlighter(highlighter); gc.fill = GridBagConstraints.HORIZONTAL; gc.weightx = 1; if (myElements.length > 1) { myFileChooser = new ComboBox( fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]), 250); updateRenderer(project); myFileChooser.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index = myFileChooser.getSelectedIndex(); if (myIndex != index) { myIndex = index; updateControls(); } } }); myLabel = new JLabel(); myLabel.setVisible(false); toolbarPanel.add(myFileChooser, gc); } else { myFileChooser = new ComboBox(); myFileChooser.setVisible(false); myCountLabel.setVisible(false); myLabel = new JLabel(); VirtualFile file = psiFile.getVirtualFile(); if (file != null) { myLabel.setIcon(getIconForFile(psiFile)); myLabel.setForeground( FileStatusManager.getInstance(project).getStatus(file).getColor()); myLabel.setText(file.getPresentableName()); myLabel.setBorder( new CompoundBorder( IdeBorderFactory.createRoundedBorder(), IdeBorderFactory.createEmptyBorder(0, 0, 0, 5))); } toolbarPanel.add(myLabel, gc); } gc.fill = GridBagConstraints.NONE; gc.weightx = 0; toolbarPanel.add(myCountLabel, gc); header.add(toolbarPanel, BorderLayout.CENTER); header.add(myLocationLabel, BorderLayout.EAST); add(header, BorderLayout.NORTH); updateControls(); return true; } }); }
private void updateViewerForSelection() { if (myAllContents.isEmpty()) return; String fullString = getSelectedText(); if (myViewer != null) { EditorFactory.getInstance().releaseEditor(myViewer); } if (myUseIdeaEditor) { myViewer = createIdeaEditor(fullString); JComponent component = myViewer.getComponent(); component.setPreferredSize(JBUI.size(300, 500)); mySplitter.setSecondComponent(component); } else { final JTextArea textArea = new JTextArea(fullString); textArea.setRows(3); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); textArea.setSelectionStart(0); textArea.setSelectionEnd(textArea.getText().length()); textArea.setEditable(false); mySplitter.setSecondComponent(ScrollPaneFactory.createScrollPane(textArea)); } mySplitter.revalidate(); }