Search in sources :

Example 46 with SmartList

use of com.intellij.util.SmartList in project intellij-plugins by JetBrains.

the class DartSdkLibUtil method enableDartSdkForSpecifiedModulesAndDisableForOthers.

public static void enableDartSdkForSpecifiedModulesAndDisableForOthers(@NotNull final Project project, @NotNull final Module[] modulesWithDart) {
    final List<ModifiableRootModel> modelsToCommit = new SmartList<>();
    for (final Module module : ModuleManager.getInstance(project).getModules()) {
        final boolean mustHaveDart = ArrayUtil.contains(module, modulesWithDart);
        boolean hasDart = false;
        final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();
        for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
            if (isDartSdkOrderEntry(orderEntry)) {
                hasDart = true;
                if (!mustHaveDart) {
                    modifiableModel.removeOrderEntry(orderEntry);
                }
            }
        }
        if (mustHaveDart && !hasDart) {
            modifiableModel.addInvalidLibrary(DartSdk.DART_SDK_LIB_NAME, LibraryTablesRegistrar.PROJECT_LEVEL);
        }
        if (modifiableModel.isChanged()) {
            modelsToCommit.add(modifiableModel);
        } else {
            modifiableModel.dispose();
        }
    }
    DartProjectComponent.commitModifiableModels(project, modelsToCommit);
}
Also used : SmartList(com.intellij.util.SmartList) Module(com.intellij.openapi.module.Module)

Example 47 with SmartList

use of com.intellij.util.SmartList in project intellij-plugins by JetBrains.

the class DartStringLiteralExpressionBase method filterOutReferencesInTemplatesOrInjected.

private PsiReference[] filterOutReferencesInTemplatesOrInjected(@NotNull final PsiReference[] references) {
    if (references.length == 0)
        return references;
    // String literal expression is a complex object that may contain injected HTML and regular Dart code (as a string template).
    // References in HTML and in Dart code are handled somewhere else, so if they occasionally appeared here we need to filter them out.
    final List<TextRange> forbiddenRanges = new SmartList<>();
    InjectedLanguageUtil.enumerate(this, (injectedPsi, places) -> {
        for (PsiLanguageInjectionHost.Shred place : places) {
            if (place.getHost() == this) {
                forbiddenRanges.add(place.getRangeInsideHost());
            }
        }
    });
    PsiElement child = getFirstChild();
    while (child != null) {
        final IElementType type = child.getNode().getElementType();
        if (type != DartTokenTypes.OPEN_QUOTE && type != DartTokenTypes.REGULAR_STRING_PART && type != DartTokenTypes.CLOSING_QUOTE && type != DartTokenTypes.RAW_SINGLE_QUOTED_STRING && type != DartTokenTypes.RAW_TRIPLE_QUOTED_STRING) {
            forbiddenRanges.add(child.getTextRange().shiftRight(-getTextRange().getStartOffset()));
        }
        child = child.getNextSibling();
    }
    final List<PsiReference> result = new ArrayList<>(references.length);
    outer: for (PsiReference reference : references) {
        for (TextRange forbiddenRange : forbiddenRanges) {
            if (reference.getRangeInElement().intersectsStrict(forbiddenRange))
                continue outer;
        }
        result.add(reference);
    }
    return result.toArray(PsiReference.EMPTY_ARRAY);
}
Also used : IElementType(com.intellij.psi.tree.IElementType) ArrayList(java.util.ArrayList) TextRange(com.intellij.openapi.util.TextRange) SmartList(com.intellij.util.SmartList)

Example 48 with SmartList

use of com.intellij.util.SmartList in project intellij-community by JetBrains.

the class PsiSearchHelperImpl method processFilesConcurrentlyDespiteWriteActions.

