KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > MetaComponentCreator


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.form;
21
22 import com.sun.source.tree.ClassTree;
23 import com.sun.source.tree.Tree;
24 import com.sun.source.util.TreePath;
25 import java.awt.*;
26 import java.io.IOException JavaDoc;
27 import java.util.logging.Level JavaDoc;
28 import java.util.logging.Logger JavaDoc;
29 import javax.lang.model.element.Element;
30 import javax.lang.model.element.TypeElement;
31 import javax.swing.*;
32 import javax.swing.undo.*;
33 import javax.swing.border.Border JavaDoc;
34 import java.util.*;
35 import java.text.MessageFormat JavaDoc;
36 import org.netbeans.api.java.source.CancellableTask;
37 import org.netbeans.api.java.source.CompilationController;
38 import org.netbeans.api.java.source.JavaSource;
39
40 import org.openide.*;
41 import org.openide.nodes.Node;
42 import org.openide.util.Mutex;
43 import org.openide.util.NbBundle;
44 import org.openide.filesystems.FileObject;
45
46 import org.netbeans.modules.form.layoutsupport.*;
47 import org.netbeans.modules.form.layoutdesign.*;
48 import org.netbeans.modules.form.layoutdesign.support.SwingLayoutBuilder;
49 import org.netbeans.modules.form.editors2.BorderDesignSupport;
50 import org.netbeans.modules.form.project.ClassSource;
51 import org.netbeans.modules.form.project.ClassPathUtils;
52
53 /**
54  * This class represents an access point for adding new components to FormModel.
55  * Its responsibility is to create new meta components (from provided bean
56  * classes) and add them to the FormModel. In some cases, no new component is
57  * created, just modified (e.g. when a border is applied). This class is
58  * intended to process user actions, so all errors are caught and reported here.
59  *
60  * @author Tomas Pavek
61  */

