Search in sources :

Example 36 with FileDocumentManager

use of com.intellij.openapi.fileEditor.FileDocumentManager in project android by JetBrains.

the class LayoutPullParserFactory method saveFileIfNecessary.

public static void saveFileIfNecessary(PsiFile psiFile) {
    if (!needSave(ResourceHelper.getFolderType(psiFile.getVirtualFile()))) {
        // Avoid need for read lock in get parent
        return;
    }
    VirtualFile file = psiFile.getVirtualFile();
    if (file == null) {
        return;
    }
    final FileDocumentManager fileManager = FileDocumentManager.getInstance();
    if (!fileManager.isFileModified(file)) {
        return;
    }
    final com.intellij.openapi.editor.Document document;
    document = fileManager.getCachedDocument(file);
    if (document == null || !fileManager.isDocumentUnsaved(document)) {
        return;
    }
    Application application = ApplicationManager.getApplication();
    application.invokeAndWait(() -> application.runWriteAction(() -> fileManager.saveDocument(document)), ModalityState.any());
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) Application(com.intellij.openapi.application.Application)

Example 37 with FileDocumentManager

use of com.intellij.openapi.fileEditor.FileDocumentManager in project android by JetBrains.

the class ConfigurationMatcher method selectConfigMatch.

@NotNull
private ConfigMatch selectConfigMatch(@NotNull List<ConfigMatch> matches) {
    List<String> deviceIds = myManager.getStateManager().getProjectState().getDeviceIds();
    Map<String, Integer> idRank = Maps.newHashMapWithExpectedSize(deviceIds.size());
    int rank = 0;
    for (String id : deviceIds) {
        idRank.put(id, rank++);
    }
    // API 11-13: look for a x-large device
    Comparator<ConfigMatch> comparator = null;
    IAndroidTarget projectTarget = myManager.getProjectTarget();
    if (projectTarget != null) {
        int apiLevel = projectTarget.getVersion().getFeatureLevel();
        if (apiLevel >= 11 && apiLevel < 14) {
            // TODO: Maybe check the compatible-screen tag in the manifest to figure out
            // what kind of device should be used for display.
            comparator = new TabletConfigComparator(idRank);
        }
    }
    if (comparator == null) {
        // lets look for a high density device
        comparator = new PhoneConfigComparator(idRank);
    }
    Collections.sort(matches, comparator);
    // Look at the currently active editor to see if it's a layout editor, and if so,
    // look up its configuration and if the configuration is in our match list,
    // use it. This means we "preserve" the current configuration when you open
    // new layouts.
    // TODO: This is running too late for the layout preview; the new editor has
    // already taken over so getSelectedTextEditor() returns self. Perhaps we
    // need to fish in the open editors instead.
    // We use FileEditorManagerImpl instead of FileEditorManager to get access to the lock-free version
    // (also used by DebuggerContextUtil) since the normal method only works from the dispatch thread
    // (grabbing a read lock is not enough).
    FileEditorManager editorManager = FileEditorManager.getInstance(myManager.getProject());
    if (editorManager instanceof FileEditorManagerImpl) {
        // not the case under test fixtures apparently
        Editor activeEditor = ((FileEditorManagerImpl) editorManager).getSelectedTextEditor(true);
        if (activeEditor != null) {
            FileDocumentManager documentManager = FileDocumentManager.getInstance();
            VirtualFile file = documentManager.getFile(activeEditor.getDocument());
            if (file != null && !file.equals(myFile) && file.getFileType() == StdFileTypes.XML && ResourceHelper.getFolderType(myFile) == ResourceHelper.getFolderType(file)) {
                Configuration configuration = myManager.getConfiguration(file);
                FolderConfiguration fullConfig = configuration.getFullConfig();
                for (ConfigMatch match : matches) {
                    if (fullConfig.equals(match.testConfig)) {
                        return match;
                    }
                }
            }
        }
    }
    // the list has been sorted so that the first item is the best config
    return matches.get(0);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileEditorManagerImpl(com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) IAndroidTarget(com.android.sdklib.IAndroidTarget) FileEditorManager(com.intellij.openapi.fileEditor.FileEditorManager) Editor(com.intellij.openapi.editor.Editor) NotNull(org.jetbrains.annotations.NotNull)

Example 38 with FileDocumentManager

use of com.intellij.openapi.fileEditor.FileDocumentManager in project android by JetBrains.

the class GradleEditorModelUtil method buildSourceBinding.

@Nullable
public static GradleEditorSourceBinding buildSourceBinding(@NotNull Location location, @NotNull Project project) {
    FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
    Document document = fileDocumentManager.getDocument(location.file);
    if (document == null) {
        LOG.warn(String.format("Can't obtain a document for file %s for processing location '%s'", location.file, location));
        return null;
    }
    RangeMarker rangeMarker = document.createRangeMarker(location.range);
    return new GradleEditorSourceBinding(project, location.file, rangeMarker);
}
Also used : GradleEditorSourceBinding(com.android.tools.idea.gradle.editor.entity.GradleEditorSourceBinding) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) RangeMarker(com.intellij.openapi.editor.RangeMarker) Document(com.intellij.openapi.editor.Document) Nullable(org.jetbrains.annotations.Nullable)

