Java Code Examples for com.intellij.openapi.fileTypes.FileTypeManager

The following examples show how to use com.intellij.openapi.fileTypes.FileTypeManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void initialize() {
    Map<String, LanguageServerDefinition> servers = new HashMap<>();
    List<ContentTypeMapping> contentTypes = new ArrayList<>();
    for (ServerExtensionPointBean server : ServerExtensionPointBean.EP_NAME.getExtensions()) {
        if (server.id != null && !server.id.isEmpty()) {
            servers.put(server.id, new ExtensionLanguageServerDefinition(server));
        }
    }
    for (ContentTypeMappingExtensionPointBean extension : ContentTypeMappingExtensionPointBean.EP_NAME.getExtensions()) {
        FileType contentType = FileTypeManager.getInstance().findFileTypeByName(extension.contenType);
        if (contentType != null) {
            contentTypes.add(new ContentTypeMapping(contentType, extension.id, extension.languageId));
        }
    }


    for (ContentTypeMapping mapping : contentTypes) {
        LanguageServerDefinition lsDefinition = servers.get(mapping.languageId);
        if (lsDefinition != null) {
            registerAssociation(mapping.contentType, lsDefinition, mapping.languageId);
        } else {
            LOGGER.warn("server '" + mapping.id + "' not available"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
}
 
Example 2
@NotNull
List<VirtualFile> suggestOCamlRoots(@NotNull VirtualFile dir, @NotNull final ProgressIndicator progressIndicator) {
    if (!dir.isDirectory()) {
        return ContainerUtil.emptyList();
    }

    final FileTypeManager typeManager = FileTypeManager.getInstance();
    final ArrayList<VirtualFile> foundDirectories = new ArrayList<>();
    try {
        VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor() {
            @NotNull
            @Override
            public Result visitFileEx(@NotNull VirtualFile file) {
                progressIndicator.checkCanceled();

                if (!file.isDirectory()) {
                    FileType type = typeManager.getFileTypeByFileName(file.getName());

                    if (type.getDefaultExtension().equals("ml")) {
                        VirtualFile root = file.getParent();
                        if (root != null) {
                            foundDirectories.add(root);
                            return skipTo(root);
                        }
                    }
                }

                return CONTINUE;
            }
        });
    } catch (ProcessCanceledException ignore) {
    }

    return foundDirectories;
}
 
Example 3
Source Project: idea-php-typo3-plugin   Source File: XLFFileTypeListener.java    License: MIT License 6 votes vote down vote up
@Override
public void projectOpened(@NotNull Project project) {
    if (!(FileTypeManager.getInstance().getFileTypeByExtension("xlf") instanceof XmlFileType)) {
        WriteCommandAction.runWriteCommandAction(ProjectManager.getInstance().getOpenProjects()[0], () -> {
            FileTypeManager.getInstance().associateExtension(XmlFileType.INSTANCE, "xlf");

            ApplicationManager.getApplication().invokeLater(() -> {
                Notification notification = GROUP_DISPLAY_ID_INFO.createNotification(
                    "TYPO3 CMS Plugin",
                    "XLF File Type Association",
                    "The XLF File Type was re-assigned to XML to prevent errors with the XLIFF Plugin and allow autocompletion. Please re-index your projects.",
                    NotificationType.INFORMATION
                );
                Project[] projects = ProjectManager.getInstance().getOpenProjects();
                Notifications.Bus.notify(notification, projects[0]);
            });
        });
    }
}
 
Example 4
Source Project: intellij   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void createMockApplication(Disposable parentDisposable) {
  final BlazeMockApplication instance = new BlazeMockApplication(parentDisposable);

  // If there was no previous application,
  // ApplicationManager leaves the MockApplication in place, which can break future tests.
  Application oldApplication = ApplicationManager.getApplication();
  if (oldApplication == null) {
    Disposer.register(
        parentDisposable,
        () -> {
          new ApplicationManager() {
            {
              ourApplication = null;
            }
          };
        });
  }

  ApplicationManager.setApplication(instance, FileTypeManager::getInstance, parentDisposable);
  instance.registerService(EncodingManager.class, EncodingManagerImpl.class);
}
 
Example 5
Source Project: intellij   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
static void createMockApplication(Disposable parentDisposable) {
  final MyMockApplication instance = new MyMockApplication(parentDisposable);

  // If there was no previous application, ApplicationManager leaves the MockApplication in place,
  // which can break future tests.
  Application oldApplication = ApplicationManager.getApplication();
  if (oldApplication == null) {
    Disposer.register(
        parentDisposable,
        () ->
            new ApplicationManager() {
              {
                ourApplication = null;
              }
            });
  }

  ApplicationManager.setApplication(instance, FileTypeManager::getInstance, parentDisposable);
  instance.registerService(EncodingManager.class, EncodingManagerImpl.class);
}
 
Example 6
public HaxeExpressionCodeFragmentImpl(Project project,
                                      @NonNls String name,
                                      CharSequence text,
                                      boolean isPhysical) {
  super(new SingleRootFileViewProvider(PsiManager.getInstance(project),
                                       new LightVirtualFile(name, FileTypeManager.getInstance().getFileTypeByFileName(name), text),
                                       isPhysical) {
    @Override
    public boolean supportsIncrementalReparse(@NotNull Language rootLanguage) {
      return false;
    }
  });

  myPhysical = isPhysical;
  ((SingleRootFileViewProvider)getViewProvider()).forceCachedPsi(this);
  final MyHaxeFileElementType type = new MyHaxeFileElementType();
  init(type, type);
}
 
Example 7
Source Project: consulo   Source File: FileTemplateManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public FileTemplateManagerImpl(@Nonnull FileTypeManager typeManager,
                               FileTemplateSettings projectSettings,
                               ExportableFileTemplateSettings defaultSettings,
                               ProjectManager pm,
                               final Project project) {
  myTypeManager = (FileTypeManagerEx)typeManager;
  myProjectSettings = projectSettings;
  myDefaultSettings = defaultSettings;
  myProject = project;

  myProjectScheme = project.isDefault() ? null : new FileTemplatesScheme("Project") {
    @Nonnull
    @Override
    public String getTemplatesDir() {
      return FileUtilRt.toSystemDependentName(StorageUtil.getStoreDir(project) + "/" + TEMPLATES_DIR);
    }

    @Nonnull
    @Override
    public Project getProject() {
      return project;
    }
  };
}
 
Example 8
Source Project: consulo   Source File: ErrorDiffTool.java    License: Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Nonnull
@Override
public ToolbarComponents init() {
  if (myRequest instanceof UnknownFileTypeDiffRequest) {
    String fileName = ((UnknownFileTypeDiffRequest)myRequest).getFileName();
    if (fileName != null && FileTypeManager.getInstance().getFileTypeByFileName(fileName) != UnknownFileType.INSTANCE) {
      // FileType was assigned elsewhere (ex: by other UnknownFileTypeDiffRequest). We should reload request.
      if (myContext instanceof DiffContextEx) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            ((DiffContextEx)myContext).reloadDiffRequest();
          }
        }, ModalityState.current());
      }
    }
  }

  return new ToolbarComponents();
}
 
