summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java
blob: 26429fc0e89678074fff2b979f813dfc0106174d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
 * Copyright 2000-2011 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.execution.impl;

import com.intellij.execution.filters.Filter;
import com.intellij.execution.filters.HyperlinkInfo;
import com.intellij.execution.filters.HyperlinkInfoBase;
import com.intellij.ide.OccurenceNavigator;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.event.EditorMouseAdapter;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.pom.NavigatableAdapter;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Consumer;
import com.intellij.util.FilteringProcessor;
import com.intellij.util.containers.hash.LinkedHashMap;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author peter
 */
public class EditorHyperlinkSupport {
  public static final Key<TextAttributes> OLD_HYPERLINK_TEXT_ATTRIBUTES = Key.create("OLD_HYPERLINK_TEXT_ATTRIBUTES");
  private static final Key<HyperlinkInfoTextAttributes> HYPERLINK = Key.create("HYPERLINK");
  private static final int HYPERLINK_LAYER = HighlighterLayer.SELECTION - 123;
  private static final int HIGHLIGHT_LAYER = HighlighterLayer.SELECTION - 111;

  private final Editor myEditor;
  @NotNull private final Project myProject;

  public EditorHyperlinkSupport(@NotNull final Editor editor, @NotNull final Project project) {
    myEditor = editor;
    myProject = project;

    editor.addEditorMouseListener(new EditorMouseAdapter() {
      @Override
      public void mouseClicked(EditorMouseEvent e) {
        final MouseEvent mouseEvent = e.getMouseEvent();
        if (mouseEvent.getButton() == MouseEvent.BUTTON1 && !mouseEvent.isPopupTrigger()) {
          Runnable runnable = getLinkNavigationRunnable(myEditor.xyToLogicalPosition(e.getMouseEvent().getPoint()));
          if (runnable != null) {
            runnable.run();
          }
        }
      }
    });

    editor.getContentComponent().addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseMoved(final MouseEvent e) {
        final HyperlinkInfo info = getHyperlinkInfoByPoint(e.getPoint());
        if (info != null) {
          myEditor.getContentComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }
        else {
            final Cursor cursor = editor instanceof EditorEx ?
                                  UIUtil.getTextCursor(((EditorEx)editor).getBackgroundColor()) :
                                  Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR);
            myEditor.getContentComponent().setCursor(cursor);
        }
      }
    }
    );
  }

  public void clearHyperlinks() {
    for (RangeHighlighter highlighter : getHyperlinks(0, myEditor.getDocument().getTextLength(), myEditor)) {
      removeHyperlink(highlighter);
    }
  }

  @Deprecated
  public Map<RangeHighlighter, HyperlinkInfo> getHyperlinks() {
    LinkedHashMap<RangeHighlighter, HyperlinkInfo> result = new LinkedHashMap<RangeHighlighter, HyperlinkInfo>();
    for (RangeHighlighter highlighter : getHyperlinks(0, myEditor.getDocument().getTextLength(), myEditor)) {
      HyperlinkInfo info = getHyperlinkInfo(highlighter);
      if (info != null) {
        result.put(highlighter, info);
      }
    }
    return result;
  }

  @Nullable
  public Runnable getLinkNavigationRunnable(final LogicalPosition logical) {
    if (EditorUtil.inVirtualSpace(myEditor, logical)) {
      return null;
    }

    final RangeHighlighter range = findLinkRangeAt(this.myEditor.logicalPositionToOffset(logical));
    if (range != null) {
      final HyperlinkInfo hyperlinkInfo = getHyperlinkInfo(range);
      if (hyperlinkInfo != null) {
        return new Runnable() {
          @Override
          public void run() {
            if (hyperlinkInfo instanceof HyperlinkInfoBase) {
              RelativePoint point = new RelativePoint(myEditor.getContentComponent(), myEditor.logicalPositionToXY(logical));
              ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, point);
            }
            else {
              hyperlinkInfo.navigate(myProject);
            }
            linkFollowed(myEditor, getHyperlinks(0, myEditor.getDocument().getTextLength(),myEditor), range);
          }
        };
      }
    }
    return null;
  }

  @Nullable
  public static HyperlinkInfo getHyperlinkInfo(@NotNull RangeHighlighter range) {
    final HyperlinkInfoTextAttributes attributes = range.getUserData(HYPERLINK);
    return attributes != null ? attributes.getHyperlinkInfo() : null;
  }

  @Nullable
  private RangeHighlighter findLinkRangeAt(final int offset) {
    //noinspection LoopStatementThatDoesntLoop
    for (final RangeHighlighter highlighter : getHyperlinks(offset, offset, myEditor)) {
        return highlighter;
    }
    return null;
  }

  @Nullable
  private HyperlinkInfo getHyperlinkAt(final int offset) {
    RangeHighlighter range = findLinkRangeAt(offset);
    return range == null ? null : getHyperlinkInfo(range);
  }

  public List<RangeHighlighter> findAllHyperlinksOnLine(int line) {
    final int lineStart = myEditor.getDocument().getLineStartOffset(line);
    final int lineEnd = myEditor.getDocument().getLineEndOffset(line);
    return getHyperlinks(lineStart, lineEnd, myEditor);
  }

  public static List<RangeHighlighter> getHyperlinks(int startOffset, int endOffset, final Editor editor) {
    final MarkupModelEx markupModel = (MarkupModelEx)editor.getMarkupModel();
    final CommonProcessors.CollectProcessor<RangeHighlighterEx> processor = new CommonProcessors.CollectProcessor<RangeHighlighterEx>();
    markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset,
                                                        new FilteringProcessor<RangeHighlighterEx>(new Condition<RangeHighlighterEx>() {
                                                          @Override
                                                          public boolean value(RangeHighlighterEx rangeHighlighterEx) {
                                                            return HYPERLINK_LAYER == rangeHighlighterEx.getLayer() &&
                                                                   rangeHighlighterEx.isValid() &&
                                                                   getHyperlinkInfo(rangeHighlighterEx) != null;
                                                          }
                                                        }, processor)
    );
    return new ArrayList<RangeHighlighter>(processor.getResults());
  }

  public void removeHyperlink(@NotNull RangeHighlighter hyperlink) {
    myEditor.getMarkupModel().removeHighlighter(hyperlink);
  }

  @Nullable
  public HyperlinkInfo getHyperlinkInfoByLineAndCol(final int line, final int col) {
    return getHyperlinkAt(myEditor.logicalPositionToOffset(new LogicalPosition(line, col)));
  }

  /**
   * @deprecated for binary compatibility with older plugins
   * @see #createHyperlink(int, int, com.intellij.openapi.editor.markup.TextAttributes, com.intellij.execution.filters.HyperlinkInfo)
   */
  public void addHyperlink(final int highlightStartOffset,
                           final int highlightEndOffset,
                           @Nullable final TextAttributes highlightAttributes,
                           @NotNull final HyperlinkInfo hyperlinkInfo) {
    createHyperlink(highlightStartOffset, highlightEndOffset, highlightAttributes, hyperlinkInfo);
  }

  @NotNull
  public RangeHighlighter createHyperlink(final int highlightStartOffset,
                                          final int highlightEndOffset,
                                          @Nullable final TextAttributes highlightAttributes,
                                          @NotNull final HyperlinkInfo hyperlinkInfo) {
    TextAttributes textAttributes = highlightAttributes != null ? highlightAttributes : getHyperlinkAttributes();
    final RangeHighlighter highlighter = myEditor.getMarkupModel().addRangeHighlighter(highlightStartOffset,
                                                                                       highlightEndOffset,
                                                                                       HYPERLINK_LAYER,
                                                                                       textAttributes,
                                                                                       HighlighterTargetArea.EXACT_RANGE);
    associateHyperlink(highlighter, hyperlinkInfo);
    return highlighter;
  }

  public static void associateHyperlink(@NotNull RangeHighlighter highlighter, @NotNull HyperlinkInfo hyperlinkInfo) {
    highlighter.putUserData(HYPERLINK, new HyperlinkInfoTextAttributes(hyperlinkInfo));
  }

  @Nullable
  public HyperlinkInfo getHyperlinkInfoByPoint(final Point p) {
    final LogicalPosition pos = myEditor.xyToLogicalPosition(new Point(p.x, p.y));
    if (EditorUtil.inVirtualSpace(myEditor, pos)) {
      return null;
    }

    return getHyperlinkInfoByLineAndCol(pos.line, pos.column);
  }

  @Deprecated
  public void highlightHyperlinks(final Filter customFilter, final Filter predefinedMessageFilter, final int line1, final int endLine) {
    highlightHyperlinks(new Filter() {
      @Nullable
      @Override
      public Result applyFilter(String line, int entireLength) {
        Result result = customFilter.applyFilter(line, entireLength);
        return result != null ? result : predefinedMessageFilter.applyFilter(line, entireLength);
      }
    }, line1, endLine);
  }
  
  public void highlightHyperlinks(final Filter customFilter, final int line1, final int endLine) {
    final Document document = myEditor.getDocument();

    final int startLine = Math.max(0, line1);

    for (int line = startLine; line <= endLine; line++) {
      int endOffset = document.getLineEndOffset(line);
      if (endOffset < document.getTextLength()) {
        endOffset++; // add '\n'
      }
      final String text = getLineText(document, line, true);
      Filter.Result result = customFilter.applyFilter(text, endOffset);
      if (result != null) {
        for (Filter.ResultItem resultItem : result.getResultItems()) {
          if (resultItem.getHyperlinkInfo() != null) {
            createHyperlink(resultItem.getHighlightStartOffset(), resultItem.getHighlightEndOffset(), resultItem.getHighlightAttributes(), resultItem.getHyperlinkInfo());
          }
          else if (resultItem.getHighlightAttributes() != null) {
            addHighlighter(resultItem.getHighlightStartOffset(), resultItem.getHighlightEndOffset(), resultItem.getHighlightAttributes());
          }
        }
      }
    }
  }

  public void addHighlighter(int highlightStartOffset, int highlightEndOffset, TextAttributes highlightAttributes) {
    myEditor.getMarkupModel().addRangeHighlighter(highlightStartOffset, highlightEndOffset, HIGHLIGHT_LAYER, highlightAttributes,
                                                  HighlighterTargetArea.EXACT_RANGE);
  }

  private static TextAttributes getHyperlinkAttributes() {
    return EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.HYPERLINK_ATTRIBUTES);
  }

  private static TextAttributes getFollowedHyperlinkAttributes() {
    return EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.FOLLOWED_HYPERLINK_ATTRIBUTES);
  }

  @Nullable
  public static OccurenceNavigator.OccurenceInfo getNextOccurrence(final Editor editor,
                                                                   final int delta,
                                                                   final Consumer<RangeHighlighter> action) {
    final List<RangeHighlighter> ranges = getHyperlinks(0, editor.getDocument().getTextLength(),editor);
    if (ranges.isEmpty()) {
      return null;
    }
    int i;
    for (i = 0; i < ranges.size(); i++) {
      RangeHighlighter range = ranges.get(i);
      if (range.getUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES) != null) {
        break;
      }
    }
    i = i % ranges.size();
    int newIndex = i;
    while (newIndex < ranges.size() && newIndex >= 0) {
      newIndex = (newIndex + delta + ranges.size()) % ranges.size();
      final RangeHighlighter next = ranges.get(newIndex);
      if (editor.getFoldingModel().getCollapsedRegionAtOffset(next.getStartOffset()) == null) {
        return new OccurenceNavigator.OccurenceInfo(new NavigatableAdapter() {
          public void navigate(final boolean requestFocus) {
            action.consume(next);
            linkFollowed(editor, ranges, next);
          }
        }, newIndex == -1 ? -1 : newIndex + 1, ranges.size());
      }
      if (newIndex == i) {
        break; // cycled through everything, found no next/prev hyperlink
      }
    }
    return null;
  }

  // todo fix link followed here!
  private static void linkFollowed(Editor editor, Collection<RangeHighlighter> ranges, final RangeHighlighter link) {
    MarkupModelEx markupModel = (MarkupModelEx)editor.getMarkupModel();
    for (RangeHighlighter range : ranges) {
      TextAttributes oldAttr = range.getUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES);
      if (oldAttr != null) {
        markupModel.setRangeHighlighterAttributes(range, oldAttr);
        range.putUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES, null);
      }
      if (range == link) {
        range.putUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES, range.getTextAttributes());
        markupModel.setRangeHighlighterAttributes(range, getFollowedHyperlinkAttributes());
      }
    }
    //refresh highlighter text attributes
    markupModel.addRangeHighlighter(0, 0, HYPERLINK_LAYER, getHyperlinkAttributes(), HighlighterTargetArea.EXACT_RANGE).dispose();
  }


  public static String getLineText(Document document, int lineNumber, boolean includeEol) {
    int endOffset = document.getLineEndOffset(lineNumber);
    if (includeEol && endOffset < document.getTextLength()) {
      endOffset++;
    }
    return document.getCharsSequence().subSequence(document.getLineStartOffset(lineNumber), endOffset).toString();
  }

  private static class HyperlinkInfoTextAttributes extends TextAttributes {
    private HyperlinkInfo myHyperlinkInfo;

    public HyperlinkInfoTextAttributes(@NotNull HyperlinkInfo hyperlinkInfo) {
      myHyperlinkInfo = hyperlinkInfo;
    }

    @NotNull
    public HyperlinkInfo getHyperlinkInfo() {
      return myHyperlinkInfo;
    }
  }
}