Search in sources :

Example 26 with FileType

use of com.intellij.openapi.fileTypes.FileType in project intellij-community by JetBrains.

the class FrameworkDetectionIndex method getIndexer.

@NotNull
@Override
public DataIndexer<Integer, Void, FileContent> getIndexer() {
    final MultiMap<FileType, Pair<ElementPattern<FileContent>, Integer>> detectors = new MultiMap<>();
    FrameworkDetectorRegistry registry = FrameworkDetectorRegistry.getInstance();
    for (FrameworkDetector detector : FrameworkDetector.EP_NAME.getExtensions()) {
        detectors.putValue(detector.getFileType(), Pair.create(detector.createSuitableFilePattern(), registry.getDetectorId(detector)));
    }
    return new DataIndexer<Integer, Void, FileContent>() {

        @NotNull
        @Override
        public Map<Integer, Void> map(@NotNull FileContent inputData) {
            final FileType fileType = inputData.getFileType();
            if (!detectors.containsKey(fileType)) {
                return Collections.emptyMap();
            }
            Map<Integer, Void> result = null;
            for (Pair<ElementPattern<FileContent>, Integer> pair : detectors.get(fileType)) {
                if (pair.getFirst().accepts(inputData)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(inputData.getFile() + " accepted by detector " + pair.getSecond());
                    }
                    if (result == null) {
                        result = new HashMap<>();
                    }
                    myDispatcher.getMulticaster().fileUpdated(inputData.getFile(), pair.getSecond());
                    result.put(pair.getSecond(), null);
                }
            }
            return result != null ? result : Collections.<Integer, Void>emptyMap();
        }
    };
}
Also used : FrameworkDetector(com.intellij.framework.detection.FrameworkDetector) ElementPattern(com.intellij.patterns.ElementPattern) NotNull(org.jetbrains.annotations.NotNull) MultiMap(com.intellij.util.containers.MultiMap) FileType(com.intellij.openapi.fileTypes.FileType) Pair(com.intellij.openapi.util.Pair) NotNull(org.jetbrains.annotations.NotNull)

Example 27 with FileType

use of com.intellij.openapi.fileTypes.FileType in project intellij-community by JetBrains.

the class FrameworkDetectionProcessor method collectSuitableFiles.

