KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jac > aspects > gui > swing > SwingDisplay


1 /*
2   Copyright (C) 2001-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,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13   GNU Lesser General Public License for more details.
14
15   You should have received a copy of the GNU Lesser General Public License
16   along with this program; if not, write to the Free Software
17   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */

18
19 package org.objectweb.jac.aspects.gui.swing;
20
21 import java.awt.Component JavaDoc;
22 import java.awt.Dialog JavaDoc;
23 import java.awt.Font JavaDoc;
24 import java.awt.Frame JavaDoc;
25 import java.awt.Window JavaDoc;
26 import java.awt.font.TextAttribute JavaDoc;
27 import java.io.File JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.OutputStreamWriter JavaDoc;
31 import java.io.Reader JavaDoc;
32 import java.util.Arrays JavaDoc;
33 import java.util.Collection JavaDoc;
34 import java.util.HashSet JavaDoc;
35 import java.util.Hashtable JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.Map JavaDoc;
38 import javax.swing.JFileChooser JavaDoc;
39 import javax.swing.SwingUtilities JavaDoc;
40 import javax.swing.UIManager JavaDoc;
41 import org.apache.log4j.Logger;
42 import org.objectweb.jac.aspects.gui.CommitException;
43 import org.objectweb.jac.aspects.gui.CustomizedDisplay;
44 import org.objectweb.jac.aspects.gui.CustomizedGUI;
45 import org.objectweb.jac.aspects.gui.CustomizedView;
46 import org.objectweb.jac.aspects.gui.DialogView;
47 import org.objectweb.jac.aspects.gui.DisplayContext;
48 import org.objectweb.jac.aspects.gui.EditorContainer;
49 import org.objectweb.jac.aspects.gui.FieldEditor;
50 import org.objectweb.jac.aspects.gui.GenericFactory;
51 import org.objectweb.jac.aspects.gui.GuiAC;
52 import org.objectweb.jac.aspects.gui.View;
53 import org.objectweb.jac.aspects.gui.ViewFactory;
54 import org.objectweb.jac.core.Collaboration;
55 import org.objectweb.jac.core.NameRepository;
56 import org.objectweb.jac.core.rtti.AbstractMethodItem;
57 import org.objectweb.jac.util.ExtArrays;
58 import org.objectweb.jac.util.Strings;
59
60 public class SwingDisplay implements CustomizedDisplay {
61     static Logger logger = Logger.getLogger("display");
62
63     /* Generic family -> Swing family */
64     static Map JavaDoc fontFamilies = new Hashtable JavaDoc();
65     static {
66         fontFamilies.put("serif","Serif");
67         fontFamilies.put("sans-serif","SansSerif");
68         fontFamilies.put("monospace","Monospaced");
69     }
70
71     ViewFactory factory;
72     // customizedID -> customized
73
Hashtable JavaDoc frames = new Hashtable JavaDoc();
74
75     public SwingDisplay(ViewFactory factory) {
76         this.factory = factory;
77         initFonts();
78     }
79
80     protected void initFonts() {
81         // Fonts settings
82
Map JavaDoc fontAttributes = GuiAC.getFontAttributes();
83         if (fontAttributes.size()>0) {
84             int type = 0;
85
86             String JavaDoc weight = (String JavaDoc)fontAttributes.get("weight");
87             if (weight!=null) {
88                 if (weight.compareToIgnoreCase("bold")==0) {
89                     type |= Font.BOLD;
90                 } else if (weight.compareToIgnoreCase("normal")==0) {
91                     // nothing
92
} else {
93                     logger.warn("Unknown font weight "+weight);
94                 }
95             }
96
97             String JavaDoc style = (String JavaDoc)fontAttributes.get("style");
98             if (style!=null) {
99                 if (style.compareToIgnoreCase("italic")==0) {
100                     type |= Font.ITALIC;
101                 } else if (style.compareToIgnoreCase("normal")==0) {
102                     // nothing
103
} else {
104                     logger.warn("Unknown font style "+style);
105                 }
106             }
107
108             String JavaDoc size = (String JavaDoc)fontAttributes.get("size");
109             String JavaDoc family = (String JavaDoc)fontAttributes.get("family");
110
111             Font JavaDoc font = new Font JavaDoc(
112                 family!=null ? family : "SansSerif",
113                 type,
114                 size!=null ? Integer.parseInt(size) : 12 );
115
116             UIManager.put("Label.font", font);
117             UIManager.put("ComboBox.font", font);
118             UIManager.put("Menu.font", font);
119             UIManager.put("MenuBar.font", font);
120             UIManager.put("Panel.font", font);
121             UIManager.put("Border.font", font);
122             UIManager.put("MenuItem.font", font);
123             UIManager.put("Button.font", font);
124             UIManager.put("RadioButton.font", font);
125             UIManager.put("RadioButtonMenuItem.font", font);
126             UIManager.put("CheckBox.font", font);
127             UIManager.put("CheckBoxMenuItem.font", font);
128             UIManager.put("TabbedPane.font", font);
129         }
130         boldifyFont("TableHeader.font");
131     }
132
133     public static void boldifyFont(String JavaDoc resourceName) {
134         Font JavaDoc font = UIManager.getFont(resourceName);
135         if (font!=null)
136             UIManager.put(resourceName,boldifyFont(font));
137     }
138
139     public static Font JavaDoc boldifyFont(Font JavaDoc font) {
140         Map JavaDoc attributes = font.getAttributes();
141         attributes.put(TextAttribute.WEIGHT,TextAttribute.WEIGHT_BOLD);
142         return new Font JavaDoc(attributes);
143     }
144
145     // Strings
146
HashSet JavaDoc timedoutDialogs = new HashSet JavaDoc();
147     public void addTimedoutDialog(DialogView dialog) {
148         timedoutDialogs.add(dialog);
149     }
150
151     public void closeWindow(View window, boolean validate) {
152         window.close(validate);
153         if (window instanceof Window JavaDoc)
154             ((Window JavaDoc)window).dispose();
155     }
156
157     public void fullRefresh() {
158         Iterator JavaDoc it = frames.entrySet().iterator();
159         while(it.hasNext()) {
160             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)it.next();
161             View frame = (View)entry.getValue();
162             CustomizedGUI customized = ((CustomizedView)frame).getCustomizedGUI();
163             frame.close(true);
164             ((Window JavaDoc)frame).dispose();
165             View newframe = factory.createView(
166                 customized.getTitle(),"Customized",
167                 new Object JavaDoc[] {customized},
168                 new DisplayContext(this,null));
169             logger.debug("frame created "+newframe);
170             frames.put(entry.getKey(),newframe);
171             ((Component JavaDoc)newframe).setVisible(true);
172         }
173     }
174
175     public void showCustomized(String JavaDoc id, Object JavaDoc object, Map JavaDoc panels) {
176     }
177
178     public void showCustomized(final String JavaDoc id, final Object JavaDoc object) {
179         logger.debug("showCustomized("+id+","+object+")");
180         try {
181             final CustomizedGUI customized = (CustomizedGUI)object;
182             final Component JavaDoc frame = (Component JavaDoc)frames.get(id);
183             if (frame!=null) {
184                 if (frame instanceof Window JavaDoc) {
185                     logger.debug("showing window "+id);
186                     ((Window JavaDoc)frame).show();
187                     ((Window JavaDoc)frame).toFront();
188                 }
189             } else {
190                 SwingUtilities.invokeAndWait(
191                     new Runnable JavaDoc() {
192                             public void run() {
193                                 try {
194                                     Component JavaDoc frame = (Component JavaDoc)factory.createView(
195                                         customized.getTitle(),"Customized",
196                                         new Object JavaDoc[] {customized},
197                                         new DisplayContext(SwingDisplay.this,null));
198                                     frames.put(id,frame);
199                                     frame.setVisible(true);
200                                 // do this after show because otherwise, percentage
201
// positions goes wrong.
202
((SwingCustomized)frame).setSplitters();
203                                 } catch(Exception JavaDoc e) {
204                                     logger.error("showCustomized("+id+","+object+")",e);
205                                 }
206                             }
207                         });
208             }
209         } catch(Exception JavaDoc e) {
210             logger.error("showCustomized("+id+","+object+")",e);
211         }
212     }
213
214     public CustomizedView getCustomizedView(String JavaDoc customizedID) {
215         return (CustomizedView)frames.get(customizedID);
216     }
217
218     public Collection JavaDoc getCustomizedViews() {
219         return frames.values();
220     }
221
222     public ViewFactory getFactory() {
223         return factory;
224     }
225
226     // implements the display interface
227

