Search in sources :

Example 66 with Module

use of com.intellij.openapi.module.Module in project intellij-community by JetBrains.

the class MavenProjectsManager method importProjects.

public List<Module> importProjects(final IdeModifiableModelsProvider modelsProvider) {
    final Map<MavenProject, MavenProjectChanges> projectsToImportWithChanges;
    final boolean importModuleGroupsRequired;
    synchronized (myImportingDataLock) {
        projectsToImportWithChanges = new LinkedHashMap<>(myProjectsToImport);
        myProjectsToImport.clear();
        importModuleGroupsRequired = myImportModuleGroupsRequired;
        myImportModuleGroupsRequired = false;
    }
    final Ref<MavenProjectImporter> importer = new Ref<>();
    final Ref<List<MavenProjectsProcessorTask>> postTasks = new Ref<>();
    final Runnable r = () -> {
        MavenProjectImporter projectImporter = new MavenProjectImporter(myProject, myProjectsTree, getFileToModuleMapping(new MavenModelsProvider() {

            @Override
            public Module[] getModules() {
                return modelsProvider.getModules();
            }

            @Override
            public VirtualFile[] getContentRoots(Module module) {
                return modelsProvider.getContentRoots(module);
            }
        }), projectsToImportWithChanges, importModuleGroupsRequired, modelsProvider, getImportingSettings());
        importer.set(projectImporter);
        postTasks.set(projectImporter.importProject());
    };
    // called from wizard or ui
    if (ApplicationManager.getApplication().isDispatchThread()) {
        r.run();
    } else {
        MavenUtil.runInBackground(myProject, ProjectBundle.message("maven.project.importing"), false, new MavenTask() {

            @Override
            public void run(MavenProgressIndicator indicator) throws MavenProcessCanceledException {
                r.run();
            }
        }).waitFor();
    }
    VirtualFileManager fm = VirtualFileManager.getInstance();
    if (isNormalProject()) {
        fm.asyncRefresh(null);
    } else {
        fm.syncRefresh();
    }
    if (postTasks.get() != null) /*may be null if importing is cancelled*/
    {
        schedulePostImportTasks(postTasks.get());
    }
    // do not block user too often
    myImportingQueue.restartTimer();
    MavenProjectImporter projectImporter = importer.get();
    if (projectImporter == null)
        return Collections.emptyList();
    return projectImporter.getCreatedModules();
}
Also used : VirtualFileManager(com.intellij.openapi.vfs.VirtualFileManager) MavenProjectImporter(org.jetbrains.idea.maven.importing.MavenProjectImporter) DumbAwareRunnable(com.intellij.openapi.project.DumbAwareRunnable) Module(com.intellij.openapi.module.Module)

Example 67 with Module

use of com.intellij.openapi.module.Module in project intellij-community by JetBrains.

the class MavenProjectsManagerWatcher method start.