private void collectSuitableFiles(@NotNull VirtualFile file) {
    try {
        VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() {

            @Override
            public boolean visitFile(@NotNull VirtualFile file) {
                // Since this code is invoked from New Project Wizard it's very possible that VFS isn't loaded to memory yet, so we need to do it
                // manually, otherwise refresh will do nothing
                myProgressIndicator.checkCanceled();
                return true;
            }
        });
        file.refresh(false, true);
        VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() {

            @Override
            public boolean visitFile(@NotNull VirtualFile file) {
                myProgressIndicator.checkCanceled();
                if (!myProcessedFiles.add(file)) {
                    return false;
                }
                if (!file.isDirectory()) {
                    final FileType fileType = file.getFileType();
                    if (myDetectorsByFileType.containsKey(fileType)) {
                        myProgressIndicator.setText2(file.getPresentableUrl());
                        try {
                            final FileContent fileContent = new FileContentImpl(file, file.contentsToByteArray(false));
                            for (FrameworkDetectorData detector : myDetectorsByFileType.get(fileType)) {
                                if (detector.myFilePattern.accepts(fileContent)) {
                                    detector.mySuitableFiles.add(file);
                                }
                            }
                        } catch (IOException e) {
                            LOG.info(e);
                        }
                    }
                }
                return true;
            }
        });
    } catch (ProcessCanceledException ignored) {
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileContent(com.intellij.util.indexing.FileContent) FileType(com.intellij.openapi.fileTypes.FileType) FileContentImpl(com.intellij.util.indexing.FileContentImpl) IOException(java.io.IOException) VirtualFileVisitor(com.intellij.openapi.vfs.VirtualFileVisitor) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 28 with FileType

use of com.intellij.openapi.fileTypes.FileType in project intellij-community by JetBrains.

the class GotoFileAction method gotoActionPerformed.

@Override
public void gotoActionPerformed(AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    if (project == null)
        return;
    FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.popup.file");
    final GotoFileModel gotoFileModel = new GotoFileModel(project);
    GotoActionCallback<FileType> callback = new GotoActionCallback<FileType>() {

        @Override
        protected ChooseByNameFilter<FileType> createFilter(@NotNull ChooseByNamePopup popup) {
            return new GotoFileFilter(popup, gotoFileModel, project);
        }

        @Override
        public void elementChosen(final ChooseByNamePopup popup, final Object element) {
            if (element == null)
                return;
            ApplicationManager.getApplication().assertIsDispatchThread();
            Navigatable n = (Navigatable) element;
            //this is for better cursor position
            if (element instanceof PsiFile) {
                VirtualFile file = ((PsiFile) element).getVirtualFile();
                if (file == null)
                    return;
                OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file, popup.getLinePosition(), popup.getColumnPosition());
                n = descriptor.setUseCurrentWindow(popup.isOpenInCurrentWindowRequested());
            }
            if (n.canNavigate()) {
                n.navigate(true);
            }
        }
    };
    GotoFileItemProvider provider = new GotoFileItemProvider(project, getPsiContext(e), gotoFileModel);
    showNavigationPopup(e, gotoFileModel, callback, IdeBundle.message("go.to.file.toolwindow.title"), true, true, provider);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) NotNull(org.jetbrains.annotations.NotNull) Navigatable(com.intellij.pom.Navigatable) Project(com.intellij.openapi.project.Project) FileType(com.intellij.openapi.fileTypes.FileType) ChooseByNamePopup(com.intellij.ide.util.gotoByName.ChooseByNamePopup) GotoFileModel(com.intellij.ide.util.gotoByName.GotoFileModel) PsiFile(com.intellij.psi.PsiFile) OpenFileDescriptor(com.intellij.openapi.fileEditor.OpenFileDescriptor)

Example 29 with FileType

use of com.intellij.openapi.fileTypes.FileType in project intellij-community by JetBrains.

the class RootType method substituteIcon.

@Nullable
public Icon substituteIcon(@NotNull Project project, @NotNull VirtualFile file) {
    Language language = substituteLanguage(project, file);
    FileType fileType = LanguageUtil.getLanguageFileType(language);
    if (fileType == null)
        fileType = ScratchUtil.getFileTypeFromName(file);
    return fileType != null ? fileType.getIcon() : null;
}
Also used : Language(com.intellij.lang.Language) FileType(com.intellij.openapi.fileTypes.FileType) Nullable(org.jetbrains.annotations.Nullable)

Example 30 with FileType

use of com.intellij.openapi.fileTypes.FileType 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

FileType (com.intellij.openapi.fileTypes.FileType)198 VirtualFile (com.intellij.openapi.vfs.VirtualFile)60 NotNull (org.jetbrains.annotations.NotNull)38 Language (com.intellij.lang.Language)31 PsiFile (com.intellij.psi.PsiFile)31 LanguageFileType (com.intellij.openapi.fileTypes.LanguageFileType)30 Nullable (org.jetbrains.annotations.Nullable)28 Project (com.intellij.openapi.project.Project)27 Document (com.intellij.openapi.editor.Document)20 IncorrectOperationException (com.intellij.util.IncorrectOperationException)13 ArrayList (java.util.ArrayList)12 IOException (java.io.IOException)11 Editor (com.intellij.openapi.editor.Editor)10 HighlighterIterator (com.intellij.openapi.editor.highlighter.HighlighterIterator)10 CustomSyntaxTableFileType (com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType)10 PlainTextFileType (com.intellij.openapi.fileTypes.PlainTextFileType)9 UnknownFileType (com.intellij.openapi.fileTypes.UnknownFileType)9 BraceMatcher (com.intellij.codeInsight.highlighting.BraceMatcher)8 AbstractFileType (com.intellij.openapi.fileTypes.impl.AbstractFileType)8 PsiElement (com.intellij.psi.PsiElement)8