// Tries to run {@code localProcessor} for each file in {@code files} concurrently on ForkJoinPool.
// When encounters write action request, stops all threads, waits for write action to finish and re-starts all threads again.
// {@localProcessor} must be as idempotent as possible.
public static boolean processFilesConcurrentlyDespiteWriteActions(@NotNull Project project, @NotNull List<VirtualFile> files, @NotNull final ProgressIndicator progress, @NotNull final Processor<VirtualFile> localProcessor) {
    ApplicationEx app = (ApplicationEx) ApplicationManager.getApplication();
    final AtomicBoolean canceled = new AtomicBoolean(false);
    while (true) {
        List<VirtualFile> failedList = new SmartList<>();
        final List<VirtualFile> failedFiles = Collections.synchronizedList(failedList);
        final Processor<VirtualFile> processor = vfile -> {
            try {
                boolean result = localProcessor.process(vfile);
                if (!result) {
                    canceled.set(true);
                }
                return result;
            } catch (ApplicationUtil.CannotRunReadActionException action) {
                failedFiles.add(vfile);
            }
            return !canceled.get();
        };
        boolean completed;
        if (app.isWriteAccessAllowed() || app.isReadAccessAllowed() && app.isWriteActionPending()) {
            // no point in processing in separate threads - they are doomed to fail to obtain read action anyway
            completed = ContainerUtil.process(files, processor);
        } else if (app.isWriteActionPending()) {
            completed = true;
            // we don't have read action now so wait for write action to complete
            failedFiles.addAll(files);
        } else {
            // try to run parallel read actions but fail as soon as possible
            completed = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(files, progress, false, true, processor);
        }
        if (!completed) {
            return false;
        }
        if (failedFiles.isEmpty()) {
            break;
        }
        // we failed to run read action in job launcher thread
        // run read action in our thread instead to wait for a write action to complete and resume parallel processing
        DumbService.getInstance(project).runReadActionInSmartMode(EmptyRunnable.getInstance());
        files = failedList;
    }
    return true;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) com.intellij.openapi.util(com.intellij.openapi.util) java.util(java.util) CommentUtilCore(com.intellij.util.codeInsight.CommentUtilCore) JobLauncher(com.intellij.concurrency.JobLauncher) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ApplicationUtil(com.intellij.openapi.application.ex.ApplicationUtil) PsiManagerEx(com.intellij.psi.impl.PsiManagerEx) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) UsageInfo(com.intellij.usageView.UsageInfo) THashSet(gnu.trove.THashSet) ContainerUtil(com.intellij.util.containers.ContainerUtil) THashMap(gnu.trove.THashMap) ReadAction(com.intellij.openapi.application.ReadAction) ApplicationEx(com.intellij.openapi.application.ex.ApplicationEx) StringSearcher(com.intellij.util.text.StringSearcher) ReadActionProcessor(com.intellij.openapi.application.ReadActionProcessor) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) TooManyUsagesStatus(com.intellij.openapi.progress.util.TooManyUsagesStatus) SmartList(com.intellij.util.SmartList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheManager(com.intellij.psi.impl.cache.CacheManager) Project(com.intellij.openapi.project.Project) FileIndexFacade(com.intellij.openapi.roots.FileIndexFacade) Logger(com.intellij.openapi.diagnostic.Logger) MultiMap(com.intellij.util.containers.MultiMap) FileBasedIndex(com.intellij.util.indexing.FileBasedIndex) DumbService(com.intellij.openapi.project.DumbService) StringUtil(com.intellij.openapi.util.text.StringUtil) Processors(com.intellij.util.Processors) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) IOException(java.io.IOException) IdIndexEntry(com.intellij.psi.impl.cache.impl.id.IdIndexEntry) ProgressIndicatorProvider(com.intellij.openapi.progress.ProgressIndicatorProvider) ExtensionPointName(com.intellij.openapi.extensions.ExtensionPointName) AsyncFuture(com.intellij.concurrency.AsyncFuture) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) com.intellij.psi.search(com.intellij.psi.search) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) IdIndex(com.intellij.psi.impl.cache.impl.id.IdIndex) com.intellij.psi(com.intellij.psi) UsageInfoFactory(com.intellij.usageView.UsageInfoFactory) AsyncUtil(com.intellij.concurrency.AsyncUtil) NotNull(org.jetbrains.annotations.NotNull) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ApplicationEx(com.intellij.openapi.application.ex.ApplicationEx) SmartList(com.intellij.util.SmartList)

Example 49 with SmartList

use of com.intellij.util.SmartList in project intellij-community by JetBrains.

the class EditorTracker method editorsByWindow.

@NotNull
private List<Editor> editorsByWindow(Window window) {
    List<Editor> list = myWindowToEditorsMap.get(window);
    if (list == null)
        return Collections.emptyList();
    List<Editor> filtered = new SmartList<>();
    for (Editor editor : list) {
        if (editor.getContentComponent().isShowing()) {
            filtered.add(editor);
        }
    }
    return filtered;
}
Also used : Editor(com.intellij.openapi.editor.Editor) SmartList(com.intellij.util.SmartList) NotNull(org.jetbrains.annotations.NotNull)

