Search in sources :

Example 1 with LwRootContainer

use of com.intellij.uiDesigner.lw.LwRootContainer in project intellij-community by JetBrains.

the class FormsInstrumenter method instrumentForms.

private Map<File, Collection<File>> instrumentForms(CompileContext context, ModuleChunk chunk, final Map<File, String> chunkSourcePath, final InstrumentationClassFinder finder, Collection<File> forms, OutputConsumer outConsumer) throws ProjectBuildException {
    final Map<File, Collection<File>> instrumented = new THashMap<>(FileUtil.FILE_HASHING_STRATEGY);
    final Map<String, File> class2form = new HashMap<>();
    final MyNestedFormLoader nestedFormsLoader = new MyNestedFormLoader(chunkSourcePath, ProjectPaths.getOutputPathsWithDependents(chunk), finder);
    for (File formFile : forms) {
        final LwRootContainer rootContainer;
        try {
            rootContainer = Utils.getRootContainer(formFile.toURI().toURL(), new CompiledClassPropertiesProvider(finder.getLoader()));
        } catch (AlienFormFileException e) {
            // ignore non-IDEA forms
            continue;
        } catch (UnexpectedFormElementException e) {
            context.processMessage(new CompilerMessage(getPresentableName(), BuildMessage.Kind.ERROR, e.getMessage(), formFile.getPath()));
            LOG.info(e);
            continue;
        } catch (UIDesignerException e) {
            context.processMessage(new CompilerMessage(getPresentableName(), BuildMessage.Kind.ERROR, e.getMessage(), formFile.getPath()));
            LOG.info(e);
            continue;
        } catch (Exception e) {
            throw new ProjectBuildException("Cannot process form file " + formFile.getAbsolutePath(), e);
        }
        final String classToBind = rootContainer.getClassToBind();
        if (classToBind == null) {
            continue;
        }
        final CompiledClass compiled = findClassFile(outConsumer, classToBind);
        if (compiled == null) {
            context.processMessage(new CompilerMessage(getPresentableName(), BuildMessage.Kind.WARNING, "Class to bind does not exist: " + classToBind, formFile.getAbsolutePath()));
            continue;
        }
        final File alreadyProcessedForm = class2form.get(classToBind);
        if (alreadyProcessedForm != null) {
            context.processMessage(new CompilerMessage(getPresentableName(), BuildMessage.Kind.WARNING, formFile.getAbsolutePath() + ": The form is bound to the class " + classToBind + ".\nAnother form " + alreadyProcessedForm.getAbsolutePath() + " is also bound to this class", formFile.getAbsolutePath()));
            continue;
        }
        class2form.put(classToBind, formFile);
        for (File file : compiled.getSourceFiles()) {
            addBinding(file, formFile, instrumented);
        }
        try {
            context.processMessage(new ProgressMessage("Instrumenting forms... [" + chunk.getPresentableShortName() + "]"));
            final BinaryContent originalContent = compiled.getContent();
            final ClassReader classReader = new FailSafeClassReader(originalContent.getBuffer(), originalContent.getOffset(), originalContent.getLength());
            final int version = ClassProcessingBuilder.getClassFileVersion(classReader);
            final InstrumenterClassWriter classWriter = new InstrumenterClassWriter(classReader, ClassProcessingBuilder.getAsmClassWriterFlags(version), finder);
            final AsmCodeGenerator codeGenerator = new AsmCodeGenerator(rootContainer, finder, nestedFormsLoader, false, classWriter);
            final byte[] patchedBytes = codeGenerator.patchClass(classReader);
            if (patchedBytes != null) {
                compiled.setContent(new BinaryContent(patchedBytes));
            }
            final FormErrorInfo[] warnings = codeGenerator.getWarnings();
            for (final FormErrorInfo warning : warnings) {
                context.processMessage(new CompilerMessage(getPresentableName(), BuildMessage.Kind.WARNING, warning.getErrorMessage(), formFile.getAbsolutePath()));
            }
            final FormErrorInfo[] errors = codeGenerator.getErrors();
            if (errors.length > 0) {
                StringBuilder message = new StringBuilder();
                for (final FormErrorInfo error : errors) {
                    if (message.length() > 0) {
                        message.append("\n");
                    }
                    message.append(formFile.getAbsolutePath()).append(": ").append(error.getErrorMessage());
                }
                context.processMessage(new CompilerMessage(getPresentableName(), BuildMessage.Kind.ERROR, message.toString()));
            }
        } catch (Exception e) {
            context.processMessage(new CompilerMessage(getPresentableName(), BuildMessage.Kind.ERROR, "Forms instrumentation failed" + e.getMessage(), formFile.getAbsolutePath()));
        }
    }
    return instrumented;
}
Also used : ProgressMessage(org.jetbrains.jps.incremental.messages.ProgressMessage) CompilerMessage(org.jetbrains.jps.incremental.messages.CompilerMessage) THashMap(gnu.trove.THashMap) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) THashMap(gnu.trove.THashMap) InstrumenterClassWriter(com.intellij.compiler.instrumentation.InstrumenterClassWriter) CompiledClassPropertiesProvider(com.intellij.uiDesigner.lw.CompiledClassPropertiesProvider) FailSafeClassReader(com.intellij.compiler.instrumentation.FailSafeClassReader) ClassReader(org.jetbrains.org.objectweb.asm.ClassReader) FailSafeClassReader(com.intellij.compiler.instrumentation.FailSafeClassReader)

