summaryrefslogtreecommitdiff
path: root/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy
blob: b462263eeba3d50820053ca150300f8bf129b61b (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
/*
 * 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.
 */
package com.intellij.codeInsight.folding;


import com.intellij.codeInsight.folding.impl.CodeFoldingManagerImpl
import com.intellij.codeInsight.folding.impl.JavaCodeFoldingSettingsImpl
import com.intellij.find.FindManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.editor.FoldRegion
import com.intellij.openapi.editor.ex.FoldingModelEx
import com.intellij.openapi.editor.impl.FoldingModelImpl
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase

/**
 * @author Denis Zhdanov
 * @since 1/17/11 1:00 PM
 */
public class JavaFoldingTest extends LightCodeInsightFixtureTestCase {

  def JavaCodeFoldingSettingsImpl myFoldingSettings
  def JavaCodeFoldingSettingsImpl myFoldingStateToRestore

  @Override
  public void setUp() {
    super.setUp()
    myFoldingSettings = JavaCodeFoldingSettings.instance as JavaCodeFoldingSettingsImpl
    myFoldingStateToRestore = new JavaCodeFoldingSettingsImpl()
    myFoldingStateToRestore.loadState(myFoldingSettings)
  }

  @Override
  protected void tearDown() {
    myFoldingSettings.loadState(myFoldingStateToRestore)
    super.tearDown()
  }

  public void testEndOfLineComments() {
    myFixture.testFolding("$PathManagerEx.testDataPath/codeInsight/folding/${getTestName(false)}.java");
  }

  public void testEditingImports() {
    configure """\
import java.util.List;
import java.util.Map;
<caret>

class Foo { List a; Map b; }
"""

    assert myFixture.editor.foldingModel.getCollapsedRegionAtOffset(10)

    myFixture.type 'import '
    myFixture.doHighlighting()
    assert !myFixture.editor.foldingModel.getCollapsedRegionAtOffset(10)
  }

  public void testJavadocLikeClassHeader() {
    def text = """\
/**
 * This is a header to collapse
 */
import java.util.*;
class Foo { List a; Map b; }
"""
    configure text
    def foldRegion = myFixture.editor.foldingModel.getCollapsedRegionAtOffset(0)
    assert foldRegion
    assertEquals 0, foldRegion.startOffset
    assertEquals text.indexOf("import") - 1, foldRegion.endOffset
  }

  public void testSubsequentCollapseBlock() {
    def text = """\
class Test {
    void test(int i) {
        if (i > 1) {
            <caret>i++;
        }
    }
}
"""
    configure text
    myFixture.performEditorAction 'CollapseBlock'
    myFixture.performEditorAction 'CollapseBlock'
    assertEquals(text.indexOf('}', text.indexOf('i++')), myFixture.editor.caretModel.offset)
  }

  public void testFoldGroup() {
    // Implied by IDEA-79420
    myFoldingSettings.COLLAPSE_CLOSURES = true
    def text = """\
class Test {
    void test() {
        new Runnable() {
            public void run() {
                int i = 1;
            }
        }.run();
    }
}
"""

    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl
    def closureStartFold = foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable"))
    assertNotNull closureStartFold
    assertFalse closureStartFold.expanded

    assertNotNull closureStartFold.group
    def closureFolds = foldingModel.getGroupedRegions(closureStartFold.group)
    assertNotNull closureFolds
    assertEquals(2, closureFolds.size())

    def closureEndFold = closureFolds.get(1)
    assertFalse closureEndFold.expanded

    myFixture.editor.caretModel.moveToOffset(closureEndFold.startOffset + 1)
    assertTrue closureStartFold.expanded
    assertTrue closureEndFold.expanded

    changeFoldRegions { closureStartFold.expanded = false }
    assertTrue closureStartFold.expanded
    assertTrue closureEndFold.expanded
  }

  public void "test closure folding when an abstract method is not in the direct superclass"() {
    myFoldingSettings.COLLAPSE_CLOSURES = true
    def text = """\
public abstract class AroundTemplateMethod<T> {
  public abstract T execute();
}
private static abstract class SetupTimer<T> extends AroundTemplateMethod<T> {
}
class Test {
    void test() {
     new SetupTimer<Integer>() {
      public Integer execute() {
        return 0;
      }
    };
  }
}
"""

    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl
    def closureStartFold = foldingModel.getCollapsedRegionAtOffset(text.indexOf("<Integer>"))
    assertNotNull closureStartFold
    assertFalse closureStartFold.expanded

    assertNotNull closureStartFold.group
    def closureFolds = foldingModel.getGroupedRegions(closureStartFold.group)
    assertNotNull closureFolds
    assertEquals(2, closureFolds.size())
  }

  public void "test builder style setter"() {
    myFoldingSettings.COLLAPSE_ACCESSORS = true
    def text = """\
class Foo {
    private String bar;

    public Foo setBar(String bar) {
        this.bar = bar;
        return this;
    }
}
"""

    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl
    int indexOfBar = text.indexOf("this.bar")
    def accessorStartFold = foldingModel.getCollapsedRegionAtOffset(indexOfBar)
    assertNotNull accessorStartFold
    assertFalse accessorStartFold.expanded
  }

  public void "test closure folding doesn't expand when editing inside"() {
    def text = """\
class Test {
    void test() {
     new Runnable() {
      static final long serialVersionUID = 42L;
      public void run() {
        System.out.println(<caret>);
      }
    };
  }
}
"""

    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl
    def closureStartFold = foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable"))
    assertNotNull closureStartFold
    assertFalse closureStartFold.expanded
    assert text.substring(closureStartFold.endOffset).startsWith('System') //one line closure

    myFixture.type('2')
    myFixture.doHighlighting()
    closureStartFold = foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable"))
    assert closureStartFold
  }

  public void "test closure folding placeholder texts"() {
    myFixture.addClass('interface Runnable2 { void run(); }')
    myFixture.addClass('interface Runnable3 { void run(); }')
    myFixture.addClass('interface Runnable4 { void run(); }')
    myFixture.addClass('abstract class MyAction { public abstract void run(); public void registerVeryCustomShortcutSet() {} }')
    myFixture.addClass('abstract class MyAction2 { public abstract void run(); public void registerVeryCustomShortcutSet() {} }')
    def text = """\
class Test {
  MyAction2 action2;

  void test() {
    Runnable r = new Runnable() {
      public void run() {
        System.out.println();
      }
    };
    new Runnable2() {
      public void run() {
        System.out.println();
      }
    }.run();
    foo(new Runnable3() {
      public void run() {
        System.out.println();
      }
    });
    bar(new Runnable4() {
      public void run() {
        System.out.println();
      }
    });
    new MyAction() {
      public void run() {
        System.out.println();
      }
    }.registerVeryCustomShortcutSet();
    action2 = new MyAction2() {
      public void run() {
        System.out.println();
      }
    }
  }

  void foo(Object o) {}
  void bar(Runnable4 o) {}
}
"""
    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl

    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable(")).placeholderText == '() -> { '
    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable2(")).placeholderText == '(Runnable2) () -> { '
    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable3(")).placeholderText == '(Runnable3) () -> { '
    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable4(")).placeholderText == '() -> { '
    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("MyAction(")).placeholderText == '(MyAction) () -> { '
    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("MyAction2(")).placeholderText == '(MyAction2) () -> { '
  }

  public void "test closure folding after paste"() {
    def text = """\
class Test {
<caret>// comment
  void test() {
    Runnable r = new Runnable() {
      public void run() {
        System.out.println();
      }
    };
  }
}
"""
    configure text
    myFixture.performEditorAction("EditorCut")
    myFixture.performEditorAction("EditorPaste")

    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl

    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable(")).placeholderText == '() -> { '
  }

  public void "test closure folding when overriding one method of many"() {
    myFixture.addClass('abstract class Runnable { void run() {}; void run2() {} }')
    myFixture.addClass('abstract class Runnable2 { void run() {}; void run2() {} }')
    def text = """\
class Test {
  void test() {
    Runnable r = new Runnable() {
      public void run() {
        System.out.println();
      }
    };
    foo(new Runnable2() {
      public void run2() {
        System.out.println();
      }
    });
  }

  void foo(Object o) {}
}
"""
    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl

    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable("))?.placeholderText == 'run() -> { '
    assert foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable2("))?.placeholderText == '(Runnable2) run2() -> { '
  }

  public void "test no closure folding when the method throws an unresolved exception"() {
    def text = """\
class Test {
    void test() { new Runnable() {
      public void run() throws Asadfsdafdfasd {
        System.out.println(<caret>);
      }
    };
  }
}
"""

    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl
    assert !foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable"))
  }

  public void "test no closure folding for synchronized methods"() {
    def text = """\
class Test {
    void test() { new Runnable() {
      public synchronized void run() {
        System.out.println(<caret>);
      }
    };
  }
}
"""
    configure text
    def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl
    assert !foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable"))
  }

  public void testFindInFolding() {
    def text = """\
class Test {
    void test1() {
    }
    void test2() {
        <caret>test1();
    }
}
"""
    configure text
    myFixture.performEditorAction 'CollapseBlock'
    myFixture.editor.caretModel.moveToOffset(text.indexOf('test1'))
    myFixture.performEditorAction 'HighlightUsagesInFile'
    FindManager.getInstance(project).findNextUsageInEditor(TextEditorProvider.getInstance().getTextEditor(myFixture.editor))
    assertEquals('test1', myFixture.editor.selectionModel.selectedText)
  }

  public void testCustomFolding() {
    myFixture.testFolding("$PathManagerEx.testDataPath/codeInsight/folding/${getTestName(false)}.java");
  }

  public void "test move methods"() {
    def initialText = '''\
class Test {
    void test1() {
    }

    void test2() {
    }
}
'''

    Closure<FoldRegion> fold = { String methodName ->
      def text = myFixture.editor.document.text
      def nameIndex = text.indexOf(methodName)
      def start = text.indexOf('{', nameIndex)
      def end = text.indexOf('}', start) + 1
      def regions = myFixture.editor.foldingModel.allFoldRegions
      for (region in regions) {
        if (region.startOffset == start && region.endOffset == end) {
          return region
        }
      }
      fail("Can't find target fold region for method with name '$methodName'. Registered regions: $regions")
      null
    }

    configure initialText
    def foldingModel = myFixture.editor.foldingModel as FoldingModelEx
    foldingModel.runBatchFoldingOperation {
      fold('test1').expanded = true
      fold('test2').expanded = false
    }

    myFixture.editor.caretModel.moveToOffset(initialText.indexOf('void'))
    myFixture.performEditorAction 'MoveStatementDown'
    CodeFoldingManager.getInstance(project).updateFoldRegions(myFixture.editor)
    assertTrue(fold('test1').expanded)
    assertFalse(fold('test2').expanded)

    myFixture.performEditorAction 'MoveStatementUp'
    CodeFoldingManager.getInstance(project).updateFoldRegions(myFixture.editor)
    assertTrue(fold('test1').expanded)
    assertFalse(fold('test2').expanded)
  }

  public void testUnorderedFoldRegionsRegistration() {
    def text = '01234567'
    configure text
    def foldModel = myFixture.editor.foldingModel as FoldingModelImpl
    foldModel.runBatchFoldingOperation {
      def innerFold = foldModel.addFoldRegion(3, 5, '...')
      def outerFold = foldModel.addFoldRegion(2, 6, '...')
      innerFold.expanded = false
      outerFold.expanded = false
    }
    def folds = foldModel.fetchVisible()
    assertEquals(1, folds.length)
    assertEquals(2, folds[0].startOffset)
    assertEquals(6, folds[0].endOffset)
  }

  private def configure(String text) {
    myFixture.configureByText("a.java", text)
    CodeFoldingManagerImpl.getInstance(getProject()).buildInitialFoldings(myFixture.editor);
    def foldingModel = myFixture.editor.foldingModel as FoldingModelEx
    foldingModel.rebuild()
    myFixture.doHighlighting()
  }

  public void "test simple property accessors in one line"() {
    configure """class Foo {
 int field;
 int field2;
 int field3;

 int getField()
 {
   return field;
 }

 void setField(int f) {
   field = f;
 }

 void setField2(int f){field2=f;} // normal method folding here

  // normal method folding here
 void setField3(int f){

   field2=f;
 }

}"""
    PsiClass fooClass = JavaPsiFacade.getInstance(project).findClass('Foo', GlobalSearchScope.allScope(project))
    def regions = myFixture.editor.foldingModel.allFoldRegions.sort { it.startOffset }
    assert regions.size() == 6

    checkAccessorFolding(regions[0], regions[1], fooClass.methods[0])
    checkAccessorFolding(regions[2], regions[3], fooClass.methods[1])

    assert regions[4].placeholderText == '{...}'
    assert regions[5].placeholderText == '{...}'
  }

  static checkAccessorFolding(FoldRegion region1, FoldRegion region2, PsiMethod method) {
    assert region1.startOffset == method.parameterList.textRange.endOffset
    assert region1.endOffset == method.body.statements[0].textRange.startOffset
    assert region1.placeholderText == ' { '

    assert region2.startOffset == method.body.statements[0].textRange.endOffset
    assert region2.endOffset == method.textRange.endOffset
    assert region2.placeholderText == ' }'
    assert region1.group == region2.group
  }

  public void "test fold one-line methods"() {
    configure """class Foo {
 int someMethod() {
   return 0;
 }

}"""
    PsiClass fooClass = JavaPsiFacade.getInstance(project).findClass('Foo', GlobalSearchScope.allScope(project))
    def regions = myFixture.editor.foldingModel.allFoldRegions.sort { it.startOffset }
    assert regions.size() == 2
    checkAccessorFolding(regions[0], regions[1], fooClass.methods[0])
  }

  public void "test don't inline very long one-line methods"() {
    configure """class Foo {
 int someVeryVeryLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongVariable;

 // don't create folding that would exceed the right margin
 int getSomeVeryVeryLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongVariable() {
   return someVeryVeryLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongVariable;
 }
}"""
    def regions = myFixture.editor.foldingModel.allFoldRegions.sort { it.startOffset }
    assert regions.size() == 1
    assert regions[0].placeholderText == '{...}'
  }

  private def changeFoldRegions(Closure op) {
    myFixture.editor.foldingModel.runBatchFoldingOperationDoNotCollapseCaret(op)
  }

  public void "test unselect word should go inside folding group"() {
    configure """class Foo {
 int field;

 <selection>int getField() {
   <caret>return field;
 }</selection>

}"""
    assertSize 2, myFixture.editor.foldingModel.allFoldRegions
    myFixture.performEditorAction(IdeActions.ACTION_EDITOR_UNSELECT_WORD_AT_CARET)
    assert 'return field;' == myFixture.editor.selectionModel.selectedText
  }
}