62
63 public class MetaComponentCreator {
64
65     private static final int NO_TARGET = 0;
66     private static final int TARGET_LAYOUT = 1;
67     private static final int TARGET_BORDER = 2;
68     private static final int TARGET_MENU = 3;
69     private static final int TARGET_VISUAL = 4;
70     private static final int TARGET_OTHER = 5;
71
72     FormModel formModel;
73
74     private RADVisualComponent preMetaComp;
75     private LayoutComponent preLayoutComp;
76
77     MetaComponentCreator(FormModel model) {
78         formModel = model;
79     }
80
81     /** Creates and adds a new metacomponent to FormModel. The new component
82      * is added to target component (if it is ComponentContainer).
83      * @param classSource ClassSource describing the component class
84      * @param constraints constraints object (for visual components only)
85      * @param targetComp component into which the new component is added
86      * @return the metacomponent if it was successfully created and added (all
87      * errors are reported immediately)
88      */

89     public RADComponent createComponent(ClassSource classSource,
90                                         RADComponent targetComp,
91                                         Object JavaDoc constraints)
92     {
93         Class JavaDoc compClass = prepareClass(classSource);
94         if (compClass == null)
95             return null; // class loading failed
96

97         return createAndAddComponent(compClass, targetComp, constraints);
98     }
99
100     /** Creates a copy of a metacomponent and adds it to FormModel. The new
101      * component is added to target component (if it is ComponentContainer)
102      * or applied to it (if it is layout or border).
103      * @param sourceComp metacomponent to be copied
104      * @param targetComp target component (where the new component is added)
105      * @return the component if it was successfully created and added (all
106      * errors are reported immediately)
107      */

108     public RADComponent copyComponent(final RADComponent sourceComp,
109                                       final RADComponent targetComp)
110     {
111         final int targetPlacement = getTargetPlacement(sourceComp.getBeanClass(),
112                                                        targetComp,
113                                                        false, false);
114         if (targetPlacement == NO_TARGET)
115             return null;
116
117         // hack needed due to screwed design of menu metacomponents
118
if (targetPlacement == TARGET_MENU
119                 && !(sourceComp instanceof RADMenuItemComponent))
120             return null;
121
122         try { // Look&Feel UI defaults remapping needed
123
return (RADComponent) FormLAF.executeWithLookAndFeel(
124                 new Mutex.ExceptionAction() {
125                     public Object JavaDoc run() throws Exception JavaDoc {
126                         return copyComponent2(sourceComp,
127                                               targetComp,
128                                               targetPlacement);
129                     }
130                 }
131             );
132         }
133         catch (Exception JavaDoc ex) { // should not happen
134
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
135             return null;
136         }
137     }
138
139     public static boolean canAddComponent(Class JavaDoc beanClass,
140                                           RADComponent targetComp)
141     {
142         int targetPlacement = getTargetPlacement(beanClass, targetComp,
143                                                  false, false);
144         return targetPlacement == TARGET_OTHER
145                 || targetPlacement == TARGET_MENU
146                 || targetPlacement == TARGET_VISUAL;
147     }
148
149     public static boolean canApplyComponent(Class JavaDoc beanClass,
150                                             RADComponent targetComp)
151     {
152         int targetPlacement = getTargetPlacement(beanClass, targetComp,
153                                                  false, false);
154         return targetPlacement == TARGET_BORDER
155                 || targetPlacement == TARGET_LAYOUT;
156     }
157
158     // --------
159
// Visual component can be precreated before added to form to provide for
160
// better visual feedback when being added. The precreated component may
161
// end up as added or canceled. If it is added to the form (by the user),
162
// addPrecreatedComponent methods gets called. If adding is canceled for
163
// whatever reason, releasePrecreatedComponent is called.
164

165     RADVisualComponent precreateVisualComponent(ClassSource classSource) {
166         final Class JavaDoc compClass = prepareClass(classSource);
167
168         if (compClass == null
169               || java.awt.Window JavaDoc.class.isAssignableFrom(compClass)
170               || java.applet.Applet JavaDoc.class.isAssignableFrom(compClass)
171               || getTargetPlacement(compClass, null, true, false)
172                     != TARGET_VISUAL)
173             return null;
174
175         if (preMetaComp != null)
176             releasePrecreatedComponent();
177
178         try { // Look&Feel UI defaults remapping needed
179
FormLAF.executeWithLookAndFeel(
180                 new Mutex.ExceptionAction() {
181                     public Object JavaDoc run() throws Exception JavaDoc {
182                         preMetaComp = createVisualComponent(compClass);
183                         return preMetaComp;
184                     }
185                 }
186             );
187             return preMetaComp;
188         }
189         catch (Exception JavaDoc ex) { // should not happen
190
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
191             return null;
192         }
193     }
194
195     RADVisualComponent getPrecreatedMetaComponent() {
196         return preMetaComp;
197     }
198
199     LayoutComponent getPrecreatedLayoutComponent() {
200         if (preMetaComp != null) {
201             if (preLayoutComp == null) {
202                 preLayoutComp = createLayoutComponent(preMetaComp);
203             }
204             return preLayoutComp;
205         }
206         return null;
207     }
208
209     LayoutComponent createLayoutComponent(RADVisualComponent metacomp) {
210         Dimension initialSize = prepareDefaultLayoutSize(
211                 (Component)metacomp.getBeanInstance(),
212                 metacomp instanceof RADVisualContainer);
213         boolean isLayoutContainer = shouldBeLayoutContainer(metacomp);
214         if (isLayoutContainer) {
215             RADVisualContainer metacont = (RADVisualContainer)metacomp;
216             Container cont = metacont.getContainerDelegate(metacont.getBeanInstance());
217             if (initialSize == null) {
218                 initialSize = cont.getPreferredSize();
219             }
220             Insets insets = cont.getInsets();
221             initialSize.width -= insets.left + insets.right;
222             initialSize.height -= insets.top + insets.bottom;
223             initialSize.width = Math.max(initialSize.width, 0); // Issue 83945
224
initialSize.height = Math.max(initialSize.height, 0);
225         }
226         // test code logging - only for precreation
227
if (metacomp == preMetaComp) {
228             LayoutDesigner ld = FormEditor.getFormDesigner(formModel).getLayoutDesigner();
229             if ((ld != null) && ld.logTestCode()) {
230                 if (initialSize == null) {
231                     ld.testCode.add("lc = new LayoutComponent(\"" + metacomp.getId() + "\", " + isLayoutContainer + ");"); //NOI18N
232
} else {
233                     ld.testCode.add("lc = new LayoutComponent(\"" + metacomp.getId() + "\", " + isLayoutContainer + ", " + //NOI18N
234
initialSize.width + ", " + initialSize.height + ");"); //NOI18N
235
}
236             }
237         }
238         return initialSize == null ?
239             new LayoutComponent(metacomp.getId(), isLayoutContainer) :
240             new LayoutComponent(metacomp.getId(), isLayoutContainer,
241                                 initialSize.width, initialSize.height);
242     }
243
244     static boolean shouldBeLayoutContainer(RADComponent metacomp) {
245         return metacomp instanceof RADVisualContainer
246                && ((RADVisualContainer)metacomp).getLayoutSupport() == null;
247     }
248
249     boolean addPrecreatedComponent(RADComponent targetComp,
250                                 Object JavaDoc constraints)
251     {
252         if (preMetaComp == null)
253             return false;
254         if (checkFormClass(preMetaComp.getBeanClass())) {
255             addVisualComponent2(preMetaComp,
256                                 targetComp,
257                                 constraints);
258
259             preMetaComp = null;
260             preLayoutComp = null;
261             return true;
262         } else {
263             releasePrecreatedComponent();
264             return false;
265         }
266     }
267
268     void releasePrecreatedComponent() {
269         if (preMetaComp != null) {
270             preMetaComp = null;
271             preLayoutComp = null;
272         }
273     }
274
275     // --------
276

277     private RADComponent createAndAddComponent(final Class JavaDoc compClass,
278                                                final RADComponent targetComp,
279                                                final Object JavaDoc constraints)
280     {
281         // check adding form class to itself
282
if (!checkFormClass(compClass))
283             return null;
284
285         final int targetPlacement =
286             getTargetPlacement(compClass, targetComp, true, true);
287
288         if (targetPlacement == NO_TARGET)
289             return null;
290
291         try { // Look&Feel UI defaults remapping needed
292
return (RADComponent) FormLAF.executeWithLookAndFeel(
293                 new Mutex.ExceptionAction() {
294                     public Object JavaDoc run() throws Exception JavaDoc {
295                         return createAndAddComponent2(compClass,
296                                                       targetComp,
297                                                       targetPlacement,
298                                                       constraints);
299                     }
300                 }
301             );
302         }
303         catch (Exception JavaDoc ex) { // should not happen
304
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
305             return null;
306         }
307     }
308
309     private RADComponent createAndAddComponent2(Class JavaDoc compClass,
310                                                 RADComponent targetComp,
311                                                 int targetPlacement,
312                                                 Object JavaDoc constraints)
313     {
314         if (targetPlacement == TARGET_LAYOUT)
315             return setContainerLayout(compClass, null, targetComp);
316
317         if (targetPlacement == TARGET_BORDER)
318             return setComponentBorder(compClass, targetComp);
319
320         RADComponent newMetaComp = null;
321
322         if (targetPlacement == TARGET_MENU)
323             newMetaComp = addMenuComponent(compClass, targetComp);
324
325         else if (targetPlacement == TARGET_VISUAL) {
326             newMetaComp = addVisualComponent(compClass, targetComp, constraints);
327             if (java.awt.Window JavaDoc.class.isAssignableFrom(compClass) ||
328                 java.applet.Applet JavaDoc.class.isAssignableFrom(compClass)) {
329                 targetComp = null;
330             }
331         } else if (targetPlacement == TARGET_OTHER)
332             newMetaComp = addOtherComponent(compClass, targetComp);
333
334         if (newMetaComp instanceof RADVisualComponent
335             && (shouldBeLayoutContainer(targetComp)
336                 || (shouldBeLayoutContainer(newMetaComp))))
337         { // container with new layout...
338
createAndAddLayoutComponent((RADVisualComponent)newMetaComp,
339                                         (RADVisualContainer)targetComp,
340                                         null);
341         }
342
343         return newMetaComp;
344     }
345     
346     private void createAndAddLayoutComponent(RADVisualComponent radComp,
347             RADVisualContainer targetCont, LayoutComponent prototype) {
348         LayoutModel layoutModel = formModel.getLayoutModel();
349         LayoutComponent layoutComp = layoutModel.getLayoutComponent(radComp.getId());
350         if (layoutComp == null) {
351             layoutComp = createLayoutComponent(radComp);
352         }
353         javax.swing.undo.UndoableEdit JavaDoc ue = layoutModel.getUndoableEdit();
354         boolean autoUndo = true;
355         try {
356             LayoutComponent parent = shouldBeLayoutContainer(targetCont) ?
357                 layoutModel.getLayoutComponent(targetCont.getId()) : null;
358             layoutModel.addNewComponent(layoutComp, parent, prototype);
359             autoUndo = false;
360         } finally {
361             formModel.addUndoableEdit(ue);
362             if (autoUndo) {
363                 formModel.forceUndoOfCompoundEdit();
364             }
365         }
366     }
367
368     private RADComponent copyComponent2(RADComponent sourceComp,
369                                         RADComponent targetComp,
370                                         int targetPlacement)
371     {
372         // if layout or border is to be copied from a meta component, we just
373
// apply the cloned instance, but don't copy the meta component
374
if (targetPlacement == TARGET_LAYOUT)
375             return copyAndApplyLayout(sourceComp, targetComp);
376
377         if (targetPlacement == TARGET_BORDER)
378             return copyAndApplyBorder(sourceComp, targetComp);
379
380         // in other cases let's copy the source meta component
381

382         if (sourceComp instanceof RADVisualComponent)
383             LayoutSupportManager.storeConstraints(
384                                      (RADVisualComponent) sourceComp);
385
386         // copy the source metacomponent
387
RADComponent newMetaComp = makeCopy(sourceComp, targetPlacement);
388
389         if (newMetaComp == null) { // copying failed (for a mystic reason)
390
return null;
391         }
392
393         I18nSupport.internationalizeComponent(newMetaComp);
394
395         if (targetPlacement == TARGET_MENU) {
396             addMenuComponent(newMetaComp, targetComp);
397         }
398         else if (targetPlacement == TARGET_VISUAL) {
399             RADVisualComponent newVisual = (RADVisualComponent) newMetaComp;
400             Object JavaDoc constraints;
401             boolean addLayoutComponent = false;
402             if (targetComp != null) {
403                 RADVisualContainer targetCont = (RADVisualContainer)targetComp;
404                 LayoutSupportManager layoutSupport = targetCont.getLayoutSupport();
405                 if (layoutSupport == null) {
406                     constraints = null;
407                     addLayoutComponent = true;
408                 } else {
409                     constraints = layoutSupport.getStoredConstraints(newVisual);
410                 }
411             }
412             else constraints = null;
413
414             newMetaComp = addVisualComponent2(newVisual, targetComp, constraints);
415             // might be null if layout support did not accept the component
416

417             if (addLayoutComponent) {
418                 RADComponent parent = sourceComp.getParentComponent();
419                 LayoutComponent source = null;
420                 if ((parent instanceof RADVisualContainer)
421                     && (((RADVisualContainer)parent).getLayoutSupport() == null)) {
422                     source = sourceComp.getFormModel().getLayoutModel().getLayoutComponent(sourceComp.getId());
423                 }
424                 createAndAddLayoutComponent(newVisual, (RADVisualContainer)targetComp, source);
425             }
426         }
427         else if (targetPlacement == TARGET_OTHER) {
428             addOtherComponent(newMetaComp, targetComp);
429         }
430
431         return newMetaComp;
432     }
433
434     /** This method is responsible for decision whether a bean can be added to
435      * (or applied on) a target component in FormModel. It returns a constant
436      * of corresponding target operation. This method is used in two modes.
437      * It is more strict for copy/cut/paste operations (paramaters canUseParent
438      * and defaultToOthers are set to false), and less strict for visual
439      * ("click") operations (canUseParent and defaultToOthers set to true).
440      */

441     private static int getTargetPlacement(Class JavaDoc beanClass,
442                                           RADComponent targetComp,
443                                           boolean canUseParent,
444                                           boolean defaultToOthers)
445     {
446         if (LayoutSupportDelegate.class.isAssignableFrom(beanClass)
447               || LayoutManager.class.isAssignableFrom(beanClass))
448         { // layout manager
449
if (targetComp == null)
450                 return TARGET_OTHER;
451
452             RADVisualContainer targetCont;
453             if (targetComp instanceof RADVisualContainer)
454                 targetCont = (RADVisualContainer) targetComp;
455             else if (canUseParent)
456                 targetCont = targetComp instanceof RADVisualComponent ?
457                     (RADVisualContainer) targetComp.getParentComponent() :
458                     null;
459             else
460                 targetCont = null;
461
462             return targetCont != null && !targetCont.hasDedicatedLayoutSupport() ?
463                 TARGET_LAYOUT : NO_TARGET;
464         }
465
466         if (Border JavaDoc.class.isAssignableFrom(beanClass)) { // border
467
if (targetComp == null)
468                 return TARGET_OTHER;
469
470             return targetComp instanceof RADVisualComponent ?
471 // && JComponent.class.isAssignableFrom(beanClass)
472
TARGET_BORDER : NO_TARGET;
473         }
474
475         if (MenuComponent.class.isAssignableFrom(beanClass)
476               || JMenuItem.class.isAssignableFrom(beanClass)
477               || JMenuBar.class.isAssignableFrom(beanClass)
478               || JPopupMenu.class.isAssignableFrom(beanClass))
479         { // menu
480
if (targetComp == null)
481                 return TARGET_MENU;
482
483             if (targetComp instanceof RADMenuComponent) {
484                 // adding to a menu
485
return ((RADMenuComponent)targetComp).canAddItem(beanClass) ?
486                     TARGET_MENU : NO_TARGET;
487             }
488             else { // adding to a visual container?
489
RADVisualContainer targetCont;
490                 if (targetComp instanceof RADVisualContainer)
491                     targetCont = (RADVisualContainer) targetComp;
492                 else if (canUseParent)
493                     targetCont = targetComp instanceof RADVisualComponent ?
494                         (RADVisualContainer) targetComp.getParentComponent() :
495                         null;
496                 else
497                     targetCont = null;
498
499                 if (targetCont != null) { // yes, this is a visual container
500
if (targetCont.getContainerMenu() == null
501                             && targetCont.canHaveMenu(beanClass))
502                         return TARGET_MENU;
503                 }
504                 else return NO_TARGET; // unknown container
505

506                 return defaultToOthers ? TARGET_MENU : NO_TARGET;
507                 // [Temporary solution - better would be to let the menu be
508
// tried as a visual component (Now, it would not have special
509
// features of menu components like adding submenus, menu items,
510
// etc). This should be fixed. Meanwhile, we return here...]
511
}
512         }
513
514         else if (JSeparator.class.isAssignableFrom(beanClass)
515                  || Separator.class.isAssignableFrom(beanClass))
516         { // separator
517
if (targetComp == null)
518                 return TARGET_VISUAL;
519
520             if (targetComp instanceof RADMenuComponent) {
521                 // adding to a menu
522
return ((RADMenuComponent)targetComp).canAddItem(beanClass) ?
523                     TARGET_MENU : NO_TARGET;
524             }
525         }
526
527         if (Component.class.isAssignableFrom(beanClass)) {
528             // visual component
529
if (targetComp == null)
530                 return TARGET_VISUAL;
531
532             if (java.awt.Window JavaDoc.class.isAssignableFrom(beanClass)
533                     || java.applet.Applet JavaDoc.class.isAssignableFrom(beanClass))
534                 return defaultToOthers ? TARGET_VISUAL : NO_TARGET;
535
536             if (!(targetComp instanceof RADVisualComponent))
537                 return NO_TARGET; // no visual target
538

539             if (!canUseParent && !(targetComp instanceof RADVisualContainer))
540                 return NO_TARGET; // no visual container target
541

542             return TARGET_VISUAL;
543         }
544
545         if (targetComp == null || defaultToOthers)
546             return TARGET_OTHER;
547
548         return NO_TARGET;
549     }
550
551     // ---------
552

553     private RADComponent makeCopy(RADComponent sourceComp, int targetPlacement) {
554         RADComponent newComp;
555
556         if (sourceComp instanceof RADVisualContainer)
557             newComp = new RADVisualContainer();
558         else if (sourceComp instanceof RADVisualComponent) {
559             if (targetPlacement == TARGET_MENU)
560                 newComp = new RADMenuItemComponent();
561             else
562                 newComp = new RADVisualComponent();
563         }
564         else if (sourceComp instanceof RADMenuComponent)
565             newComp = new RADMenuComponent();
566         else if (sourceComp instanceof RADMenuItemComponent) {
567             if (targetPlacement == TARGET_VISUAL)
568                 newComp = new RADVisualComponent();
569             else
570                 newComp = new RADMenuItemComponent();
571         }
572         else
573             newComp = new RADComponent();
574
575         newComp.initialize(formModel);
576         if (sourceComp != sourceComp.getFormModel().getTopRADComponent())
577             newComp.setStoredName(sourceComp.getName());
578
579         try {
580             newComp.initInstance(sourceComp.getBeanClass());
581             newComp.setInModel(true); // need code epxression created (issue 68897)
582
}
583         catch (Exception JavaDoc ex) { // this is rather unlikely to fail
584
ErrorManager em = ErrorManager.getDefault();
585             em.annotate(ex,
586                         FormUtils.getBundleString("MSG_ERR_CannotCopyInstance")); // NOI18N
587
em.notify(ex);
588             return null;
589         }
590
591         // 1st - copy subcomponents
592
if (sourceComp instanceof ComponentContainer) {
593             RADComponent[] sourceSubs =
594                 ((ComponentContainer)sourceComp).getSubBeans();
595             RADComponent[] newSubs = new RADComponent[sourceSubs.length];
596
597             for (int i=0; i < sourceSubs.length; i++) {
598                 RADComponent newSubComp = makeCopy(sourceSubs[i], -1);
599                 if (newSubComp == null)
600                     return null;
601                 newSubs[i] = newSubComp;
602             }
603
604             ((ComponentContainer)newComp).initSubComponents(newSubs);
605
606             // 2nd - clone layout support
607
if (sourceComp instanceof RADVisualContainer) {
608                 RADVisualComponent[] newComps =
609                     new RADVisualComponent[newSubs.length];
610                 System.arraycopy(newSubs, 0, newComps, 0, newSubs.length);
611
612                 LayoutSupportManager sourceLayout =
613                     ((RADVisualContainer)sourceComp).getLayoutSupport();
614                 
615                 if (sourceLayout != null) {
616                     RADVisualContainer newCont = (RADVisualContainer)newComp;
617                     newCont.setOldLayoutSupport(true);
618                     newCont.getLayoutSupport()
619                         .copyLayoutDelegateFrom(sourceLayout, newComps);
620                 } else {
621                     Map sourceToTargetIds = new HashMap(sourceSubs.length);
622                     for (int i=0; i<sourceSubs.length; i++) {
623                         sourceToTargetIds.put(sourceSubs[i].getId(), newSubs[i].getId());
624                     }
625                     LayoutModel sourceLayoutModel = sourceComp.getFormModel().getLayoutModel();
626                     String JavaDoc sourceContainerId = sourceComp.getId();
627                     String JavaDoc targetContainerId = newComp.getId();
628                     formModel.getLayoutModel().copyModelFrom(sourceLayoutModel, sourceToTargetIds,
629                         sourceContainerId, targetContainerId);
630                 }
631             }
632         }
633
634         // 3rd - copy changed properties
635
java.util.List JavaDoc sourceList = new ArrayList();
636         java.util.List JavaDoc namesList = new ArrayList();
637
638         Iterator it = sourceComp.getBeanPropertiesIterator(
639                                    FormProperty.CHANGED_PROPERTY_FILTER,
640                                    false);
641         while (it.hasNext()) {
642             RADProperty prop = (RADProperty) it.next();
643             sourceList.add(prop);
644             namesList.add(prop.getName());
645         }
646
647         RADProperty[] sourceProps = new RADProperty[sourceList.size()];
648         sourceList.toArray(sourceProps);
649         String JavaDoc[] propNames = new String JavaDoc[namesList.size()];
650         namesList.toArray(propNames);
651         RADProperty[] newProps = newComp.getBeanProperties(propNames);
652         int copyMode = FormUtils.DISABLE_CHANGE_FIRING;
653         if (formModel == sourceComp.getFormModel())
654             copyMode |= FormUtils.PASS_DESIGN_VALUES;
655
656         FormUtils.copyProperties(sourceProps, newProps, copyMode);
657
658         // temporary hack for AWT menus - to update their Swing design parallels
659
if (newComp instanceof RADMenuItemComponent)
660             formModel.fireComponentPropertyChanged(newComp, null, null, null);
661
662         // 4th - copy aux values
663
Map auxValues = sourceComp.getAuxValues();
664         if (auxValues != null)
665             for (it = auxValues.entrySet().iterator(); it.hasNext(); ) {
666                 Map.Entry entry = (Map.Entry)it.next();
667                 String JavaDoc auxName = (String JavaDoc)entry.getKey();
668                 Object JavaDoc auxValue = entry.getValue();
669                 try {
670                     newComp.setAuxValue(auxName,
671                                         FormUtils.cloneObject(auxValue, formModel));
672                 }
673                 catch (Exception JavaDoc e) { // ignore problem with aux value
674
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
675                 }
676             }
677     
678         // 5th - copy layout constraints
679
if (sourceComp instanceof RADVisualComponent
680             && newComp instanceof RADVisualComponent)
681         {
682             Map constraints = ((RADVisualComponent)sourceComp).getConstraintsMap();
683             Map newConstraints = new HashMap();
684
685             for (it = constraints.entrySet().iterator(); it.hasNext(); ) {
686                 Map.Entry entry = (Map.Entry)it.next();
687                 Object JavaDoc layoutClassName = entry.getKey();
688                 LayoutConstraints clonedConstr =
689                     ((LayoutConstraints)entry.getValue())
690                         .cloneConstraints();
691                 newConstraints.put(layoutClassName, clonedConstr);
692             }
693             ((RADVisualComponent)newComp).setConstraintsMap(newConstraints);
694         }
695
696         // 6th - copy events
697
Event[] sourceEvents = sourceComp.getKnownEvents();
698     String JavaDoc[] eventNames = new String JavaDoc[sourceEvents.length];
699     String JavaDoc[][] eventHandlers = new String JavaDoc[sourceEvents.length][];
700     for (int eventsIdx=0; eventsIdx < sourceEvents.length; eventsIdx++) {
701         eventNames[eventsIdx] = sourceEvents[eventsIdx].getName();
702         eventHandlers[eventsIdx] = sourceEvents[eventsIdx].getEventHandlers();
703     }
704         
705     FormEvents formEvents = formModel.getFormEvents();
706     Event[] targetEvents = newComp.getEvents(eventNames);
707     for (int targetEventsIdx = 0; targetEventsIdx < targetEvents.length; targetEventsIdx++) {
708         
709         Event targetEvent = targetEvents[targetEventsIdx];
710         if (targetEvent == null)
711         continue; // [uknown event error - should be reported!]
712

713         String JavaDoc[] handlers = eventHandlers[targetEventsIdx];
714         for (int handlersIdx = 0; handlersIdx < handlers.length; handlersIdx++) {
715         String JavaDoc newHandlerName;
716         String JavaDoc oldHandlerName = handlers[handlersIdx];
717         String JavaDoc sourceVariableName = sourceComp.getName();
718         String JavaDoc targetVariableName = newComp.getName();
719
720         int idx = oldHandlerName.indexOf(sourceVariableName);
721         if (idx >= 0) {
722             newHandlerName = oldHandlerName.substring(0, idx)
723                    + targetVariableName
724                    + oldHandlerName.substring(idx + sourceVariableName.length());
725         } else {
726             newHandlerName = targetVariableName
727                    + oldHandlerName;
728         }
729         newHandlerName = formEvents.findFreeHandlerName(newHandlerName);
730                 
731         String JavaDoc bodyText = null;
732         if(sourceComp.getFormModel() != formModel) {
733             // copying to different form -> let's copy also the event handler content
734
JavaCodeGenerator javaCodeGenerator =
735                 ((JavaCodeGenerator)FormEditor.getCodeGenerator(sourceComp.getFormModel()));
736             bodyText = javaCodeGenerator.getEventHandlerText(oldHandlerName);
737         }
738         
739         try {
740             formEvents.attachEvent(targetEvent, newHandlerName, bodyText);
741         }
742         catch (IllegalArgumentException JavaDoc ex) {
743             // [incompatible handler error - should be reported!]
744
ex.printStackTrace();
745         }
746         }
747     }
748     
749         return newComp;
750     }
751
752     // --------
753

754     private RADComponent addVisualComponent(Class JavaDoc compClass,
755                                             RADComponent targetComp,
756                                             Object JavaDoc constraints)
757     {
758         RADVisualComponent newMetaComp = createVisualComponent(compClass);
759
760 // Class beanClass = newMetaComp.getBeanClass();
761
if (java.awt.Window JavaDoc.class.isAssignableFrom(compClass)
762                 || java.applet.Applet JavaDoc.class.isAssignableFrom(compClass))
763             targetComp = null;
764
765         return addVisualComponent2(newMetaComp, targetComp, constraints);
766     }
767
768     private RADVisualComponent createVisualComponent(Class JavaDoc compClass) {
769         RADVisualComponent newMetaComp = null;
770         RADVisualContainer newMetaCont =
771             FormUtils.isContainer(compClass) ? new RADVisualContainer() : null;
772
773         while (newMetaComp == null) {
774             // initialize metacomponent and its bean instance
775
newMetaComp = newMetaCont == null ?
776                 new RADVisualComponent() : newMetaCont;
777
778             newMetaComp.initialize(formModel);
779             if (!initComponentInstance(newMetaComp, compClass))
780                 return null; // failure (reported)
781

782             if (newMetaCont == null)
783                 break; // not a container, the component is done
784

785             // prepare layout support (the new component is a container)
786
boolean knownLayout = false;
787             Throwable JavaDoc layoutEx = null;
788             try {
789         newMetaCont.setOldLayoutSupport(true);
790                 LayoutSupportManager laysup = newMetaCont.getLayoutSupport();
791                 knownLayout = laysup.prepareLayoutDelegate(false, false);
792                 if ((knownLayout && !laysup.isDedicated() && formModel.isFreeDesignDefaultLayout())
793                     || (!knownLayout && SwingLayoutBuilder.isRelevantContainer(laysup.getPrimaryContainerDelegate())))
794                 { // general containers should use the new layout support when created
795
newMetaCont.setOldLayoutSupport(false);
796                     FormEditor.getFormEditor(formModel).updateProjectForNaturalLayout();
797                     knownLayout = true;
798                 }
799             }
800             catch (RuntimeException JavaDoc ex) { // silently ignore, try again as non-container
801
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
802                 newMetaComp = null;
803                 newMetaCont = null;
804                 continue;
805             }
806             catch (Exception JavaDoc ex) {
807                 layoutEx = ex;
808             }
809             catch (LinkageError JavaDoc ex) {
810                 layoutEx = ex;
811             }
812
813             if (!knownLayout) {
814                 if (layoutEx == null) {
815                     // no LayoutSupportDelegate found for the container
816
System.err.println("[WARNING] No layout support found for "+compClass.getName()); // NOI18N
817
System.err.println(" Just a limited basic support will be used."); // NOI18N
818
}
819                 else { // layout support initialization failed
820
ErrorManager em = ErrorManager.getDefault();
821                     em.annotate(
822                         layoutEx,
823                         FormUtils.getBundleString("MSG_ERR_LayoutInitFailed2")); // NOI18N
824
em.notify(layoutEx);
825                 }
826
827                 newMetaCont.getLayoutSupport().setUnknownLayoutDelegate(false);
828             }
829         }
830
831         newMetaComp.setStoredName(formModel.getCodeStructure().getExternalVariableName(compClass, null, false));
832
833         // for some components, we initialize their properties with some
834
// non-default values e.g. a label on buttons, checkboxes
835
defaultVisualComponentInit(newMetaComp);
836
837         // hack: automatically enclose some components into scroll pane
838
// [PENDING check for undo/redo!]
839
if (shouldEncloseByScrollPane(newMetaComp.getBeanInstance())) {
840             RADVisualContainer metaScroll = (RADVisualContainer)
841                 createVisualComponent(JScrollPane.class);
842             // Mark this scroll pane as automatically created.
843
// Some action (e.g. delete) behave differently on
844
// components in such scroll panes.
845
metaScroll.setAuxValue("autoScrollPane", Boolean.TRUE); // NOI18N
846
metaScroll.add(newMetaComp);
847             Container scroll = (Container) metaScroll.getBeanInstance();
848             Component inScroll = (Component) newMetaComp.getBeanInstance();
849             metaScroll.getLayoutSupport().addComponentsToContainer(
850                     scroll, scroll, new Component[] { inScroll }, 0);
851             newMetaComp = metaScroll;
852         }
853
854         return newMetaComp;
855     }
856
857     private static boolean shouldEncloseByScrollPane(Object JavaDoc bean) {
858         return (bean instanceof JList) || (bean instanceof JTable)
859             || (bean instanceof JTree) || (bean instanceof JTextArea)
860             || (bean instanceof JTextPane) || (bean instanceof JEditorPane);
861     }
862
863     private RADComponent addVisualComponent2(RADVisualComponent newMetaComp,
864                                              RADComponent targetComp,
865                                              Object JavaDoc constraints)
866     {
867         // Issue 65254: beware of nested JScrollPanes
868
if ((targetComp != null) && JScrollPane.class.isAssignableFrom(targetComp.getBeanClass())) {
869             Object JavaDoc bean = newMetaComp.getBeanInstance();
870             if (bean instanceof JScrollPane) {
871                 if (newMetaComp.getAuxValue("autoScrollPane") != null) { // NOI18N
872
RADVisualContainer metaCont = (RADVisualContainer)newMetaComp;
873                     newMetaComp = metaCont.getSubComponent(0);
874                 }
875             }
876         }
877
878         // get parent container into which the new component will be added
879
RADVisualContainer parentCont;
880         if (targetComp != null) {
881             parentCont = targetComp instanceof RADVisualContainer ?
882                 (RADVisualContainer) targetComp :
883                 (RADVisualContainer) targetComp.getParentComponent();
884         }
885         else parentCont = null;
886
887         // add the new metacomponent to the model
888
if (parentCont != null) {
889             try {
890                 formModel.addVisualComponent(newMetaComp, parentCont, constraints, true);
891             }
892             catch (RuntimeException JavaDoc ex) {
893                 // LayoutSupportDelegate may not accept the component
894
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
895                 return null;
896             }
897         }
898         else formModel.addComponent(newMetaComp, null, true);
899
900         return newMetaComp;
901     }
902     
903     private RADComponent addOtherComponent(Class JavaDoc compClass,
904                                            RADComponent targetComp)
905     {
906         RADComponent newMetaComp = new RADComponent();
907         newMetaComp.initialize(formModel);
908         if (!initComponentInstance(newMetaComp, compClass))
909             return null;
910
911         addOtherComponent(newMetaComp, targetComp);
912         return newMetaComp;
913     }
914
915     private void addOtherComponent(RADComponent newMetaComp,
916                                    RADComponent targetComp)
917     {
918         ComponentContainer targetCont =
919             targetComp instanceof ComponentContainer
920                 && !(targetComp instanceof RADVisualContainer)
921                 && !(targetComp instanceof RADMenuComponent) ?
922             (ComponentContainer) targetComp : null;
923
924         formModel.addComponent(newMetaComp, targetCont, true);
925     }
926
927 // private RADComponent setContainerLayout(Class layoutClass,
928
// RADComponent targetComp)
929
// {
930
// return setContainerLayout(layoutClass, null, targetComp);
931
// }
932

933     private RADComponent setContainerLayout(Class JavaDoc layoutClass,
934                                             LayoutManager layoutInstance,
935                                             RADComponent targetComp)
936     {
937         // get container on which the layout is to be set
938
RADVisualContainer metacont;
939         if (targetComp instanceof RADVisualContainer)
940             metacont = (RADVisualContainer) targetComp;
941         else {
942             metacont = (RADVisualContainer) targetComp.getParentComponent();
943             if (metacont == null)
944                 return null;
945         }
946
947         LayoutSupportDelegate layoutDelegate = null;
948         Throwable JavaDoc t = null;
949         try {
950             if (LayoutManager.class.isAssignableFrom(layoutClass)) {
951                 // LayoutManager -> find LayoutSupportDelegate for it
952
layoutDelegate = LayoutSupportRegistry.getRegistry(formModel)
953                                      .createSupportForLayout(layoutClass);
954             }
955             else if (LayoutSupportDelegate.class.isAssignableFrom(layoutClass)) {
956                 // LayoutSupportDelegate -> use it directly
957
layoutDelegate = LayoutSupportRegistry.getRegistry(formModel)
958                                      .createSupportInstance(layoutClass);
959             }
960         }
961         catch (Exception JavaDoc ex) {
962             t = ex;
963         }
964         catch (LinkageError JavaDoc ex) {
965             t = ex;
966         }
967         if (t != null) {
968             String JavaDoc msg = FormUtils.getFormattedBundleString(
969                 "FMT_ERR_LayoutInit", // NOI18N
970
new Object JavaDoc[] { layoutClass.getName() });
971
972             ErrorManager em = ErrorManager.getDefault();
973             em.annotate(t, msg);
974             em.notify(t);
975             return null;
976         }
977
978         if (layoutDelegate == null) {
979             DialogDisplayer.getDefault().notify(
980                 new NotifyDescriptor.Message(
981                     FormUtils.getFormattedBundleString(
982                         "FMT_ERR_LayoutNotFound", // NOI18N
983
new Object JavaDoc[] { layoutClass.getName() }),
984                     NotifyDescriptor.WARNING_MESSAGE));
985
986             return null;
987         }
988
989         try {
990             formModel.setContainerLayout(metacont,
991                                          layoutDelegate,
992                                          layoutInstance);
993         }
994         catch (Exception JavaDoc ex) {
995             t = ex;
996         }
997         catch (LinkageError JavaDoc ex) {
998             t = ex;
999         }
1000        if (t != null) {
1001            String JavaDoc msg = FormUtils.getFormattedBundleString(
1002                "FMT_ERR_LayoutInit", // NOI18N
1003
new Object JavaDoc[] { layoutClass.getName() });
1004
1005            ErrorManager em = ErrorManager.getDefault();
1006            em.annotate(t, msg);
1007            em.notify(t);
1008            return null;
1009        }
1010
1011        return metacont;
1012    }
1013
1014    private RADComponent copyAndApplyLayout(RADComponent sourceComp,
1015                                            RADComponent targetComp)
1016    {
1017        try {
1018            LayoutManager lmInstance = (LayoutManager)
1019                                       sourceComp.cloneBeanInstance(null);
1020            // we clone the instance as we need the property values copied
1021
// for the LayoutSupportDelegate initialization which is done
1022
// and the delegate set before we can copy the properties...
1023

1024            RADVisualContainer targetCont = (RADVisualContainer)
1025                setContainerLayout(sourceComp.getBeanClass(),
1026                                   lmInstance,
1027                                   targetComp);
1028
1029            // copy properties additionally to handle design values
1030
Node.Property[] sourceProps = sourceComp.getKnownBeanProperties();
1031            Node.Property[] targetProps =
1032                targetCont.getLayoutSupport().getAllProperties();
1033            int copyMode = FormUtils.CHANGED_ONLY
1034                           | FormUtils.DISABLE_CHANGE_FIRING;
1035            if (formModel == sourceComp.getFormModel())
1036                copyMode |= FormUtils.PASS_DESIGN_VALUES;
1037
1038            FormUtils.copyProperties(sourceProps, targetProps, copyMode);
1039        }
1040        catch (Exception JavaDoc ex) { // ignore
1041
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1042        }
1043        catch (LinkageError JavaDoc ex) { // ignore
1044
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1045        }
1046
1047        return targetComp;
1048    }
1049
1050    private RADComponent setComponentBorder(Class JavaDoc borderClass,
1051                                            RADComponent targetComp)
1052    {
1053        FormProperty prop = getBorderProperty(targetComp);
1054        if (prop == null)
1055            return null;
1056
1057        try { // set border property
1058
Object JavaDoc border = CreationFactory.createInstance(borderClass);
1059            prop.setValue(border);
1060        }
1061        catch (Exception JavaDoc ex) {
1062            showInstErrorMessage(ex);
1063            return null;
1064        }
1065        catch (LinkageError JavaDoc ex) {
1066            showInstErrorMessage(ex);
1067            return null;
1068        }
1069
1070        FormDesigner designer = FormEditor.getFormDesigner(formModel);
1071        if (designer != null)
1072            designer.setSelectedComponent(targetComp);
1073
1074        return targetComp;
1075    }
1076
1077    private void setComponentBorderProperty(Object JavaDoc borderInstance,
1078                                            RADComponent targetComp)
1079    {
1080        FormProperty prop = getBorderProperty(targetComp);
1081        if (prop == null)
1082            return;
1083
1084        try { // set border property
1085
prop.setValue(borderInstance);
1086        }
1087        catch (Exception JavaDoc ex) { // should not happen
1088
ex.printStackTrace();
1089            return;
1090        }
1091
1092        FormDesigner designer = FormEditor.getFormDesigner(formModel);
1093        if (designer != null)
1094            designer.setSelectedComponent(targetComp);
1095    }
1096
1097    private RADComponent copyAndApplyBorder(RADComponent sourceComp,
1098                                            RADComponent targetComp)
1099    {
1100        try {
1101            Border JavaDoc borderInstance = (Border JavaDoc) sourceComp.createBeanInstance();
1102            BorderDesignSupport designBorder =
1103                new BorderDesignSupport(borderInstance);
1104
1105            Node.Property[] sourceProps = sourceComp.getKnownBeanProperties();
1106            Node.Property[] targetProps = designBorder.getProperties();
1107            int copyMode = FormUtils.CHANGED_ONLY | FormUtils.DISABLE_CHANGE_FIRING;
1108            if (formModel == sourceComp.getFormModel())
1109                copyMode |= FormUtils.PASS_DESIGN_VALUES;
1110
1111            FormUtils.copyProperties(sourceProps, targetProps, copyMode);
1112
1113            setComponentBorderProperty(designBorder, targetComp);
1114        }
1115        catch (Exception JavaDoc ex) { // ignore
1116
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1117        }
1118        catch (LinkageError JavaDoc ex) { // ignore
1119
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
1120        }
1121
1122        return targetComp;
1123    }
1124
1125    private FormProperty getBorderProperty(RADComponent targetComp) {
1126        FormProperty prop;
1127        if (JComponent.class.isAssignableFrom(targetComp.getBeanClass())
1128                && (prop = targetComp.getBeanProperty("border")) != null) // NOI18N
1129
return prop;
1130
1131        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
1132            FormUtils.getBundleString("MSG_BorderNotApplicable"), // NOI18N
1133
NotifyDescriptor.INFORMATION_MESSAGE));
1134
1135        return null;
1136    }
1137
1138    private RADComponent addMenuComponent(Class JavaDoc compClass,
1139                                          RADComponent targetComp)
1140    {
1141        // create new metacomponent
1142
RADMenuComponent newMenuComp;
1143        RADMenuItemComponent newMenuItemComp;
1144        if ((RADMenuItemComponent.recognizeType(compClass)
1145                 & RADMenuItemComponent.MASK_CONTAINER) != 0) {
1146            newMenuComp = new RADMenuComponent();
1147            newMenuItemComp = newMenuComp;
1148        }
1149        else {
1150            newMenuComp = null;
1151            newMenuItemComp = new RADMenuItemComponent();
1152        }
1153
1154        newMenuItemComp.initialize(formModel);
1155        if (!initComponentInstance(newMenuItemComp, compClass))
1156            return null;
1157        if (newMenuComp != null)
1158            newMenuComp.initSubComponents(new RADComponent[0]);
1159
1160        // for some components, we initialize their properties with some
1161
// non-default values e.g. a label on buttons, checkboxes
1162
defaultMenuInit(newMenuItemComp);
1163
1164        addMenuComponent(newMenuItemComp, targetComp);
1165
1166        // for new menu bars we do some additional special things...
1167
if (newMenuComp != null) {
1168            int type = newMenuComp.getMenuItemType();
1169            if (type == RADMenuItemComponent.T_MENUBAR
1170                    || type == RADMenuItemComponent.T_JMENUBAR)
1171            { // create first menu for the new menu bar
1172
org.openide.util.datatransfer.NewType[]
1173                    newTypes = newMenuComp.getNewTypes();
1174                if (newTypes.length > 0) {
1175                    try {
1176                        newTypes[0].create();
1177                    }
1178                    catch (java.io.IOException JavaDoc e) {} // ignore
1179
}
1180            }
1181        }
1182
1183        return newMenuItemComp;
1184    }
1185
1186    private void addMenuComponent(RADComponent newMenuComp,
1187                                  RADComponent targetComp)
1188    {
1189        Class JavaDoc beanClass = newMenuComp.getBeanClass();
1190        ComponentContainer menuContainer = null;
1191
1192        if (targetComp instanceof RADMenuComponent) {
1193            // adding to a menu
1194
if (newMenuComp instanceof RADMenuItemComponent
1195                    && ((RADMenuComponent)targetComp).canAddItem(beanClass))
1196                menuContainer = (ComponentContainer) targetComp;
1197        }
1198        else if (targetComp instanceof RADVisualComponent) {
1199            RADVisualContainer targetCont =
1200                targetComp instanceof RADVisualContainer ?
1201                    (RADVisualContainer) targetComp :
1202                    (RADVisualContainer) targetComp.getParentComponent();
1203
1204            if (targetCont != null
1205                    && targetCont.getContainerMenu() == null
1206                    && targetCont.canHaveMenu(beanClass))
1207                menuContainer = targetCont;
1208        }
1209
1210        formModel.addComponent(newMenuComp, menuContainer, true);
1211    }
1212
1213    // --------
1214