Example 2 with LwRootContainer

use of com.intellij.uiDesigner.lw.LwRootContainer in project intellij-community by JetBrains.

the class DataBindingWizardAction method actionPerformed.

public void actionPerformed(final AnActionEvent e) {
    final Project project;
    final VirtualFile formFile;
    GuiEditor editor = FormEditingUtil.getActiveEditor(e.getDataContext());
    if (editor == null) {
        return;
    }
    project = editor.getProject();
    formFile = editor.getFile();
    try {
        final WizardData wizardData = new WizardData(project, formFile);
        final Module module = ModuleUtilCore.findModuleForFile(formFile, wizardData.myProject);
        LOG.assertTrue(module != null);
        final LwRootContainer[] rootContainer = new LwRootContainer[1];
        Generator.exposeForm(wizardData.myProject, formFile, rootContainer);
        final String classToBind = rootContainer[0].getClassToBind();
        if (classToBind == null) {
            Messages.showInfoMessage(project, UIDesignerBundle.message("info.form.not.bound"), UIDesignerBundle.message("title.data.binding.wizard"));
            return;
        }
        final PsiClass boundClass = FormEditingUtil.findClassToBind(module, classToBind);
        if (boundClass == null) {
            Messages.showErrorDialog(project, UIDesignerBundle.message("error.bound.to.not.found.class", classToBind), UIDesignerBundle.message("title.data.binding.wizard"));
            return;
        }
        Generator.prepareWizardData(wizardData, boundClass);
        if (!hasBinding(rootContainer[0])) {
            Messages.showInfoMessage(project, UIDesignerBundle.message("info.no.bound.components"), UIDesignerBundle.message("title.data.binding.wizard"));
            return;
        }
        if (!wizardData.myBindToNewBean) {
            final String[] variants = new String[] { UIDesignerBundle.message("action.alter.data.binding"), UIDesignerBundle.message("action.bind.to.another.bean"), CommonBundle.getCancelButtonText() };
            final int result = Messages.showYesNoCancelDialog(project, UIDesignerBundle.message("info.data.binding.regenerate", wizardData.myBeanClass.getQualifiedName()), UIDesignerBundle.message("title.data.binding"), variants[0], variants[1], variants[2], Messages.getQuestionIcon());
            if (result == Messages.YES) {
            // do nothing here
            } else if (result == Messages.NO) {
                wizardData.myBindToNewBean = true;
            } else {
                return;
            }
        }
        final DataBindingWizard wizard = new DataBindingWizard(project, wizardData);
        wizard.show();
    } catch (Generator.MyException exc) {
        Messages.showErrorDialog(project, exc.getMessage(), CommonBundle.getErrorTitle());
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiClass(com.intellij.psi.PsiClass) WizardData(com.intellij.uiDesigner.wizard.WizardData) GuiEditor(com.intellij.uiDesigner.designSurface.GuiEditor) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) Project(com.intellij.openapi.project.Project) DataBindingWizard(com.intellij.uiDesigner.wizard.DataBindingWizard) Module(com.intellij.openapi.module.Module) Generator(com.intellij.uiDesigner.wizard.Generator)

Example 3 with LwRootContainer

use of com.intellij.uiDesigner.lw.LwRootContainer in project intellij-community by JetBrains.

the class GenerateMainAction method actionPerformed.

public void actionPerformed(AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    assert project != null;
    final Editor editor = e.getData(CommonDataKeys.EDITOR);
    assert editor != null;
    final int offset = editor.getCaretModel().getOffset();
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    PsiClass psiClass = PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiClass.class);
    assert psiClass != null;
    if (!PsiUtil.hasDefaultConstructor(psiClass)) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("generate.main.no.default.constructor"), UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    }
    final List<PsiFile> boundForms = FormClassIndex.findFormsBoundToClass(project, psiClass.getQualifiedName());
    final LwRootContainer rootContainer;
    try {
        rootContainer = Utils.getRootContainer(boundForms.get(0).getText(), null);
    } catch (AlienFormFileException ex) {
        Messages.showMessageDialog(project, "The form bound to the class is not a valid IntelliJ IDEA form", UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    } catch (Exception ex) {
        LOG.error(ex);
        return;
    }
    if (rootContainer.getComponentCount() == 0) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("generate.main.empty.form"), UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    }
    String rootBinding = rootContainer.getComponent(0).getBinding();
    if (rootBinding == null || psiClass.findFieldByName(rootBinding, true) == null) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("generate.main.no.root.binding"), UIDesignerBundle.message("generate.main.title"), Messages.getErrorIcon());
        return;
    }
    @NonNls final StringBuilder mainBuilder = new StringBuilder("public static void main(String[] args) { ");
    final JavaCodeStyleManager csm = JavaCodeStyleManager.getInstance(project);
    SuggestedNameInfo nameInfo = csm.suggestVariableName(VariableKind.LOCAL_VARIABLE, "frame", null, null);
    String varName = nameInfo.names[0];
    mainBuilder.append(JFrame.class.getName()).append(" ").append(varName).append("= new ").append(JFrame.class.getName());
    mainBuilder.append("(\"").append(psiClass.getName()).append("\");");
    mainBuilder.append(varName).append(".setContentPane(new ").append(psiClass.getQualifiedName()).append("().").append(rootBinding).append(");");
    mainBuilder.append(varName).append(".setDefaultCloseOperation(").append(JFrame.class.getName()).append(".EXIT_ON_CLOSE);");
    mainBuilder.append(varName).append(".pack();");
    mainBuilder.append(varName).append(".setVisible(true);");
    mainBuilder.append("}\n");
    CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            PsiMethod method = JavaPsiFacade.getInstance(file.getProject()).getElementFactory().createMethodFromText(mainBuilder.toString(), file);
            List<PsiGenerationInfo<PsiMethod>> infos = Collections.singletonList(new PsiGenerationInfo<>(method));
            List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersAtOffset(file, offset, infos);
            resultMembers.get(0).positionCaret(editor, false);
        } catch (IncorrectOperationException e1) {
            LOG.error(e1);
        }
    }), null, null);
}
Also used : NonNls(org.jetbrains.annotations.NonNls) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) IncorrectOperationException(com.intellij.util.IncorrectOperationException) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) List(java.util.List) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) PsiGenerationInfo(com.intellij.codeInsight.generation.PsiGenerationInfo)