Example 9
Source Project: consulo   Source File: CodeInsightTestFixtureImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PsiFile configureByText(final FileType fileType, @NonNls final String text) {
  assertInitialized();
  final String extension = fileType.getDefaultExtension();
  final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
  if (fileTypeManager.getFileTypeByExtension(extension) != fileType) {
    new WriteCommandAction(getProject()) {
      @Override
      protected void run(Result result) throws Exception {
        fileTypeManager.associateExtension(fileType, extension);
      }
    }.execute();
  }
  final String fileName = "aaa." + extension;
  return configureByText(fileName, text);
}
 
Example 10
Source Project: consulo   Source File: IdeaGateway.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isVersioned(@Nonnull VirtualFile f, boolean shouldBeInContent) {
  if (!f.isInLocalFileSystem()) return false;

  if (!f.isDirectory() && StringUtil.endsWith(f.getNameSequence(), ".class")) return false;

  VersionedFilterData versionedFilterData = getVersionedFilterData();

  boolean isInContent = false;
  int numberOfOpenProjects = versionedFilterData.myOpenedProjects.size();
  for (int i = 0; i < numberOfOpenProjects; ++i) {
    if (f.equals(versionedFilterData.myWorkspaceFiles.get(i))) return false;
    ProjectFileIndex index = versionedFilterData.myProjectFileIndices.get(i);

    if (index.isExcluded(f)) return false;
    isInContent |= index.isInContent(f);
  }
  if (shouldBeInContent && !isInContent) return false;

  // optimisation: FileTypeManager.isFileIgnored(f) already checked inside ProjectFileIndex.isIgnored()
  return numberOfOpenProjects != 0 || !FileTypeManager.getInstance().isFileIgnored(f);
}
 
