summaryrefslogtreecommitdiff
path: root/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java
blob: 49766b110bfaf3cc706f001af2ac35314c75265d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.uiDesigner.actions;

import com.intellij.CommonBundle;
import com.intellij.compiler.PsiClassWriter;
import com.intellij.compiler.impl.FileSetCompileScope;
import com.intellij.compiler.instrumentation.InstrumentationClassFinder;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.execution.runners.ExecutionUtil;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.lang.properties.PropertiesFileType;
import com.intellij.lang.properties.PropertiesReferenceManager;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileStatusNotification;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.OrderEnumerator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.uiDesigner.compiler.AsmCodeGenerator;
import com.intellij.uiDesigner.compiler.FormErrorInfo;
import com.intellij.uiDesigner.compiler.Utils;
import com.intellij.uiDesigner.designSurface.GuiEditor;
import com.intellij.uiDesigner.lw.*;
import com.intellij.uiDesigner.make.PreviewNestedFormLoader;
import com.intellij.util.PathsList;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.incremental.java.CopyResourcesUtil;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

/**
 * @author Anton Katilin
 * @author Vladimir Kondratyev
 */
public final class PreviewFormAction extends AnAction{
  private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.actions.PreviewFormAction");

  /**
   * The problem is that this class is in a default package so it's not
   * import this class to refer
   */
  private static final String CLASS_TO_BIND_NAME = "FormPreviewFrame";
  @NonNls private static final String RUNTIME_BUNDLE_PREFIX = "RuntimeBundle";
  @NonNls public static final String PREVIEW_BINDING_FIELD = "myComponent";

  @NotNull
  public static InstrumentationClassFinder createClassFinder(@NotNull final String classPath){
    final ArrayList<URL> urls = new ArrayList<URL>();
    for (StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); tokenizer.hasMoreTokens();) {
      final String s = tokenizer.nextToken();
      try {
        urls.add(new File(s).toURI().toURL());
      }
      catch (Exception exc) {
        throw new RuntimeException(exc);
      }
    }
    return new InstrumentationClassFinder(urls.toArray(new URL[urls.size()]));
  }

  public void actionPerformed(final AnActionEvent e) {
    final GuiEditor editor = FormEditingUtil.getActiveEditor(e.getDataContext());
    if (editor != null) {
      showPreviewFrame(editor.getModule(), editor.getFile(), editor.getStringDescriptorLocale());
    }
  }

  public void update(final AnActionEvent e) {
    final GuiEditor editor = FormEditingUtil.getActiveEditor(e.getDataContext());

    if(editor == null){
      e.getPresentation().setVisible(false);
      return;
    }

    final VirtualFile file = editor.getFile();
    e.getPresentation().setVisible(
      FileDocumentManager.getInstance().getDocument(file) != null &&
      file.getFileType() == StdFileTypes.GUI_DESIGNER_FORM
    );
  }

  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<String>();
      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<VirtualFile>();
        HashSet<Module> modules = new HashSet<Module>();
        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();
    }
  }

  public static void setPreviewBindings(final LwRootContainer rootContainer, final String classToBindName) {
    // 1. Prepare form to preview. We have to change container so that it has only one binding.
    rootContainer.setClassToBind(classToBindName);
    FormEditingUtil.iterate(
      rootContainer,
      new FormEditingUtil.ComponentVisitor<LwComponent>() {
        public boolean visit(final LwComponent iComponent) {
          iComponent.setBinding(null);
          return true;
        }
      }
    );
    if (rootContainer.getComponentCount() == 1) {
      //noinspection HardCodedStringLiteral
      ((LwComponent)rootContainer.getComponent(0)).setBinding(PREVIEW_BINDING_FIELD);
    }
  }

  private static void runPreviewProcess(final String tempPath, final PathsList sources, final Module module, final VirtualFile formFile,
                                        @Nullable final Locale stringDescriptorLocale) {
    // 3. Now we are ready to launch Java process
    final JavaParameters parameters = new JavaParameters();
    parameters.getClassPath().add(tempPath);
    parameters.getClassPath().add(PathManager.findFileInLibDirectory("jgoodies-forms.jar").getAbsolutePath());
    final List<String> paths = sources.getPathList();
    for (final String path : paths) {
      parameters.getClassPath().add(path);
    }
    try {
      parameters.configureByModule(module, JavaParameters.JDK_AND_CLASSES);
    }
    catch (CantRunException e) {
      Messages.showErrorDialog(
        module.getProject(),
        UIDesignerBundle.message("error.cannot.preview.form", formFile.getPath().replace('/', File.separatorChar), e.getMessage()),
        CommonBundle.getErrorTitle()
      );
      return;
    }
    parameters.setMainClass("FormPreviewFrame");
    parameters.setWorkingDirectory(tempPath);
    if (stringDescriptorLocale != null && stringDescriptorLocale.getDisplayName().length() > 0) {
      parameters.getVMParametersList().add("-Duser.language=" + stringDescriptorLocale.getLanguage());
    }

    try {
      RunProfile profile = new MyRunProfile(module, parameters, tempPath,
                                            UIDesignerBundle.message("progress.preview.started", formFile.getPresentableUrl()));
      ExecutionEnvironmentBuilder.create(module.getProject(), DefaultRunExecutor.getRunExecutorInstance(), profile).buildAndExecute();
    }
    catch (ExecutionException e) {
      Messages.showErrorDialog(
        module.getProject(),
        UIDesignerBundle.message("error.cannot.preview.form", formFile.getPath().replace('/', File.separatorChar), e.getMessage()),
        CommonBundle.getErrorTitle()
      );
    }
  }

  private static final class MyRunProfile implements ModuleRunProfile {
    private final Module myModule;
    private final JavaParameters myParams;
    private final String myTempPath;
    private final String myStatusbarMessage;

    public MyRunProfile(final Module module, final JavaParameters params, final String tempPath, final String statusbarMessage) {
      myModule = module;
      myParams = params;
      myTempPath = tempPath;
      myStatusbarMessage = statusbarMessage;
    }

    public Icon getIcon() {
      return null;
    }

    public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
      return new JavaCommandLineState(env) {
        protected JavaParameters createJavaParameters() {
          return myParams;
        }

        public ExecutionResult execute(@NotNull final Executor executor, @NotNull final ProgramRunner runner) throws ExecutionException {
          try {
            ExecutionResult executionResult = super.execute(executor, runner);
            executionResult.getProcessHandler().addProcessListener(new ProcessAdapter() {
              @Override
              public void processTerminated(ProcessEvent event) {
                FileUtil.asyncDelete(new File(myTempPath));
              }
            });
            return executionResult;
          }
          finally {
            final Project project = myModule.getProject();
            SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                WindowManager.getInstance().getStatusBar(project).setInfo(myStatusbarMessage);
              }
            });
          }
        }
      };
    }

    public String getName() {
      return UIDesignerBundle.message("title.form.preview");
    }

    @NotNull
    public Module[] getModules() {
      return new Module[] {myModule};
    }
  }
}