public synchronized void start() {
    final MessageBusConnection myBusConnection = myProject.getMessageBus().connect(myChangedDocumentsQueue);
    myBusConnection.subscribe(VirtualFileManager.VFS_CHANGES, new MyFileChangeListener());
    myBusConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyRootChangesListener());
    myChangedDocumentsQueue.makeUserAware(myProject);
    myChangedDocumentsQueue.activate();
    myBusConnection.subscribe(ProjectTopics.MODULES, new ModuleListener() {

        @Override
        public void moduleRemoved(@NotNull Project project, @NotNull Module module) {
            MavenProject mavenProject = myManager.findProject(module);
            if (mavenProject != null && !myManager.isIgnored(mavenProject)) {
                VirtualFile file = mavenProject.getFile();
                if (myManager.isManagedFile(file) && myManager.getModules(mavenProject).isEmpty()) {
                    myManager.removeManagedFiles(Collections.singletonList(file));
                } else {
                    myManager.setIgnoredState(Collections.singletonList(mavenProject), true);
                }
            }
        }

        @Override
        public void moduleAdded(@NotNull final Project project, @NotNull final Module module) {
            // this method is needed to return non-ignored status for modules that were deleted (and thus ignored) and then created again with a different module type
            if (myManager.isMavenizedModule(module)) {
                MavenProject mavenProject = myManager.findProject(module);
                if (mavenProject != null)
                    myManager.setIgnoredState(Collections.singletonList(mavenProject), false);
            }
        }
    });
    DocumentAdapter myDocumentListener = new DocumentAdapter() {

        @Override
        public void documentChanged(DocumentEvent event) {
            Document doc = event.getDocument();
            VirtualFile file = FileDocumentManager.getInstance().getFile(doc);
            if (file == null)
                return;
            String fileName = file.getName();
            boolean isMavenFile = fileName.equals(MavenConstants.POM_XML) || fileName.equals(MavenConstants.PROFILES_XML) || isSettingsFile(file) || fileName.startsWith("pom.");
            if (!isMavenFile)
                return;
            synchronized (myChangedDocuments) {
                myChangedDocuments.add(doc);
            }
            myChangedDocumentsQueue.queue(new Update(MavenProjectsManagerWatcher.this) {

                @Override
                public void run() {
                    final Document[] copy;
                    synchronized (myChangedDocuments) {
                        copy = myChangedDocuments.toArray(new Document[myChangedDocuments.size()]);
                        myChangedDocuments.clear();
                    }
                    MavenUtil.invokeLater(myProject, () -> new WriteAction() {

                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            for (Document each : copy) {
                                PsiDocumentManager.getInstance(myProject).commitDocument(each);
                                ((FileDocumentManagerImpl) FileDocumentManager.getInstance()).saveDocument(each, false);
                            }
                        }
                    }.execute());
                }
            });
        }
    };
    EditorFactory.getInstance().getEventMulticaster().addDocumentListener(myDocumentListener, myBusConnection);
    final MavenGeneralSettings.Listener mySettingsPathsChangesListener = new MavenGeneralSettings.Listener() {

        @Override
        public void changed() {
            updateSettingsFilePointers();
            onSettingsChange();
        }
    };
    myGeneralSettings.addListener(mySettingsPathsChangesListener);
    Disposer.register(myChangedDocumentsQueue, new Disposable() {

        @Override
        public void dispose() {
            myGeneralSettings.removeListener(mySettingsPathsChangesListener);
            mySettingsFilesPointers.clear();
        }
    });
    updateSettingsFilePointers();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Disposable(com.intellij.openapi.Disposable) MessageBusConnection(com.intellij.util.messages.MessageBusConnection) ModuleListener(com.intellij.openapi.project.ModuleListener) ModuleRootListener(com.intellij.openapi.roots.ModuleRootListener) VirtualFilePointerListener(com.intellij.openapi.vfs.pointers.VirtualFilePointerListener) ModuleListener(com.intellij.openapi.project.ModuleListener) WriteAction(com.intellij.openapi.application.WriteAction) DocumentAdapter(com.intellij.openapi.editor.event.DocumentAdapter) DocumentEvent(com.intellij.openapi.editor.event.DocumentEvent) Document(com.intellij.openapi.editor.Document) Update(com.intellij.util.ui.update.Update) Result(com.intellij.openapi.application.Result) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module)

Example 68 with Module

use of com.intellij.openapi.module.Module in project intellij-community by JetBrains.

the class MavenGroovyPomScriptType method doPatchResolveScope.

public GlobalSearchScope doPatchResolveScope(@NotNull GroovyFile file, @NotNull GlobalSearchScope baseScope) {
    final Module module = ModuleUtilCore.findModuleForPsiElement(file);
    if (module == null) {
        return baseScope;
    }
    Project project = module.getProject();
    GlobalSearchScope result = baseScope;
    CachedValuesManager cachedValuesManager = CachedValuesManager.getManager(file.getProject());
    Boolean hasGroovyModuleLib = cachedValuesManager.getCachedValue(file.getProject(), () -> CachedValueProvider.Result.createSingleDependency(hasModuleWithGroovyLibrary(project), ProjectRootManagerEx.getInstanceEx(project)));
    if (hasGroovyModuleLib) {
        final Collection<VirtualFile> files = additionalScopeFiles();
        result = result.uniteWith(new NonClasspathDirectoriesScope(files));
    }
    return result;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) NonClasspathDirectoriesScope(com.intellij.psi.search.NonClasspathDirectoriesScope) Project(com.intellij.openapi.project.Project) CachedValuesManager(com.intellij.psi.util.CachedValuesManager) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Module(com.intellij.openapi.module.Module)