Example 39 with FileDocumentManager

use of com.intellij.openapi.fileEditor.FileDocumentManager in project intellij-plugins by JetBrains.

the class DartAnalysisServerService method doUpdateFilesContent.

private void doUpdateFilesContent() {
    // may be use DocumentListener to collect deltas instead of sending the whole Document.getText() each time?
    AnalysisServer server = myServer;
    if (server == null) {
        return;
    }
    myUpdateFilesAlarm.cancelAllRequests();
    final Map<String, Object> filesToUpdate = new THashMap<>();
    ApplicationManager.getApplication().assertReadAccessAllowed();
    synchronized (myLock) {
        final Set<String> oldTrackedFiles = new THashSet<>(myFilePathWithOverlaidContentToTimestamp.keySet());
        final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
        // some documents in myChangedDocuments may be updated by external change, suxh as switch branch, that's why we track them,
        // getUnsavedDocuments() is not enough, we must make sure that overlaid content is sent for for myChangedDocuments as well (to trigger DAS notifications)
        final Set<Document> documents = new THashSet<>(myChangedDocuments);
        myChangedDocuments.clear();
        ContainerUtil.addAll(documents, fileDocumentManager.getUnsavedDocuments());
        for (Document document : documents) {
            final VirtualFile file = fileDocumentManager.getFile(document);
            if (isLocalAnalyzableFile(file)) {
                oldTrackedFiles.remove(file.getPath());
                final Long oldTimestamp = myFilePathWithOverlaidContentToTimestamp.get(file.getPath());
                if (oldTimestamp == null || document.getModificationStamp() != oldTimestamp) {
                    filesToUpdate.put(FileUtil.toSystemDependentName(file.getPath()), new AddContentOverlay(document.getText()));
                    myFilePathWithOverlaidContentToTimestamp.put(file.getPath(), document.getModificationStamp());
                }
            }
        }
        // oldTrackedFiles at this point contains only those files that are not in FileDocumentManager.getUnsavedDocuments() any more
        for (String oldPath : oldTrackedFiles) {
            final Long removed = myFilePathWithOverlaidContentToTimestamp.remove(oldPath);
            LOG.assertTrue(removed != null, oldPath);
            filesToUpdate.put(FileUtil.toSystemDependentName(oldPath), new RemoveContentOverlay());
        }
        if (LOG.isDebugEnabled()) {
            final Set<String> overlaid = new THashSet<>(filesToUpdate.keySet());
            for (String removeOverlaid : oldTrackedFiles) {
                overlaid.remove(FileUtil.toSystemDependentName(removeOverlaid));
            }
            if (!overlaid.isEmpty()) {
                LOG.debug("Sending overlaid content: " + StringUtil.join(overlaid, ",\n"));
            }
            if (!oldTrackedFiles.isEmpty()) {
                LOG.debug("Removing overlaid content: " + StringUtil.join(oldTrackedFiles, ",\n"));
            }
        }
    }
    if (!filesToUpdate.isEmpty()) {
        server.analysis_updateContent(filesToUpdate, myServerData::onFilesContentUpdated);
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) Document(com.intellij.openapi.editor.Document) THashSet(gnu.trove.THashSet) AnalysisServer(com.google.dart.server.generated.AnalysisServer) THashMap(gnu.trove.THashMap)

Example 40 with FileDocumentManager

use of com.intellij.openapi.fileEditor.FileDocumentManager in project intellij-plugins by JetBrains.

the class FlexCompilerConfigFileUtil method getNamespacesInfos.

public static Collection<NamespacesInfo> getNamespacesInfos(final VirtualFile configFile) {
    if (configFile == null || !configFile.isValid() || configFile.isDirectory()) {
        return Collections.emptyList();
    }
    Pair<Long, Collection<NamespacesInfo>> data = configFile.getUserData(MOD_STAMP_TO_NAMESPACES_INFOS);
    final FileDocumentManager documentManager = FileDocumentManager.getInstance();
    final Document cachedDocument = documentManager.getCachedDocument(configFile);
    final Long currentTimestamp = cachedDocument != null ? cachedDocument.getModificationStamp() : configFile.getModificationCount();
    final Long cachedTimestamp = data == null ? null : data.first;
    if (cachedTimestamp == null || !cachedTimestamp.equals(currentTimestamp)) {
        data = null;
        configFile.putUserData(MOD_STAMP_TO_NAMESPACES_INFOS, data);
        try {
            final NamespacesXmlBuilder builder = new NamespacesXmlBuilder();
            if (cachedDocument != null) {
                //noinspection IOResourceOpenedButNotSafelyClosed
                NanoXmlUtil.parse(new CharSequenceReader(cachedDocument.getCharsSequence()), builder);
            } else {
                NanoXmlUtil.parse(configFile.getInputStream(), builder);
            }
            final Collection<NamespacesInfo> namespacesInfos = new ArrayList<>();
            final Collection<String> includedInSwcNamespaces = builder.getIncludedNamespaces();
            for (Pair<String, String> namespaceAndManifest : builder.getNamespacesAndManifests()) {
                namespacesInfos.add(new NamespacesInfo(namespaceAndManifest.first, namespaceAndManifest.second, includedInSwcNamespaces.contains(namespaceAndManifest.first)));
            }
            data = Pair.create(currentTimestamp, namespacesInfos);
            configFile.putUserData(MOD_STAMP_TO_NAMESPACES_INFOS, data);
        } catch (IOException ignored) {
        }
    }
    return data == null ? Collections.emptyList() : data.second;
}
Also used : FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) IOException(java.io.IOException) Document(com.intellij.openapi.editor.Document) CharSequenceReader(com.intellij.util.text.CharSequenceReader)