228     public void show(Object JavaDoc object) {
229         show(object,
230              "Object",new String JavaDoc[] {GuiAC.DEFAULT_VIEW});
231     }
232
233     public void show(Object JavaDoc object,
234                      String JavaDoc viewType, Object JavaDoc[] viewParams) {
235         logger.debug("show("+Strings.hex(object)+")");
236         if (object==null) {
237             return;
238             /*
239               } else if (object instanceof Throwable) {
240               Log.trace("exception",(Throwable)object);
241               String message = ((Throwable)object).getMessage();
242               if ("".equals(message) || message==null)
243               showMessage(object.getClass().getName(),"Error",false,false,true);
244               else
245               showMessage(message,"Error",false,false,true);
246             */

247         } else if (object instanceof Reader JavaDoc) {
248             saveStreamToFile((Reader JavaDoc)object);
249         } else if (object.getClass().isArray()) {
250             // create a customized gui to show the array
251
/*
252               SwingCustomizedGUI gui = new SwingCustomizedGUI(true);
253               gui.setSubPanesGeometry(2, Constants.HORIZONTAL, new boolean[] {false,true});
254               CollectionWrapper c = new CollectionWrapper(Arrays.asList((Object[])object));
255               gui.setObjectForPane(NameRepository.get().getName(c),0);
256               gui.addReferenceToPane("org.objectweb.jac.aspects.gui.CollectionWrapper","collection",1);
257               gui.applicationStarted();
258               gui.setPosition(0,0,60,60);
259               gui.show();
260             */

261         } else {
262             String JavaDoc name = NameRepository.get().getName(object);
263             logger.debug("name of "+object.getClass().getName()+" is "+name);
264             addViewFor(object,viewType,viewParams);
265         }
266     }
267
268     public boolean showModal(Object JavaDoc object,
269                              String JavaDoc viewType, Object JavaDoc[] viewParams,
270                              String JavaDoc title, String JavaDoc header,
271                              Object JavaDoc parent,
272                              boolean okButton,
273                              boolean cancelButton,
274                              boolean closeButton)
275     {
276         logger.debug("showModal("+
277                   (object!=null?object.getClass().getName():"null")+
278                   viewType+Arrays.asList(viewParams)+
279                   ","+title+",parent="+parent+")");
280         if (object==null) {
281             return addViewFor(
282                 null,viewType,viewParams,
283                 title, header, parent,
284                 okButton, cancelButton, closeButton);
285         } else if (object instanceof CommitException) {
286             CommitException e = (CommitException)object;
287             showError(
288                 "Commit error",
289                 "Failed to set value of "+e.getField()+
290                 " on "+GuiAC.toString(e.getObject())+
291                 ": "+e.getNested().getMessage());
292             return true;
293         } else if (object.getClass().isArray()) {
294             return addViewFor(
295                 Arrays.asList((Object JavaDoc[])object),viewType,viewParams,
296                 title, header, parent,
297                 okButton, cancelButton, closeButton);
298         } else {
299             return addViewFor(
300                 object,viewType,viewParams,
301                 title, header, parent,
302                 okButton, cancelButton, closeButton);
303         }
304     }
305
306     public boolean showModal(Object JavaDoc object, String JavaDoc title, String JavaDoc header,
307                              Object JavaDoc parent,
308                              boolean okButton,
309                              boolean cancelButton,
310                              boolean closeButton)
311     {
312         return showModal(object,
313                          "Object",new String JavaDoc[] {GuiAC.DEFAULT_VIEW},
314                          title,header,
315                          parent,
316                          okButton,cancelButton,closeButton);
317     }
318
319     public void openView(Object JavaDoc object) {
320         logger.debug("openView("+object.getClass().getName()+")");
321         show(object);
322     }
323
324     public boolean showInput(Object JavaDoc substance, AbstractMethodItem method,
325                              Object JavaDoc[] parameters)
326     {
327         logger.debug("showInput("+method.getName()+
328                   ","+Arrays.asList(parameters)+")");
329         DisplayContext dc = (DisplayContext)Collaboration.get()
330             .getAttribute(GuiAC.DISPLAY_CONTEXT);
331         if (dc==null) {
332             dc = new DisplayContext(this,null);
333         }
334
335         DialogView page = GenericFactory.createInputDialog(substance,
336                                                            method,parameters,dc);
337         if (page.waitForClose()) {
338             EditorContainer inputView = (EditorContainer)page.getContentView();
339             Iterator JavaDoc it = inputView.getEditors().iterator();
340             int i=0;
341             while (it.hasNext()) {
342                 if (method.getParameterTypes()[i] != DisplayContext.class) {
343                     FieldEditor editor = (FieldEditor)it.next();
344                     method.setParameter(parameters,i,editor.getValue());
345                 }
346                 i++;
347             }
348             return true;
349         } else {
350             return false;
351         }
352     }
353
354     String JavaDoc displayID;
355
356     public String JavaDoc getDisplayID() {
357         return displayID;
358     }
359
360     public void setDisplayID(String JavaDoc displayID) {
361         this.displayID = displayID;
362     }
363
364     public boolean showMessage(String JavaDoc message, String JavaDoc title,
365                                boolean okButton,
366                                boolean cancelButton,
367                                boolean closeButton )
368     {
369         DisplayContext context =
370             (DisplayContext)Collaboration.get().getAttribute(
371                 GuiAC.DISPLAY_CONTEXT);
372         return showModal(null,title,message,context.getWindow(),
373                          okButton,cancelButton,closeButton);
374     }
375
376     public void showMessage(String JavaDoc message, String JavaDoc title) {
377         showMessage(message,title,false,false,true);
378     }
379
380     public Object JavaDoc showRefreshMessage(String JavaDoc message, String JavaDoc title) {
381         View page;
382         try {
383             logger.debug("showMessage("+title+","+message+")");
384             DisplayContext context = new DisplayContext(this,null);
385             View label = factory.createView(message,"Label",
386                                             new Object JavaDoc[] {},context);
387             page = factory.createView("Object view","Window",
388                                       new Object JavaDoc[] {label},context);
389         } finally {
390             refresh();
391         }
392         return page;
393     }
394
395     public void showError(String JavaDoc message, String JavaDoc title) {
396         showMessage(title,message);
397     }
398
399     public void refresh() {}
400
401     public void applicationStarted() {
402     }
403    
404     public void close() {
405         // close all customized guis
406
Iterator JavaDoc i = frames.values().iterator();
407         while(i.hasNext()) {
408             View view = (View)i.next();
409             view.close(true);
410         }
411     }
412
413     /** show a save dialog and save the stream into the selected file
414     * @param reader the stream to save
415     */