Example 11
Source Project: consulo   Source File: RemovedMappingTracker.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
static List<RemovedMapping> readRemovedMappings(@Nonnull Element e) {
  List<Element> children = e.getChildren(ELEMENT_REMOVED_MAPPING);
  if (children.isEmpty()) {
    return Collections.emptyList();
  }

  List<RemovedMapping> result = new ArrayList<>();
  for (Element mapping : children) {
    String ext = mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_EXT);
    FileNameMatcher matcher = ext == null ? FileTypeManager.parseFromString(mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_PATTERN)) : new ExtensionFileNameMatcher(ext);
    boolean approved = Boolean.parseBoolean(mapping.getAttributeValue(ATTRIBUTE_APPROVED));
    String fileTypeName = mapping.getAttributeValue(ATTRIBUTE_TYPE);
    if (fileTypeName == null) continue;

    RemovedMapping removedMapping = new RemovedMapping(matcher, fileTypeName, approved);
    result.add(removedMapping);
  }
  return result;
}
 
Example 12
Source Project: consulo   Source File: EditorHighlighterUpdater.java    License: Apache License 2.0 6 votes vote down vote up
public EditorHighlighterUpdater(@Nonnull Project project, @Nonnull Disposable parentDisposable, @Nonnull EditorEx editor, @Nullable VirtualFile file) {
  myProject = project;
  myEditor = editor;
  myFile = file;
  MessageBusConnection connection = project.getMessageBus().connect(parentDisposable);
  connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());
  connection.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {
    @Override
    public void enteredDumbMode() {
      updateHighlighters();
    }

    @Override
    public void exitDumbMode() {
      updateHighlighters();
    }
  });
}
 
Example 13
Source Project: consulo   Source File: TextEditorComponent.java    License: Apache License 2.0 6 votes vote down vote up
public TextEditorComponent(@Nonnull final Project project, @Nonnull final VirtualFile file, @Nonnull final DesktopTextEditorImpl textEditor) {
  super(new BorderLayout(), textEditor);

  myProject = project;
  myFile = file;
  myTextEditor = textEditor;

  myDocument = FileDocumentManager.getInstance().getDocument(myFile);
  LOG.assertTrue(myDocument != null);
  myDocument.addDocumentListener(new MyDocumentListener(), this);

  myEditor = createEditor();
  add(myEditor.getComponent(), BorderLayout.CENTER);
  myModified = isModifiedImpl();
  myValid = isEditorValidImpl();
  LOG.assertTrue(myValid);

  MyVirtualFileListener myVirtualFileListener = new MyVirtualFileListener();
  myFile.getFileSystem().addVirtualFileListener(myVirtualFileListener);
  Disposer.register(this, () -> myFile.getFileSystem().removeVirtualFileListener(myVirtualFileListener));
  MessageBusConnection myConnection = project.getMessageBus().connect(this);
  myConnection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());

  myEditorHighlighterUpdater = new EditorHighlighterUpdater(myProject, this, (EditorEx)myEditor, myFile);
}
 
Example 14
Source Project: consulo   Source File: AssociateFileType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  Presentation presentation = e.getPresentation();
  VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE);
  Project project = e.getData(CommonDataKeys.PROJECT);
  boolean haveSmthToDo;
  if (project == null || file == null || file.isDirectory()) {
    haveSmthToDo = false;
  }
  else {
    // the action should also be available for files which have been auto-detected as text or as a particular language (IDEA-79574)
    haveSmthToDo = FileTypeManager.getInstance().getFileTypeByFileName(file.getName()) == UnknownFileType.INSTANCE;
  }
  presentation.setVisible(haveSmthToDo || ActionPlaces.MAIN_MENU.equals(e.getPlace()));
  presentation.setEnabled(haveSmthToDo);
}
 
