Search in sources :

Example 51 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project android by JetBrains.

the class AndroidModuleInfoTest method testManifestMerger.

public void testManifestMerger() throws Exception {
    loadProject(MODULE_INFO_MANIFEST_MERGER);
    assertNotNull(myAndroidFacet);
    assertEquals(1, AndroidUtils.getAllAndroidDependencies(myAndroidFacet.getModule(), true).size());
    MergedManifest manifestInfo = MergedManifest.get(myAndroidFacet);
    List<Element> mergedActivities = manifestInfo.getActivities();
    assertEquals(3, mergedActivities.size());
    Set<String> activities = Sets.newHashSet(ActivityLocatorUtils.getQualifiedName(mergedActivities.get(0)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(1)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(2)));
    assertTrue(activities.contains("test.helloworldapp.Debug"));
    assertTrue(activities.contains("test.helloworldapp.MyActivity"));
    assertTrue(activities.contains("test.helloworldapp.lib.LibActivity"));
    assertNotNull(manifestInfo.getVersionCode());
    assertEquals(2, manifestInfo.getVersionCode().intValue());
    // Make a change to the psi
    VirtualFile manifestFile = AndroidRootUtil.getPrimaryManifestFile(myAndroidFacet);
    assertNotNull(manifestFile);
    PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(manifestFile);
    assertNotNull(psiFile);
    new WriteCommandAction.Simple(getProject(), psiFile) {

        @Override
        protected void run() throws Throwable {
            assertNotNull(myAndroidFacet.getManifest());
            XmlTag manifestTag = myAndroidFacet.getManifest().getXmlTag();
            XmlTag applicationTag = Iterables.find(Arrays.asList(manifestTag.getSubTags()), new Predicate<XmlTag>() {

                @Override
                public boolean apply(@Nullable XmlTag input) {
                    assertNotNull(input);
                    return "application".equals(input.getName());
                }
            });
            XmlTag activityTag = applicationTag.createChildTag("activity", "", null, false);
            activityTag.setAttribute("android:name", ".AddedActivity");
            applicationTag.addSubTag(activityTag, false);
        }
    }.execute();
    UIUtil.dispatchAllInvocationEvents();
    // reload data and check it is correct
    manifestInfo.clear();
    mergedActivities = manifestInfo.getActivities();
    assertEquals(4, mergedActivities.size());
    activities = Sets.newHashSet(ActivityLocatorUtils.getQualifiedName(mergedActivities.get(0)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(1)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(2)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(3)));
    assertTrue(activities.contains("test.helloworldapp.Debug"));
    assertTrue(activities.contains("test.helloworldapp.MyActivity"));
    assertTrue(activities.contains("test.helloworldapp.lib.LibActivity"));
    assertTrue(activities.contains("test.helloworldapp.AddedActivity"));
    // make a change to the psi
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    final Document document = documentManager.getDocument(psiFile);
    WriteCommandAction.runWriteCommandAction(null, new Runnable() {

        @Override
        public void run() {
            assertNotNull(document);
            int index = document.getText().indexOf("</application>");
            document.insertString(index, "<activity android:name=\".AddedActivity2\" />\n");
            documentManager.commitDocument(document);
        }
    });
    UIUtil.dispatchAllInvocationEvents();
    // reload data and check it is correct
    manifestInfo.clear();
    mergedActivities = manifestInfo.getActivities();
    assertEquals(5, mergedActivities.size());
    activities = Sets.newHashSet(ActivityLocatorUtils.getQualifiedName(mergedActivities.get(0)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(1)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(2)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(3)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(4)));
    assertTrue(activities.contains("test.helloworldapp.Debug"));
    assertTrue(activities.contains("test.helloworldapp.MyActivity"));
    assertTrue(activities.contains("test.helloworldapp.lib.LibActivity"));
    assertTrue(activities.contains("test.helloworldapp.AddedActivity"));
    assertTrue(activities.contains("test.helloworldapp.AddedActivity2"));
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Element(org.w3c.dom.Element) Document(com.intellij.openapi.editor.Document) Predicate(com.google.common.base.Predicate) PsiFile(com.intellij.psi.PsiFile) Nullable(org.jetbrains.annotations.Nullable) XmlTag(com.intellij.psi.xml.XmlTag) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 52 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project android by JetBrains.

the class ProjectResourceRepositoryTest method testInvalidateIds.

// Ensure that we invalidate the id cache when the file is rescanned but ids don't change
// (this was broken)
public void testInvalidateIds() {
    // Like testOverlayUpdates1, but rather than testing changes to layout resources (file-based resource)
    // perform document edits in value-documents
    VirtualFile layoutFile = myFixture.copyFileToProject(LAYOUT, "res/layout/layout1.xml");
    VirtualFile res1 = myFixture.copyFileToProject(VALUES, "res/values/values.xml").getParent().getParent();
    VirtualFile res2 = myFixture.copyFileToProject(VALUES_OVERLAY1, "res2/values/values.xml").getParent().getParent();
    VirtualFile res3 = myFixture.copyFileToProject(VALUES_OVERLAY2, "res3/values/nameDoesNotMatter.xml").getParent().getParent();
    myFixture.copyFileToProject(VALUES_OVERLAY2_NO, "res3/values-no/values.xml");
    assertNotSame(res1, res2);
    assertNotSame(res1, res3);
    assertNotSame(res2, res3);
    // Just need an empty repository to make it a real module -set-; otherwise with a single
    // module we just get a module repository, not a module set repository
    LocalResourceRepository other = new LocalResourceRepository("unit test") {

        @NonNull
        @Override
        protected Map<ResourceType, ListMultimap<String, ResourceItem>> getMap() {
            return Collections.emptyMap();
        }

        @Nullable
        @Override
        protected ListMultimap<String, ResourceItem> getMap(ResourceType type, boolean create) {
            return ArrayListMultimap.create();
        }

        @NotNull
        @Override
        protected Set<VirtualFile> computeResourceDirs() {
            return ImmutableSet.of();
        }
    };
    ModuleResourceRepository module = ModuleResourceRepository.createForTest(myFacet, Arrays.asList(res1, res2, res3));
    final ProjectResourceRepository resources = ProjectResourceRepository.createForTest(myFacet, Arrays.asList(module, other));
    PsiFile layoutPsiFile = PsiManager.getInstance(getProject()).findFile(layoutFile);
    assertNotNull(layoutPsiFile);
    assertTrue(resources.hasResourceItem(ResourceType.ID, "btn_title_refresh"));
    final ResourceItem item = getFirstItem(resources, ResourceType.ID, "btn_title_refresh");
    final long generation = resources.getModificationCount();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    final Document document = documentManager.getDocument(layoutPsiFile);
    assertNotNull(document);
    WriteCommandAction.runWriteCommandAction(null, () -> {
        String string = "<ImageView style=\"@style/TitleBarSeparator\" />";
        int offset = document.getText().indexOf(string);
        document.deleteString(offset, offset + string.length());
        documentManager.commitDocument(document);
    });
    assertTrue(resources.isScanPending(layoutPsiFile));
    ApplicationManager.getApplication().invokeLater(() -> {
        assertTrue(generation < resources.getModificationCount());
        // Should still be defined:
        assertTrue(resources.hasResourceItem(ResourceType.ID, "btn_title_refresh"));
        ResourceItem newItem = getFirstItem(resources, ResourceType.ID, "btn_title_refresh");
        assertNotNull(newItem.getSource());
        // However, should be a different item
        assertNotSame(item, newItem);
    });
    UIUtil.dispatchAllInvocationEvents();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ResourceType(com.android.resources.ResourceType) Document(com.intellij.openapi.editor.Document) PsiFile(com.intellij.psi.PsiFile) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) ListMultimap(com.google.common.collect.ListMultimap) ResourceItem(com.android.ide.common.res2.ResourceItem) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 53 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project android by JetBrains.

the class ResourceFolderRepositoryTest method testAddTypedArrayItemElements.

public void testAddTypedArrayItemElements() throws Exception {
    resetScanCounter();
    VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml");
    PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1);
    assertNotNull(psiFile1);
    ResourceFolderRepository resources = createRepository();
    assertNotNull(resources);
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    final Document document = documentManager.getDocument(psiFile1);
    assertNotNull(document);
    assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "my_colors"));
    ResourceItem array = getOnlyItem(resources, ResourceType.ARRAY, "my_colors");
    ResourceValue resourceValue = array.getResourceValue(false);
    assertNotNull(resourceValue);
    assertEquals("#FFFF0000", resourceValue.getValue());
    assertTrue(resourceValue instanceof ArrayResourceValue);
    ArrayResourceValue arv = (ArrayResourceValue) resourceValue;
    assertEquals(3, arv.getElementCount());
    assertEquals("#FFFF0000", arv.getElement(0));
    assertEquals("#FF00FF00", arv.getElement(1));
    assertEquals("#FF0000FF", arv.getElement(2));
    WriteCommandAction.runWriteCommandAction(null, new Runnable() {

        @Override
        public void run() {
            int offset = document.getText().indexOf("<item>#FFFF0000</item>");
            document.insertString(offset, "<item>#FFFFFF00</item>");
            documentManager.commitDocument(document);
        }
    });
    // First edit won't be incremental (file -> Psi).
    assertTrue(resources.isScanPending(psiFile1));
    UIUtil.dispatchAllInvocationEvents();
    assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "my_colors"));
    array = getOnlyItem(resources, ResourceType.ARRAY, "my_colors");
    resourceValue = array.getResourceValue(false);
    assertNotNull(resourceValue);
    assertEquals("#FFFFFF00", resourceValue.getValue());
    assertTrue(resourceValue instanceof ArrayResourceValue);
    arv = (ArrayResourceValue) resourceValue;
    assertEquals(4, arv.getElementCount());
    assertEquals("#FFFFFF00", arv.getElement(0));
    assertEquals("#FFFF0000", arv.getElement(1));
    assertEquals("#FF00FF00", arv.getElement(2));
    resetScanCounter();
    // Now try a second edit.
    WriteCommandAction.runWriteCommandAction(null, new Runnable() {

        @Override
        public void run() {
            int offset = document.getText().indexOf("<item>#FFFFFF00</item>");
            document.insertString(offset, "<item>#FFFFFFFF</item>");
            documentManager.commitDocument(document);
        }
    });
    assertTrue(resources.hasResourceItem(ResourceType.ARRAY, "my_colors"));
    array = getOnlyItem(resources, ResourceType.ARRAY, "my_colors");
    resourceValue = array.getResourceValue(false);
    assertNotNull(resourceValue);
    assertEquals("#FFFFFFFF", resourceValue.getValue());
    assertTrue(resourceValue instanceof ArrayResourceValue);
    arv = (ArrayResourceValue) resourceValue;
    assertEquals(5, arv.getElementCount());
    assertEquals("#FFFFFFFF", arv.getElement(0));
    assertEquals("#FFFFFF00", arv.getElement(1));
    assertEquals("#FFFF0000", arv.getElement(2));
    assertEquals("#FF00FF00", arv.getElement(3));
    // Shouldn't have done any full file rescans during the above edits
    ensureIncremental();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) Document(com.intellij.openapi.editor.Document) ResourceItem(com.android.ide.common.res2.ResourceItem) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 54 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project android by JetBrains.