416     public void saveStreamToFile(Reader JavaDoc reader)
417     {
418         JFileChooser JavaDoc chooser = new JFileChooser JavaDoc();
419         if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(null)) {
420             try {
421                 File JavaDoc file = chooser.getSelectedFile();
422                 logger.debug("saving stream to "+file.getAbsolutePath());
423                 OutputStreamWriter JavaDoc writer = new OutputStreamWriter JavaDoc(
424                     new FileOutputStream JavaDoc(file),"UTF-8");
425                 int b = reader.read();
426                 while (b != -1) {
427                     writer.write(b);
428                     b = reader.read();
429                 }
430                 writer.close();
431             } catch (IOException JavaDoc e) {
432                 logger.error("saveStreamToFile() failed",e);
433             }
434         }
435     }
436
437     public boolean addViewFor(final Object JavaDoc substance) {
438         return addViewFor(substance, null, null, null,
439                           false, false, true);
440     }
441
442     public boolean addViewFor(final Object JavaDoc substance,
443                               String JavaDoc viewType, Object JavaDoc[] viewParams) {
444         return addViewFor(substance,
445                           viewType,viewParams,
446                           null,null,null,
447                           false,false,true);
448     }
449
450     public boolean addViewFor(Object JavaDoc substance,
451                               String JavaDoc title, String JavaDoc header,
452                               Object JavaDoc parent,
453                               boolean okButton, boolean cancelButton,
454                               boolean closeButton)
455     {
456         return addViewFor(substance,
457                           "Object",new String JavaDoc[] {GuiAC.DEFAULT_VIEW},
458                           title,header,parent,
459                           okButton,cancelButton,closeButton);
460     }
461     /**
462      * Adds a view for a given Jac object.<p>
463      *
464      * @param substance the object to add a view for
465      * @return true if the OK button or the close button were clicked.
466      */