1215    private Class JavaDoc prepareClass(final ClassSource classSource) {
1216        if (classSource.getCPRootCount() == 0) { // Just some optimization
1217
return prepareClass0(classSource);
1218        } else {
1219            try {
1220                return (Class JavaDoc)FormLAF.executeWithLookAndFeel(
1221                    new Mutex.ExceptionAction() {
1222                        public Object JavaDoc run() throws Exception JavaDoc {
1223                            FormLAF.setCustomizingUIClasses(true); // Issue 80198
1224
try {
1225                                Class JavaDoc clazz = prepareClass0(classSource);
1226                                // Force creation of the default instance in the correct L&F context
1227
BeanSupport.getDefaultInstance(clazz);
1228                                return clazz;
1229                            } finally {
1230                                FormLAF.setCustomizingUIClasses(false);
1231                            }
1232                        }
1233                    }
1234                );
1235            } catch (Exception JavaDoc ex) {
1236                // should not happen
1237
ex.printStackTrace();
1238                return null;
1239            }
1240        }
1241    }
1242
1243    private Class JavaDoc prepareClass0(ClassSource classSource) {
1244        Throwable JavaDoc error = null;
1245        FileObject formFile = FormEditor.getFormDataObject(formModel).getFormFile();
1246        String JavaDoc className = classSource.getClassName();
1247        Class JavaDoc loadedClass = null;
1248        try {
1249            if (!ClassPathUtils.checkUserClass(className, formFile)) {
1250                ClassPathUtils.updateProject(formFile, classSource);
1251            }
1252            loadedClass = ClassPathUtils.loadClass(className, formFile);
1253        }
1254        catch (Exception JavaDoc ex) {
1255            error = ex;
1256        }
1257        catch (LinkageError JavaDoc ex) {
1258            error = ex;
1259        }
1260
1261        if (loadedClass == null) {
1262            showClassLoadingErrorMessage(error, classSource);
1263        }
1264        
1265        return loadedClass;
1266    }
1267
1268    private boolean checkFormClass(Class JavaDoc compClass) {
1269        if (formModel.getFormBaseClass().isAssignableFrom(compClass)) {
1270            
1271            String JavaDoc formClassBinaryName = getClassBinaryName(
1272                    FormEditor.getFormDataObject(formModel).getPrimaryFile());
1273            
1274            if (formClassBinaryName.equals(compClass.getName())) {
1275                DialogDisplayer.getDefault().notify(
1276                    new NotifyDescriptor.Message(
1277                        FormUtils.getBundleString("MSG_ERR_CannotAddForm"), // NOI18N
1278
NotifyDescriptor.WARNING_MESSAGE));
1279                return false;
1280            }
1281        }
1282        return true;
1283    }
1284    
1285    private static String JavaDoc getClassBinaryName(final FileObject fo) {
1286        final String JavaDoc[] result = new String JavaDoc[1];
1287        JavaSource js = JavaSource.forFileObject(fo);
1288        try {
1289            js.runUserActionTask(new CancellableTask<CompilationController>() {
1290                public void cancel() {
1291                }
1292                public void run(CompilationController controller) throws Exception JavaDoc {
1293                    controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
1294                    for (Tree t: controller.getCompilationUnit().getTypeDecls()) {
1295                        if (t.getKind() == Tree.Kind.CLASS &&
1296                                fo.getName().equals(((ClassTree) t).getSimpleName().toString())) {
1297                            TreePath classTreePath = controller.getTrees().getPath(controller.getCompilationUnit(), t);
1298                            Element classElm = controller.getTrees().getElement(classTreePath);
1299                            result[0] = classElm != null
1300                                    ? controller.getElements().getBinaryName((TypeElement) classElm).toString()
1301                                    : ""; // NOI18N
1302
break;
1303                        }
1304                    }
1305                }
1306            }, true);
1307        } catch (IOException JavaDoc ex) {
1308            Logger.getLogger(MetaComponentCreator.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
1309        }
1310        return result[0];
1311    }
1312
1313    private static void showClassLoadingErrorMessage(Throwable JavaDoc ex,
1314                                                     ClassSource classSource)
1315    {
1316        ErrorManager em = ErrorManager.getDefault();
1317        String JavaDoc msg = FormUtils.getFormattedBundleString(
1318            "FMT_ERR_CannotLoadClass4", // NOI18N
1319
new Object JavaDoc[] { classSource.getClassName(),
1320                           ClassPathUtils.getClassSourceDescription(classSource) });
1321        em.annotate(ex, msg);
1322        em.notify(ErrorManager.USER, ex); // Issue 65116 - don't show the exception to the user
1323
em.notify(ErrorManager.INFORMATIONAL, ex); // Make sure the exception is in the console and log file
1324
}
1325
1326    private boolean initComponentInstance(RADComponent metacomp,
1327                                          Class JavaDoc compClass)
1328    {
1329
1330        try {
1331            metacomp.initInstance(compClass);
1332        }
1333        catch (Exception JavaDoc ex) {
1334            showInstErrorMessage(ex);
1335            return false;
1336        }
1337        catch (LinkageError JavaDoc ex) {
1338            showInstErrorMessage(ex);
1339            return false;
1340        }
1341        return true;
1342    }
1343
1344    private static void showInstErrorMessage(Throwable JavaDoc ex) {
1345        ErrorManager em = ErrorManager.getDefault();
1346        em.annotate(ex,
1347                    FormUtils.getBundleString("MSG_ERR_CannotInstantiate")); // NOI18N
1348
em.notify(ex);
1349    }
1350
1351    // --------
1352
// default component initialization
1353

1354    static void defaultVisualComponentInit(RADComponent radComp) {
1355        Object JavaDoc comp = radComp.getBeanInstance();
1356        String JavaDoc varName = radComp.getName();
1357        // Map of propertyNames -> propertyValues
1358
Map changes = new HashMap();
1359        String JavaDoc propName = null;
1360        Object JavaDoc propValue = null;
1361
1362        if (comp instanceof AbstractButton) { // JButton, JToggleButton, JCheckBox, JRadioButton
1363
if ("".equals(((AbstractButton)comp).getText())) { // NOI18N
1364
propName = "text"; // NOI18N
1365
propValue = varName;
1366                changes.put(propName, propValue);
1367            }
1368            if (comp instanceof JCheckBox || comp instanceof JRadioButton) {
1369                if (((JToggleButton)comp).getBorder() instanceof javax.swing.plaf.UIResource JavaDoc) {
1370                    changes.put("border", BorderFactory.createEmptyBorder()); // NOI18N
1371
changes.put("margin", new Insets(0, 0, 0, 0)); // NOI18N
1372
}
1373            }
1374        }
1375        else if (comp instanceof JLabel) {
1376            if ("".equals(((JLabel)comp).getText())) { // NOI18N
1377
propName = "text"; // NOI18N
1378
propValue = varName;
1379                changes.put(propName, propValue);
1380            }
1381        }
1382        else if (comp instanceof JTable) {
1383            javax.swing.table.TableModel JavaDoc tm = ((JTable)comp).getModel();
1384            if (tm == null
1385                || (tm instanceof javax.swing.table.DefaultTableModel JavaDoc
1386                    && tm.getRowCount() == 0 && tm.getColumnCount() == 0))
1387            {
1388                String JavaDoc prefix = NbBundle.getMessage(MetaComponentCreator.class, "FMT_CreatorTableTitle"); // NOI18N
1389
prefix += ' ';
1390                propValue =
1391                    new org.netbeans.modules.form.editors2.TableModelEditor.NbTableModel(
1392                        new javax.swing.table.DefaultTableModel JavaDoc(
1393                            new String JavaDoc[] {
1394                                prefix + 1, prefix + 2, prefix + 3, prefix + 4 },
1395                            4));
1396                propName = "model"; // NOI18N
1397
changes.put(propName, propValue);
1398            }
1399        }
1400        else if (comp instanceof JTextField) {
1401            if ("".equals(((JTextField)comp).getText())) { // NOI18N
1402
propName = "text"; // NOI18N
1403
propValue = varName;
1404                changes.put(propName, propValue);
1405            }
1406        }
1407        else if (comp instanceof JInternalFrame) {
1408            propName = "visible"; // NOI18N
1409
propValue = Boolean.TRUE;
1410            changes.put(propName, propValue);
1411        }
1412        else if (comp instanceof Button) {
1413            if ("".equals(((Button)comp).getLabel())) { // NOI18N
1414
propName = "label"; // NOI18N
1415
propValue = varName;
1416                changes.put(propName, propValue);
1417            }
1418        }
1419        else if (comp instanceof Checkbox) {
1420            if ("".equals(((Checkbox)comp).getLabel())) { // NOI18N
1421
propName = "label"; // NOI18N
1422
propValue = varName;
1423                changes.put(propName, propValue);
1424            }
1425        }
1426        else if (comp instanceof Label) {
1427            if ("".equals(((Label)comp).getText())) { // NOI18N
1428
propName = "text"; // NOI18N
1429
propValue = varName;
1430                changes.put(propName, propValue);
1431            }
1432        }
1433        else if (comp instanceof TextField) {
1434            if ("".equals(((TextField)comp).getText())) { // NOI18N
1435
propName = "text"; // NOI18N
1436
propValue = varName;
1437                changes.put(propName, propValue);
1438            }
1439        } else if (comp instanceof JComboBox) {
1440            ComboBoxModel model = ((JComboBox)comp).getModel();
1441            if ((model == null) || (model.getSize() == 0)) {
1442                String JavaDoc prefix = NbBundle.getMessage(MetaComponentCreator.class, "FMT_CreatorComboBoxItem"); // NOI18N
1443
prefix += ' ';
1444                propValue = new DefaultComboBoxModel(new String JavaDoc[] {
1445                    prefix + 1, prefix + 2, prefix + 3, prefix + 4
1446                });
1447                propName = "model"; // NOI18N
1448
changes.put(propName, propValue);
1449            }
1450
1451        } else if (comp instanceof JList) {
1452            ListModel model = ((JList)comp).getModel();
1453            if ((model == null) || (model.getSize() == 0)) {
1454                String JavaDoc prefix = NbBundle.getMessage(MetaComponentCreator.class, "FMT_CreatorListItem"); // NOI18N
1455
prefix += ' ';
1456                DefaultListModel defaultModel = new DefaultListModel();
1457                for (int i=1; i<6; i++) {
1458                    defaultModel.addElement(prefix + i); // NOI18N
1459
}
1460                propValue = defaultModel;
1461                propName = "model"; // NOI18N
1462
changes.put(propName, propValue);
1463            }
1464        } else if (comp instanceof JTextArea) {
1465            JTextArea textArea = (JTextArea)comp;
1466            if (textArea.getRows() == 0) {
1467                propName = "rows"; // NOI18N
1468
propValue = new Integer JavaDoc(5);
1469                changes.put(propName, propValue);
1470            }
1471            if (textArea.getColumns() == 0) {
1472                propName = "columns"; // NOI18N
1473
propValue = new Integer JavaDoc(20);
1474                changes.put(propName, propValue);
1475            }
1476        }
1477
1478        Iterator iter = changes.entrySet().iterator();
1479        while (iter.hasNext()) {
1480            Map.Entry change = (Map.Entry)iter.next();
1481            propName = (String JavaDoc)change.getKey();
1482            propValue = change.getValue();
1483            FormProperty prop = radComp.getBeanProperty(propName);
1484            if (prop != null) {
1485                try {
1486                    prop.setChangeFiring(false);
1487                    prop.setValue(propValue);
1488                    prop.setChangeFiring(true);
1489                }
1490                catch (Exception JavaDoc e) {} // never mind, ignore
1491
}
1492        }
1493    }
1494
1495    static void defaultMenuInit(RADMenuItemComponent menuComp) {
1496        Object JavaDoc comp = menuComp.getBeanInstance();
1497        String JavaDoc varName = menuComp.getName();
1498        String JavaDoc propName = null;
1499        Object JavaDoc propValue = null;
1500
1501        if (comp instanceof JMenuItem) {
1502            if ("".equals(((JMenuItem)comp).getText())) { // NOI18N
1503
String JavaDoc value = "{0}"; // NOI18N
1504
propName = "text"; // NOI18N
1505
if (comp instanceof JCheckBoxMenuItem)
1506                    value = FormUtils.getBundleString("FMT_LAB_JCheckBoxMenuItem"); // NOI18N
1507
else if (comp instanceof JMenu)
1508                    value = FormUtils.getBundleString("FMT_LAB_JMenu"); // NOI18N
1509
else if (comp instanceof JRadioButtonMenuItem)
1510                    value = FormUtils.getBundleString("FMT_LAB_JRadioButtonMenuItem"); // NOI18N
1511
else
1512                    value = FormUtils.getBundleString("FMT_LAB_JMenuItem"); // NOI18N
1513

1514                propValue = MessageFormat.format(value, new Object JavaDoc[] { varName });
1515            }
1516        }
1517        else if (comp instanceof MenuItem) {
1518            if ("".equals(((MenuItem)comp).getLabel())) { // NOI18N
1519
String JavaDoc value = "{0}"; // NOI18N
1520
propName = "label"; // NOI18N
1521
if (comp instanceof PopupMenu)
1522                    value = FormUtils.getBundleString("FMT_LAB_PopupMenu"); // NOI18N
1523
else if (comp instanceof Menu)
1524                    value = FormUtils.getBundleString("FMT_LAB_Menu"); // NOI18N
1525
else if (comp instanceof CheckboxMenuItem)
1526                    value = FormUtils.getBundleString("FMT_LAB_CheckboxMenuItem"); // NOI18N
1527
else
1528                    value = FormUtils.getBundleString("FMT_LAB_MenuItem"); // NOI18N
1529

1530                propValue = MessageFormat.format(value, new Object JavaDoc[] { varName });
1531            }
1532        }
1533
1534        if (propName != null) {
1535            RADProperty prop = menuComp.getBeanProperty(propName);
1536            if (prop != null) {
1537                try {
1538                    prop.setChangeFiring(false);
1539                    prop.setValue(propValue);
1540                    prop.setChangeFiring(true);
1541                }
1542                catch (Exception JavaDoc e) {} // never mind, ignore
1543
}
1544        }
1545    }
1546
1547    private Dimension prepareDefaultLayoutSize(Component comp, boolean isContainer) {
1548        int width = -1;
1549        int height = -1;
1550        if (comp instanceof JToolBar) {
1551            width = 100;
1552            height = 25;
1553        }
1554        else if (isContainer) {
1555            Dimension pref = comp.getPreferredSize();
1556            if (pref.width < 16 && pref.height < 12) {
1557                if (comp instanceof Window || comp instanceof java.applet.Applet JavaDoc) {
1558                    width = 400;
1559                    height = 300;
1560                }
1561                else {
1562                    width = 100;
1563                    height = 100;
1564                }
1565            }
1566            else {
1567                Dimension designerSize = FormEditor.getFormDesigner(formModel).getDesignerSize();
1568                if (pref.width > designerSize.width || pref.height > designerSize.height) {
1569                    width = Math.min(pref.width, designerSize.width - 25);
1570                    height = Math.min(pref.height, designerSize.height - 25);
1571                }
1572            }
1573        }
1574        else if (comp instanceof JSeparator) {
1575            width = 50;
1576            height = 10;
1577        }
1578
1579        if (width < 0 || height < 0)
1580            return null;
1581
1582        Dimension size = new Dimension(width, height);
1583        if (comp instanceof JComponent) {
1584            ((JComponent)comp).setPreferredSize(size);
1585        }
1586        return size;
1587    }
1588}
1589
Popular Tags