Aggregations

FileDocumentManager (com.intellij.openapi.fileEditor.FileDocumentManager)63 Document (com.intellij.openapi.editor.Document)42 VirtualFile (com.intellij.openapi.vfs.VirtualFile)32 IOException (java.io.IOException)16 Editor (com.intellij.openapi.editor.Editor)10 Project (com.intellij.openapi.project.Project)9 LightVirtualFile (com.intellij.testFramework.LightVirtualFile)7 File (java.io.File)7 Nullable (org.jetbrains.annotations.Nullable)7 DiscordIntegrationProjectComponent (com.almightyalpaca.jetbrains.plugins.discord.components.DiscordIntegrationProjectComponent)5 MockVirtualFile (com.intellij.mock.MockVirtualFile)5 PsiFile (com.intellij.psi.PsiFile)5 IncorrectOperationException (com.intellij.util.IncorrectOperationException)4 TaskFile (com.jetbrains.edu.learning.courseFormat.TaskFile)4 NotNull (org.jetbrains.annotations.NotNull)4 AnswerPlaceholder (com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder)3 ArrayList (java.util.ArrayList)3 DataContext (com.intellij.openapi.actionSystem.DataContext)2 ActionManagerEx (com.intellij.openapi.actionSystem.ex.ActionManagerEx)2 Application (com.intellij.openapi.application.Application)2