467     public boolean addViewFor(Object JavaDoc substance,
468                               String JavaDoc viewType, Object JavaDoc[] viewParams,
469                               String JavaDoc title, String JavaDoc header,
470                               Object JavaDoc parent,
471                               boolean okButton, boolean cancelButton,
472                               boolean closeButton)
473     {
474         logger.debug("addViewFor: parent="+parent);
475         if (title == null) {
476             if (substance!=null) {
477                 Class JavaDoc substance_type = substance.getClass();
478                 if(substance_type==String JavaDoc.class) {
479                     title = "Message" + " -" +
480                         org.objectweb.jac.core.dist.Distd.getLocalContainerName() + "-";
481                 } else {
482                     String JavaDoc tn = substance_type.getName();
483                     title = tn.substring( tn.lastIndexOf('.') + 1) + " " +
484                         GuiAC.toString( substance ) + " -" +
485                         org.objectweb.jac.core.dist.Distd.getLocalContainerName() + "-";
486                 }
487             } else {
488                 if (title == null) {
489                     title= "<null> -" +
490                         org.objectweb.jac.core.dist.Distd.getLocalContainerName() + "-";
491                 }
492             }
493         }
494
495         ObjectViewDialog view = null;
496         try {
497             DisplayContext context = new DisplayContext(this,null);
498             View objectView =
499                 substance==null ? null : factory.createView(
500                     "object",viewType,ExtArrays.add(substance,viewParams),context);
501
502             if (parent==null)
503                 view = new ObjectViewDialog(
504                     objectView,title,header,okButton,cancelButton,closeButton,context);
505             else if (parent instanceof Dialog)
506                 view = new ObjectViewDialog(
507                     objectView,title,header,(Dialog)parent,
508                     okButton,cancelButton,closeButton,context);
509             else if (parent instanceof Frame JavaDoc)
510                 view = new ObjectViewDialog(
511                     objectView,title,header,(Frame JavaDoc)parent,
512                     okButton,cancelButton,closeButton,context);
513
514             context.setWindow(view);
515             return view.ok;
516
517         } catch (Exception JavaDoc e) {
518             e.printStackTrace();
519             return false;
520         }
521
522     }
523
524     public boolean fillParameters(AbstractMethodItem method, Object JavaDoc[] parameters) {
525         return false;
526     }
527
528     public void onInvocationReturn(Object JavaDoc substance, AbstractMethodItem method) {
529     }
530 }
531
Popular Tags