the class ResourceFolderRepositoryTest method testLoadDuplicatedValues.

public void testLoadDuplicatedValues() throws Exception {
    resetScanCounter();
    // Test loading up a file that already illegally had duplicates.
    VirtualFile file1 = myFixture.copyFileToProject(VALUES_WITH_DUPES, "res/values/values.xml");
    PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1);
    assertNotNull(psiFile1);
    final ResourceFolderRepository resources = createRepository();
    assertNotNull(resources);
    assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name"));
    assertFalse(resources.hasResourceItem(ResourceType.STRING, "dupe_name"));
    //noinspection ConstantConditions
    assertEquals("Animations Demo", resources.getResourceItem(ResourceType.STRING, "app_name").get(0).getResourceValue(false).getValue());
    long generation = resources.getModificationCount();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    final Document document = documentManager.getDocument(psiFile1);
    assertNotNull(document);
    // Try editting one of the duplicated string contents, and check that
    // the copies are not tied together.
    WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {

        @Override
        public void run() {
            String origString = "<string name=\"app_name\">Animations Demo</string>";
            String newString = "<string name=\"dupe_name\">Duplicate Demo</string>";
            int offset = document.getText().indexOf(origString);
            document.replaceString(offset, offset + origString.length(), newString);
            documentManager.commitDocument(document);
        }
    });
    assertFalse(resources.isScanPending(psiFile1));
    assertTrue(generation < resources.getModificationCount());
    assertTrue(resources.hasResourceItem(ResourceType.STRING, "dupe_name"));
    assertTrue(resources.hasResourceItem(ResourceType.STRING, "app_name"));
    //noinspection ConstantConditions
    assertEquals("Duplicate Demo", resources.getResourceItem(ResourceType.STRING, "dupe_name").get(0).getResourceValue(false).getValue());
    //noinspection ConstantConditions
    assertEquals("Animations Demo", resources.getResourceItem(ResourceType.STRING, "app_name").get(0).getResourceValue(false).getValue());
    // Try editting something else, like the ID item.
    assertTrue(resources.hasResourceItem(ResourceType.ID, "action_next"));
    assertFalse(resources.hasResourceItem(ResourceType.ID, "action_prev"));
    WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {

        @Override
        public void run() {
            String origString = "<item type=\"id\" name=\"action_next\" />";
            String newString = "<item type=\"id\" name=\"action_prev\" />";
            int offset = document.getText().indexOf(origString);
            document.replaceString(offset, offset + origString.length(), newString);
            documentManager.commitDocument(document);
        }
    });
    assertTrue(resources.hasResourceItem(ResourceType.ID, "action_next"));
    assertTrue(resources.hasResourceItem(ResourceType.ID, "action_prev"));
    ensureIncremental();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) Document(com.intellij.openapi.editor.Document) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 55 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project android by JetBrains.

