summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/openapi/editor/impl/SelectionModelImpl.java
blob: 574780a661c28c327f02dfb607144715be926b24 (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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
 * Copyright 2000-2014 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.
 */

/*
 * Created by IntelliJ IDEA.
 * User: max
 * Date: Apr 19, 2002
 * Time: 1:51:41 PM
 * To change template for new class use
 * Code Style | Class Templates options (Tools | IDE Options).
 */
package com.intellij.openapi.editor.impl;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.SelectionEvent;
import com.intellij.openapi.editor.event.SelectionListener;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.PrioritizedDocumentListener;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.TIntArrayList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class SelectionModelImpl implements SelectionModel, PrioritizedDocumentListener {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.SelectionModelImpl");

  private final List<SelectionListener> mySelectionListeners = ContainerUtil.createLockFreeCopyOnWriteList();
  private final EditorImpl myEditor;

  private TextAttributes myTextAttributes;

  private LogicalPosition myBlockStart;
  private LogicalPosition myBlockEnd;
  private int[] myBlockSelectionStarts;
  private int[] myBlockSelectionEnds;

  private DocumentEvent myIsInUpdate;

  public SelectionModelImpl(EditorImpl editor) {
    myEditor = editor;
  }

  @Override
  public void beforeDocumentChange(DocumentEvent event) {
    myIsInUpdate = event;
    for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
      ((CaretImpl)caret).beforeDocumentChange();
    }
  }

  @Override
  public void documentChanged(DocumentEvent event) {
    if (myIsInUpdate == event) {
      myIsInUpdate = null;
      myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
        public void run() {
          for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
            ((CaretImpl)caret).documentChanged();
          }
        }
      });
    }
  }

  @Override
  public int getPriority() {
    return EditorDocumentPriorities.SELECTION_MODEL;
  }

  /**
   * @see CaretImpl#setUnknownDirection(boolean)
   */
  public boolean isUnknownDirection() {
    return myEditor.getCaretModel().getCurrentCaret().isUnknownDirection();
  }

  /**
   * @see CaretImpl#setUnknownDirection(boolean)
   */
  public void setUnknownDirection(boolean unknownDirection) {
    myEditor.getCaretModel().getCurrentCaret().setUnknownDirection(unknownDirection);
  }

  @Override
  public int getSelectionStart() {
    return myEditor.getCaretModel().getCurrentCaret().getSelectionStart();
  }

  @NotNull
  @Override
  public VisualPosition getSelectionStartPosition() {
    return myEditor.getCaretModel().getCurrentCaret().getSelectionStartPosition();
  }

  @Override
  public int getSelectionEnd() {
    return myEditor.getCaretModel().getCurrentCaret().getSelectionEnd();
  }

  @NotNull
  @Override
  public VisualPosition getSelectionEndPosition() {
    return myEditor.getCaretModel().getCurrentCaret().getSelectionEndPosition();
  }

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

  @Override
  public boolean hasSelection(boolean anyCaret) {
    if (!anyCaret) {
      return myEditor.getCaretModel().getCurrentCaret().hasSelection();
    }
    for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
      if (caret.hasSelection()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public void setSelection(int startOffset, int endOffset) {
    myEditor.getCaretModel().getCurrentCaret().setSelection(startOffset, endOffset);
  }

  @Override
  public void setSelection(int startOffset, @Nullable VisualPosition endPosition, int endOffset) {
    myEditor.getCaretModel().getCurrentCaret().setSelection(startOffset, endPosition, endOffset);
  }

  @Override
  public void setSelection(@Nullable VisualPosition startPosition, int startOffset, @Nullable VisualPosition endPosition, int endOffset) {
    myEditor.getCaretModel().getCurrentCaret().setSelection(startPosition, startOffset, endPosition, endOffset);
  }

  void fireSelectionChanged(int oldSelectionStart, int oldSelectionEnd, int startOffset, int endOffset) {
    repaintBySelectionChange(oldSelectionStart, startOffset, oldSelectionEnd, endOffset);

    SelectionEvent event = new SelectionEvent(myEditor,
                                              oldSelectionStart, oldSelectionEnd,
                                              startOffset, endOffset);

    broadcastSelectionEvent(event);
  }

  private void broadcastSelectionEvent(SelectionEvent event) {
    for (SelectionListener listener : mySelectionListeners) {
      try {
        listener.selectionChanged(event);
      }
      catch (Exception e) {
        LOG.error(e);
      }
    }
  }

  private void repaintBySelectionChange(int oldSelectionStart, int startOffset, int oldSelectionEnd, int endOffset) {
    myEditor.repaint(Math.min(oldSelectionStart, startOffset), Math.max(oldSelectionStart, startOffset));
    myEditor.repaint(Math.min(oldSelectionEnd, endOffset), Math.max(oldSelectionEnd, endOffset));
  }

  @Override
  public void removeSelection() {
    removeSelection(false);
  }

  @Override
  public void removeSelection(boolean allCarets) {
    if (!allCarets) {
      myEditor.getCaretModel().getCurrentCaret().removeSelection();
    }
    else {
      for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
        caret.removeSelection();
      }
    }
  }

  @Override
  public void setBlockSelection(@NotNull LogicalPosition blockStart, @NotNull LogicalPosition blockEnd) {
    if (myEditor.getCaretModel().supportsMultipleCarets()) {
      int startLine = Math.max(Math.min(blockStart.line, myEditor.getDocument().getLineCount() - 1), 0);
      int endLine = Math.max(Math.min(blockEnd.line, myEditor.getDocument().getLineCount() - 1), 0);
      int step = endLine < startLine ? -1 : 1;
      int count = 1 + Math.abs(endLine - startLine);
      List<CaretState> caretStates = new LinkedList<CaretState>();
      boolean hasSelection = false;
      for (int line = startLine, i = 0; i < count; i++, line += step) {
        int startColumn = blockStart.column;
        int endColumn = blockEnd.column;
        int lineEndOffset = myEditor.getDocument().getLineEndOffset(line);
        LogicalPosition lineEndPosition = myEditor.offsetToLogicalPosition(lineEndOffset);
        int lineWidth = lineEndPosition.column;
        if (startColumn > lineWidth && endColumn > lineWidth && !myEditor.isColumnMode()) {
          LogicalPosition caretPos = new LogicalPosition(line, Math.min(startColumn, endColumn));
          caretStates.add(new CaretState(caretPos,
                                         lineEndPosition,
                                         lineEndPosition));
        }
        else {
          LogicalPosition startPos = new LogicalPosition(line, myEditor.isColumnMode() ? startColumn : Math.min(startColumn, lineWidth));
          LogicalPosition endPos = new LogicalPosition(line, myEditor.isColumnMode() ? endColumn : Math.min(endColumn, lineWidth));
          int startOffset = myEditor.logicalPositionToOffset(startPos);
          int endOffset = myEditor.logicalPositionToOffset(endPos);
          caretStates.add(new CaretState(endPos, startPos, endPos));
          hasSelection |= startOffset != endOffset;
        }
      }
      if (hasSelection && !myEditor.isColumnMode()) { // filtering out lines without selection
        Iterator<CaretState> caretStateIterator = caretStates.iterator();
        while(caretStateIterator.hasNext()) {
          CaretState state = caretStateIterator.next();
          //noinspection ConstantConditions
          if (state.getSelectionStart().equals(state.getSelectionEnd())) {
            caretStateIterator.remove();
          }
        }
      }
      myEditor.getCaretModel().setCaretsAndSelections(caretStates);
    }
    else {
      removeSelection();

      int oldStartLine = 0;
      int oldEndLine = 0;

      if (hasBlockSelection()) {
        oldStartLine = myBlockStart.line;
        oldEndLine = myBlockEnd.line;
        if (oldStartLine > oldEndLine) {
          int t = oldStartLine;
          oldStartLine = oldEndLine;
          oldEndLine = t;
        }
      }

      int newStartLine = blockStart.line;
      int newEndLine = blockEnd.line;

      if (newStartLine > newEndLine) {
        int t = newStartLine;
        newStartLine = newEndLine;
        newEndLine = t;
      }

      myEditor.repaintLines(Math.min(oldStartLine, newStartLine), Math.max(newEndLine, oldEndLine));

      final int[] oldStarts = getBlockSelectionStarts();
      final int[] oldEnds = getBlockSelectionEnds();

      myBlockStart = blockStart;
      myBlockEnd = blockEnd;
      recalculateBlockOffsets();

      final int[] newStarts = getBlockSelectionStarts();
      final int[] newEnds = getBlockSelectionEnds();

      broadcastSelectionEvent(new SelectionEvent(myEditor, oldStarts, oldEnds, newStarts, newEnds));
    }
  }

  @Override
  public void removeBlockSelection() {
    if (!myEditor.getCaretModel().supportsMultipleCarets()) {
      myEditor.getCaretModel().getCurrentCaret().setUnknownDirection(false);
      if (hasBlockSelection()) {
        myEditor.repaint(0, myEditor.getDocument().getTextLength());

        final int[] oldStarts = getBlockSelectionStarts();
        final int[] oldEnds = getBlockSelectionEnds();

        myBlockStart = null;
        myBlockEnd = null;

        final int[] newStarts = getBlockSelectionStarts();
        final int[] newEnds = getBlockSelectionEnds();

        broadcastSelectionEvent(new SelectionEvent(myEditor, oldStarts, oldEnds, newStarts, newEnds));
      }
    }
  }

  @Override
  public boolean hasBlockSelection() {
    return myBlockStart != null;
  }

  @Override
  public LogicalPosition getBlockStart() {
    return myBlockStart;
  }

  @Override
  public LogicalPosition getBlockEnd() {
    return myBlockEnd;
  }

  @Override
  public boolean isBlockSelectionGuarded() {
    if (!hasBlockSelection()) return false;
    int[] starts = getBlockSelectionStarts();
    int[] ends = getBlockSelectionEnds();
    Document doc = myEditor.getDocument();
    for (int i = 0; i < starts.length; i++) {
      int start = starts[i];
      int end = ends[i];
      if (start == end && doc.getOffsetGuard(start) != null || start != end && doc.getRangeGuard(start, end) != null) {
        return true;
      }
    }
    return false;
  }

  @Override
  public RangeMarker getBlockSelectionGuard() {
    if (!hasBlockSelection()) return null;

    int[] starts = getBlockSelectionStarts();
    int[] ends = getBlockSelectionEnds();
    Document doc = myEditor.getDocument();
    for (int i = 0; i < starts.length; i++) {
      int start = starts[i];
      int end = ends[i];
      if (start == end) {
        RangeMarker guard = doc.getOffsetGuard(start);
        if (guard != null) return guard;
      }
      if (start != end) {
        RangeMarker guard = doc.getRangeGuard(start, end);
        if (guard != null) return guard;
      }
    }

    return null;
  }

  private void recalculateBlockOffsets() {
    TIntArrayList startOffsets = new TIntArrayList();
    TIntArrayList endOffsets = new TIntArrayList();
    final int startLine = Math.min(myBlockStart.line, myBlockEnd.line);
    final int endLine = Math.max(myBlockStart.line, myBlockEnd.line);
    final int startColumn = Math.min(myBlockStart.column, myBlockEnd.column);
    final int endColumn = Math.max(myBlockStart.column, myBlockEnd.column);
    FoldingModelImpl foldingModel = myEditor.getFoldingModel();
    DocumentEx document = myEditor.getDocument();
    boolean insideFoldRegion = false;
    for (int line = startLine; line <= endLine; line++) {
      int startOffset = myEditor.logicalPositionToOffset(new LogicalPosition(line, startColumn));
      FoldRegion startRegion = foldingModel.getCollapsedRegionAtOffset(startOffset);
      boolean startInsideFold = startRegion != null && startRegion.getStartOffset() < startOffset;

      int endOffset = myEditor.logicalPositionToOffset(new LogicalPosition(line, endColumn));
      FoldRegion endRegion = foldingModel.getCollapsedRegionAtOffset(endOffset);
      boolean endInsideFold = endRegion != null && endRegion.getStartOffset() < endOffset;

      if (!startInsideFold && !endInsideFold) {
        startOffsets.add(startOffset);
        endOffsets.add(endOffset);
      }
      else if (startInsideFold && endInsideFold) {
        if (insideFoldRegion) {
          startOffsets.add(Math.max(document.getLineStartOffset(line), startRegion.getStartOffset()));
          endOffsets.add(Math.min(document.getLineEndOffset(line), endRegion.getEndOffset()));
        }
      }
      else if (startInsideFold && !endInsideFold) {
        if (startRegion.getEndOffset() < endOffset) {
          startOffsets.add(Math.max(document.getLineStartOffset(line), startRegion.getStartOffset()));
          endOffsets.add(endOffset);
        }
        insideFoldRegion = false;
      }
      else {
        startOffsets.add(startOffset);
        endOffsets.add(Math.min(document.getLineEndOffset(line), endRegion.getEndOffset()));
        insideFoldRegion = true;
      }
    }

    myBlockSelectionStarts = startOffsets.toNativeArray();
    myBlockSelectionEnds = endOffsets.toNativeArray();
  }

  @Override
  @NotNull
  public int[] getBlockSelectionStarts() {
    if (myEditor.getCaretModel().supportsMultipleCarets()) {
      Collection<Caret> carets = myEditor.getCaretModel().getAllCarets();
      int[] result = new int[carets.size()];
      int i = 0;
      for (Caret caret : carets) {
        result[i++] = caret.getSelectionStart();
      }
      return result;
    } else {
      if (hasSelection()) {
        return new int[]{getSelectionStart()};
      }
      else if (!hasBlockSelection() || myBlockSelectionStarts == null) {
        return ArrayUtil.EMPTY_INT_ARRAY;
      }
      else {
        return myBlockSelectionStarts;
      }
    }
  }

  @Override
  @NotNull
  public int[] getBlockSelectionEnds() {
    if (myEditor.getCaretModel().supportsMultipleCarets()) {
      Collection<Caret> carets = myEditor.getCaretModel().getAllCarets();
      int[] result = new int[carets.size()];
      int i = 0;
      for (Caret caret : carets) {
        result[i++] = caret.getSelectionEnd();
      }
      return result;
    } else {
      if (hasSelection()) {
        return new int[]{getSelectionEnd()};
      }
      else if (!hasBlockSelection() || myBlockSelectionEnds == null) {
        return ArrayUtil.EMPTY_INT_ARRAY;
      }
      else {
        return myBlockSelectionEnds;
      }
    }
  }

  @Override
  public void addSelectionListener(SelectionListener listener) {
    mySelectionListeners.add(listener);
  }

  public void addSelectionListener(final SelectionListener listener, Disposable parent) {
    mySelectionListeners.add(listener);
    Disposer.register(parent, new Disposable() {
      @Override
      public void dispose() {
        mySelectionListeners.remove(listener);
      }
    });
  }

  @Override
  public void removeSelectionListener(SelectionListener listener) {
    boolean success = mySelectionListeners.remove(listener);
    LOG.assertTrue(success);
  }

  @Override
  public String getSelectedText() {
    return getSelectedText(false);
  }

  @Override
  public String getSelectedText(boolean allCarets) {
    validateContext(false);

    if (hasBlockSelection()) {
      CharSequence text = myEditor.getDocument().getCharsSequence();
      int[] starts = getBlockSelectionStarts();
      int[] ends = getBlockSelectionEnds();
      int width = myEditor.getCaretModel().supportsMultipleCarets() ? 0 : Math.abs(myBlockEnd.column - myBlockStart.column);
      final StringBuilder buf = new StringBuilder();
      for (int i = 0; i < starts.length; i++) {
        if (i > 0) buf.append('\n');
        final int len = ends[i] - starts[i];
        appendCharSequence(buf, text, starts[i], len);
        for (int j = len; j < width; j++) buf.append(' ');
      }
      return buf.toString();
    }
    else if (myEditor.getCaretModel().supportsMultipleCarets() && allCarets) {
      final StringBuilder buf = new StringBuilder();
      String separator = "";
      for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
        buf.append(separator);
        String caretSelectedText = caret.getSelectedText();
        if (caretSelectedText != null) {
          buf.append(caretSelectedText);
        }
        separator = "\n";
      }
      return buf.toString();
    }
    else {
      return myEditor.getCaretModel().getCurrentCaret().getSelectedText();
    }
  }

  private static void appendCharSequence(@NotNull StringBuilder buf, @NotNull CharSequence s, int srcOffset, int len) {
    if (srcOffset < 0 || len < 0 || srcOffset > s.length() - len) {
      throw new IndexOutOfBoundsException("srcOffset " + srcOffset + ", len " + len + ", s.length() " + s.length());
    }
    if (len == 0) {
      return;
    }
    final int limit = srcOffset + len;
    for (int i = srcOffset; i < limit; i++) {
      buf.append(s.charAt(i));
    }
  }

  public static void doSelectLineAtCaret(Editor editor) {
    int lineNumber = editor.getCaretModel().getLogicalPosition().line;
    Document document = editor.getDocument();
    if (lineNumber >= document.getLineCount()) {
      return;
    }

    Pair<LogicalPosition, LogicalPosition> lines = EditorUtil.calcCaretLineRange(editor);
    LogicalPosition lineStart = lines.first;
    LogicalPosition nextLineStart = lines.second;

    int start = editor.logicalPositionToOffset(lineStart);
    int end = editor.logicalPositionToOffset(nextLineStart);

    //myEditor.getCaretModel().moveToOffset(start);
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    editor.getSelectionModel().removeSelection();
    editor.getSelectionModel().setSelection(start, end);
  }

  @Override
  public int getLeadSelectionOffset() {
    return myEditor.getCaretModel().getCurrentCaret().getLeadSelectionOffset();
  }

  @NotNull
  @Override
  public VisualPosition getLeadSelectionPosition() {
    return myEditor.getCaretModel().getCurrentCaret().getLeadSelectionPosition();
  }

  @Override
  public void selectLineAtCaret() {
    myEditor.getCaretModel().getCurrentCaret().selectLineAtCaret();
  }

  @Override
  public void selectWordAtCaret(boolean honorCamelWordsSettings) {
    myEditor.getCaretModel().getCurrentCaret().selectWordAtCaret(honorCamelWordsSettings);
  }

  @Override
  public void copySelectionToClipboard() {
    EditorCopyPasteHelper.getInstance().copySelectionToClipboard(myEditor);
  }

  @Override
  public TextAttributes getTextAttributes() {
    if (myTextAttributes == null) {
      TextAttributes textAttributes = new TextAttributes();
      EditorColorsScheme scheme = myEditor.getColorsScheme();
      textAttributes.setForegroundColor(scheme.getColor(EditorColors.SELECTION_FOREGROUND_COLOR));
      textAttributes.setBackgroundColor(scheme.getColor(EditorColors.SELECTION_BACKGROUND_COLOR));
      myTextAttributes = textAttributes;
    }

    return myTextAttributes;
  }

  public void reinitSettings() {
    myTextAttributes = null;
  }

  private void validateContext(boolean isWrite) {
    if (!myEditor.getComponent().isShowing()) return;
    if (isWrite) {
      ApplicationManager.getApplication().assertIsDispatchThread();
    }
    else {
      ApplicationManager.getApplication().assertReadAccessAllowed();
    }
  }
}