Example 15
Source Project: consulo   Source File: UpdatingChangeListBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void processChangeInList(final Change change, @Nullable final ChangeList changeList, final VcsKey vcsKey) {
  checkIfDisposed();

  LOG.debug("[processChangeInList-1] entering, cl name: " + ((changeList == null) ? null : changeList.getName()) +
            " change: " + ChangesUtil.getFilePath(change).getPath());
  final String fileName = ChangesUtil.getFilePath(change).getName();
  if (FileTypeManager.getInstance().isFileIgnored(fileName)) {
    LOG.debug("[processChangeInList-1] file type ignored");
    return;
  }

  if (ChangeListManagerImpl.isUnder(change, myScope)) {
    if (changeList != null) {
      LOG.debug("[processChangeInList-1] to add change to cl");
      myChangeListWorker.addChangeToList(changeList.getName(), change, vcsKey);
    }
    else {
      LOG.debug("[processChangeInList-1] to add to corresponding list");
      myChangeListWorker.addChangeToCorrespondingList(change, vcsKey);
    }
  }
  else {
    LOG.debug("[processChangeInList-1] not under scope");
  }
}
 
Example 16
Source Project: consulo   Source File: CopyrightFormattingConfigurable.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Configurable[] buildConfigurables() {
  getOrCreateMainPanel();
  FileType[] registeredFileTypes = FileTypeManager.getInstance().getRegisteredFileTypes();
  List<Configurable> list = new ArrayList<>();
  for (FileType fileType : registeredFileTypes) {
    UpdateCopyrightsProvider updateCopyrightsProvider = CopyrightUpdaters.INSTANCE.forFileType(fileType);
    if (updateCopyrightsProvider == null) {
      continue;
    }
    list.add(updateCopyrightsProvider.createConfigurable(myProject, myPanel, fileType));
  }
  Collections.sort(list, (o1, o2) -> o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()));

  return ContainerUtil.toArray(list, Configurable.ARRAY_FACTORY);
}
 
Example 17
Source Project: consulo   Source File: BreadcrumbsInitializingActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void runActivity(@Nonnull Project project) {
  if (project.isDefault() || ApplicationManager.getApplication().isUnitTestMode() || project.isDisposed()) {
    return;
  }

  MessageBusConnection connection = project.getMessageBus().connect();
  connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MyFileEditorManagerListener());
  connection.subscribe(FileTypeManager.TOPIC, new FileTypeListener() {
    @Override
    public void fileTypesChanged(@Nonnull FileTypeEvent event) {
      reinitBreadcrumbsInAllEditors(project);
    }
  });

  VirtualFileManager.getInstance().addVirtualFileListener(new MyVirtualFileListener(project), project);
  connection.subscribe(UISettingsListener.TOPIC, uiSettings -> reinitBreadcrumbsInAllEditors(project));

  UIUtil.invokeLaterIfNeeded(() -> reinitBreadcrumbsInAllEditors(project));
}
 
Example 18
Source Project: EasyCode   Source File: SaveFile.java    License: MIT License 5 votes vote down vote up
/**
 * 构建对象
 *
 * @param path     路径
 * @param fileName 文件没
 * @param reformat 是否重新格式化代码
 */
public SaveFile(Project project, String path, String fileName, String content, boolean reformat, boolean operateTitle) {
    this.path = path;
    this.project = project;
    // 构建文件对象
    PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);
    LOG.assertTrue(content != null);
    FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
    // 换行符统一使用\n
    this.file = psiFileFactory.createFileFromText(fileName, fileType, content.replace("\r", ""));
    this.virtualFile = new LightVirtualFile(fileName, fileType, content.replace("\r", ""));
    this.reformat = reformat;
    this.operateTitle = operateTitle;
}
 
Example 19
Source Project: SmartIM4IntelliJ   Source File: VFSUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static FileType getArchiveFileType() {
    FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(".zip");
    if (fileType == FileTypeManager.getInstance().getFileTypeByExtension(".kokoko")) {
        fileType = FileTypeManager.getInstance().getFileTypeByExtension("zip");
    }
    return fileType;
}
 
Example 20
Source Project: reasonml-idea-plugin   Source File: JsInjector.java    License: MIT License 5 votes vote down vote up
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
                                 @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
    if (host instanceof PsiRawBody) {
        FileType jsFileType = FileTypeManager.getInstance().getFileTypeByExtension("js");
        if (jsFileType instanceof LanguageFileType) {
            Language jsLanguage = ((LanguageFileType) jsFileType).getLanguage();
            PsiRawBody macroHost = (PsiRawBody) host;
            TextRange macroTextRange = macroHost.getMacroTextRange();
            injectionPlacesRegistrar.addPlace(jsLanguage, macroTextRange, null, null);
        }
    }
}
 