the class ResourceFolderRepositoryTest method testRenameValueFile.

public void testRenameValueFile() throws Exception {
    final VirtualFile file1 = myFixture.copyFileToProject(VALUES1, "res/values/myvalues.xml");
    PsiFile psiFile1 = PsiManager.getInstance(getProject()).findFile(file1);
    assertNotNull(psiFile1);
    ResourceFolderRepository resources = createRepository();
    assertNotNull(resources);
    assertTrue(resources.hasResourceItem(ResourceType.STRING, "title_template_step"));
    List<ResourceItem> items = resources.getResourceItem(ResourceType.STRING, "title_template_step");
    assertNotNull(items);
    assertEquals(1, items.size());
    ResourceItem item = items.get(0);
    assertEquals("myvalues.xml", item.getSource().getFile().getName());
    // We need to make sure there is a document. PsiVFSListener uses createFileCopyWithNewName
    // to populate the new Psi file with the old Psi file's content. However, by the time that runs,
    // the old file will already be physically moved to the new file. If it cannot find a cached
    // document for the old file, then it will make up an empty old Psi file and copy the empty content
    // to the new PsiFile.
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    Document document = documentManager.getDocument(psiFile1);
    assertNotNull(document);
    // Renaming a value file should have no visible effect
    WriteCommandAction.runWriteCommandAction(null, new Runnable() {

        @Override
        public void run() {
            try {
                file1.rename(this, "renamedvalues.xml");
            } catch (IOException e) {
                fail(e.toString());
            }
        }
    });
    assertTrue(resources.hasResourceItem(ResourceType.STRING, "title_template_step"));
    items = resources.getResourceItem(ResourceType.STRING, "title_template_step");
    assertNotNull(items);
    assertEquals(1, items.size());
    item = items.get(0);
    assertEquals("renamedvalues.xml", item.getSource().getFile().getName());
// TODO: Optimize this such that there's no modification change for this. It's tricky because
// for file names we get separate notification from the old file deletion (beforePropertyChanged)
// and the new file name (propertyChanged). (Note that I tried performing the rename via a
// setName operation on the PsiFile instead of at the raw VirtualFile level, but the resulting
// events were the same.)
//assertEquals(generation, resources.getModificationCount());
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) IOException(java.io.IOException) ResourceItem(com.android.ide.common.res2.ResourceItem) Document(com.intellij.openapi.editor.Document) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Aggregations

PsiDocumentManager (com.intellij.psi.PsiDocumentManager)140 Document (com.intellij.openapi.editor.Document)111 PsiFile (com.intellij.psi.PsiFile)100 VirtualFile (com.intellij.openapi.vfs.VirtualFile)51 ResourceItem (com.android.ide.common.res2.ResourceItem)26 PsiElement (com.intellij.psi.PsiElement)24 Project (com.intellij.openapi.project.Project)22 TextRange (com.intellij.openapi.util.TextRange)13 NotNull (org.jetbrains.annotations.NotNull)12 Nullable (org.jetbrains.annotations.Nullable)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)8 Editor (com.intellij.openapi.editor.Editor)7 XmlFile (com.intellij.psi.xml.XmlFile)6 FileType (com.intellij.openapi.fileTypes.FileType)5 XmlTag (com.intellij.psi.xml.XmlTag)5 ASTNode (com.intellij.lang.ASTNode)3 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)3 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)2 DocumentEx (com.intellij.openapi.editor.ex.DocumentEx)2 EditorEx (com.intellij.openapi.editor.ex.EditorEx)2