Example 4 with LwRootContainer

use of com.intellij.uiDesigner.lw.LwRootContainer in project intellij-community by JetBrains.

the class FormWordsScanner method processWords.

@Override
public void processWords(CharSequence fileText, final Processor<WordOccurrence> processor) {
    super.processWords(fileText, processor);
    try {
        LwRootContainer container = Utils.getRootContainer(fileText.toString(), null);
        String className = container.getClassToBind();
        if (className != null) {
            processClassAndPackagesNames(className, processor);
        }
        FormEditingUtil.iterate(container, new FormEditingUtil.ComponentVisitor() {

            WordOccurrence occurence;

            public boolean visit(IComponent iComponent) {
                String componentClassName = iComponent.getComponentClassName();
                processClassAndPackagesNames(componentClassName, processor);
                final String binding = iComponent.getBinding();
                if (binding != null) {
                    if (occurence == null)
                        occurence = new WordOccurrence(binding, 0, binding.length(), WordOccurrence.Kind.FOREIGN_LANGUAGE);
                    else
                        occurence.init(binding, 0, binding.length(), WordOccurrence.Kind.FOREIGN_LANGUAGE);
                    processor.process(occurence);
                }
                return true;
            }
        });
    } catch (AlienFormFileException | JDOMParseException | UnexpectedFormElementException ex) {
    // ignore
    } catch (Exception e) {
        LOG.error("Error indexing form file", e);
    }
}
Also used : JDOMParseException(org.jdom.input.JDOMParseException) WordOccurrence(com.intellij.lang.cacheBuilder.WordOccurrence) IComponent(com.intellij.uiDesigner.lw.IComponent) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) FormEditingUtil(com.intellij.uiDesigner.FormEditingUtil) UnexpectedFormElementException(com.intellij.uiDesigner.compiler.UnexpectedFormElementException) AlienFormFileException(com.intellij.uiDesigner.compiler.AlienFormFileException) JDOMParseException(org.jdom.input.JDOMParseException) UnexpectedFormElementException(com.intellij.uiDesigner.compiler.UnexpectedFormElementException)