Example 21
Source Project: code-generator   Source File: TemplateEditForm.java    License: Apache License 2.0 5 votes vote down vote up
private void initEditor(String template) {
    EditorFactory factory = EditorFactory.getInstance();
    Document velocityTemplate = factory.createDocument(template);
    editor = factory.createEditor(velocityTemplate, null, FileTypeManager.getInstance()
        .getFileTypeByExtension("vm"), false);
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.fill = GridBagConstraints.BOTH;
    constraints.weightx = 1;
    constraints.weighty = 1;
    editPanel.add(editor.getComponent(), constraints);
}
 
Example 22
Source Project: idea-php-typo3-plugin   Source File: TranslatorTest.java    License: MIT License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> {
        FileTypeManager.getInstance().associateExtension(XmlFileType.INSTANCE, "xlf");
    });

    FileBasedIndex.getInstance().requestRebuild(TranslationIndex.KEY);

    myFixture.addFileToProject("typo3conf/ext/foo/ext_emconf.php", "");
}
 
Example 23
Source Project: idea-php-typo3-plugin   Source File: AbstractTranslationTest.java    License: MIT License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> {
        FileTypeManager.getInstance().associateExtension(XmlFileType.INSTANCE, "xlf");
    });

    FileBasedIndex.getInstance().requestRebuild(TranslationIndex.KEY);

    myFixture.addFileToProject("typo3conf/ext/foo/ext_emconf.php", "");

    myFixture.copyFileToProject("sample.xlf", "typo3conf/ext/foo/sample.xlf");
    myFixture.copyFileToProject("de.sample.xlf", "typo3conf/ext/foo/de.sample.xlf");
}
 
Example 24
Source Project: CodeMaker   Source File: Editors.java    License: Apache License 2.0 5 votes vote down vote up
public static Editor createSourceEditor(Project project, String language, String content, boolean readOnly) {
    final EditorFactory factory = EditorFactory.getInstance();
    final Editor editor = factory.createEditor(factory.createDocument(content), project, FileTypeManager.getInstance()
            .getFileTypeByExtension(language), readOnly);
    editor.getSettings().setRefrainFromScrolling(false);
    return editor;
}
 
Example 25
Source Project: consulo   Source File: PsiVFSListener.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public PsiVFSListener(@Nonnull Project project, Provider<ProjectFileIndex> fileIndex) {
  installGlobalListener();

  myProject = project;
  myFileTypeManager = FileTypeManager.getInstance();
  myFileIndex = fileIndex;
  myManager = (PsiManagerImpl)PsiManager.getInstance(project);
  myFileManager = (FileManagerImpl)myManager.getFileManager();

  if (project.isDefault()) {
    return;
  }

  // events must handled only after pre-startup (https://upsource.jetbrains.com/intellij/review/IDEA-CR-47395)
  StartupManager.getInstance(project).registerPreStartupActivity(() -> {
    MessageBusConnection connection = project.getMessageBus().connect();
    connection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyModuleRootListener());
    connection.subscribe(FileTypeManager.TOPIC, new FileTypeListener() {
      @Override
      public void fileTypesChanged(@Nonnull FileTypeEvent e) {
        myFileManager.processFileTypesChanged(e.getRemovedFileType() != null);
      }
    });
    connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new MyFileDocumentManagerAdapter());
  });
}
 
