KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jac > aspects > gui > GenericFactory


1 /*
2   Copyright (C) 2002-2003 Renaud Pawlak <renaud@aopsys.com>,
3                           Laurent Martelli <laurent@aopsys.com>
4   
5   This program is free software; you can redistribute it and/or modify
6   it under the terms of the GNU Lesser General Public License as
7   published by the Free Software Foundation; either version 2 of the
8   License, or (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13   Lesser General Public License for more details.
14
15   You should have received a copy of the GNU Lesser General Public
16   License along with this program; if not, write to the Free Software
17   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18   USA */

19
20 package org.objectweb.jac.aspects.gui;
21
22 import java.lang.reflect.Array;
23 import java.lang.reflect.Modifier;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Hashtable;
27 import java.util.Iterator;
28 import java.util.Map;
29 import java.util.Vector;
30 import org.apache.log4j.Logger;
31 import org.objectweb.jac.core.Collaboration;
32 import org.objectweb.jac.core.Naming;
33 import org.objectweb.jac.core.ObjectRepository;
34 import org.objectweb.jac.core.Wrappee;
35 import org.objectweb.jac.core.rtti.AbstractMethodItem;
36 import org.objectweb.jac.core.rtti.ClassItem;
37 import org.objectweb.jac.core.rtti.ClassRepository;
38 import org.objectweb.jac.core.rtti.CollectionItem;
39 import org.objectweb.jac.core.rtti.FieldItem;
40 import org.objectweb.jac.core.rtti.MetaItem;
41 import org.objectweb.jac.core.rtti.MethodItem;
42 import org.objectweb.jac.core.rtti.MixinMethodItem;
43 import org.objectweb.jac.core.rtti.RttiAC;
44 import org.objectweb.jac.core.rtti.VirtualClassItem;
45 import org.objectweb.jac.util.Classes;
46 import org.objectweb.jac.util.Enum;
47 import org.objectweb.jac.util.ExtArrays;
48 import org.objectweb.jac.util.ExtBoolean;
49 import org.objectweb.jac.util.NotInCollectionPredicate;
50 import org.objectweb.jac.util.Predicate;
51 import org.objectweb.jac.util.Stack;
52 import org.objectweb.jac.util.Strings;
53
54 /**
55  * This class implements static methods that generically create GUI
56  * items. Depending on the actual view factory, the created items are
57  * for SWING, WEB or other GUI. */

