2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com
.intellij
.testFramework
.fixtures
.impl
;
19 import com
.intellij
.analysis
.AnalysisScope
;
20 import com
.intellij
.codeHighlighting
.HighlightDisplayLevel
;
21 import com
.intellij
.codeHighlighting
.TextEditorHighlightingPass
;
22 import com
.intellij
.codeInsight
.CodeInsightActionHandler
;
23 import com
.intellij
.codeInsight
.TargetElementUtilBase
;
24 import com
.intellij
.codeInsight
.completion
.CodeCompletionHandlerBase
;
25 import com
.intellij
.codeInsight
.completion
.CompletionContext
;
26 import com
.intellij
.codeInsight
.completion
.CompletionProgressIndicator
;
27 import com
.intellij
.codeInsight
.completion
.CompletionType
;
28 import com
.intellij
.codeInsight
.daemon
.DaemonCodeAnalyzer
;
29 import com
.intellij
.codeInsight
.daemon
.DaemonCodeAnalyzerSettings
;
30 import com
.intellij
.codeInsight
.daemon
.HighlightDisplayKey
;
31 import com
.intellij
.codeInsight
.daemon
.impl
.*;
32 import com
.intellij
.codeInsight
.intention
.IntentionAction
;
33 import com
.intellij
.codeInsight
.intention
.impl
.ShowIntentionActionsHandler
;
34 import com
.intellij
.codeInsight
.lookup
.LookupElement
;
35 import com
.intellij
.codeInsight
.lookup
.LookupManager
;
36 import com
.intellij
.codeInsight
.lookup
.impl
.LookupImpl
;
37 import com
.intellij
.codeInspection
.*;
38 import com
.intellij
.codeInspection
.ex
.*;
39 import com
.intellij
.facet
.Facet
;
40 import com
.intellij
.facet
.FacetManager
;
41 import com
.intellij
.find
.FindManager
;
42 import com
.intellij
.find
.findUsages
.FindUsagesHandler
;
43 import com
.intellij
.find
.findUsages
.FindUsagesOptions
;
44 import com
.intellij
.find
.impl
.FindManagerImpl
;
45 import com
.intellij
.ide
.DataManager
;
46 import com
.intellij
.lang
.annotation
.HighlightSeverity
;
47 import com
.intellij
.openapi
.Disposable
;
48 import com
.intellij
.openapi
.actionSystem
.DataContext
;
49 import com
.intellij
.openapi
.actionSystem
.IdeActions
;
50 import com
.intellij
.openapi
.application
.ApplicationManager
;
51 import com
.intellij
.openapi
.application
.ModalityState
;
52 import com
.intellij
.openapi
.application
.Result
;
53 import com
.intellij
.openapi
.command
.WriteCommandAction
;
54 import com
.intellij
.openapi
.editor
.Document
;
55 import com
.intellij
.openapi
.editor
.Editor
;
56 import com
.intellij
.openapi
.editor
.EditorFactory
;
57 import com
.intellij
.openapi
.editor
.RangeMarker
;
58 import com
.intellij
.openapi
.editor
.actionSystem
.EditorActionManager
;
59 import com
.intellij
.openapi
.editor
.ex
.DocumentEx
;
60 import com
.intellij
.openapi
.editor
.ex
.util
.EditorUtil
;
61 import com
.intellij
.openapi
.editor
.markup
.GutterIconRenderer
;
62 import com
.intellij
.openapi
.editor
.markup
.RangeHighlighter
;
63 import com
.intellij
.openapi
.extensions
.ExtensionPoint
;
64 import com
.intellij
.openapi
.extensions
.ExtensionPointName
;
65 import com
.intellij
.openapi
.extensions
.ExtensionsArea
;
66 import com
.intellij
.openapi
.fileEditor
.FileEditorManager
;
67 import com
.intellij
.openapi
.fileEditor
.OpenFileDescriptor
;
68 import com
.intellij
.openapi
.fileTypes
.FileType
;
69 import com
.intellij
.openapi
.fileTypes
.FileTypeManager
;
70 import com
.intellij
.openapi
.module
.Module
;
71 import com
.intellij
.openapi
.progress
.ProgressIndicator
;
72 import com
.intellij
.openapi
.progress
.ProgressManager
;
73 import com
.intellij
.openapi
.project
.DumbServiceImpl
;
74 import com
.intellij
.openapi
.project
.Project
;
75 import com
.intellij
.openapi
.util
.*;
76 import com
.intellij
.openapi
.util
.io
.FileUtil
;
77 import com
.intellij
.openapi
.util
.text
.StringUtil
;
78 import com
.intellij
.openapi
.vfs
.LocalFileSystem
;
79 import com
.intellij
.openapi
.vfs
.VfsUtil
;
80 import com
.intellij
.openapi
.vfs
.VirtualFile
;
81 import com
.intellij
.openapi
.vfs
.VirtualFileFilter
;
82 import com
.intellij
.profile
.codeInspection
.InspectionProfileManager
;
83 import com
.intellij
.profile
.codeInspection
.InspectionProjectProfileManager
;
84 import com
.intellij
.psi
.*;
85 import com
.intellij
.psi
.impl
.PsiManagerImpl
;
86 import com
.intellij
.psi
.impl
.source
.PostprocessReformattingAspect
;
87 import com
.intellij
.psi
.impl
.source
.PsiFileImpl
;
88 import com
.intellij
.psi
.impl
.source
.resolve
.FileContextUtil
;
89 import com
.intellij
.psi
.impl
.source
.tree
.injected
.InjectedLanguageUtil
;
90 import com
.intellij
.psi
.search
.GlobalSearchScope
;
91 import com
.intellij
.psi
.search
.UsageSearchContext
;
92 import com
.intellij
.psi
.stubs
.StubUpdatingIndex
;
93 import com
.intellij
.psi
.util
.PsiUtilBase
;
94 import com
.intellij
.refactoring
.move
.moveFilesOrDirectories
.MoveFilesOrDirectoriesProcessor
;
95 import com
.intellij
.refactoring
.rename
.RenameProcessor
;
96 import com
.intellij
.refactoring
.rename
.RenamePsiElementProcessor
;
97 import com
.intellij
.testFramework
.*;
98 import com
.intellij
.testFramework
.fixtures
.*;
99 import com
.intellij
.usageView
.UsageInfo
;
100 import com
.intellij
.util
.ArrayUtil
;
101 import com
.intellij
.util
.CommonProcessors
;
102 import com
.intellij
.util
.Function
;
103 import com
.intellij
.util
.SmartList
;
104 import com
.intellij
.util
.containers
.ContainerUtil
;
105 import com
.intellij
.util
.indexing
.FileBasedIndex
;
106 import gnu
.trove
.THashMap
;
107 import junit
.framework
.Assert
;
108 import org
.jetbrains
.annotations
.NonNls
;
109 import org
.jetbrains
.annotations
.NotNull
;
110 import org
.jetbrains
.annotations
.Nullable
;
112 import javax
.swing
.*;
114 import java
.io
.IOException
;
115 import java
.io
.OutputStream
;
119 * @author Dmitry Avdeev
121 @SuppressWarnings({"TestMethodWithIncorrectSignature"})
122 public class CodeInsightTestFixtureImpl
extends BaseFixture
implements CodeInsightTestFixture
{
124 @NonNls private static final String PROFILE
= "Configurable";
126 private PsiManagerImpl myPsiManager
;
127 private PsiFile myFile
;
128 private Editor myEditor
;
129 private String myTestDataPath
;
130 private boolean myEmptyLookup
;
132 private InspectionProfileEntry
[] myInspections
;
133 private final Map
<String
, InspectionProfileEntry
> myAvailableTools
= new THashMap
<String
, InspectionProfileEntry
>();
134 private final Map
<String
, InspectionTool
> myAvailableLocalTools
= new THashMap
<String
, InspectionTool
>();
136 private final TempDirTestFixture myTempDirFixture
;
137 protected final IdeaProjectTestFixture myProjectFixture
;
138 @NonNls private static final String XXX
= "XXX";
139 private PsiElement myFileContext
;
140 private final FileTreeAccessFilter myJavaFilesFilter
= new FileTreeAccessFilter();
142 public CodeInsightTestFixtureImpl(IdeaProjectTestFixture projectFixture
, TempDirTestFixture tempDirTestFixture
) {
143 myProjectFixture
= projectFixture
;
144 myTempDirFixture
= tempDirTestFixture
;
147 public void setTestDataPath(String dataPath
) {
148 myTestDataPath
= dataPath
;
151 public String
getTempDirPath() {
152 return myTempDirFixture
.getTempDirPath();
155 public TempDirTestFixture
getTempDirFixture() {
156 return myTempDirFixture
;
159 public VirtualFile
copyFileToProject(@NonNls final String sourceFilePath
, @NonNls final String targetPath
) throws IOException
{
160 File fromFile
= new File(getTestDataPath() + "/" + sourceFilePath
);
161 if (!fromFile
.exists()) {
162 fromFile
= new File(sourceFilePath
);
165 if (myTempDirFixture
instanceof LightTempDirTestFixtureImpl
) {
166 VirtualFile fromVFile
= LocalFileSystem
.getInstance().refreshAndFindFileByIoFile(fromFile
);
167 if (fromVFile
== null) {
168 fromVFile
= myTempDirFixture
.getFile(sourceFilePath
);
170 assert fromVFile
!= null: "can't find testdata file " + sourceFilePath
;
171 return myTempDirFixture
.copyFile(fromVFile
, targetPath
);
173 final File destFile
= new File(getTempDirPath() + "/" + targetPath
);
174 if (!destFile
.exists()) {
176 if (fromFile
.isDirectory()) {
180 FileUtil
.copy(fromFile
, destFile
);
183 final VirtualFile file
= LocalFileSystem
.getInstance().refreshAndFindFileByIoFile(destFile
);
184 Assert
.assertNotNull(file
);
188 public VirtualFile
copyDirectoryToProject(@NonNls final String sourceFilePath
, @NonNls final String targetPath
) throws IOException
{
189 assert getTestDataPath() != null: "test data path not specified";
190 final File fromFile
= new File(getTestDataPath() + "/" + sourceFilePath
);
191 if (myTempDirFixture
instanceof LightTempDirTestFixtureImpl
) {
192 return myTempDirFixture
.copyAll(fromFile
.getPath(), targetPath
);
195 final File destFile
= new File(getTempDirPath() + "/" + targetPath
);
196 FileUtil
.copyDir(fromFile
, destFile
);
197 final VirtualFile file
= LocalFileSystem
.getInstance().refreshAndFindFileByIoFile(destFile
);
198 Assert
.assertNotNull(file
);
199 file
.refresh(false, true);
204 public VirtualFile
copyFileToProject(@NonNls final String sourceFilePath
) throws IOException
{
205 return copyFileToProject(sourceFilePath
, sourceFilePath
);
208 public void enableInspections(InspectionProfileEntry
... inspections
) {
209 myInspections
= inspections
;
210 if (isInitialized()) {
211 configureInspections(myInspections
);
215 private boolean isInitialized() {
216 return myPsiManager
!= null;
219 public void enableInspections(final Class
<?
extends LocalInspectionTool
>... inspections
) {
220 final ArrayList
<LocalInspectionTool
> tools
= new ArrayList
<LocalInspectionTool
>();
221 for (Class clazz
: inspections
) {
223 LocalInspectionTool inspection
= (LocalInspectionTool
)clazz
.getConstructor().newInstance();
224 tools
.add(inspection
);
226 catch (Exception e
) {
227 throw new RuntimeException("Cannot instantiate " + clazz
);
230 enableInspections(tools
.toArray(new LocalInspectionTool
[tools
.size()]));
233 public void disableInspections(InspectionProfileEntry
... inspections
) {
234 myAvailableTools
.clear();
235 myAvailableLocalTools
.clear();
236 final ArrayList
<InspectionProfileEntry
> tools
= new ArrayList
<InspectionProfileEntry
>(Arrays
.asList(myInspections
));
237 for (Iterator
<InspectionProfileEntry
> i
= tools
.iterator(); i
.hasNext();) {
238 final InspectionProfileEntry tool
= i
.next();
239 for (InspectionProfileEntry toRemove
: inspections
) {
240 if (tool
.getShortName().equals(toRemove
.getShortName())) {
246 myInspections
= tools
.toArray(new InspectionProfileEntry
[tools
.size()]);
247 configureInspections(myInspections
);
250 public void enableInspections(InspectionToolProvider
... providers
) {
251 final ArrayList
<LocalInspectionTool
> tools
= new ArrayList
<LocalInspectionTool
>();
252 for (InspectionToolProvider provider
: providers
) {
253 for (Class clazz
: provider
.getInspectionClasses()) {
255 LocalInspectionTool inspection
= (LocalInspectionTool
)clazz
.getConstructor().newInstance();
256 tools
.add(inspection
);
258 catch (Exception e
) {
259 throw new RuntimeException("Cannot instantiate " + clazz
);
263 myInspections
= tools
.toArray(new LocalInspectionTool
[tools
.size()]);
264 configureInspections(myInspections
);
267 public long testHighlighting(final boolean checkWarnings
,
268 final boolean checkInfos
,
269 final boolean checkWeakWarnings
,
270 final String
... filePaths
) throws Exception
{
271 final Ref
<Long
> duration
= new Ref
<Long
>();
272 new WriteCommandAction
.Simple(myProjectFixture
.getProject()) {
274 protected void run() throws Exception
{
275 if (filePaths
.length
> 0) {
276 configureByFilesInner(filePaths
);
278 collectAndCheckHighlightings(checkWarnings
, checkInfos
, checkWeakWarnings
, duration
);
280 }.execute().throwException();
281 return duration
.get().longValue();
284 public long testHighlightingAllFiles(final boolean checkWarnings
,
285 final boolean checkInfos
,
286 final boolean checkWeakWarnings
,
287 @NonNls final String
... filePaths
) throws Exception
{
288 final ArrayList
<VirtualFile
> files
= new ArrayList
<VirtualFile
>();
289 for (String path
: filePaths
) {
290 files
.add(copyFileToProject(path
));
292 return testHighlightingAllFiles(checkWarnings
, checkInfos
, checkWeakWarnings
, VfsUtil
.toVirtualFileArray(files
));
295 public long testHighlightingAllFiles(final boolean checkWarnings
,
296 final boolean checkInfos
,
297 final boolean checkWeakWarnings
,
298 @NonNls final VirtualFile
... files
) throws Exception
{
299 final Ref
<Long
> duration
= new Ref
<Long
>();
300 new WriteCommandAction
.Simple(myProjectFixture
.getProject()) {
302 protected void run() throws Exception
{
303 collectAndCheckHighlightings(checkWarnings
, checkInfos
, checkWeakWarnings
, duration
, files
);
305 }.execute().throwException();
306 return duration
.get().longValue();
309 private void collectAndCheckHighlightings(final boolean checkWarnings
, final boolean checkInfos
, final boolean checkWeakWarnings
, final Ref
<Long
> duration
,
310 final VirtualFile
[] files
) {
311 final List
<Trinity
<PsiFile
, Editor
, ExpectedHighlightingData
>> datas
= ContainerUtil
.map2List(files
, new Function
<VirtualFile
, Trinity
<PsiFile
, Editor
, ExpectedHighlightingData
>>() {
312 public Trinity
<PsiFile
, Editor
, ExpectedHighlightingData
> fun(final VirtualFile file
) {
313 final PsiFile psiFile
= myPsiManager
.findFile(file
);
314 assertNotNull(psiFile
);
315 final Document document
= PsiDocumentManager
.getInstance(getProject()).getDocument(psiFile
);
316 assertNotNull(document
);
317 return Trinity
.create(psiFile
, createEditor(file
), new ExpectedHighlightingData(document
, checkWarnings
, checkWeakWarnings
, checkInfos
, psiFile
));
320 for (Trinity
<PsiFile
, Editor
, ExpectedHighlightingData
> trinity
: datas
) {
321 myEditor
= trinity
.second
;
322 myFile
= trinity
.first
;
323 collectAndCheckHighlightings(trinity
.third
, duration
);
327 public long checkHighlighting(final boolean checkWarnings
, final boolean checkInfos
, final boolean checkWeakWarnings
) throws Exception
{
328 final Ref
<Long
> duration
= new Ref
<Long
>();
329 new WriteCommandAction
.Simple(myProjectFixture
.getProject()) {
330 protected void run() throws Exception
{
331 collectAndCheckHighlightings(checkWarnings
, checkInfos
, checkWeakWarnings
, duration
);
333 }.execute().throwException();
334 return duration
.get().longValue();
337 public long checkHighlighting() throws Exception
{
338 return checkHighlighting(true, true, true);
341 public long testHighlighting(final String
... filePaths
) throws Exception
{
342 return testHighlighting(true, true, true, filePaths
);
345 public long testHighlighting(final boolean checkWarnings
, final boolean checkInfos
, final boolean checkWeakWarnings
, final VirtualFile file
) throws Exception
{
346 final Ref
<Long
> duration
= new Ref
<Long
>();
347 new WriteCommandAction
.Simple(myProjectFixture
.getProject()) {
348 protected void run() throws Exception
{
349 openFileInEditor(file
);
350 collectAndCheckHighlightings(checkWarnings
, checkInfos
, checkWeakWarnings
, duration
);
352 }.execute().throwException();
353 return duration
.get().longValue();
356 public void openFileInEditor(@NotNull final VirtualFile file
) {
357 myFile
= myPsiManager
.findFile(file
);
358 myEditor
= createEditor(file
);
361 public void testInspection(String testDir
, InspectionTool tool
) throws Exception
{
362 VirtualFile sourceDir
= copyDirectoryToProject(new File(testDir
, "src").getPath(), "src");
363 AnalysisScope scope
= new AnalysisScope(getPsiManager().findDirectory(sourceDir
));
365 InspectionManagerEx inspectionManager
= (InspectionManagerEx
) InspectionManager
.getInstance(getProject());
366 final GlobalInspectionContextImpl globalContext
= inspectionManager
.createNewGlobalContext(!(myProjectFixture
instanceof LightIdeaTestFixture
));
367 globalContext
.setCurrentScope(scope
);
370 InspectionTestUtil
.runTool(tool
, scope
, globalContext
, inspectionManager
);
371 InspectionTestUtil
.compareToolResults(tool
, false, new File(getTestDataPath(), testDir
).getPath());
375 public PsiReference
getReferenceAtCaretPosition(final String
... filePaths
) throws Exception
{
376 new WriteCommandAction
<PsiReference
>(myProjectFixture
.getProject()) {
377 protected void run(final Result
<PsiReference
> result
) throws Exception
{
378 configureByFilesInner(filePaths
);
380 }.execute().throwException();
381 return getFile().findReferenceAt(myEditor
.getCaretModel().getOffset());
385 public PsiReference
getReferenceAtCaretPositionWithAssertion(final String
... filePaths
) throws Exception
{
386 final PsiReference reference
= getReferenceAtCaretPosition(filePaths
);
387 assert reference
!= null: "no reference found at " + myEditor
.getCaretModel().getLogicalPosition();
392 public List
<IntentionAction
> getAvailableIntentions(final String
... filePaths
) throws Exception
{
394 final Project project
= myProjectFixture
.getProject();
395 return new WriteCommandAction
<List
<IntentionAction
>>(project
) {
396 protected void run(final Result
<List
<IntentionAction
>> result
) throws Exception
{
397 configureByFilesInner(filePaths
);
398 result
.setResult(getAvailableIntentions());
400 }.execute().getResultObject();
404 public List
<IntentionAction
> getAvailableIntentions() {
406 return getAvailableIntentions(myEditor
, myFile
);
409 public List
<IntentionAction
> filterAvailableIntentions(@NotNull final String hint
) throws Exception
{
410 return ContainerUtil
.findAll(getAvailableIntentions(),new Condition
<IntentionAction
>() {
411 public boolean value(final IntentionAction intentionAction
) {
412 return intentionAction
.getText().startsWith(hint
);
417 public IntentionAction
findSingleIntention(@NotNull final String hint
) throws Exception
{
418 final List
<IntentionAction
> list
= filterAvailableIntentions(hint
);
419 if (list
.size() != 1) {
420 Assert
.fail(StringUtil
.join(getAvailableIntentions(), new Function
<IntentionAction
, String
>() {
421 public String
fun(final IntentionAction intentionAction
) {
422 return intentionAction
.getText();
426 return UsefulTestCase
.assertOneElement(list
);
429 public IntentionAction
getAvailableIntention(final String intentionName
, final String
... filePaths
) throws Exception
{
430 List
<IntentionAction
> intentions
= getAvailableIntentions(filePaths
);
431 return CodeInsightTestUtil
.findIntentionByText(intentions
, intentionName
);
434 public void launchAction(@NotNull final IntentionAction action
) throws Exception
{
435 new WriteCommandAction(myProjectFixture
.getProject()) {
436 protected void run(final Result result
) throws Exception
{
437 ShowIntentionActionsHandler
.chooseActionAndInvoke(getFile(), getEditor(), action
, action
.getText());
439 }.execute().throwException();
443 public void testCompletion(final String
[] filesBefore
, final String fileAfter
) throws Exception
{
445 configureByFiles(filesBefore
);
446 final LookupElement
[] items
= complete(CompletionType
.BASIC
);
448 System
.out
.println("items = " + Arrays
.toString(items
));
450 checkResultByFile(fileAfter
);
453 protected void assertInitialized() {
454 Assert
.assertNotNull("setUp() hasn't been called", myPsiManager
);
457 public void testCompletion(String fileBefore
, String fileAfter
, final String
... additionalFiles
) throws Exception
{
458 testCompletion(ArrayUtil
.reverseArray(ArrayUtil
.append(additionalFiles
, fileBefore
)), fileAfter
);
461 public void testCompletionVariants(final String fileBefore
, final String
... expectedItems
) throws Exception
{
463 final List
<String
> result
= getCompletionVariants(fileBefore
);
464 UsefulTestCase
.assertSameElements(result
, expectedItems
);
467 public List
<String
> getCompletionVariants(final String
... filesBefore
) throws Exception
{
469 configureByFiles(filesBefore
);
470 final LookupElement
[] items
= complete(CompletionType
.BASIC
);
471 Assert
.assertNotNull("No lookup was shown, probably there was only one lookup element that was inserted automatically", items
);
472 return getLookupElementStrings();
476 public List
<String
> getLookupElementStrings() {
478 final LookupElement
[] elements
= getLookupElements();
479 if (elements
== null) return null;
481 return ContainerUtil
.map(elements
, new Function
<LookupElement
, String
>() {
482 public String
fun(final LookupElement lookupItem
) {
483 return lookupItem
.getLookupString();
488 public void testRename(final String fileBefore
, final String fileAfter
, final String newName
, final String
... additionalFiles
) throws Exception
{
490 configureByFiles(ArrayUtil
.reverseArray(ArrayUtil
.append(additionalFiles
, fileBefore
)));
491 testRename(fileAfter
, newName
);
494 public void testRename(final String fileAfter
, final String newName
) throws Exception
{
495 renameElementAtCaret(newName
);
496 checkResultByFile(fileAfter
);
499 public void renameElementAtCaret(final String newName
) throws Exception
{
501 new WriteCommandAction
.Simple(myProjectFixture
.getProject()) {
502 protected void run() throws Exception
{
503 PsiElement element
= TargetElementUtilBase
.findTargetElement(getCompletionEditor(), TargetElementUtilBase
.REFERENCED_ELEMENT_ACCEPTED
| TargetElementUtilBase
.ELEMENT_NAME_ACCEPTED
);
504 assert element
!= null: "element not found in file " + myFile
.getName() + " at caret position, offset " + myEditor
.getCaretModel().getOffset();
505 final PsiElement substitution
= RenamePsiElementProcessor
.forElement(element
).substituteElementToRename(element
, myEditor
);
506 new RenameProcessor(myProjectFixture
.getProject(), substitution
, newName
, false, false).run();
508 }.execute().throwException();
511 public void type(final char c
) {
513 new WriteCommandAction(getProject()) {
514 protected void run(Result result
) throws Exception
{
515 EditorActionManager actionManager
= EditorActionManager
.getInstance();
516 final DataContext dataContext
= DataManager
.getInstance().getDataContext();
518 performEditorAction(IdeActions
.ACTION_EDITOR_BACKSPACE
);
522 if (LookupManager
.getActiveLookup(getEditor()) != null) {
523 performEditorAction(IdeActions
.ACTION_CHOOSE_LOOKUP_ITEM
);
527 performEditorAction(IdeActions
.ACTION_EDITOR_ENTER
);
531 if (LookupManager
.getInstance(getProject()).getActiveLookup() != null) {
532 performEditorAction(IdeActions
.ACTION_CHOOSE_LOOKUP_ITEM_REPLACE
);
537 actionManager
.getTypedAction().actionPerformed(getEditor(), c
, dataContext
);
542 public void performEditorAction(final String actionId
) {
544 final DataContext dataContext
= DataManager
.getInstance().getDataContext();
545 EditorActionManager actionManager
= EditorActionManager
.getInstance();
546 actionManager
.getActionHandler(actionId
).execute(getEditor(), dataContext
);
549 public Collection
<UsageInfo
> testFindUsages(@NonNls final String
... fileNames
) throws Exception
{
551 configureByFiles(fileNames
);
552 final PsiElement targetElement
= TargetElementUtilBase
553 .findTargetElement(getEditor(), TargetElementUtilBase
.ELEMENT_NAME_ACCEPTED
| TargetElementUtilBase
.REFERENCED_ELEMENT_ACCEPTED
);
554 assert targetElement
!= null : "Cannot find referenced element";
555 return findUsages(targetElement
);
558 public Collection
<UsageInfo
> findUsages(@NotNull final PsiElement targetElement
) {
559 final Project project
= getProject();
560 final FindUsagesHandler handler
= ((FindManagerImpl
)FindManager
.getInstance(project
)).getFindUsagesManager().getFindUsagesHandler(targetElement
, false);
562 final CommonProcessors
.CollectProcessor
<UsageInfo
> processor
= new CommonProcessors
.CollectProcessor
<UsageInfo
>();
563 final FindUsagesOptions options
= new FindUsagesOptions(project
, null);
564 options
.isUsages
= true;
565 assert handler
!= null : "Cannot find handler for: " + targetElement
;
566 final PsiElement
[] psiElements
= ArrayUtil
.mergeArrays(handler
.getPrimaryElements(), handler
.getSecondaryElements(), PsiElement
.class);
567 for (PsiElement psiElement
: psiElements
) {
568 handler
.processElementUsages(psiElement
, processor
, options
);
570 return processor
.getResults();
573 public void moveFile(@NonNls final String filePath
, @NonNls final String to
, final String
... additionalFiles
) throws Exception
{
575 final Project project
= myProjectFixture
.getProject();
576 new WriteCommandAction
.Simple(project
) {
577 protected void run() throws Exception
{
578 configureByFiles(ArrayUtil
.reverseArray(ArrayUtil
.append(additionalFiles
, filePath
)));
579 final VirtualFile file
= findFileInTempDir(to
);
580 assert file
.isDirectory() : to
+ " is not a directory";
581 final PsiDirectory directory
= myPsiManager
.findDirectory(file
);
582 new MoveFilesOrDirectoriesProcessor(project
, new PsiElement
[] {myFile
}, directory
,
583 false, false, null, null).run();
585 }.execute().throwException();
590 public GutterIconRenderer
findGutter(final String filePath
) throws Exception
{
592 final Project project
= myProjectFixture
.getProject();
593 final Ref
<GutterIconRenderer
> result
= new Ref
<GutterIconRenderer
>();
594 new WriteCommandAction
.Simple(project
) {
596 protected void run() throws Exception
{
597 final int offset
= configureByFilesInner(filePath
);
599 final Collection
<HighlightInfo
> infos
= doHighlighting();
600 for (HighlightInfo info
:infos
) {
601 if (info
.endOffset
>= offset
&& info
.startOffset
<= offset
) {
602 final GutterIconRenderer renderer
= info
.getGutterIconRenderer();
603 if (renderer
!= null) {
604 result
.set(renderer
);
611 }.execute().throwException();
616 public Collection
<GutterIconRenderer
> findAllGutters(final String filePath
) throws Exception
{
618 final Project project
= myProjectFixture
.getProject();
619 final SortedMap
<Integer
, List
<GutterIconRenderer
>> result
= new TreeMap
<Integer
, List
<GutterIconRenderer
>>();
620 new WriteCommandAction
.Simple(project
) {
622 protected void run() throws Exception
{
623 configureByFilesInner(filePath
);
625 for (HighlightInfo info
: doHighlighting()) {
626 addGutterIconRenderer(info
.getGutterIconRenderer(), info
.startOffset
);
629 for (final RangeHighlighter highlighter
: myEditor
.getDocument().getMarkupModel(project
).getAllHighlighters()) {
630 addGutterIconRenderer(highlighter
.getGutterIconRenderer(), highlighter
.getStartOffset());
634 private void addGutterIconRenderer(final GutterIconRenderer renderer
, final int offset
) {
635 if (renderer
== null) return;
637 List
<GutterIconRenderer
> renderers
= result
.get(offset
);
638 if (renderers
== null) {
639 result
.put(offset
, renderers
= new SmartList
<GutterIconRenderer
>());
641 renderers
.add(renderer
);
644 }.execute().throwException();
645 return ContainerUtil
.concat(result
.values());
649 public PsiFile
addFileToProject(@NonNls final String relativePath
, @NonNls final String fileText
) throws IOException
{
651 return addFileToProject(getTempDirPath(), relativePath
, fileText
);
654 protected PsiFile
addFileToProject(String rootPath
, String relativePath
, String fileText
) throws IOException
{
655 if (myTempDirFixture
instanceof LightTempDirTestFixtureImpl
) {
656 final VirtualFile file
= myTempDirFixture
.createFile(relativePath
, fileText
);
657 return PsiManager
.getInstance(getProject()).findFile(file
);
660 return ((HeavyIdeaTestFixture
)myProjectFixture
).addFileToProject(rootPath
, relativePath
, fileText
);
663 public <T
> void registerExtension(final ExtensionsArea area
, final ExtensionPointName
<T
> epName
, final T extension
) {
665 final ExtensionPoint
<T
> extensionPoint
= area
.getExtensionPoint(epName
);
666 extensionPoint
.registerExtension(extension
);
667 disposeOnTearDown(new Disposable() {
668 public void dispose() {
669 extensionPoint
.unregisterExtension(extension
);
674 public PsiManager
getPsiManager() {
678 public LookupElement
[] complete(final CompletionType type
) {
680 myEmptyLookup
= false;
681 new WriteCommandAction(getProject()) {
682 protected void run(Result result
) throws Exception
{
683 final CodeInsightActionHandler handler
= new CodeCompletionHandlerBase(type
) {
684 protected PsiFile
createFileCopy(final PsiFile file
) {
685 final PsiFile copy
= super.createFileCopy(file
);
686 if (myFileContext
!= null) {
687 final PsiElement contextCopy
= myFileContext
.copy();
688 final PsiFile containingFile
= contextCopy
.getContainingFile();
689 if (containingFile
instanceof PsiFileImpl
) {
690 ((PsiFileImpl
)containingFile
).setOriginalFile(myFileContext
.getContainingFile());
692 setContext(copy
, contextCopy
);
698 protected void completionFinished(final int offset1
, final int offset2
, final CompletionContext context
, final CompletionProgressIndicator indicator
,
699 final LookupElement
[] items
) {
700 myEmptyLookup
= items
.length
== 0;
701 super.completionFinished(offset1
, offset2
, context
, indicator
, items
);
704 Editor editor
= getCompletionEditor();
705 handler
.invoke(getProject(), editor
, PsiUtilBase
.getPsiFileInEditor(editor
, getProject()));
708 return getLookupElements();
712 protected Editor
getCompletionEditor() {
713 return InjectedLanguageUtil
.getEditorForInjectedLanguageNoCommit(myEditor
, myFile
);
717 public LookupElement
[] completeBasic() {
718 return complete(CompletionType
.BASIC
);
722 public LookupElement
[] getLookupElements() {
723 LookupImpl lookup
= (LookupImpl
)LookupManager
.getActiveLookup(myEditor
);
724 if (lookup
== null) {
725 return myEmptyLookup ? LookupElement
.EMPTY_ARRAY
: null;
728 final List
<LookupElement
> list
= lookup
.getItems();
729 return list
.toArray(new LookupElement
[list
.size()]);
733 public void checkResult(final String text
) throws IOException
{
734 PsiDocumentManager
.getInstance(getProject()).commitAllDocuments();
735 EditorUtil
.fillVirtualSpaceUntilCaret(myEditor
);
736 checkResult("TEXT", false, SelectionAndCaretMarkupLoader
.fromText(text
, getProject()), myFile
.getText());
739 public void checkResultByFile(final String expectedFile
) throws Exception
{
740 checkResultByFile(expectedFile
, false);
743 public void checkResultByFile(final String expectedFile
, final boolean ignoreWhitespaces
) throws Exception
{
745 new WriteCommandAction
.Simple(myProjectFixture
.getProject()) {
747 protected void run() throws Exception
{
748 checkResultByFile(expectedFile
, myFile
, ignoreWhitespaces
);
750 }.execute().throwException();
753 public void checkResultByFile(final String filePath
, final String expectedFile
, final boolean ignoreWhitespaces
) throws Exception
{
756 new WriteCommandAction
.Simple(myProjectFixture
.getProject()) {
758 protected void run() throws Exception
{
759 final VirtualFile copy
= findFileInTempDir(filePath
.replace(File
.separatorChar
, '/'));
760 final PsiFile psiFile
= myPsiManager
.findFile(copy
);
761 assert psiFile
!= null;
762 checkResultByFile(expectedFile
, psiFile
, ignoreWhitespaces
);
764 }.execute().throwException();
767 public void setUp() throws Exception
{
770 myProjectFixture
.setUp();
771 myTempDirFixture
.setUp();
772 myPsiManager
= (PsiManagerImpl
)PsiManager
.getInstance(getProject());
773 configureInspections(myInspections
== null ?
new LocalInspectionTool
[0] : myInspections
);
774 DaemonCodeAnalyzerSettings
.getInstance().setImportHintEnabled(false);
777 private void enableInspectionTool(InspectionProfileEntry tool
){
778 final String shortName
= tool
.getShortName();
779 final HighlightDisplayKey key
= HighlightDisplayKey
.find(shortName
);
781 String id
= tool
instanceof LocalInspectionTool ?
((LocalInspectionTool
)tool
).getID() : shortName
;
782 HighlightDisplayKey
.register(shortName
, tool
.getDisplayName(), id
);
784 myAvailableTools
.put(shortName
, tool
);
785 myAvailableLocalTools
.put(shortName
, tool
instanceof LocalInspectionTool ?
786 new LocalInspectionToolWrapper((LocalInspectionTool
)tool
) :
787 (InspectionTool
)tool
);
790 private void configureInspections(final InspectionProfileEntry
[] tools
) {
791 for (InspectionProfileEntry tool
: tools
) {
792 enableInspectionTool(tool
);
795 final InspectionProfileImpl profile
= new InspectionProfileImpl(PROFILE
) {
797 public ModifiableModel
getModifiableModel() {
803 public InspectionProfileEntry
[] getInspectionTools(PsiElement element
) {
804 final Collection
<InspectionTool
> tools
= myAvailableLocalTools
.values();
805 return tools
.toArray(new InspectionTool
[tools
.size()]);
809 public List
<ToolsImpl
> getAllEnabledInspectionTools() {
810 List
<ToolsImpl
> result
= new ArrayList
<ToolsImpl
>();
811 for (InspectionProfileEntry entry
: getInspectionTools(null)) {
812 result
.add(new ToolsImpl(entry
, entry
.getDefaultLevel(), true));
817 public boolean isToolEnabled(HighlightDisplayKey key
, PsiElement element
) {
818 return key
!= null && key
.toString() != null && myAvailableTools
.containsKey(key
.toString());
821 public HighlightDisplayLevel
getErrorLevel(@NotNull HighlightDisplayKey key
, PsiElement element
) {
822 final InspectionProfileEntry entry
= myAvailableTools
.get(key
.toString());
823 return entry
!= null ? entry
.getDefaultLevel() : HighlightDisplayLevel
.WARNING
;
826 public InspectionTool
getInspectionTool(@NotNull String shortName
, @NotNull PsiElement element
) {
827 return myAvailableLocalTools
.get(shortName
);
830 final InspectionProfileManager inspectionProfileManager
= InspectionProfileManager
.getInstance();
831 inspectionProfileManager
.addProfile(profile
);
832 Disposer
.register(getProject(), new Disposable() {
833 public void dispose() {
834 inspectionProfileManager
.deleteProfile(PROFILE
);
837 inspectionProfileManager
.setRootProfile(profile
.getName());
838 InspectionProjectProfileManager
.getInstance(getProject()).updateProfile(profile
);
839 InspectionProjectProfileManager
.getInstance(getProject()).setProjectProfile(profile
.getName());
842 public void tearDown() throws Exception
{
843 if (SwingUtilities
.isEventDispatchThread()) {
844 LookupManager
.getInstance(getProject()).hideActiveLookup();
847 ApplicationManager
.getApplication().invokeAndWait(new Runnable() {
849 LookupManager
.getInstance(getProject()).hideActiveLookup();
851 }, ModalityState
.NON_MODAL
);
854 FileEditorManager editorManager
= FileEditorManager
.getInstance(getProject());
855 VirtualFile
[] openFiles
= editorManager
.getOpenFiles();
856 for (VirtualFile openFile
: openFiles
) {
857 editorManager
.closeFile(openFile
);
860 myProjectFixture
.tearDown();
861 myTempDirFixture
.tearDown();
866 private int configureByFilesInner(@NonNls String
... filePaths
) throws IOException
{
870 for (int i
= filePaths
.length
- 1; i
> 0; i
--) {
871 configureByFileInner(filePaths
[i
]);
873 return configureByFileInner(filePaths
[0]);
876 public void configureByFile(final String file
) throws IOException
{
878 new WriteCommandAction
.Simple(getProject()) {
879 protected void run() throws Exception
{
880 configureByFilesInner(file
);
885 public void configureByFiles(@NonNls final String
... files
) throws Exception
{
886 new WriteCommandAction
.Simple(getProject()) {
887 protected void run() throws Exception
{
888 configureByFilesInner(files
);
893 public PsiFile
configureByText(final FileType fileType
, @NonNls final String text
) throws IOException
{
895 final String extension
= fileType
.getDefaultExtension();
896 final FileTypeManager fileTypeManager
= FileTypeManager
.getInstance();
897 if (fileTypeManager
.getFileTypeByExtension(extension
) != fileType
) {
898 new WriteCommandAction(getProject()) {
899 protected void run(Result result
) throws Exception
{
900 fileTypeManager
.associateExtension(fileType
, extension
);
904 final VirtualFile vFile
;
905 if (myTempDirFixture
instanceof LightTempDirTestFixtureImpl
) {
906 final VirtualFile root
= LightPlatformTestCase
.getSourceRoot();
907 root
.refresh(false, false);
908 vFile
= root
.findOrCreateChildData(this, "aaa." + extension
);
911 final File tempFile
= File
.createTempFile("aaa", "." + extension
, new File(getTempDirPath()));
912 vFile
= LocalFileSystem
.getInstance().refreshAndFindFileByIoFile(tempFile
);
914 VfsUtil
.saveText(vFile
, text
);
915 configureInner(vFile
, SelectionAndCaretMarkupLoader
.fromFile(vFile
, getProject()));
919 public PsiFile
configureByText(String fileName
, @NonNls String text
) throws IOException
{
920 return configureByText(FileTypeManager
.getInstance().getFileTypeByFileName(fileName
), text
);
923 public Document
getDocument(final PsiFile file
) {
925 return PsiDocumentManager
.getInstance(getProject()).getDocument(file
);
928 public void setFileContext(@Nullable final PsiElement context
) {
929 myFileContext
= context
;
930 setContext(myFile
, context
);
936 * @return caret offset or -1 if caret marker does not present
937 * @throws IOException
939 private int configureByFileInner(@NonNls String filePath
) throws IOException
{
941 final VirtualFile file
= copyFileToProject(filePath
);
942 return configureByFileInner(file
);
945 public int configureFromTempProjectFile(final String filePath
) throws IOException
{
946 return configureByFileInner(findFileInTempDir(filePath
));
949 public void configureFromExistingVirtualFile(VirtualFile f
) throws IOException
{
950 configureByFileInner(f
);
953 private int configureByFileInner(final VirtualFile copy
) throws IOException
{
954 return configureInner(copy
, SelectionAndCaretMarkupLoader
.fromFile(copy
, getProject()));
957 private int configureInner(@NotNull final VirtualFile copy
, final SelectionAndCaretMarkupLoader loader
) {
960 final OutputStream outputStream
= copy
.getOutputStream(null, 0, 0);
961 outputStream
.write(loader
.newFileText
.getBytes());
962 outputStream
.close();
964 catch (IOException e
) {
965 throw new RuntimeException(e
);
967 myFile
= myPsiManager
.findFile(copy
);
968 setContext(myFile
, myFileContext
);
969 myEditor
= createEditor(copy
);
970 assert myEditor
!= null : "Editor couldn't be created for file: " + copy
.getPath() + ", use copyFileToProject(..) method for this file instead of configureByFile(..)" ;
972 if (loader
.caretMarker
!= null) {
973 offset
= loader
.caretMarker
.getStartOffset();
974 myEditor
.getCaretModel().moveToOffset(offset
);
976 if (loader
.selStartMarker
!= null && loader
.selEndMarker
!= null) {
977 myEditor
.getSelectionModel().setSelection(loader
.selStartMarker
.getStartOffset(), loader
.selEndMarker
.getStartOffset());
980 Module module
= getModule();
981 if (module
!= null) {
982 for (Facet facet
: FacetManager
.getInstance(module
).getAllFacets()) {
983 module
.getMessageBus().syncPublisher(FacetManager
.FACETS_TOPIC
).facetConfigurationChanged(facet
);
990 private static void setContext(final PsiFile file
, final PsiElement context
) {
991 if (file
!= null && context
!= null) {
992 file
.putUserData(FileContextUtil
.INJECTED_IN_ELEMENT
, new IdentitySmartPointer
<PsiElement
>(context
));
996 public VirtualFile
findFileInTempDir(final String filePath
) {
997 if (myTempDirFixture
instanceof LightTempDirTestFixtureImpl
) {
998 return myTempDirFixture
.getFile(filePath
);
1000 String fullPath
= getTempDirPath() + "/" + filePath
;
1002 final VirtualFile copy
= LocalFileSystem
.getInstance().refreshAndFindFileByPath(fullPath
.replace(File
.separatorChar
, '/'));
1003 assert copy
!= null : "file " + fullPath
+ " not found";
1008 private Editor
createEditor(VirtualFile file
) {
1009 final Project project
= getProject();
1010 final FileEditorManager instance
= FileEditorManager
.getInstance(project
);
1011 if (file
.getFileType().isBinary()) {
1014 return instance
.openTextEditor(new OpenFileDescriptor(project
, file
, 0), false);
1017 private void collectAndCheckHighlightings(boolean checkWarnings
, boolean checkInfos
, boolean checkWeakWarnings
, Ref
<Long
> duration
)
1019 ExpectedHighlightingData data
= new ExpectedHighlightingData(myEditor
.getDocument(), checkWarnings
, checkWeakWarnings
, checkInfos
, myFile
);
1021 collectAndCheckHighlightings(data
, duration
);
1024 private void collectAndCheckHighlightings(final ExpectedHighlightingData data
, final Ref
<Long
> duration
) {
1025 final Project project
= getProject();
1026 PsiDocumentManager
.getInstance(project
).commitAllDocuments();
1028 ((PsiFileImpl
)myFile
).calcTreeElement(); //to load text
1030 //to initialize caches
1031 myPsiManager
.getCacheManager().getFilesWithWord(XXX
, UsageSearchContext
.IN_COMMENTS
, GlobalSearchScope
.allScope(project
), true);
1033 ((PsiManagerImpl
)PsiManager
.getInstance(project
)).setAssertOnFileLoadingFilter(myJavaFilesFilter
);
1035 final long start
= System
.currentTimeMillis();
1036 // ProfilingUtil.startCPUProfiling();
1037 List
<HighlightInfo
> infos
= doHighlighting();
1038 removeDuplicatedRangesForInjected(infos
);
1039 final long elapsed
= System
.currentTimeMillis() - start
;
1040 duration
.set(duration
.isNull()? elapsed
: duration
.get().longValue() + elapsed
);
1041 // ProfilingUtil.captureCPUSnapshot("testing");
1043 ((PsiManagerImpl
)PsiManager
.getInstance(project
)).setAssertOnFileLoadingFilter(VirtualFileFilter
.NONE
);
1045 data
.checkResult(infos
, myEditor
.getDocument().getText());
1048 private static void removeDuplicatedRangesForInjected(List
<HighlightInfo
> infos
) {
1049 Collections
.sort(infos
, new Comparator
<HighlightInfo
>() {
1050 public int compare(HighlightInfo o1
, HighlightInfo o2
) {
1051 final int i
= o2
.startOffset
- o1
.startOffset
;
1052 return i
!= 0 ? i
: o1
.getSeverity().myVal
- o2
.getSeverity().myVal
;
1055 HighlightInfo prevInfo
= null;
1056 for (Iterator
<HighlightInfo
> it
= infos
.iterator(); it
.hasNext();) {
1057 final HighlightInfo info
= it
.next();
1058 if (prevInfo
!= null &&
1059 info
.getSeverity() == HighlightSeverity
.INFORMATION
&&
1060 info
.description
== null &&
1061 info
.startOffset
== prevInfo
.startOffset
&&
1062 info
.endOffset
== prevInfo
.endOffset
) {
1065 prevInfo
= info
.getSeverity() == HighlightInfoType
.INJECTED_FRAGMENT_SEVERITY ? info
: null;
1070 public List
<HighlightInfo
> doHighlighting() {
1071 final Project project
= myProjectFixture
.getProject();
1072 PsiDocumentManager
.getInstance(project
).commitAllDocuments();
1075 ApplicationManager
.getApplication().runReadAction(new Computable
<List
<HighlightInfo
>>() {
1076 public List
<HighlightInfo
> compute() {
1077 return instantiateAndRun(getFile(), getEditor(), ArrayUtil
.EMPTY_INT_ARRAY
, false);
1083 public static List
<HighlightInfo
> instantiateAndRun(PsiFile file
, Editor editor
, int[] toIgnore
, boolean allowDirt
) {
1084 Project project
= file
.getProject();
1085 FileBasedIndex
.getInstance().ensureUpToDate(StubUpdatingIndex
.INDEX_ID
, project
, null);
1086 assertTrue(!DumbServiceImpl
.getInstance(project
).isDumb());
1087 FileStatusMap fileStatusMap
= ((DaemonCodeAnalyzerImpl
)DaemonCodeAnalyzer
.getInstance(project
)).getFileStatusMap();
1088 for (int ignoreId
: toIgnore
) {
1089 fileStatusMap
.markFileUpToDate(editor
.getDocument(), file
, ignoreId
);
1091 fileStatusMap
.allowDirt(allowDirt
);
1093 TextEditorHighlightingPassRegistrarEx registrar
= TextEditorHighlightingPassRegistrarEx
.getInstanceEx(project
);
1094 final List
<TextEditorHighlightingPass
> passes
= registrar
.instantiatePasses(file
, editor
, toIgnore
);
1095 final ProgressIndicator progress
= new DaemonProgressIndicator();
1096 ProgressManager
.getInstance().runProcess(new Runnable() {
1098 for (TextEditorHighlightingPass pass
: passes
) {
1099 pass
.collectInformation(progress
);
1101 for (TextEditorHighlightingPass pass
: passes
) {
1102 pass
.applyInformationToEditor();
1106 List
<HighlightInfo
> infos
= DaemonCodeAnalyzerImpl
.getHighlights(editor
.getDocument(), project
);
1107 return infos
== null ? Collections
.<HighlightInfo
>emptyList() : new ArrayList
<HighlightInfo
>(infos
);
1110 fileStatusMap
.allowDirt(true);
1114 public String
getTestDataPath() {
1115 return myTestDataPath
;
1118 public Project
getProject() {
1119 return myProjectFixture
.getProject();
1122 public Module
getModule() {
1123 return myProjectFixture
.getModule();
1126 public Editor
getEditor() {
1130 public PsiFile
getFile() {
1134 public static List
<IntentionAction
> getAvailableIntentions(final Editor editor
, final PsiFile file
) {
1135 return ApplicationManager
.getApplication().runReadAction(new Computable
<List
<IntentionAction
>>() {
1136 public List
<IntentionAction
> compute() {
1137 return doGetAvailableIntentions(editor
, file
);
1142 private static List
<IntentionAction
> doGetAvailableIntentions(Editor editor
, PsiFile file
) {
1143 ShowIntentionsPass
.IntentionsInfo intentions
= new ShowIntentionsPass
.IntentionsInfo();
1144 ShowIntentionsPass
.getActionsToShow(editor
, file
, intentions
, -1);
1145 List
<HighlightInfo
.IntentionActionDescriptor
> descriptors
= new ArrayList
<HighlightInfo
.IntentionActionDescriptor
>();
1146 descriptors
.addAll(intentions
.intentionsToShow
);
1147 descriptors
.addAll(intentions
.errorFixesToShow
);
1148 descriptors
.addAll(intentions
.inspectionFixesToShow
);
1149 descriptors
.addAll(intentions
.guttersToShow
);
1151 PsiElement element
= file
.findElementAt(editor
.getCaretModel().getOffset());
1152 List
<IntentionAction
> result
= new ArrayList
<IntentionAction
>();
1154 List
<HighlightInfo
> infos
= DaemonCodeAnalyzerImpl
.getFileLevelHighlights(file
.getProject(), file
);
1155 for (HighlightInfo info
: infos
) {
1156 for (Pair
<HighlightInfo
.IntentionActionDescriptor
, TextRange
> pair
: info
.quickFixActionRanges
) {
1157 HighlightInfo
.IntentionActionDescriptor actionInGroup
= pair
.first
;
1158 if (actionInGroup
.getAction().isAvailable(file
.getProject(), editor
, file
)) {
1159 descriptors
.add(actionInGroup
);
1164 // add all intention options for simplicity
1165 for (HighlightInfo
.IntentionActionDescriptor descriptor
: descriptors
) {
1166 result
.add(descriptor
.getAction());
1167 List
<IntentionAction
> options
= descriptor
.getOptions(element
);
1168 if (options
!= null) {
1169 for (IntentionAction option
: options
) {
1170 if (option
.isAvailable(file
.getProject(), editor
, file
)) {
1179 public void allowTreeAccessForFile(final VirtualFile file
) {
1180 myJavaFilesFilter
.allowTreeAccessForFile(file
);
1183 static class SelectionAndCaretMarkupLoader
{
1184 final String newFileText
;
1185 final RangeMarker caretMarker
;
1186 final RangeMarker selStartMarker
;
1187 final RangeMarker selEndMarker
;
1189 static SelectionAndCaretMarkupLoader
fromFile(String path
, Project project
) throws IOException
{
1190 return new SelectionAndCaretMarkupLoader(StringUtil
.convertLineSeparators(new String(FileUtil
.loadFileText(new File(path
)))), project
);
1192 static SelectionAndCaretMarkupLoader
fromFile(VirtualFile file
, Project project
) throws IOException
{
1193 return new SelectionAndCaretMarkupLoader(StringUtil
.convertLineSeparators(VfsUtil
.loadText(file
)), project
);
1196 static SelectionAndCaretMarkupLoader
fromText(String text
, Project project
) {
1197 return new SelectionAndCaretMarkupLoader(text
, project
);
1200 private SelectionAndCaretMarkupLoader(String fileText
, Project project
) {
1201 final Document document
= EditorFactory
.getInstance().createDocument(fileText
);
1203 int caretIndex
= fileText
.indexOf(CARET_MARKER
);
1204 int selStartIndex
= fileText
.indexOf(SELECTION_START_MARKER
);
1205 int selEndIndex
= fileText
.indexOf(SELECTION_END_MARKER
);
1207 caretMarker
= caretIndex
>= 0 ? document
.createRangeMarker(caretIndex
, caretIndex
) : null;
1208 selStartMarker
= selStartIndex
>= 0 ? document
.createRangeMarker(selStartIndex
, selStartIndex
) : null;
1209 selEndMarker
= selEndIndex
>= 0 ? document
.createRangeMarker(selEndIndex
, selEndIndex
) : null;
1211 new WriteCommandAction(project
) {
1212 protected void run(Result result
) throws Exception
{
1213 if (caretMarker
!= null) {
1214 document
.deleteString(caretMarker
.getStartOffset(), caretMarker
.getStartOffset() + CARET_MARKER
.length());
1216 if (selStartMarker
!= null) {
1217 document
.deleteString(selStartMarker
.getStartOffset(), selStartMarker
.getStartOffset() + SELECTION_START_MARKER
.length());
1219 if (selEndMarker
!= null) {
1220 document
.deleteString(selEndMarker
.getStartOffset(), selEndMarker
.getStartOffset() + SELECTION_END_MARKER
.length());
1225 newFileText
= document
.getText();
1229 private void checkResultByFile(@NonNls String expectedFile
,
1230 @NotNull PsiFile originalFile
,
1231 boolean stripTrailingSpaces
) throws IOException
{
1232 if (!stripTrailingSpaces
) {
1233 EditorUtil
.fillVirtualSpaceUntilCaret(myEditor
);
1235 PsiDocumentManager
.getInstance(getProject()).commitAllDocuments();
1236 checkResult(expectedFile
, stripTrailingSpaces
, SelectionAndCaretMarkupLoader
.fromFile(getTestDataPath() + "/" + expectedFile
, getProject()), originalFile
.getText());
1239 private void checkResult(final String expectedFile
,
1240 final boolean stripTrailingSpaces
,
1241 final SelectionAndCaretMarkupLoader loader
,
1242 String actualText
) {
1243 assertInitialized();
1244 Project project
= myProjectFixture
.getProject();
1246 project
.getComponent(PostprocessReformattingAspect
.class).doPostponedFormatting();
1247 if (stripTrailingSpaces
) {
1248 actualText
= stripTrailingSpaces(actualText
);
1251 PsiDocumentManager
.getInstance(project
).commitAllDocuments();
1253 String newFileText1
= loader
.newFileText
;
1254 if (stripTrailingSpaces
) {
1255 newFileText1
= stripTrailingSpaces(newFileText1
);
1258 actualText
= StringUtil
.convertLineSeparators(actualText
);
1260 //noinspection HardCodedStringLiteral
1261 Assert
.assertEquals("Text mismatch in file " + expectedFile
, newFileText1
, actualText
);
1263 if (loader
.caretMarker
!= null) {
1264 int caretLine
= StringUtil
.offsetToLineNumber(loader
.newFileText
, loader
.caretMarker
.getStartOffset());
1265 int caretCol
= loader
.caretMarker
.getStartOffset() - StringUtil
.lineColToOffset(loader
.newFileText
, caretLine
, 0);
1267 Assert
.assertEquals("caretLine", caretLine
+ 1, myEditor
.getCaretModel().getLogicalPosition().line
+ 1);
1268 Assert
.assertEquals("caretColumn", caretCol
+ 1, myEditor
.getCaretModel().getLogicalPosition().column
+ 1);
1271 if (loader
.selStartMarker
!= null && loader
.selEndMarker
!= null) {
1272 int selStartLine
= StringUtil
.offsetToLineNumber(loader
.newFileText
, loader
.selStartMarker
.getStartOffset());
1273 int selStartCol
= loader
.selStartMarker
.getStartOffset() - StringUtil
.lineColToOffset(loader
.newFileText
, selStartLine
, 0);
1275 int selEndLine
= StringUtil
.offsetToLineNumber(loader
.newFileText
, loader
.selEndMarker
.getEndOffset());
1276 int selEndCol
= loader
.selEndMarker
.getEndOffset() - StringUtil
.lineColToOffset(loader
.newFileText
, selEndLine
, 0);
1278 Assert
.assertEquals("selectionStartLine", selStartLine
+ 1,
1279 StringUtil
.offsetToLineNumber(loader
.newFileText
, myEditor
.getSelectionModel().getSelectionStart()) + 1);
1281 Assert
.assertEquals("selectionStartCol", selStartCol
+ 1, myEditor
.getSelectionModel().getSelectionStart() -
1282 StringUtil
.lineColToOffset(loader
.newFileText
, selStartLine
, 0) + 1);
1284 Assert
.assertEquals("selectionEndLine", selEndLine
+ 1,
1285 StringUtil
.offsetToLineNumber(loader
.newFileText
, myEditor
.getSelectionModel().getSelectionEnd()) + 1);
1287 Assert
.assertEquals("selectionEndCol", selEndCol
+ 1,
1288 myEditor
.getSelectionModel().getSelectionEnd() - StringUtil
.lineColToOffset(loader
.newFileText
, selEndLine
, 0) +
1291 else if (myEditor
!= null) {
1292 Assert
.assertTrue("has no selection", !myEditor
.getSelectionModel().hasSelection());
1296 private static String
stripTrailingSpaces(String actualText
) {
1297 final Document document
= EditorFactory
.getInstance().createDocument(actualText
);
1298 ((DocumentEx
)document
).stripTrailingSpaces(false);
1299 actualText
= document
.getText();