Example 50 with SmartList

use of com.intellij.util.SmartList in project intellij-community by JetBrains.

the class TemplateModuleBuilder method unzip.

private void unzip(@Nullable final String projectName, String path, final boolean moduleMode, @Nullable ProgressIndicator pI, boolean reportFailuresWithDialog) {
    final WizardInputField basePackage = getBasePackageField();
    try {
        final File dir = new File(path);
        class ExceptionConsumer implements Consumer<VelocityException> {

            private String myPath;

            private String myText;

            private SmartList<Trinity<String, String, VelocityException>> myFailures = new SmartList<>();

            @Override
            public void consume(VelocityException e) {
                myFailures.add(Trinity.create(myPath, myText, e));
            }

            private void setCurrentFile(String path, String text) {
                myPath = path;
                myText = text;
            }

            private void reportFailures() {
                if (myFailures.isEmpty()) {
                    return;
                }
                if (reportFailuresWithDialog) {
                    String dialogMessage;
                    if (myFailures.size() == 1) {
                        dialogMessage = "Failed to decode file \'" + myFailures.get(0).getFirst() + "\'";
                    } else {
                        StringBuilder dialogMessageBuilder = new StringBuilder();
                        dialogMessageBuilder.append("Failed to decode files: \n");
                        for (Trinity<String, String, VelocityException> failure : myFailures) {
                            dialogMessageBuilder.append(failure.getFirst()).append("\n");
                        }
                        dialogMessage = dialogMessageBuilder.toString();
                    }
                    Messages.showErrorDialog(dialogMessage, "Decoding Template");
                }
                StringBuilder reportBuilder = new StringBuilder();
                for (Trinity<String, String, VelocityException> failure : myFailures) {
                    reportBuilder.append("File: ").append(failure.getFirst()).append("\n");
                    reportBuilder.append("Exception:\n").append(ExceptionUtil.getThrowableText(failure.getThird())).append("\n");
                    reportBuilder.append("File content:\n\'").append(failure.getSecond()).append("\'\n");
                    reportBuilder.append("\n===========================================\n");
                }
                LOG.error(LogMessageEx.createEvent("Cannot decode files in template", "", new Attachment("Files in template", reportBuilder.toString())));
            }
        }
        ExceptionConsumer consumer = new ExceptionConsumer();
        List<File> filesToRefresh = new ArrayList<>();
        myTemplate.processStream(new ArchivedProjectTemplate.StreamProcessor<Void>() {

            @Override
            public Void consume(@NotNull ZipInputStream stream) throws IOException {
                ZipUtil.unzip(ProgressManager.getInstance().getProgressIndicator(), dir, stream, path1 -> {
                    if (moduleMode && path1.contains(Project.DIRECTORY_STORE_FOLDER)) {
                        return null;
                    }
                    if (basePackage != null) {
                        return path1.replace(getPathFragment(basePackage.getDefaultValue()), getPathFragment(basePackage.getValue()));
                    }
                    return path1;
                }, new ZipUtil.ContentProcessor() {

                    @Override
                    public byte[] processContent(byte[] content, File file) throws IOException {
                        if (pI != null) {
                            pI.checkCanceled();
                        }
                        FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(FileUtilRt.getExtension(file.getName()));
                        String text = new String(content, CharsetToolkit.UTF8_CHARSET);
                        consumer.setCurrentFile(file.getName(), text);
                        return fileType.isBinary() ? content : processTemplates(projectName, text, file, consumer);
                    }
                }, true);
                myTemplate.handleUnzippedDirectories(dir, filesToRefresh);
                return null;
            }
        });
        if (pI != null) {
            pI.setText("Refreshing...");
        }
        String iml = ContainerUtil.find(dir.list(), s -> s.endsWith(".iml"));
        if (moduleMode) {
            File from = new File(path, iml);
            File to = new File(getModuleFilePath());
            if (!from.renameTo(to)) {
                throw new IOException("Can't rename " + from + " to " + to);
            }
        }
        RefreshQueue refreshQueue = RefreshQueue.getInstance();
        LOG.assertTrue(!filesToRefresh.isEmpty());
        for (File file : filesToRefresh) {
            VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
            if (virtualFile == null) {
                throw new IOException("Can't find " + file);
            }
            refreshQueue.refresh(false, true, null, virtualFile);
        }
        consumer.reportFailures();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : FileUtilRt(com.intellij.openapi.util.io.FileUtilRt) Trinity(com.intellij.openapi.util.Trinity) com.intellij.openapi.module(com.intellij.openapi.module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) JDOMException(org.jdom.JDOMException) SmartList(com.intellij.util.SmartList) ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) CodeStyleFacade(com.intellij.codeStyle.CodeStyleFacade) Messages(com.intellij.openapi.ui.Messages) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) VelocityException(org.apache.velocity.exception.VelocityException) ProgressManager(com.intellij.openapi.progress.ProgressManager) FileTypeManager(com.intellij.openapi.fileTypes.FileTypeManager) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) PathMacroUtil(org.jetbrains.jps.model.serialization.PathMacroUtil) com.intellij.ide.util.projectWizard(com.intellij.ide.util.projectWizard) Nullable(org.jetbrains.annotations.Nullable) LogMessageEx(com.intellij.diagnostic.LogMessageEx) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) ApplicationManager(com.intellij.openapi.application.ApplicationManager) ModulesProvider(com.intellij.openapi.roots.ui.configuration.ModulesProvider) ConfigurationException(com.intellij.openapi.options.ConfigurationException) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) RunConfiguration(com.intellij.execution.configurations.RunConfiguration) WriteAction(com.intellij.openapi.application.WriteAction) ZipInputStream(java.util.zip.ZipInputStream) CharsetToolkit(com.intellij.openapi.vfs.CharsetToolkit) Computable(com.intellij.openapi.util.Computable) InvalidDataException(com.intellij.openapi.util.InvalidDataException) ContainerUtil(com.intellij.util.containers.ContainerUtil) ModuleBasedConfiguration(com.intellij.execution.configurations.ModuleBasedConfiguration) ArrayList(java.util.ArrayList) RefreshQueue(com.intellij.openapi.vfs.newvfs.RefreshQueue) StartupManager(com.intellij.openapi.startup.StartupManager) RunManager(com.intellij.execution.RunManager) Project(com.intellij.openapi.project.Project) Properties(java.util.Properties) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) ProjectManagerEx(com.intellij.openapi.project.ex.ProjectManagerEx) ZipUtil(com.intellij.platform.templates.github.ZipUtil) IOException(java.io.IOException) FileType(com.intellij.openapi.fileTypes.FileType) File(java.io.File) StringUtilRt(com.intellij.openapi.util.text.StringUtilRt) ExceptionUtil(com.intellij.util.ExceptionUtil) FileTemplateUtil(com.intellij.ide.fileTemplates.FileTemplateUtil) Attachment(com.intellij.openapi.diagnostic.Attachment) javax.swing(javax.swing) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ArrayList(java.util.ArrayList) Attachment(com.intellij.openapi.diagnostic.Attachment) RefreshQueue(com.intellij.openapi.vfs.newvfs.RefreshQueue) Consumer(com.intellij.util.Consumer) VelocityException(org.apache.velocity.exception.VelocityException) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) FileType(com.intellij.openapi.fileTypes.FileType) SmartList(com.intellij.util.SmartList) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Aggregations

SmartList (com.intellij.util.SmartList)163 NotNull (org.jetbrains.annotations.NotNull)70 Nullable (org.jetbrains.annotations.Nullable)25 VirtualFile (com.intellij.openapi.vfs.VirtualFile)24 Module (com.intellij.openapi.module.Module)15 Project (com.intellij.openapi.project.Project)14 TextRange (com.intellij.openapi.util.TextRange)12 PsiElement (com.intellij.psi.PsiElement)12 List (java.util.List)12 Element (org.jdom.Element)12 File (java.io.File)11 THashSet (gnu.trove.THashSet)9 ContainerUtil (com.intellij.util.containers.ContainerUtil)8 ArrayList (java.util.ArrayList)8 Collection (java.util.Collection)8 Pair (com.intellij.openapi.util.Pair)7 PsiFile (com.intellij.psi.PsiFile)6 IOException (java.io.IOException)6 PropertiesFile (com.intellij.lang.properties.psi.PropertiesFile)5 IElementType (com.intellij.psi.tree.IElementType)5