58
59 public class GenericFactory {
60     static Logger logger = Logger.getLogger("gui.generic");
61     static Logger loggerAssoc = Logger.getLogger("associations");
62
63     /**
64      * Creates a view on an object.
65      *
66      * @param factory the used factory
67      * @param context the display context (passed to ceated sub-item so
68      * that they know displays and customized)
69      * @param viewName name of the view to build
70      * @param substance the object to build a view of */

71
72     public static View createObjectView(
73         ViewFactory factory,
74         DisplayContext context,
75         String viewName,
76         Object substance)
77     {
78         logger.debug("createObjectView("
79                 + factory + "," + Strings.hex(substance) + "," + viewName + ")");
80
81         if (substance == null) {
82             return factory.createView("null", "Empty", context);
83         }
84
85         if (substance instanceof Number
86             || substance instanceof Boolean
87             || substance instanceof Character
88             || substance instanceof String) {
89             return factory.createView(
90                 substance.getClass().getName(),
91                 "Field",
92                 new Object[] { substance, null, null },
93                 context);
94         }
95
96         Class substance_type = substance.getClass();
97         ClassItem cli = ClassRepository.get().getClass(substance_type);
98
99         CompositeView view =
100             (CompositeView) factory.createCompositeView(
101                 cli.getName(),
102                 "ObjectView",
103                 context);
104
105         fillObjectView(view, cli, viewName, substance);
106         Collection dependencies = GuiAC.getDependentFields(cli);
107         if (dependencies != null) {
108             Iterator it = dependencies.iterator();
109             while (it.hasNext()) {
110                 FieldItem field = (FieldItem) it.next();
111                 Utils.registerField(substance, field, EventHandler.get(), view);
112             }
113         }
114         return view;
115     }
116
117     public static void fillObjectView(
118         CompositeView view,
119         ClassItem cli,
120         String viewName,
121         Object substance)
122     {
123         ObjectView objectView = GuiAC.getView(cli, viewName);
124         ViewFactory factory = view.getFactory();
125         DisplayContext context = view.getContext();
126         String[] categories = (String[]) cli.getAttribute(GuiAC.CATEGORIES);
127         String[] icons = GuiAC.getCategoriesIcons(cli);
128         String[] labels = GuiAC.getCategoriesLabels(cli);
129         if (labels == null)
130             labels = categories;
131
132         view.setStyle((String) cli.getAttribute(GuiAC.STYLE));
133         view.setDescription(GuiAC.getDescription(substance, "<b>", "</b>"));
134
135         logger.debug("categories = "
136                 + (categories != null
137                     ? Arrays.asList(categories).toString()
138                     : "null"));
139
140         if (categories == null) {
141             view.addView(
142                 createObjectView(
143                     factory,
144                     context,
145                     objectView,
146                     substance,
147                     null));
148         } else {
149             TabsView tabbedPane =
150                 (TabsView) factory.createCompositeView(
151                     cli.getName(),
152                     "Tabbed",
153                     context);
154             for (int i = 0; i < categories.length; i++) {
155                 logger.debug("add tab for category " + categories[i]);
156
157                 String icon;
158                 if ((icons != null) && (Array.getLength(icons) > i))
159                     icon = icons[i];
160                 else
161                     icon = null;
162
163                 CompositeView tab =
164                     createObjectView(
165                         factory,
166                         context,
167                         objectView,
168                         substance,
169                         categories[i]);
170                 if (!compositeViewIsEmpty(tab))
171                     tabbedPane.addTab(tab, labels[i], icon);
172                 else
173                     logger.debug("tab[" + categories[i] + "] is empty");
174             }
175             view.addView((CompositeView) tabbedPane);
176         }
177     }
178
179     /**
180      * Creates a view of an object (containing no tabs).
181      *
182      * @param factory the used factory
183      * @param context the display context (passed to ceated sub-item so
184      * that they know displays and customized)
185      * @param substance the viewed object */

186
187     public static View createObjectViewNoTab(
188         ViewFactory factory,
189         DisplayContext context,
190         Object substance)
191     {
192         logger.debug("createObjectViewNoTab("
193                 + factory
194                 + ","
195                 + Strings.hex(substance)
196                 + ")");
197
198         if (substance == null) {
199             return factory.createView(
200                 substance.getClass().getName(),
201                 "Empty",
202                 context);
203         } else {
204             return createObjectView(
205                 factory,
206                 context,
207                 GuiAC.getView(
208                     ClassRepository.get().getClass(substance),
209                     "default"),
210                 substance,
211                 null);
212         }
213     }
214
215     /**
216      * Returns true is the CompositeView contains a view other than
217      * CompositeView.
218      */

219     public static boolean compositeViewIsEmpty(CompositeView view) {
220         Iterator it = view.getViews().iterator();
221         while (it.hasNext()) {
222             View subView = (View) it.next();
223             if (!(subView instanceof CompositeView))
224                 return false;
225             else if (!compositeViewIsEmpty((CompositeView) subView))
226                 return false;
227         }
228         return true;
229     }
230
231     /**
232      * Create a view of an object, including only the attributes of a
233      * category.
234      *
235      * @param factory the ViewFactory
236      * @param context the DisplayContext
237      * @param substance the object to build the view of
238      * @param category the category; if null, all fields are shown
239      * @return a CompositeView representing the object
240      */

241     protected static CompositeView createObjectView(
242         ViewFactory factory,
243         DisplayContext context,
244         ObjectView view,
245         Object substance,
246         String category)
247     {
248         logger.debug("createObjectView("
249                 + factory + "," + Strings.hex(substance) + ","
250                 + category+ "," + view.getName() + ")");
251         CompositeView resultPane =
252             factory.createCompositeView(
253                 substance.getClass().getName() + "[" + category + "]",
254                 "Container",
255                 new Object[] { new Integer(Constants.VERTICAL)},
256                 context);
257
258         Class substance_type = substance.getClass();
259         ClassItem cli = ClassRepository.get().getClass(substance_type);
260
261         CompositeView fieldpane =
262             factory.createCompositeView(
263                 "fields",
264                 "ParameterContainer",
265                 new Object[] { Boolean.TRUE },
266                 context);
267         // EditorContainer editorContainer = (EditorContainer)fieldpane;
268

269         // primitive fields and references
270

271         FieldItem[] fields = null;
272         fields = view.getAttributesOrder();
273         if (fields == null)
274             fields = cli.getFields();
275
276         boolean embedded = view.getName().equals(GuiAC.AUTOCREATE_VIEW);
277         logger.debug("attributes_order = " + Arrays.asList(fields));
278         FieldItem[] groups = (FieldItem[]) cli.getAttribute(GuiAC.LINE_BREAKS);
279         int curgroup = 0;
280
281         CompositeView subFieldPane = null;
282         FieldItem oppositeRole =
283             (FieldItem) Collaboration.get().getAttribute(GuiAC.OPPOSITE_ROLE);
284         loggerAssoc.debug("opposite role = " + oppositeRole);
285         boolean first = true;
286         for (int i = 0; i < fields.length; i++) {
287             if (groups != null
288                 && curgroup < groups.length
289                 && groups[curgroup] == fields[i]) {
290                 if (subFieldPane != null) {
291                     fieldpane.addView(subFieldPane);
292                 }
293                 subFieldPane =
294                     factory.createCompositeView(
295                         "subField[" + i + "]",
296                         "Container",
297                         new Object[] { new Integer(Constants.HORIZONTAL)},
298                         context);
299                 first = true;
300                 curgroup++;
301             }
302             FieldItem field = fields[i];
303             //if(field==null) continue;
304
if (GuiAC.isMemberInCategory(field, category)
305                 && GuiAC.isVisible(substance, field)
306                 && !field.isStatic()
307                 && !field.equals(oppositeRole)) {
308                 CompositeView pane =
309                     subFieldPane != null ? subFieldPane : fieldpane;
310                 try {
311                     if (!first && subFieldPane != null)
312                         subFieldPane.addHorizontalStrut(10);
313                     pane.addView(
314                         getFieldPane(
315                             factory,
316                             context,
317                             substance,
318                             view,
319                             field,
320                             embedded));
321                     first = false;
322                 } catch (Exception e) {
323                     logger.error(
324                         "Failed to build view for field \""+field+"\"", e);
325                 }
326             }
327         }
328         if (subFieldPane != null) {
329             fieldpane.addView(subFieldPane);
330         }
331
332         resultPane.addView(fieldpane);
333
334         logger.debug("getMethodsPane for " + cli);
335
336         Collection meths = new Vector();
337         //if (Collaboration.get().getAttribute(GuiAC.AUTO_CREATION) == null) {
338
MethodItem[] ms = view.getMethodsOrder();
339         if (ms != null) {
340             meths = Arrays.asList(ms);
341         }
342         //}
343

344         logger.debug("methods = " + meths);
345
346         CompositeView methodsPane =
347             getMethodsPane(factory, context, substance, meths, category, view);
348         if (methodsPane != null) {
349             logger.debug("adding methodPane");
350             resultPane.addView(methodsPane);
351         }
352
353         return resultPane;
354
355     }
356
357     public static View getFieldPane(
358         ViewFactory factory,
359         DisplayContext context,
360         Object substance,
361         ObjectView objectView,
362         FieldItem field,
363         boolean embedded)
364     {
365         GuiAC.pushGraphicContext(field);
366         try {
367             MemberItemView memberView = GuiAC.getView(field, objectView.getName());
368             if (field.isReference()) {
369                 return getReferenceFieldPane(
370                     factory,
371                     context,
372                     substance,
373                     field,
374                     embedded,
375                     objectView,memberView);
376             } else if (field.isPrimitive()
377                     || factory.hasViewerFor(field.getTypeItem().getName())) {
378                 return getPrimitiveFieldPane(
379                     factory,
380                     context,
381                     substance,
382                     field,
383                     objectView,
384                     memberView,
385                     embedded);
386             } else if (field instanceof CollectionItem) {
387                 return getCollectionPane(
388                     factory,
389                     context,
390                     substance,
391                     objectView,
392                     (CollectionItemView) memberView,
393                     (CollectionItem) field);
394             }
395         } finally {
396             GuiAC.popGraphicContext();
397         }
398         return null;
399     }
400
401     /**
402      * Instantiates a viewer for a value of a field and add it to a
403      * container.
404      */

405     protected static boolean getViewer(
406         Object substance,
407         FieldItem field,
408         Object value,
409         CompositeView container,
410         ViewFactory factory,
411         DisplayContext context)
412     {
413         Stack types = new Stack();
414         types.push(ClassRepository.get().getClass(field.getType()));
415         if (value != null) {
416             ClassItem actualClass = ClassRepository.get().getClass(value);
417             if (types.safeTop()!=actualClass)
418                 types.push(actualClass);
419         }
420
421         Enum enum = GuiAC.getEnum(field);
422         if (enum!=null) {
423             types.push(ClassRepository.get().getVirtualClass("Enum"));
424         }
425
426         MetaItem type = RttiAC.getFieldType(field,substance);
427         if (type!=null && types.safeTop()!=type)
428             types.push(type);
429
430         logger.debug("types = " + types);
431         boolean foundViewer = false;
432         while (!types.empty()) {
433             type = (MetaItem) types.pop();
434             if (factory.hasViewerFor(type.getName())) {
435                 container.addView(
436                     factory.createView(
437                         field.getName(),
438                         type.getName(),
439                         new Object[] { value, substance, field },
440                         context));
441                 foundViewer = true;
442                 break;
443             }
444         }
445         return foundViewer;
446     }
447
448     /**
449      * Returns a view of a primitive field. It contains a label and the
450      * value of the field.
451      *
452      * @param factory the view factory
453      * @param context the display context
454      * @param substance the object the field is part of
455      * @param field the field item
456      * @param objectView the object view that contains the field view
457      * @param memberView the view to build the field for
458      * @param embedded use embbeded editors
459      */

460     protected static View getPrimitiveFieldPane(
461         ViewFactory factory,
462         DisplayContext context,
463         Object substance,
464         FieldItem field,
465         ObjectView objectView,
466         MemberItemView memberView,
467         boolean embedded)
468     {
469         logger.debug("primitive field : " + substance + "," + field.getName());
470
471         /*
472         Boolean attrValue = (Boolean)field.getAttribute(GuiAC.BORDER);
473         boolean border = attrValue!=null && attrValue.booleanValue();
474         */

475
476         CompositeView container =
477             factory.createCompositeView(
478                 "field[" + field.getName() + "]",
479                 "Container",
480                 new Object[] { new Integer(Constants.HORIZONTAL)},
481                 context);
482         Border border = GuiAC.getBorder(field);
483         if (border != null) {
484             border.setTitle(GuiAC.getLabel(field));
485             container.setViewBorder(border);
486         }
487         container.setStyle((String) field.getAttribute(GuiAC.STYLE));
488         Boolean displayLabel =
489             (Boolean) field.getAttribute(GuiAC.DISPLAY_LABEL);
490         boolean useEditor =
491             GuiAC.isEditable(substance, field)
492             && memberView.isEmbeddedEditor(embedded)
493             && !objectView.isReadOnly();
494         if ((border == null)
495             && (displayLabel == null
496                 || (displayLabel != null && displayLabel.booleanValue()))) {
497             container.addView(
498                 factory.createView(
499                     GuiAC.getLabel(field) + ": ",
500                     "Label",
501                     context));
502         }
503
504         FieldEditor editor = null;
505         if (useEditor) {
506             MethodItem setter = field.getSetter();
507             if (setter != null) {
508                 try {
509                     editor =
510                         getEditorComponent(
511                             factory,
512                             context,
513                             field.getSubstance(substance),
514                             setter,
515                             0,
516                             true,
517                             null);
518                     context.addEditor(editor);
519                     container.addView(editor);
520                 } catch (Exception e) {
521                     // If the editor failed, we'll try a normal view
522
logger.error("Failed to build editor component for "+
523                                  substance+"."+field.getName(),e);
524                 }
525             }
526         }
527         if (editor==null) {
528             Object value = field.getThroughAccessor(substance);
529             if (!getViewer(substance,
530                            field,
531                            value,
532                            container,
533                            factory,
534                            context))
535             {
536                 Enum enum = GuiAC.getEnum(field);
537                 if (enum != null) {
538                     container.addView(
539                         factory.createView(
540                             field.getName(),
541                             "Enum",
542                             new Object[] { value, enum, substance, field },
543                             context));
544                 } else {
545                     container.addView(
546                         factory.createView(
547                             field.getName(),
548                             "Field",
549                             new Object[] { value, substance, field },
550                             context));
551                 }
552             }
553
554             if (GuiAC.isEditable(substance, field) && !objectView.isReadOnly()) {
555                 container.addView(
556                     getEditButton(factory, substance, field, context));
557             }
558         }
559         return container;
560     }
561
562     /**
563      * Build a view containing a label for the name of the field, and
564      * the view of the reference.
565      *
566      * @param factory the view factory
567      * @param context the display context
568      * @param substance the object the field is part of
569      * @param field the field item
570      * @param embedded use embbeded editors
571      */

572     static protected View getReferenceFieldPane(
573         ViewFactory factory,
574         DisplayContext context,
575         Object substance,
576         FieldItem field,
577         boolean embedded,
578         ObjectView objectView,
579         MemberItemView memberView)
580     {
581         logger.debug("reference field : " + field.getName());
582         /*
583         Boolean attrValue = (Boolean)field.getAttribute(GuiAC.BORDER);
584         boolean border = attrValue!=null && attrValue.booleanValue();
585         */

586         CompositeView container =
587             factory.createCompositeView(
588                 "field[" + field.getName() + "]",
589                 "Container",
590                 new Object[] { new Integer(Constants.HORIZONTAL)},
591                 context);
592
593         Border border = GuiAC.getBorder(field);
594         if (border != null) {
595             border.setTitle(GuiAC.getLabel(field));
596             container.setViewBorder(border);
597         }
598
599         container.setStyle((String) field.getAttribute(GuiAC.STYLE));
600         Boolean displayLabel =
601             (Boolean) field.getAttribute(GuiAC.DISPLAY_LABEL);
602
603         if ((border == null)
604             && (displayLabel == null
605                 || (displayLabel != null && displayLabel.booleanValue()))) {
606
607             container.addView(
608                 factory.createView(
609                     GuiAC.getLabel(field) + ": ",
610                     "Label",
611                     context));
612         }
613
614         if ((memberView != null && memberView.isEmbedded()) && !embedded) {
615             FieldItem oppositeRole =
616                 (FieldItem) field.getAttribute(RttiAC.OPPOSITE_ROLE);
617             if (oppositeRole instanceof CollectionItem) {
618                 loggerAssoc.debug("Ignoring collection oppositeRole " + oppositeRole);
619                 oppositeRole = null;
620             }
621             Collaboration.get().addAttribute(GuiAC.OPPOSITE_ROLE, oppositeRole);
622             try {
623                 logger.debug("embedded view for " + field);
624                 container.addView(
625                     factory.createObjectView(
626                         "embbeded " + field.getName(),
627                         field.getThroughAccessor(substance),
628                         substance,
629                         field,
630                         context));
631             } finally {
632                 Collaboration.get().addAttribute(GuiAC.OPPOSITE_ROLE, null);
633             }
634         } else {
635             if (memberView.isEmbeddedEditor(embedded)
636                 && GuiAC.isEditable(substance, field)
637                 && !objectView.isReadOnly())
638             {
639                 MethodItem setter = field.getSetter();
640                 FieldEditor editor =
641                     getEditorComponent(
642                         factory,
643                         context,
644                         field.getSubstance(substance),
645                         setter,
646                         0,
647                         true,
648                         null);
649                 container.addView(editor);
650                 context.addEditor(editor);
651             } else {
652                 //Object value = field.getThroughAccessor(substance);
653
//if (!getViewer(substance,field,value,container,factory,context)) {
654
View refView =
655                     factory.createView(
656                         field.getName(),
657                         "Reference",
658                         new Object[] {
659                             field.getThroughAccessor(substance),
660                             field.getSubstance(substance),
661                             field.getField()},
662                         context);
663                 if (refView instanceof LinkGenerator)
664                     ((LinkGenerator)refView).setEnableLinks(objectView.areLinksEnabled());
665                 container.addView(refView);
666
667                 if (GuiAC.isEditable(field.getSubstance(substance),field.getField())
668                     && !objectView.isReadOnly()) {
669                     container.addView(
670                         getEditButton(
671                             factory,
672                             field.getSubstance(substance),
673                             field.getField(),
674                             context));
675                 }
676                 //}
677
}
678         }
679         return container;
680     }
681
682     /**
683      * Adds choices within a container containing a combobox and sort
684      * them.
685      *
686      * @param choice combo box model to fill
687      * @param type type of objects to fill the model with
688      * @param field associated field item
689      * @param nullAllowed boolean telling wether the add null to themodel
690      * @param nullLabel if nullAllowed==true, the label to use for the null value (if not null)
691      * @param predicate if not null, only add objects which match this
692      * predicate
693      */

694     static protected void addChoices(
695         ComboBoxModel choice,
696         ClassItem type,
697         Enum enum,
698         Object substance,
699         FieldItem field,
700         boolean nullAllowed,
701         String nullLabel,
702         Predicate predicate)
703     {
704         // use JacObjects.getObjects(type) instead
705
Collection all_objects = null;
706         logger.debug("ObjectChooser.type = " + type
707                 + "; predicate=" + predicate
708                 + "; field=" + field
709                 + "; nullAllowed=" + nullAllowed);
710         if (field != null) {
711             Object fieldChoice = field.getAttribute(GuiAC.FIELD_CHOICE);
712             logger.debug(" fieldChoice = "+fieldChoice);
713             if (fieldChoice instanceof MethodItem) {
714                 try {
715                     all_objects =
716                         (Collection) (((MethodItem) fieldChoice)
717                             .invoke(null, ExtArrays.emptyObjectArray));
718                 } catch (Exception e) {
719                     e.printStackTrace();
720                 }
721             } else if (fieldChoice instanceof CollectionItem) {
722                 all_objects = ((CollectionItem)fieldChoice).getActualCollectionThroughAccessor(substance);
723             }
724             choice.setType(type);
725         }
726
727         if (enum!=null) {
728             Iterator it = enum.getValues().iterator();
729             while (it.hasNext()) {
730                 String str = (String) it.next();
731                 choice.addObject(new Integer(enum.string2int(str)), str);
732             }
733             choice.setType(type);
734             if (nullAllowed) {
735                 choice.setNullLabel(nullLabel);
736                 choice.addObject(null);
737             }
738         } else {
739
740             if (all_objects == null) {
741                 all_objects = ObjectRepository.getObjects(type);
742                 choice.setType(type);
743             }
744             if (nullAllowed) {
745                 choice.setNullLabel(nullLabel);
746                 choice.addObject(null);
747             }
748             
749             Iterator i = all_objects.iterator();
750             while (i.hasNext()) {
751                 Object object = i.next();
752                 if (predicate == null || predicate.apply(object)) {
753                     choice.addObject(object);
754                 }
755             }
756             choice.sort();
757         }
758     }
759
760     /**
761      * Constructs an edit button for reference views.
762      */

763     static protected View getEditButton(
764         ViewFactory factory,
765         Object substance,
766         FieldItem field,
767         DisplayContext context)
768     {
769         MethodView methodView =
770             (MethodView) factory.createView(
771                 "edit " + field.getName(),
772                 "Method",
773                 new Object[] { substance, field.getSetter()},
774                 context);
775         methodView.setIcon(ResourceManager.getResource("edit_icon"));
776         methodView.setOnlyIcon(true);
777         return methodView;
778     }
779
780     /**
781      * Builds a view that will display a given collection field of an
782      * object.
783      *
784      * @param factory the view factory to use to build other inner views
785      * @param context the display context
786      * @param substance the object that contains the collection
787      * @param collection the collection to show
788      * @return the associated view
789      * @see TableModel
790      */

791     static public View getCollectionPane(
792         ViewFactory factory,
793         DisplayContext context,
794         Object substance,
795         ObjectView objectView,
796         CollectionItemView memberView,
797         CollectionItem collection) throws ViewFactory.UnhandledViewTypeException
798     {
799         logger.debug("collection : " + collection.getName());
800         String label = "collection[" + collection.getName() + "]";
801         /*
802         View newPane;
803         if (collection.isMap() && collection.getAttribute("Gui.tableView")==null) {
804            newPane = new MapView(parent,this,substance,collection);
805         } else {
806            newPane = new CollectionView(parent,this,substance,collection);
807         }
808         newPane.setName( collection.getName() );
809         }
810         */

811
812         CompositeView container =
813             factory.createCompositeView(
814                 label,
815                 "Container",
816                 new Object[] { new Integer(Constants.VERTICAL)},
817                 context);
818
819         Boolean displayLabel =
820             (Boolean) collection.getAttribute(GuiAC.DISPLAY_LABEL);
821         Border border = GuiAC.getBorder(collection);
822         logger.debug(" border="+border);
823         if (displayLabel == null
824             || (displayLabel != null && displayLabel.booleanValue())) {
825
826             if (border != null) {
827                 border.setTitle(GuiAC.getLabel(collection));
828             } else {
829                 if (GuiAC.isChoiceView(collection)) {
830                     border = new Border(null, Border.LEFT, Border.LINE);
831                 } else {
832                     border =
833                         new Border(
834                             GuiAC.getLabel(collection),
835                             Border.LEFT,
836                             Border.LINE);
837                 }
838             }
839             container.setViewBorder(border);
840         }
841
842         container.setStyle((String) collection.getAttribute(GuiAC.STYLE));
843
844         View view = null;
845         Collaboration.get().addAttribute(
846             GuiAC.OPPOSITE_ROLE,
847             collection.getAttribute(RttiAC.OPPOSITE_ROLE));
848         GuiAC.pushGraphicContext(collection);
849         try {
850
851             if (memberView.getViewType() != null) {
852
853                 view =
854                     factory.createView(
855                         label,
856                         memberView.getViewType(),
857                         new Object[] { collection, substance, memberView },
858                         context);
859                 container.addView(view);
860
861             } else if (memberView != null && memberView.isEmbedded()) {
862                 Collection values =
863                     collection.getActualCollectionThroughAccessor(substance);
864                 Iterator it = values.iterator();
865                 while (it.hasNext()) {
866                     Object value = it.next();
867                     container.addView(
868                         factory.createView(
869                             "embbeded " + collection.getName(),
870                             "Object",
871                             new Object[] { value },
872                             context));
873                 }
874
875             } else {
876                 if (GuiAC.isTableView(collection)) {
877
878                     // TABLE
879
logger.debug(" isTableView");
880                     ExtendedTableModel model =
881                         new TableModel(
882                             collection,
883                             substance,
884                             objectView != null
885                                 ? objectView.getName()
886                                 : GuiAC.DEFAULT_VIEW,
887                             factory);
888
889                     Collection filteredColumns =
890                         (Collection)collection.getAttribute(GuiAC.FILTERED_COLUMNS);
891                     if (filteredColumns!=null) {
892                         model = new TableFilter(model,filteredColumns);
893                     }
894
895                     model = new TableSorter(model);
896
897                     view =
898                         factory.createView(
899                             label,
900                             "Table",
901                             new Object[] {
902                                 collection,
903                                 substance,
904                                 model,
905                                 memberView },
906                             context);
907
908                 } else if (GuiAC.isChoiceView(collection)) {
909
910                     // CHOICE VIEW
911
logger.debug(" isChoiView");
912                     ComboBoxModel model =
913                         new ComboBoxModel(collection, substance);
914                     view =
915                         factory.createView(
916                             label,
917                             "ChoiceCollection",
918                             new Object[] {
919                                 collection,
920                                 substance,
921                                 model,
922                                 memberView },
923                             context);
924
925                 } else {
926
927                     // LIST
928
logger.debug(" isListView");
929                     ListModel model = new ListModel(collection, substance);
930                     view =
931                         factory.createView(
932                             label,
933                             "List",
934                             new Object[] {
935                                 collection,
936                                 substance,
937                                 model,
938                                 memberView },
939                             context);
940                 }
941
942                 Length height =
943                     (Length) collection.getAttribute(GuiAC.VIEW_HEIGHT);
944                 Length width =
945                     (Length) collection.getAttribute(GuiAC.VIEW_WIDTH);
946                 /*
947                 if (height == null)
948                     height = new Length("70px");
949                 if (width == null)
950                     width = new Length("500px");
951                 */

952                 view.setSize(width,height);
953                 container.addView(view);
954             }
955         } finally {
956             Collaboration.get().addAttribute(GuiAC.OPPOSITE_ROLE, null);
957             GuiAC.popGraphicContext();
958         }
959
960         return container;
961     }
962
963     /**
964      * Gets a composite panel containing a set of methods that are held
965      * by the substance object. */

966
967     static protected CompositeView getMethodsPane(
968         ViewFactory factory,
969         DisplayContext context,
970         Object substance,
971         Collection methods,
972         String category,
973         ObjectView objectView) throws ViewFactory.UnhandledViewTypeException
974     {
975         CompositeView methodpane =
976             factory.createCompositeView(
977                 "methods",
978                 "Container",
979                 new Object[] { new Integer(Constants.VERTICAL)},
980                 context);
981         methodpane.setStyle("methods");
982
983         CompositeView subMP =
984             factory.createCompositeView(
985                 "methods0",
986                 "Container",
987                 new Object[] { new Integer(Constants.HORIZONTAL)},
988                 context);
989
990         Iterator it = methods.iterator();
991         int i = 0;
992         int nbMethods = 0;
993
994         while (it.hasNext()) {
995
996             MethodItem curmeth = (MethodItem) it.next();
997             MemberItemView memberView =
998                 GuiAC.getView(curmeth, objectView.getName());
999
1000            logger.debug("handling method " + curmeth);
1001
1002            if (i == 3) {
1003                methodpane.addView(subMP);
1004                subMP =
1005                    factory.createCompositeView(
1006                        "methods" + i,
1007                        "Container",
1008                        new Object[] { new Integer(Constants.HORIZONTAL)},
1009                        context);
1010                i = 0;
1011            }
1012
1013            if (curmeth == null)
1014                continue;
1015
1016            if (!GuiAC.isMemberInCategory(curmeth, category)) {
1017                logger.debug("category, skipping " + curmeth);
1018                continue;
1019            }
1020
1021            if (!GuiAC.isVisible(substance, curmeth)) {
1022                logger.debug("invisible, skipping " + curmeth);
1023                continue;
1024            }
1025
1026            subMP.addView(
1027                getMethodView(
1028                    curmeth,
1029                    substance,
1030                    context,
1031                    factory,
1032                    memberView));
1033            i++;
1034            nbMethods++;
1035        }
1036
1037        if (nbMethods > 0) {
1038            methodpane.addView(subMP);
1039            return methodpane;
1040        } else {
1041            return null;
1042        }
1043    }
1044
1045    /**
1046     * Build view for a method
1047     * @param method the method item to build a view for
1048     * @param substance the object the method shall be invoked on
1049     * @param context display context
1050     * @param factory a view factory
1051     * @return a MethodView
1052     */

1053    public static MethodView getMethodView(
1054        AbstractMethodItem method,
1055        Object substance,
1056        DisplayContext context,
1057        ViewFactory factory,
1058        MemberItemView memberView)
1059    {
1060        String text = GuiAC.getLabel(method);
1061        if (method.getParameterTypes().length > 0) {
1062            text += "...";
1063        }
1064        MethodView methodView = null;
1065        if (memberView != null && memberView.isEmbedded()) {
1066            EditorContainer inputView =
1067                (EditorContainer) factory.createView(
1068                    "parameters[" + method.getName() + "]",
1069                    "InputParameters",
1070                    new Object[] { method, substance, null },
1071                    context);
1072            methodView =
1073                (MethodView) factory.createView(
1074                    text,
1075                    "EmbeddedMethod",
1076                    new Object[] { substance, method, inputView },
1077                    context);
1078        } else {
1079            methodView =
1080                (MethodView) factory.createView(
1081                    text,
1082                    "Method",
1083                    new Object[] { substance, method },
1084                    context);
1085        }
1086        methodView.setIcon(GuiAC.getIcon(method));
1087        return methodView;
1088    }
1089
1090    /**
1091     * <p>Create a view containing editor components for the parameters of
1092     * a method.</p>
1093     *
1094     * <p>Parameters of type
1095     * <code>org.objectweb.jac.aspects.gui.DisplayContext</code> are
1096     * not displayed.</p>
1097     *
1098     * <p>If method is a MixinMethodItem, the first parameter is at
1099     * index 1 of the parameters array.</p>
1100     *
1101     * @param factory the ViewFactory
1102     * @param context the DisplayContext
1103     * @param method the method whose parameters you the view of
1104     * @param substance the object on which the method will be
1105     * called. It used to get a default value if the method is a
1106     * setter.
1107     * @param parameters
1108     * @return a CompositeView containing an editor component for each
1109     * parameter of the method. The returned View implements the
1110     * EditorContainer interface
1111     */

1112    static public View createParameters(
1113        ViewFactory factory,
1114        DisplayContext context,
1115        final AbstractMethodItem method,
1116        Object substance,
1117        Object[] parameters)
1118    {
1119        logger.debug("createParameters(" + method.getLongName() + ")");
1120
1121        CompositeView panel =
1122            factory.createCompositeView(
1123                method.toString(),
1124                "ParameterContainer",
1125                new Object[] { Boolean.FALSE },
1126                context);
1127
1128        Class[] paramTypes = method.getParameterTypes();
1129        String[] paramNames = GuiAC.getParameterNames(method);
1130
1131        for (int i=0; i<paramTypes.length; i++)
1132        {
1133
1134            if (paramTypes[i]==DisplayContext.class)
1135                continue;
1136
1137            String paramName = null;
1138            if (paramNames != null && paramNames.length>i && paramNames[i] != null) {
1139                paramName = paramNames[i];
1140            } else {
1141                paramName = "arg" + i + " (" + paramTypes[i] + ")";
1142            }
1143
1144            CompositeView container =
1145                factory.createCompositeView(
1146                    method.toString(),
1147                    "Container",
1148                    new Object[] { new Integer(Constants.HORIZONTAL)},
1149                    context);
1150            container.addView(
1151                factory.createView(
1152                    paramName + " : ",
1153                    "Label",
1154                    ExtArrays.emptyObjectArray,
1155                    context));
1156            // ((Component)ve).setName( "arg" + i );
1157

1158            try {
1159                FieldEditor editor =
1160                    getEditorComponent(
1161                        factory,
1162                        context,
1163                        substance,
1164                        method,
1165                        i,
1166                        false,
1167                        parameters != null ? method.getParameter(parameters,i) : null);
1168                ((EditorContainer) panel).addEditor(editor);
1169                container.addView(editor);
1170            } catch (Exception e) {
1171                logger.error(
1172                    "Failed to build editor component for "
1173                        + method + "[" + i + "]",e);
1174            }
1175
1176            panel.addView(container);
1177        }
1178        return panel;
1179    }
1180
1181    /**
1182     * Returns a ValueEditor suitable for editing the i-th parameter of
1183     * a method.
1184     *
1185     * @param factory the view factory
1186     * @param substance the substance object
1187     * @param method the method that contains the parameter
1188     * @param i the parameter index
1189     * @param embedded wether the editor is an embedded field
1190     * editor. If true, the component will commit changes when it
1191     * looses the focus (only works for swing).
1192     * @param value the initial edited value. Used only if non null.
1193     */

1194    public static FieldEditor getEditorComponent(
1195        ViewFactory factory,
1196        DisplayContext context,
1197        Object substance,
1198        AbstractMethodItem method,
1199        int i,
1200        boolean embedded,
1201        Object value)
1202    {
1203        logger.debug("getEditorComponent " + method + "[" + i + "]");
1204        Class[] paramTypes = method.getParameterTypes();
1205        ClassRepository cr = ClassRepository.get();
1206        ClassItem paramType = cr.getClass(paramTypes[i]);
1207        String[] passwordParams =
1208            (String[]) method.getAttribute(GuiAC.PASSWORD_PARAMETERS);
1209        Object[] defaultValues =
1210            (Object[]) method.getAttribute(GuiAC.DEFAULT_VALUES);
1211        FieldItem[] parameterFields =
1212            (FieldItem[]) method.getAttribute(RttiAC.PARAMETERS_FIELDS);
1213        Object[] parameterChoices =
1214            (Object[]) method.getAttribute(GuiAC.PARAMETER_CHOICES);
1215        boolean[] editableChoices =
1216            (boolean[]) method.getAttribute(GuiAC.EDITABLE_CHOICES);
1217        MetaItem[] parametersType =
1218            (MetaItem[]) method.getAttribute(RttiAC.PARAMETER_TYPES);
1219        Enum[] enums = (Enum[]) method.getAttribute(GuiAC.PARAMETER_ENUMS);
1220        CollectionItem[] linkedColls =
1221            (CollectionItem[]) method.getAttribute(GuiAC.LINKED_PARAMETERS);
1222
1223        FieldItem editedField = null;
1224        FieldItem parameterField = null;
1225
1226        Object defaultValue = null;
1227        boolean defaultValueSet = false;
1228        if (defaultValues != null) {
1229            defaultValue = defaultValues[i];
1230            defaultValueSet = true;
1231        }
1232        if (value != null) {
1233            defaultValue = value;
1234            defaultValueSet = true;
1235        }
1236        Object choiceObject = null;
1237        Object[] choice = null;
1238        Enum enum = null;
1239        boolean editableChoice = false;
1240        // the most specific type of the edited value
1241
MetaItem type = null;
1242        // a stack of type of the edited value (most specific on top)
1243
Stack types = new Stack();
1244
1245        if (parameterFields != null) {
1246            parameterField = parameterFields[i];
1247        }
1248        // if it's a set-method, get the default value from the field
1249
// as well as the editableChoice attribute
1250
editedField = ((MethodItem) method).getSetField();
1251        if (editedField != null) {
1252            editedField = cr.getActualField(substance,editedField);
1253            logger.debug("edited field = " + editedField);
1254            if (substance != null) {
1255                defaultValue = editedField.getThroughAccessor(substance);
1256                defaultValueSet = true;
1257            }
1258
1259            Object[] def_value =
1260                ((Object[]) editedField.getAttribute(GuiAC.DYN_DEFAULT_VALUE));
1261            if ((!RttiAC.isNullAllowed(editedField))
1262                && (defaultValue == null)
1263                && (def_value != null))
1264                defaultValue =
1265                    ((MethodItem) def_value[0]).invokeStatic(
1266                        new Object[] { editedField, def_value[1] });
1267
1268            choiceObject = editedField.getAttribute(GuiAC.FIELD_CHOICE);
1269            editableChoice = GuiAC.isEditableChoice(editedField);
1270            enum = (Enum) editedField.getAttribute(GuiAC.FIELD_ENUM);
1271            logger.debug(
1272                "choiceObject = "+ choiceObject
1273                + (editableChoice ? " editable" : ""));
1274            type = RttiAC.getFieldType(editedField,substance);
1275            if (type != null) {
1276                logger.debug("adding rtti type = " + type);
1277                if (!types.contains(type))
1278                    types.add(0, type);
1279            }
1280            if (type == null)
1281                type = editedField.getTypeItem();
1282            if (editedField.getTypeItem() != null) {
1283                logger.debug("adding type item = " + editedField.getTypeItem());
1284                if (!types.contains(editedField.getTypeItem()))
1285                    types.add(0, editedField.getTypeItem());
1286            }
1287        }
1288
1289        if (parameterField != null) {
1290            logger.debug("parameter field = " + parameterField);
1291
1292            Object[] def_value =
1293                ((Object[]) parameterField
1294                    .getAttribute(GuiAC.DYN_DEFAULT_VALUE));
1295            if ((!RttiAC.isNullAllowed(parameterField))
1296                && (defaultValue == null)
1297                && (def_value != null))
1298                defaultValue =
1299                    ((MethodItem) def_value[0]).invokeStatic(
1300                        new Object[] { parameterField, def_value[1] });
1301
1302            choiceObject = parameterField.getAttribute(GuiAC.FIELD_CHOICE);
1303            editableChoice = GuiAC.isEditableChoice(parameterField);
1304            enum = (Enum) parameterField.getAttribute(GuiAC.FIELD_ENUM);
1305            logger.debug("choiceObject = "
1306                    + choiceObject
1307                    + (editableChoice ? " editable" : ""));
1308            type = RttiAC.getFieldType(parameterField,substance);
1309            if (type != null) {
1310                logger.debug("adding rtti type = " + type);
1311                if (!types.contains(type))
1312                    types.add(0, type);
1313            }
1314            if (type == null)
1315                type = parameterField.getTypeItem();
1316            if (parameterField.getTypeItem() != null) {
1317                logger.debug("adding type item = " + parameterField.getTypeItem());
1318                if (!types.contains(parameterField.getTypeItem()))
1319                    types.add(0, parameterField.getTypeItem());
1320            }
1321        }
1322
1323        if (defaultValueSet && defaultValue != null) {
1324            if (type == null)
1325                type = cr.getClass(defaultValue);
1326            if (!types.contains(cr.getClass(defaultValue)))
1327                types.add(0, cr.getClass(defaultValue));
1328            logger.debug("adding default value type = "
1329                    + cr.getClass(defaultValue));
1330        }
1331        if (parametersType != null) {
1332            if (type == null && parametersType[i] instanceof ClassItem)
1333                type = (ClassItem) parametersType[i];
1334            if (!types.contains(parametersType[i]))
1335                types.add(0, parametersType[i]);
1336            logger.debug("adding rtti parameter type = " + parametersType[i]);
1337        }
1338        if (type == null)
1339            type = paramType;
1340        if (!types.contains(paramType))
1341            types.add(0, paramType);
1342        logger.debug("adding parameter type = "
1343                     + paramType);
1344
1345        if (parameterField != null) {
1346            choiceObject = parameterField.getAttribute(GuiAC.FIELD_CHOICE);
1347        }
1348
1349        if (enum == null && enums != null)
1350            enum = enums[i];
1351
1352        logger.debug("types: " + types);
1353        logger.debug("type=" + type);
1354
1355        if (parameterChoices != null) {
1356            choiceObject = parameterChoices[i];
1357        }
1358
1359        boolean classChoice = false;
1360        if (choiceObject==null) {
1361            choiceObject = type.getAttribute(GuiAC.CLASS_CHOICES);
1362            logger.debug("classChoices="+choiceObject);
1363            classChoice = choiceObject!=null;
1364        }
1365
1366        if (choiceObject != null) {
1367            if (choiceObject instanceof MethodItem) {
1368                MethodItem choiceMethod = (MethodItem) choiceObject;
1369                logger.debug("choiceMethod="+choiceMethod);
1370                try {
1371                    if (classChoice) {
1372                        choiceObject =
1373                            choiceMethod.invokeStatic(new Object[] {type});
1374                    } else {
1375                        if (choiceMethod.isStatic()) {
1376                            choiceObject =
1377                                choiceMethod.invokeStatic(
1378                                    new Object[] { substance });
1379                        } else {
1380                            choiceObject =
1381                                choiceMethod.invoke(
1382                                    substance,
1383                                    ExtArrays.emptyObjectArray);
1384                        }
1385                    }
1386                    logger.debug("choiceMethod returned "+choiceObject);
1387                } catch (Exception e) {
1388                    logger.error(
1389                        "Invocation of choice "+choiceMethod+" method failed",e);
1390                }
1391            }
1392            if (choiceObject instanceof Object[]) {
1393                choice = (Object[]) choiceObject;
1394            } else if (
1395                choiceObject.getClass().isArray()
1396                    && choiceObject.getClass().getComponentType().isPrimitive()) {
1397                choice = Classes.convertPrimitiveArray(choiceObject);
1398            } else if (choiceObject instanceof Collection) {
1399                choice = ((Collection) choiceObject).toArray();
1400            }
1401        }
1402
1403        FieldEditor editor = null;
1404        String editorName =
1405            "editor " + Naming.getName(substance) + "." +
1406            method.getName() + "[" + i + "]";
1407
1408        boolean nullAllowed = false;
1409        if (editedField == null) {
1410            nullAllowed = RttiAC.isNullAllowedParameter(method, i);
1411        } else {
1412            nullAllowed = RttiAC.isNullAllowed(editedField);
1413        }
1414
1415        if (linkedColls != null && linkedColls[i] != null) {
1416
1417            ComboBoxModel model = new ComboBoxModel(linkedColls[i], substance);
1418
1419            editor =
1420                factory.createEditor(
1421                    editorName,
1422                    "ObjectChooser",
1423                    new Object[] {
1424                        substance,
1425                        editedField,
1426                        model,
1427                        Boolean.FALSE },
1428                    context);
1429
1430        } else if (choice != null) {
1431            if (editableChoices != null) {
1432                editableChoice = editableChoices[i];
1433            }
1434            ComboBoxModel model = new ComboBoxModel();
1435            for (int j = 0; j < choice.length; j++) {
1436                if (enum != null)
1437                    model.addObject(
1438                        choice[j],
1439                        enum.int2string(((Integer) choice[j]).intValue()));
1440                else
1441                    model.addObject(choice[j]);
1442            }
1443            if (nullAllowed)
1444                model.addObject(null);
1445            if (type instanceof ClassItem)
1446                model.setType((ClassItem) type);
1447            model.sort();
1448
1449            editor =
1450                factory.createEditor(
1451                    editorName,
1452                    "ObjectChooser",
1453                    new Object[] {
1454                        substance,
1455                        editedField,
1456                        model,
1457                        ExtBoolean.valueOf(editableChoice)},
1458                    context);
1459        } else if (enum != null) {
1460            ComboBoxModel model = new ComboBoxModel();
1461            Iterator it = enum.getValues().iterator();
1462            while (it.hasNext()) {
1463                String str = (String) it.next();
1464                model.addObject(new Integer(enum.string2int(str)), str);
1465            }
1466
1467            editor =
1468                factory.createEditor(
1469                    editorName,
1470                    "ObjectChooser",
1471                    new Object[] {
1472                        substance,
1473                        editedField,
1474                        model,
1475                        Boolean.FALSE },
1476                    context);
1477
1478        } else if (
1479            !factory.hasViewerFor(
1480                "editor:" + ((MetaItem) types.peek()).getName())
1481                && (Wrappee.class.isAssignableFrom(paramTypes[i])
1482                    || paramTypes[i] == Object.class)) {
1483            // jac objects
1484
ClassItem collectionType = null;
1485            if (types.size() > 0)
1486                collectionType = (ClassItem) types.peek();
1487            else
1488                collectionType = paramType;
1489            Predicate predicate = null;
1490            if (method instanceof MethodItem) {
1491                CollectionItem[] collections =
1492                    ((MethodItem) method).getAddedCollections();
1493                if (collections != null && collections.length > 0) {
1494                    predicate =
1495                        new NotInCollectionPredicate(
1496                            (Collection) collections[0].getActualCollectionThroughAccessor(
1497                                substance));
1498                }
1499            }
1500            editor =
1501                createReferenceEditor(
1502                    factory,
1503                    context,
1504                    substance,
1505                    editedField,
1506                    editorName,
1507                    collectionType,
1508                    predicate,
1509                    nullAllowed,null,
1510                    GuiAC.isCreationAllowedParameter(method, i));
1511            /*
1512        } else if (paramTypes[i].isArray()
1513                   || Collection.class.isAssignableFrom(paramTypes[i])) {
1514            */

1515            // array and collections
1516
// editor = new ArrayEditor(paramTypes[i]);
1517
} else {
1518
1519            boolean isPassword =
1520                passwordParams != null && passwordParams[i].equals("true");
1521
1522            Vector tried_types = new Vector();
1523            Stack viewerTypes = new Stack();
1524            while (!types.empty() && editor == null) {
1525                String typeName = ((MetaItem)types.pop()).getName();
1526                viewerTypes.add(0, typeName);
1527                typeName = "editor:" + typeName;
1528                tried_types.add(typeName);
1529                logger.debug("Trying " + typeName);
1530                if (factory.hasViewerFor(typeName) && !isPassword) {
1531                    logger.debug("Factory has viewer for " + typeName);
1532                    editor =
1533                        (FieldEditor) factory.createView(
1534                            editorName,
1535                            typeName,
1536                            new Object[] { substance, editedField },
1537                            context);
1538                }
1539            }
1540            if (editor == null) {
1541                if (!isPassword)
1542                    logger.error(
1543                        "Could not find an editor component for any of the type "
1544                        + tried_types);
1545                editor =
1546                    factory.createEditor(
1547                        editorName,
1548                        "PrimitiveTypeEditor",
1549                        new Object[] {
1550                            substance,
1551                            editedField,
1552                            ExtBoolean.valueOf(isPassword)},
1553                        context);
1554            }
1555        }
1556
1557        //if( fieldEditor != null && ve!=null ) {
1558
// System.out.println("added focus listener for "+ve);
1559
// System.out.println("--- Listener is: "+fieldEditor);
1560
// ve.getValueComponent().addFocusListener(fieldEditor);
1561
//((Component)ve).addFocusListener(fieldEditor);
1562
// }
1563

1564        if (defaultValueSet) {
1565            logger.debug("setting default value for "
1566                    + method.getName() + " : " + defaultValue);
1567            editor.setValue(defaultValue);
1568        }
1569
1570        editor.setEmbedded(embedded);
1571
1572        logger.debug("type = " + type);
1573        logger.debug("types = " + types);
1574
1575        if (parameterField == null) {
1576            parameterField = editedField;
1577        }
1578        Length width = null;
1579        Length[] cols = GuiAC.getMethodParametersWidth(method);
1580        if (cols != null) {
1581            width = cols[i];
1582        }
1583        if (width == null && parameterField != null) {
1584            width = GuiAC.getEditorWidth(parameterField);
1585        }
1586        if (width == null)
1587            width = GuiAC.getEditorWidth(type);
1588
1589        Length height = null;
1590        Length[] rows = GuiAC.getMethodParametersHeight(method);
1591        if (rows != null) {
1592            height = rows[i];
1593        }
1594        if (height == null && parameterField != null) {
1595            height = GuiAC.getEditorHeight(parameterField);
1596        }
1597        if (height == null)
1598            height = GuiAC.getEditorHeight(type);
1599
1600        editor.setSize(width,height);
1601
1602        logger.debug("editedType = "+type);
1603        if (type instanceof ClassItem) {
1604            editor.setEditedType((ClassItem)type);
1605        } else if (type instanceof VirtualClassItem) {
1606            if (editedField!=null)
1607                editor.setEditedType(editedField.getTypeItem());
1608            else
1609                editor.setEditedType(paramType);
1610        }
1611        return editor;
1612
1613    }
1614
1615    /**
1616     * Initialize the panels of a customized gui.
1617     *
1618     * @param factory the view factory
1619     * @param context the display context
1620     * @param internalView the CompositeView which holds the panels
1621     * @param customized the CustomizedGUI
1622     * @param panels if not null, overrides the content of panels
1623     * (panelID -> PanelContent)
1624     */

1625    public static void initCustomized(
1626        ViewFactory factory,
1627        DisplayContext context,
1628        CompositeView internalView,
1629        CustomizedGUI customized,
1630        Map panels)
1631    {
1632        logger.debug("initCustomized...");
1633        // open the views on the objects in the right subpanes
1634
if (panels == null)
1635            panels = customized.getPaneContents();
1636        for (Iterator it = panels.keySet().iterator(); it.hasNext();) {
1637            String paneId = (String) it.next();
1638            PanelContent panel = (PanelContent) panels.get(paneId);
1639            logger.debug("init pane " + paneId + " -> " + panel);
1640            try {
1641                View view =
1642                    factory.createView(
1643                        paneId,
1644                        panel.getType(),
1645                        panel.getArgs(),
1646                        context);
1647                internalView.addView(view, paneId);
1648            } catch (Exception e) {
1649                logger.error(
1650                    "Failed to build content for pane \""
1651                        + paneId + "\"",e);
1652            }
1653            logger.debug("init pane " + paneId + " DONE");
1654        }
1655        logger.debug("initCustomized DONE");
1656    }
1657
1658    /**
1659     * Sets a status bar to a customized view.
1660     *
1661     * @param factory the used factory
1662     * @param context the passed context
1663     * @param view the customized that will hold the status bar
1664     * @param statusBar the method item that defines the text to print within the status bar
1665     * @param position the position
1666     * (<code>Constants.TOP||Constants.BOTTOM</code>) */

1667
1668    public static void setStatusBar(
1669        ViewFactory factory,
1670        DisplayContext context,
1671        CustomizedView view,
1672        MethodItem statusBar,
1673        String position)
1674    {
1675        logger.debug("setStatusbar(" + statusBar + ")");
1676        StatusView statusView =
1677            (StatusView) factory.createView(
1678                "StatusBar",
1679                "StatusBar",
1680                new Object[] { statusBar },
1681                context);
1682        view.setStatusBar(statusView, position);
1683    }
1684
1685    /**
1686     * Build the menu bar of a customized gui.
1687     *
1688     * @param factory the view factory
1689     * @param context the display context
1690     * @param view the CustomizedView where to put the menu bar
1691     * @param menuBars the menuBars
1692     */

1693    public static void setMenuBars(
1694        ViewFactory factory,
1695        DisplayContext context,
1696        CustomizedView view,
1697        Hashtable menuBars)
1698    {
1699        logger.debug("setMenuBars(" + menuBars + ")");
1700        Menu menus;
1701        Iterator it = menuBars.values().iterator();
1702        while (it.hasNext()) {
1703            menus = (Menu) it.next();
1704            MenuView menuBar =
1705                (MenuView) factory.createView("MenuBar", "MenuBar", context);
1706            menuBar.setPosition(menus.getPosition());
1707            Iterator i = menus.getKeys().iterator();
1708            while (i.hasNext()) {
1709                String key = (String) i.next();
1710                logger.debug("createMenu " + key);
1711                Object item = menus.get(key);
1712                if (item instanceof Menu) {
1713                    Menu subMenu = (Menu) item;
1714                    menuBar.addSubMenu(
1715                        key,
1716                        subMenu.getIcon(),
1717                        createMenu(factory, context, key, subMenu));
1718                } else {
1719                    if (key == null) {
1720                        menuBar.addSeparator();
1721                    } else {
1722                        Callback callback = (Callback) item;
1723                        if (GuiAC.isVisible(callback.getMethod())) {
1724                            menuBar.addAction(
1725                                key,
1726                                callback.getMethod() != null
1727                                    ? GuiAC.getIcon(callback.getMethod())
1728                                    : null,
1729                                callback);
1730                        }
1731                    }
1732                }
1733            }
1734            view.setMenuBar(menuBar, menus.getPosition());
1735        }
1736    }
1737
1738    /**
1739     * Creates a menu in a a customized gui.
1740     *
1741     * @param factory the view factory
1742     * @param context the display context
1743     * @param content the content of the menu view
1744     */

1745
1746    public static MenuView createMenu(
1747        ViewFactory factory,
1748        DisplayContext context,
1749        String label,
1750        Menu content)
1751    {
1752        MenuView menu = (MenuView) factory.createView(label, "Menu", context);
1753        Iterator i = content.getKeys().iterator();
1754        while (i.hasNext()) {
1755            String key = (String) i.next();
1756            if (key == null) {
1757                menu.addSeparator();
1758            } else {
1759                Object value = content.get(key);
1760                if (value instanceof Menu) {
1761                    // submenu
1762
MenuView subMenu =
1763                        createMenu(factory, context, key, (Menu)value);
1764                    menu.addSubMenu(key, ((Menu) value).getIcon(), subMenu);
1765                } else {
1766                    // action or separator
1767
logger.debug("menu action: " + key + "->" + value);
1768                    if (key == null) {
1769                        menu.addSeparator();
1770                    } else {
1771                        Callback callback = (Callback) value;
1772                        if (callback.getMethod() == null
1773                            || GuiAC.isVisible(callback.getMethod()))
1774                        {
1775                            menu.addAction(
1776                                key,
1777                                GuiAC.getIcon(callback),
1778                                callback);
1779                        }
1780                    }
1781                }
1782            }
1783        }
1784        return menu;
1785    }
1786
1787    /**
1788     * Build the toolbar of a customized gui.
1789     *
1790     * @param factory the view factory
1791     * @param context the display context
1792     * @param view the CustomizedView where to put the menu bar
1793     * @param toolbar the toolbar definition
1794     */

1795    public static void setToolBar(
1796        ViewFactory factory,
1797        DisplayContext context,
1798        CustomizedView view,
1799        Collection toolbar)
1800    {
1801        logger.debug("setToolbar(" + toolbar + ")");
1802        MenuView toolbarView =
1803            (MenuView) factory.createView("ToolBar", "ToolBar", context);
1804        Iterator i = toolbar.iterator();
1805        while (i.hasNext()) {
1806            Callback callback = (Callback) i.next();
1807            logger.debug("createButton " + callback);
1808            if (callback != null) {
1809                toolbarView.addAction(
1810                    GuiAC.getLabel(callback.method),
1811                    GuiAC.getIcon(callback.method),
1812                    callback);
1813            } else {
1814                toolbarView.addSeparator();
1815            }
1816        }
1817        view.setToolBar(toolbarView);
1818    }
1819
1820    /**
1821     * Builds a dialog box to enter the parameters of method
1822     *
1823     * @param substance object the method will be invoked on
1824     * @param method the method
1825     * @param parameters an array where to store the value enteres by the user
1826     * @param context a display context
1827     *
1828     * @see #createParameters(ViewFactory,DisplayContext,AbstractMethodItem,Object,Object[])
1829     */

1830    public static DialogView createInputDialog(
1831        Object substance,
1832        AbstractMethodItem method,
1833        Object[] parameters,
1834        DisplayContext context)
1835    {
1836        ViewFactory factory = context.getDisplay().getFactory();
1837        EditorContainer inputView =
1838            (EditorContainer) factory.createView(
1839                "parameters",
1840                "InputParameters",
1841                new Object[] { method, substance, parameters },
1842                context);
1843        String description = (String) method.getAttribute(GuiAC.DESCRIPTION);
1844        String title = GuiAC.getLabel(method);
1845        DialogView dialog =
1846            (DialogView) factory.createView(
1847                method.getName(),
1848                "Dialog",
1849                new Object[] { inputView, null, title, description },
1850                context);
1851        dialog.setLabel(GuiAC.getLabel(method));
1852        return dialog;
1853    }
1854
1855    /**
1856     * A generic view builder for a reference editor. Returns a combox
1857     * box or a text input depending on the field's configuration
1858     *
1859     * @param factory
1860     * @param context
1861     * @param substance the object holding the field
1862     * @param field the field to build an editor for (may be null)
1863     * @param editorName the name of the editor to build
1864     * @param type the type of the objects to choose from
1865     * @param predicate a predicate used to filter proposed objects in
1866     * the case of a combobox.
1867     * @param nullAllowed wether the user is authorised to select the null value
1868     * @param isCreationAllowed wether the user is authorised to create
1869     * new instances of type
1870     *
1871     * @see org.objectweb.jac.aspects.gui.ClassAppearenceGuiConf#selectWithIndexedField(ClassItem,CollectionItem,String)
1872     */

1873    public static FieldEditor createReferenceEditor(
1874        ViewFactory factory,
1875        DisplayContext context,
1876        Object substance,
1877        FieldItem field,
1878        String editorName,
1879        ClassItem type,
1880        Predicate predicate,
1881        boolean nullAllowed,
1882        String nullLabel,
1883        boolean isCreationAllowed)
1884    {
1885        logger.debug("createReferenceEditor isCreationAllowed="+isCreationAllowed);
1886        CollectionItem index =
1887            (CollectionItem) type.getAttribute(GuiAC.INDEXED_FIELD_SELECTOR);
1888        if (index != null) {
1889            return factory.createEditor(
1890                editorName,
1891                "IndexSelector",
1892                new Object[] {
1893                    substance,
1894                    field,
1895                    index,
1896                    GuiAC.getRepository(type),
1897                    ExtBoolean.valueOf(isCreationAllowed),
1898                    type.getAttribute(GuiAC.INDEX_NOT_FOUND_HANDLER)},
1899                context);
1900        } else {
1901            ComboBoxModel model = new ComboBoxModel();
1902            addChoices(model, type, null, substance, field,
1903                       nullAllowed, nullLabel, predicate);
1904            return factory.createEditor(
1905                editorName,
1906                "ObjectChooser",
1907                new Object[] {
1908                    substance,
1909                    field,
1910                    model,
1911                    ExtBoolean.valueOf(isCreationAllowed)},
1912                context);
1913        }
1914    }
1915
1916    public static FieldEditor createEnumEditor(
1917        ViewFactory factory,
1918        DisplayContext context,
1919        Object substance,
1920        FieldItem field,
1921        String editorName,
1922        Enum enum,
1923        boolean nullAllowed,
1924        String nullLabel)
1925    {
1926        ComboBoxModel model = new ComboBoxModel();
1927        ClassItem type = ClassRepository.get().getClass("java.lang.Integer");
1928        addChoices(model, type, enum, substance, field,
1929                   nullAllowed, nullLabel, null);
1930        return factory.createEditor(
1931            editorName,
1932            "ObjectChooser",
1933            new Object[] {
1934                substance,
1935                field,
1936                model,
1937                Boolean.FALSE},
1938            context);
1939    }
1940}
1941
Popular Tags