Example 26
Source Project: intellij   Source File: BlazeAndroidModelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void initTest(Container applicationServices, Container projectServices) {
  applicationServices.register(FileTypeManager.class, new MockFileTypeManager());
  applicationServices.register(
      FileDocumentManager.class, new MockFileDocumentManagerImpl(null, null));
  applicationServices.register(VirtualFileManager.class, mock(VirtualFileManager.class));
  applicationServices.register(BlazeBuildService.class, new BlazeBuildService());
  projectServices.register(ProjectScopeBuilder.class, new ProjectScopeBuilderImpl(project));
  projectServices.register(ProjectViewManager.class, new MockProjectViewManager());

  BlazeProjectDataManager mockProjectDataManager =
      new MockBlazeProjectDataManager(MockBlazeProjectDataBuilder.builder().build());
  projectServices.register(BlazeProjectDataManager.class, mockProjectDataManager);

  BlazeImportSettingsManager manager = new BlazeImportSettingsManager(project);
  manager.setImportSettings(new BlazeImportSettings("", "", "", "", BuildSystem.Blaze));
  projectServices.register(BlazeImportSettingsManager.class, manager);
  projectServices.register(JvmPsiConversionHelper.class, new JvmPsiConversionHelperImpl());

  facade =
      new MockJavaPsiFacade(
          project,
          ImmutableList.of("com.google.example.Modified", "com.google.example.NotModified"));

  projectServices.register(JavaPsiFacade.class, facade);
  module = new MockModule(() -> {});
  model = new BlazeAndroidModel(project, null, mock(SourceProvider.class), null, 0, false);
}
 
Example 27
Source Project: intellij   Source File: CppSyncStatusContributor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean handlesFile(BlazeProjectData projectData, VirtualFile virtualFile) {
  if (!projectData.getWorkspaceLanguageSettings().isLanguageActive(LanguageClass.C)) {
    return false;
  }
  FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(virtualFile.getName());
  return fileType instanceof OCFileType;
}
 
Example 28
Source Project: consulo   Source File: TodoView.java    License: Apache License 2.0 5 votes vote down vote up
public TodoView(@Nonnull Project project) {
  myProject = project;

  state.all.arePackagesShown = true;
  state.all.isAutoScrollToSource = true;

  state.current.isAutoScrollToSource = true;

  MessageBusConnection connection = project.getMessageBus().connect(this);
  connection.subscribe(TodoConfiguration.PROPERTY_CHANGE, new MyPropertyChangeListener());
  connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());
  connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, myVcsListener);
}
 
Example 29
Source Project: idea-gitignore   Source File: IgnoreManager.java    License: MIT License 5 votes vote down vote up
/**
 * Associates given file with proper {@link IgnoreFileType}.
 *
 * @param fileName to associate
 * @param fileType file type to bind with pattern
 */
public static void associateFileType(@NotNull final String fileName, @NotNull final IgnoreFileType fileType) {
    final Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread()) {
        final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
        application.invokeLater(() -> application.runWriteAction(() -> {
            fileTypeManager.associate(fileType, new ExactFileNameMatcher(fileName));
            FILE_TYPES_ASSOCIATION_QUEUE.remove(fileName);
        }), ModalityState.NON_MODAL);
    } else if (!FILE_TYPES_ASSOCIATION_QUEUE.containsKey(fileName)) {
        FILE_TYPES_ASSOCIATION_QUEUE.put(fileName, fileType);
    }
}
 
Example 30
Source Project: consulo   Source File: PackageNodeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * a directory is considered "empty" if it has at least one child and all its children are only directories
 *
 * @param strictlyEmpty if true, the package is considered empty if it has only 1 child and this child  is a directory
 *                      otherwise the package is considered as empty if all direct children that it has are directories
 */
public static boolean isEmptyMiddlePackage(@Nonnull PsiDirectory dir,
                                           @Nullable Class<? extends ModuleExtension> moduleExtensionClass,
                                           boolean strictlyEmpty) {
  final VirtualFile[] files = dir.getVirtualFile().getChildren();
  if (files.length == 0) {
    return false;
  }
  PsiManager manager = dir.getManager();
  int subpackagesCount = 0;
  int directoriesCount = 0;
  for (VirtualFile file : files) {
    if (FileTypeManager.getInstance().isFileIgnored(file)) continue;
    if (!file.isDirectory()) return false;
    PsiDirectory childDir = manager.findDirectory(file);
    if (childDir != null) {
      directoriesCount++;
      if (strictlyEmpty && directoriesCount > 1) return false;

      final PsiPackageManager psiPackageManager = PsiPackageManager.getInstance(dir.getProject());
      PsiPackage tempPackage = moduleExtensionClass == null
                               ? psiPackageManager.findAnyPackage(childDir)
                               : psiPackageManager.findPackage(dir, moduleExtensionClass);
      if (tempPackage != null) {
        subpackagesCount++;
      }
    }
  }
  if (strictlyEmpty) {
    return directoriesCount == subpackagesCount && directoriesCount == 1;
  }
  return directoriesCount == subpackagesCount && directoriesCount > 0;
}