Search in sources :

Example 1 with InstrumentationClassFinder

use of com.intellij.compiler.instrumentation.InstrumentationClassFinder in project intellij-community by JetBrains.

the class FormsInstrumenter method build.

@Override
public ExitCode build(CompileContext context, ModuleChunk chunk, DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, OutputConsumer outputConsumer) throws ProjectBuildException, IOException {
    final JpsProject project = context.getProjectDescriptor().getProject();
    final JpsUiDesignerConfiguration config = JpsUiDesignerExtensionService.getInstance().getOrCreateUiDesignerConfiguration(project);
    if (!config.isInstrumentClasses()) {
        return ExitCode.NOTHING_DONE;
    }
    final Map<File, Collection<File>> srcToForms = FORMS_TO_COMPILE.get(context);
    FORMS_TO_COMPILE.set(context, null);
    if (srcToForms == null || srcToForms.isEmpty()) {
        return ExitCode.NOTHING_DONE;
    }
    final Set<File> formsToCompile = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
    for (Collection<File> files : srcToForms.values()) {
        formsToCompile.addAll(files);
    }
    if (JavaBuilderUtil.isCompileJavaIncrementally(context)) {
        final ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger();
        if (logger.isEnabled()) {
            logger.logCompiledFiles(formsToCompile, getPresentableName(), "Compiling forms:");
        }
    }
    try {
        final Collection<File> platformCp = ProjectPaths.getPlatformCompilationClasspath(chunk, false);
        final List<File> classpath = new ArrayList<>();
        classpath.addAll(ProjectPaths.getCompilationClasspath(chunk, false));
        // forms_rt.jar
        classpath.add(getResourcePath(GridConstraints.class));
        final Map<File, String> chunkSourcePath = ProjectPaths.getSourceRootsWithDependents(chunk);
        // sourcepath for loading forms resources
        classpath.addAll(chunkSourcePath.keySet());
        final JpsSdk<JpsDummyElement> sdk = chunk.representativeTarget().getModule().getSdk(JpsJavaSdkType.INSTANCE);
        final InstrumentationClassFinder finder = ClassProcessingBuilder.createInstrumentationClassFinder(sdk, platformCp, classpath, outputConsumer);
        try {
            final Map<File, Collection<File>> processed = instrumentForms(context, chunk, chunkSourcePath, finder, formsToCompile, outputConsumer);
            final OneToManyPathsMapping sourceToFormMap = context.getProjectDescriptor().dataManager.getSourceToFormMap();
            for (Map.Entry<File, Collection<File>> entry : processed.entrySet()) {
                final File src = entry.getKey();
                final Collection<File> forms = entry.getValue();
                final Collection<String> formPaths = new ArrayList<>(forms.size());
                for (File form : forms) {
                    formPaths.add(form.getPath());
                }
                sourceToFormMap.update(src.getPath(), formPaths);
                srcToForms.remove(src);
            }
            // clean mapping
            for (File srcFile : srcToForms.keySet()) {
                sourceToFormMap.remove(srcFile.getPath());
            }
        } finally {
            finder.releaseResources();
        }
    } finally {
        context.processMessage(new ProgressMessage("Finished instrumenting forms [" + chunk.getPresentableShortName() + "]"));
    }
    return ExitCode.OK;
}
Also used : ProgressMessage(org.jetbrains.jps.incremental.messages.ProgressMessage) OneToManyPathsMapping(org.jetbrains.jps.incremental.storage.OneToManyPathsMapping) InstrumentationClassFinder(com.intellij.compiler.instrumentation.InstrumentationClassFinder) THashSet(gnu.trove.THashSet) ProjectBuilderLogger(org.jetbrains.jps.builders.logging.ProjectBuilderLogger) JpsUiDesignerConfiguration(org.jetbrains.jps.uiDesigner.model.JpsUiDesignerConfiguration) GridConstraints(com.intellij.uiDesigner.core.GridConstraints) JpsProject(org.jetbrains.jps.model.JpsProject) JpsDummyElement(org.jetbrains.jps.model.JpsDummyElement) THashMap(gnu.trove.THashMap)

Example 2 with InstrumentationClassFinder

use of com.intellij.compiler.instrumentation.InstrumentationClassFinder 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)

Example 3 with InstrumentationClassFinder

use of com.intellij.compiler.instrumentation.InstrumentationClassFinder in project intellij-community by JetBrains.

the class Javac2 method compile.

/**
   * The overridden compile method that does not actually compiles java sources but only instruments
   * class files.
   */
