Search in sources :

Example 1 with FormErrorInfo

use of com.intellij.uiDesigner.compiler.FormErrorInfo 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 2 with FormErrorInfo

use of com.intellij.uiDesigner.compiler.FormErrorInfo in project intellij-community by JetBrains.

the class Form2SourceCompiler method getProcessingItems.

@NotNull
public ProcessingItem[] getProcessingItems(final CompileContext context) {
    final Project project = context.getProject();
    if (GuiDesignerConfiguration.getInstance(project).INSTRUMENT_CLASSES) {
        return ProcessingItem.EMPTY_ARRAY;
    }
    final ArrayList<ProcessingItem> items = new ArrayList<>();
    DumbService.getInstance(project).runReadActionInSmartMode(() -> {
        final CompileScope scope = context.getCompileScope();
        final CompileScope projectScope = context.getProjectCompileScope();
        final VirtualFile[] formFiles = projectScope.getFiles(StdFileTypes.GUI_DESIGNER_FORM, true);
        final CompilerManager compilerManager = CompilerManager.getInstance(project);
        final BindingsCache bindingsCache = new BindingsCache(project);
        try {
            final HashMap<String, VirtualFile> class2form = new HashMap<>();
            for (final VirtualFile formFile : formFiles) {
                if (compilerManager.isExcludedFromCompilation(formFile)) {
                    continue;
                }
                final String classToBind;
                try {
                    classToBind = bindingsCache.getBoundClassName(formFile);
                } catch (AlienFormFileException e) {
                    // ignore non-IDEA forms
                    continue;
                } catch (Exception e) {
                    addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)), formFile);
                    continue;
                }
                if (classToBind == null) {
                    continue;
                }
                final VirtualFile sourceFile = findSourceFile(context, formFile, classToBind);
                if (sourceFile == null) {
                    if (scope.belongs(formFile.getUrl())) {
                        addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind)), formFile);
                    }
                    continue;
                }
                final boolean inScope = scope.belongs(sourceFile.getUrl()) || scope.belongs(formFile.getUrl());
                final VirtualFile alreadyProcessedForm = class2form.get(classToBind);
                if (alreadyProcessedForm != null) {
                    if (inScope) {
                        addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.duplicate.bind", classToBind, alreadyProcessedForm.getPresentableUrl())), formFile);
                    }
                    continue;
                }
                class2form.put(classToBind, formFile);
                if (!inScope) {
                    continue;
                }
                items.add(new MyInstrumentationItem(sourceFile, formFile));
            }
        } finally {
            bindingsCache.close();
        }
    });
    return items.toArray(new ProcessingItem[items.size()]);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) IOException(java.io.IOException) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) Project(com.intellij.openapi.project.Project) FormErrorInfo(com.intellij.uiDesigner.compiler.FormErrorInfo) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with FormErrorInfo

use of com.intellij.uiDesigner.compiler.FormErrorInfo in project intellij-community by JetBrains.

the class PreviewNestedFormLoader method generateStubClass.

private void generateStubClass(final LwRootContainer rootContainer, final String generatedClassName) throws IOException, CodeGenerationException {
    @NonNls ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    cw.visit(Opcodes.V1_1, Opcodes.ACC_PUBLIC, generatedClassName, null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY);
    cw.visitField(Opcodes.ACC_PUBLIC, PreviewFormAction.PREVIEW_BINDING_FIELD, "Ljavax/swing/JComponent;", null, null);
    @NonNls MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
    cw.visitEnd();
    ByteArrayInputStream bais = new ByteArrayInputStream(cw.toByteArray());
    AsmCodeGenerator acg = new AsmCodeGenerator(rootContainer, myFinder, this, true, new PsiClassWriter(myModule));
    byte[] data = acg.patchClass(bais);
    FormErrorInfo[] errors = acg.getErrors();
    if (errors.length > 0) {
        throw new CodeGenerationException(errors[0].getComponentId(), errors[0].getErrorMessage());
    }
    FileUtil.writeToFile(new File(myTempPath, generatedClassName + ".class"), data);
}
Also used : NonNls(org.jetbrains.annotations.NonNls) CodeGenerationException(com.intellij.uiDesigner.compiler.CodeGenerationException) ByteArrayInputStream(java.io.ByteArrayInputStream) PsiClassWriter(com.intellij.compiler.PsiClassWriter) FormErrorInfo(com.intellij.uiDesigner.compiler.FormErrorInfo) AsmCodeGenerator(com.intellij.uiDesigner.compiler.AsmCodeGenerator) File(java.io.File) ClassWriter(org.jetbrains.org.objectweb.asm.ClassWriter) PsiClassWriter(com.intellij.compiler.PsiClassWriter) MethodVisitor(org.jetbrains.org.objectweb.asm.MethodVisitor)