Example 69 with Module

use of com.intellij.openapi.module.Module in project intellij-community by JetBrains.

the class MavenResourceCompilerConfigurationGenerator method addNonMavenResources.

private void addNonMavenResources(MavenProjectConfiguration projectCfg) {
    Set<VirtualFile> processedRoots = new HashSet<>();
    for (MavenProject project : myMavenProjectsManager.getProjects()) {
        for (String dir : ContainerUtil.concat(project.getSources(), project.getTestSources())) {
            VirtualFile file = LocalFileSystem.getInstance().findFileByPath(dir);
            if (file != null) {
                processedRoots.add(file);
            }
        }
        for (MavenResource resource : ContainerUtil.concat(project.getResources(), project.getTestResources())) {
            VirtualFile file = LocalFileSystem.getInstance().findFileByPath(resource.getDirectory());
            if (file != null) {
                processedRoots.add(file);
            }
        }
    }
    CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(myProject);
    for (Module module : ModuleManager.getInstance(myProject).getModules()) {
        if (!myMavenProjectsManager.isMavenizedModule(module))
            continue;
        for (ContentEntry contentEntry : ModuleRootManager.getInstance(module).getContentEntries()) {
            for (SourceFolder folder : contentEntry.getSourceFolders()) {
                VirtualFile file = folder.getFile();
                if (file == null)
                    continue;
                if (!compilerConfiguration.isExcludedFromCompilation(file) && !isUnderRoots(processedRoots, file)) {
                    MavenModuleResourceConfiguration configuration = projectCfg.moduleConfigurations.get(module.getName());
                    if (configuration == null)
                        continue;
                    List<ResourceRootConfiguration> resourcesList = folder.isTestSource() ? configuration.testResources : configuration.resources;
                    final ResourceRootConfiguration cfg = new ResourceRootConfiguration();
                    cfg.directory = FileUtil.toSystemIndependentName(FileUtil.toSystemIndependentName(file.getPath()));
                    CompilerModuleExtension compilerModuleExtension = CompilerModuleExtension.getInstance(module);
                    if (compilerModuleExtension == null)
                        continue;
                    String compilerOutputUrl = folder.isTestSource() ? compilerModuleExtension.getCompilerOutputUrlForTests() : compilerModuleExtension.getCompilerOutputUrl();
                    cfg.targetPath = VfsUtilCore.urlToPath(compilerOutputUrl);
                    convertIdeaExcludesToMavenExcludes(cfg, (CompilerConfigurationImpl) compilerConfiguration);
                    resourcesList.add(cfg);
                }
            }
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) MavenResource(org.jetbrains.idea.maven.model.MavenResource) CompilerConfiguration(com.intellij.compiler.CompilerConfiguration) Module(com.intellij.openapi.module.Module)

Example 70 with Module

use of com.intellij.openapi.module.Module in project intellij-community by JetBrains.

the class PreviewFormAction method showPreviewFrame.

private static void showPreviewFrame(@NotNull final Module module, @NotNull final VirtualFile formFile, @Nullable final Locale stringDescriptorLocale) {
    final String tempPath;
    try {
        final File tempDirectory = FileUtil.createTempDirectory("FormPreview", "");
        tempPath = tempDirectory.getAbsolutePath();
        CopyResourcesUtil.copyFormsRuntime(tempPath, true);
    } catch (IOException e) {
        Messages.showErrorDialog(module.getProject(), UIDesignerBundle.message("error.cannot.preview.form", formFile.getPath().replace('/', File.separatorChar), e.toString()), CommonBundle.getErrorTitle());
        return;
    }
    final PathsList sources = OrderEnumerator.orderEntries(module).withoutSdk().withoutLibraries().withoutDepModules().getSourcePathsList();
    final String classPath = OrderEnumerator.orderEntries(module).recursively().getPathsList().getPathsString() + File.pathSeparator + sources.getPathsString() + File.pathSeparator + /* resources bundles */
    tempPath;
    final InstrumentationClassFinder finder = createClassFinder(classPath);
    try {
        final Document doc = FileDocumentManager.getInstance().getDocument(formFile);
        final LwRootContainer rootContainer;
        try {
            rootContainer = Utils.getRootContainer(doc.getText(), new CompiledClassPropertiesProvider(finder.getLoader()));
        } catch (Exception e) {
            Messages.showErrorDialog(module.getProject(), UIDesignerBundle.message("error.cannot.read.form", formFile.getPath().replace('/', File.separatorChar), e.getMessage()), CommonBundle.getErrorTitle());
            return;
        }
        if (rootContainer.getComponentCount() == 0) {
            Messages.showErrorDialog(module.getProject(), UIDesignerBundle.message("error.cannot.preview.empty.form", formFile.getPath().replace('/', File.separatorChar)), CommonBundle.getErrorTitle());
            return;
        }
        setPreviewBindings(rootContainer, CLASS_TO_BIND_NAME);
        // 2. Copy previewer class and all its superclasses into TEMP directory and instrument it.
        try {
            PreviewNestedFormLoader nestedFormLoader = new PreviewNestedFormLoader(module, tempPath, finder);
            final File tempFile = CopyResourcesUtil.copyClass(tempPath, CLASS_TO_BIND_NAME, true);
            //CopyResourcesUtil.copyClass(tempPath, CLASS_TO_BIND_NAME + "$1", true);
            CopyResourcesUtil.copyClass(tempPath, CLASS_TO_BIND_NAME + "$MyExitAction", true);
            CopyResourcesUtil.copyClass(tempPath, CLASS_TO_BIND_NAME + "$MyPackAction", true);
            CopyResourcesUtil.copyClass(tempPath, CLASS_TO_BIND_NAME + "$MySetLafAction", true);
            Locale locale = Locale.getDefault();
            if (locale.getCountry().length() > 0 && locale.getLanguage().length() > 0) {
                CopyResourcesUtil.copyProperties(tempPath, RUNTIME_BUNDLE_PREFIX + "_" + locale.getLanguage() + "_" + locale.getCountry() + PropertiesFileType.DOT_DEFAULT_EXTENSION);
            }
            if (locale.getLanguage().length() > 0) {
                CopyResourcesUtil.copyProperties(tempPath, RUNTIME_BUNDLE_PREFIX + "_" + locale.getLanguage() + PropertiesFileType.DOT_DEFAULT_EXTENSION);
            }
            CopyResourcesUtil.copyProperties(tempPath, RUNTIME_BUNDLE_PREFIX + "_" + locale.getLanguage() + PropertiesFileType.DOT_DEFAULT_EXTENSION);
            CopyResourcesUtil.copyProperties(tempPath, RUNTIME_BUNDLE_PREFIX + PropertiesFileType.DOT_DEFAULT_EXTENSION);
            final AsmCodeGenerator codeGenerator = new AsmCodeGenerator(rootContainer, finder, nestedFormLoader, true, new PsiClassWriter(module));
            codeGenerator.patchFile(tempFile);
            final FormErrorInfo[] errors = codeGenerator.getErrors();
            if (errors.length != 0) {
                Messages.showErrorDialog(module.getProject(), UIDesignerBundle.message("error.cannot.preview.form", formFile.getPath().replace('/', File.separatorChar), errors[0].getErrorMessage()), CommonBundle.getErrorTitle());
                return;
            }
        } catch (Exception e) {
            LOG.debug(e);
            Messages.showErrorDialog(module.getProject(), UIDesignerBundle.message("error.cannot.preview.form", formFile.getPath().replace('/', File.separatorChar), e.getMessage() != null ? e.getMessage() : e.toString()), CommonBundle.getErrorTitle());
            return;
        }
        // 2.5. Copy up-to-date properties files to the output directory.
        final HashSet<String> bundleSet = new HashSet<>();
        FormEditingUtil.iterateStringDescriptors(rootContainer, new FormEditingUtil.StringDescriptorVisitor<IComponent>() {

            public boolean visit(final IComponent component, final StringDescriptor descriptor) {
                if (descriptor.getBundleName() != null) {
                    bundleSet.add(descriptor.getDottedBundleName());
                }
                return true;
            }
        });
        if (bundleSet.size() > 0) {
            HashSet<VirtualFile> virtualFiles = new HashSet<>();
            HashSet<Module> modules = new HashSet<>();
            PropertiesReferenceManager manager = PropertiesReferenceManager.getInstance(module.getProject());
            for (String bundleName : bundleSet) {
                for (PropertiesFile propFile : manager.findPropertiesFiles(module, bundleName)) {
                    virtualFiles.add(propFile.getVirtualFile());
                    final Module moduleForFile = ModuleUtil.findModuleForFile(propFile.getVirtualFile(), module.getProject());
                    if (moduleForFile != null) {
                        modules.add(moduleForFile);
                    }
                }
            }
            FileSetCompileScope scope = new FileSetCompileScope(virtualFiles, modules.toArray(new Module[modules.size()]));
            CompilerManager.getInstance(module.getProject()).make(scope, new CompileStatusNotification() {

                public void finished(boolean aborted, int errors, int warnings, final CompileContext compileContext) {
                    if (!aborted && errors == 0) {
                        runPreviewProcess(tempPath, sources, module, formFile, stringDescriptorLocale);
                    }
                }
            });
        } else {
            runPreviewProcess(tempPath, sources, module, formFile, stringDescriptorLocale);
        }
    } finally {
        finder.releaseResources();
    }
}
Also used : Locale(java.util.Locale) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiClassWriter(com.intellij.compiler.PsiClassWriter) PreviewNestedFormLoader(com.intellij.uiDesigner.make.PreviewNestedFormLoader) Document(com.intellij.openapi.editor.Document) CompileContext(com.intellij.openapi.compiler.CompileContext) CompileStatusNotification(com.intellij.openapi.compiler.CompileStatusNotification) FormErrorInfo(com.intellij.uiDesigner.compiler.FormErrorInfo) PropertiesFile(com.intellij.lang.properties.psi.PropertiesFile) PropertiesReferenceManager(com.intellij.lang.properties.PropertiesReferenceManager) HashSet(com.intellij.util.containers.HashSet) InstrumentationClassFinder(com.intellij.compiler.instrumentation.InstrumentationClassFinder) IOException(java.io.IOException) ExecutionException(com.intellij.execution.ExecutionException) IOException(java.io.IOException) CantRunException(com.intellij.execution.CantRunException) PathsList(com.intellij.util.PathsList) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PropertiesFile(com.intellij.lang.properties.psi.PropertiesFile) File(java.io.File) AsmCodeGenerator(com.intellij.uiDesigner.compiler.AsmCodeGenerator) FormEditingUtil(com.intellij.uiDesigner.FormEditingUtil) FileSetCompileScope(com.intellij.compiler.impl.FileSetCompileScope)

Aggregations

Module (com.intellij.openapi.module.Module)1893 VirtualFile (com.intellij.openapi.vfs.VirtualFile)585 Project (com.intellij.openapi.project.Project)379 NotNull (org.jetbrains.annotations.NotNull)330 Nullable (org.jetbrains.annotations.Nullable)267 File (java.io.File)185 PsiFile (com.intellij.psi.PsiFile)147 AndroidFacet (org.jetbrains.android.facet.AndroidFacet)134 ArrayList (java.util.ArrayList)118 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)112 Sdk (com.intellij.openapi.projectRoots.Sdk)95 PsiElement (com.intellij.psi.PsiElement)89 PsiDirectory (com.intellij.psi.PsiDirectory)77 ModuleManager (com.intellij.openapi.module.ModuleManager)65 PsiClass (com.intellij.psi.PsiClass)65 IOException (java.io.IOException)61 ModifiableRootModel (com.intellij.openapi.roots.ModifiableRootModel)57 ProjectFileIndex (com.intellij.openapi.roots.ProjectFileIndex)57 List (java.util.List)57 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)51