Example 5 with LwRootContainer

use of com.intellij.uiDesigner.lw.LwRootContainer in project intellij-community by JetBrains.

the class GuiEditor method readFromFile.

/**
   * Creates and sets new <code>RadRootContainer</code>
   *
   * @param keepSelection if true, the GUI designer tries to preserve the selection state after reload.
   */
public void readFromFile(final boolean keepSelection) {
    try {
        ComponentPtr[] selection = null;
        Map<String, String> tabbedPaneSelectedTabs = null;
        if (keepSelection) {
            selection = SelectionState.getSelection(this);
            tabbedPaneSelectedTabs = saveTabbedPaneSelectedTabs();
        }
        Locale oldLocale = null;
        if (myRootContainer != null) {
            oldLocale = myRootContainer.getStringDescriptorLocale();
        }
        final String text = myDocument.getText();
        final ClassLoader classLoader = LoaderFactory.getInstance(getProject()).getLoader(myFile);
        final LwRootContainer rootContainer = Utils.getRootContainer(text, new CompiledClassPropertiesProvider(classLoader));
        final RadRootContainer container = XmlReader.createRoot(this, rootContainer, classLoader, oldLocale);
        setRootContainer(container);
        if (keepSelection) {
            SelectionState.restoreSelection(this, selection);
            restoreTabbedPaneSelectedTabs(tabbedPaneSelectedTabs);
        }
        myInvalid = false;
        myCardLayout.show(myCardPanel, CARD_VALID);
        refresh();
    } catch (Exception exc) {
        Throwable original = exc;
        while (original instanceof InvocationTargetException) {
            original = original.getCause();
        }
        showInvalidCard(original);
    } catch (final LinkageError exc) {
        showInvalidCard(exc);
    }
}
Also used : Locale(java.util.Locale) CompiledClassPropertiesProvider(com.intellij.uiDesigner.lw.CompiledClassPropertiesProvider) RadRootContainer(com.intellij.uiDesigner.radComponents.RadRootContainer) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ComponentPtr(com.intellij.uiDesigner.componentTree.ComponentPtr)

Aggregations

LwRootContainer (com.intellij.uiDesigner.lw.LwRootContainer)15 Module (com.intellij.openapi.module.Module)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)4 Project (com.intellij.openapi.project.Project)3 FormEditingUtil (com.intellij.uiDesigner.FormEditingUtil)3 PsiPropertiesProvider (com.intellij.uiDesigner.PsiPropertiesProvider)3 AlienFormFileException (com.intellij.uiDesigner.compiler.AlienFormFileException)3 CompiledClassPropertiesProvider (com.intellij.uiDesigner.lw.CompiledClassPropertiesProvider)3 IncorrectOperationException (com.intellij.util.IncorrectOperationException)3 FailSafeClassReader (com.intellij.compiler.instrumentation.FailSafeClassReader)2 InstrumenterClassWriter (com.intellij.compiler.instrumentation.InstrumenterClassWriter)2 Document (com.intellij.openapi.editor.Document)2 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)2 IComponent (com.intellij.uiDesigner.lw.IComponent)2 PsiGenerationInfo (com.intellij.codeInsight.generation.PsiGenerationInfo)1 WordOccurrence (com.intellij.lang.cacheBuilder.WordOccurrence)1 Editor (com.intellij.openapi.editor.Editor)1 OpenFileDescriptor (com.intellij.openapi.fileEditor.OpenFileDescriptor)1 PsiClass (com.intellij.psi.PsiClass)1 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)1