Example 4 with FormErrorInfo

use of com.intellij.uiDesigner.compiler.FormErrorInfo in project intellij-community by JetBrains.

the class Form2SourceCompiler method process.

public ProcessingItem[] process(final CompileContext context, final ProcessingItem[] items) {
    final ArrayList<ProcessingItem> compiledItems = new ArrayList<>();
    context.getProgressIndicator().setText(UIDesignerBundle.message("progress.compiling.ui.forms"));
    int formsProcessed = 0;
    final Project project = context.getProject();
    final FormSourceCodeGenerator generator = new FormSourceCodeGenerator(project);
    final HashSet<Module> processedModules = new HashSet<>();
    final List<File> filesToRefresh = new ArrayList<>();
    for (ProcessingItem item1 : items) {
        context.getProgressIndicator().setFraction((double) (++formsProcessed) / ((double) items.length));
        final MyInstrumentationItem item = (MyInstrumentationItem) item1;
        final VirtualFile formFile = item.getFormFile();
        if (GuiDesignerConfiguration.getInstance(project).COPY_FORMS_RUNTIME_TO_OUTPUT) {
            ApplicationManager.getApplication().runReadAction(() -> {
                final Module module = ModuleUtilCore.findModuleForFile(formFile, project);
                if (module != null && !processedModules.contains(module)) {
                    processedModules.add(module);
                    final String moduleOutputPath = CompilerPaths.getModuleOutputPath(module, false);
                    try {
                        if (moduleOutputPath != null) {
                            filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(moduleOutputPath, false));
                        }
                        final String testsOutputPath = CompilerPaths.getModuleOutputPath(module, true);
                        if (testsOutputPath != null && !testsOutputPath.equals(moduleOutputPath)) {
                            filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(testsOutputPath, false));
                        }
                    } catch (IOException e) {
                        addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.copy.gui.designer.form.runtime", module.getName(), e.toString())), null);
                    }
                }
            });
        }
        ApplicationManager.getApplication().invokeAndWait(() -> {
            CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
                PsiDocumentManager.getInstance(project).commitAllDocuments();
                generator.generate(formFile);
                final ArrayList<FormErrorInfo> errors = generator.getErrors();
                if (errors.size() == 0) {
                    compiledItems.add(item);
                } else {
                    for (final FormErrorInfo e : errors) {
                        addError(context, e, formFile);
                    }
                }
            }), "", null);
            FileDocumentManager.getInstance().saveAllDocuments();
        }, ModalityState.NON_MODAL);
    }
    CompilerUtil.refreshIOFiles(filesToRefresh);
    return compiledItems.toArray(new ProcessingItem[compiledItems.size()]);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) FormErrorInfo(com.intellij.uiDesigner.compiler.FormErrorInfo) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) HashSet(java.util.HashSet)

Aggregations

FormErrorInfo (com.intellij.uiDesigner.compiler.FormErrorInfo)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 File (java.io.File)3 IOException (java.io.IOException)3 PsiClassWriter (com.intellij.compiler.PsiClassWriter)2 Module (com.intellij.openapi.module.Module)2 Project (com.intellij.openapi.project.Project)2 AsmCodeGenerator (com.intellij.uiDesigner.compiler.AsmCodeGenerator)2 ArrayList (java.util.ArrayList)2 FileSetCompileScope (com.intellij.compiler.impl.FileSetCompileScope)1 InstrumentationClassFinder (com.intellij.compiler.instrumentation.InstrumentationClassFinder)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 PsiFile (com.intellij.psi.PsiFile)1 FormEditingUtil (com.intellij.uiDesigner.FormEditingUtil)1