protected void compile() {
    // compile java
    if (areJavaClassesCompiled()) {
        super.compile();
    }
    InstrumentationClassFinder finder = buildClasspathClassLoader();
    if (finder == null) {
        return;
    }
    try {
        instrumentForms(finder);
        if (getInstrumentNotNull()) {
            //NotNull instrumentation
            final int instrumented = instrumentNotNull(getDestdir(), finder);
            log("Added @NotNull assertions to " + instrumented + " files", Project.MSG_INFO);
        }
    } finally {
        finder.releaseResources();
    }
}
Also used : InstrumentationClassFinder(com.intellij.compiler.instrumentation.InstrumentationClassFinder)

Example 4 with InstrumentationClassFinder

use of com.intellij.compiler.instrumentation.InstrumentationClassFinder in project intellij-community by JetBrains.

the class ClassProcessingBuilder method chunkBuildFinished.

@Override
public void chunkBuildFinished(CompileContext context, ModuleChunk chunk) {
    final InstrumentationClassFinder finder = CLASS_FINDER.get(context);
    if (finder != null) {
        CLASS_FINDER.set(context, null);
        finder.releaseResources();
    }
}
Also used : InstrumentationClassFinder(com.intellij.compiler.instrumentation.InstrumentationClassFinder)

Example 5 with InstrumentationClassFinder

use of com.intellij.compiler.instrumentation.InstrumentationClassFinder in project intellij-community by JetBrains.

the class ClassProcessingBuilder method build.

@Override
public final ExitCode build(CompileContext context, ModuleChunk chunk, DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, OutputConsumer outputConsumer) throws ProjectBuildException, IOException {
    if (outputConsumer.getCompiledClasses().isEmpty() || !isEnabled(context, chunk)) {
        return ExitCode.NOTHING_DONE;
    }
    final String progress = getProgressMessage();
    final boolean shouldShowProgress = !StringUtil.isEmptyOrSpaces(progress);
    if (shouldShowProgress) {
        context.processMessage(new ProgressMessage(progress + " [" + chunk.getPresentableShortName() + "]"));
    }
    ExitCode exitCode = ExitCode.NOTHING_DONE;
    try {
        // try using shared finder
        InstrumentationClassFinder finder = CLASS_FINDER.get(context);
        if (finder == null) {
            final Collection<File> platformCp = ProjectPaths.getPlatformCompilationClasspath(chunk, false);
            final Collection<File> classpath = new ArrayList<>();
            classpath.addAll(ProjectPaths.getCompilationClasspath(chunk, false));
            classpath.addAll(ProjectPaths.getSourceRootsWithDependents(chunk).keySet());
            final JpsSdk<JpsDummyElement> sdk = chunk.representativeTarget().getModule().getSdk(JpsJavaSdkType.INSTANCE);
            finder = createInstrumentationClassFinder(sdk, platformCp, classpath, outputConsumer);
            CLASS_FINDER.set(context, finder);
        }
        exitCode = performBuild(context, chunk, finder, outputConsumer);
    } finally {
        if (shouldShowProgress) {
            // cleanup progress
            context.processMessage(new ProgressMessage(""));
        }
    }
    return exitCode;
}
Also used : ProgressMessage(org.jetbrains.jps.incremental.messages.ProgressMessage) InstrumentationClassFinder(com.intellij.compiler.instrumentation.InstrumentationClassFinder) ArrayList(java.util.ArrayList) JpsDummyElement(org.jetbrains.jps.model.JpsDummyElement) File(java.io.File)

Aggregations

InstrumentationClassFinder (com.intellij.compiler.instrumentation.InstrumentationClassFinder)6 File (java.io.File)3 ProgressMessage (org.jetbrains.jps.incremental.messages.ProgressMessage)2 JpsDummyElement (org.jetbrains.jps.model.JpsDummyElement)2 PsiClassWriter (com.intellij.compiler.PsiClassWriter)1 FileSetCompileScope (com.intellij.compiler.impl.FileSetCompileScope)1 CantRunException (com.intellij.execution.CantRunException)1 ExecutionException (com.intellij.execution.ExecutionException)1 PropertiesReferenceManager (com.intellij.lang.properties.PropertiesReferenceManager)1 PropertiesFile (com.intellij.lang.properties.psi.PropertiesFile)1 CompileContext (com.intellij.openapi.compiler.CompileContext)1 CompileStatusNotification (com.intellij.openapi.compiler.CompileStatusNotification)1 Document (com.intellij.openapi.editor.Document)1 Module (com.intellij.openapi.module.Module)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 FormEditingUtil (com.intellij.uiDesigner.FormEditingUtil)1 AsmCodeGenerator (com.intellij.uiDesigner.compiler.AsmCodeGenerator)1 FormErrorInfo (com.intellij.uiDesigner.compiler.FormErrorInfo)1 GridConstraints (com.intellij.uiDesigner.core.GridConstraints)1 PreviewNestedFormLoader (com.intellij.uiDesigner.make.PreviewNestedFormLoader)1