KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > qfs > apps > qflog > logview > LogFrame


1 // {{{ copyright
2

3 /********************************************************************
4  *
5  * $Id: LogFrame.java,v 1.22 2000/07/05 14:07:44 gs Exp $
6  *
7  * The contents of this file are subject to the Mozilla Public
8  * License Version 1.1 (the "License"); you may not use this file
9  * except in compliance with the License. You may obtain a copy of
10  * the License at http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS
13  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
14  * implied. See the License for the specific language governing
15  * rights and limitations under the License.
16  *
17  * The Original Code is qfs.de code.
18  *
19  * The Initial Developer of the Original Code is Gregor Schmid.
20  * Portions created by Gregor Schmid are
21  * Copyright (C) 1999 Quality First Software, Gregor Schmid.
22  * All Rights Reserved.
23  *
24  * Contributor(s):
25  *
26  *******************************************************************/

27
28 // }}}
29

30 package de.qfs.apps.qflog.logview;
31
32 // {{{ imports
33

34 import java.awt.Event JavaDoc;
35 import java.awt.Dimension JavaDoc;
36 import java.awt.Point JavaDoc;
37 import java.awt.event.ActionListener JavaDoc;
38 import java.awt.event.ActionEvent JavaDoc;
39 import java.awt.event.KeyEvent JavaDoc;
40
41 import java.util.Observable JavaDoc;
42 import java.util.Observer JavaDoc;
43
44 import javax.swing.ImageIcon JavaDoc;
45 import javax.swing.Action JavaDoc;
46 import javax.swing.AbstractAction JavaDoc;
47 import javax.swing.JComponent JavaDoc;
48 import javax.swing.JDialog JavaDoc;
49 import javax.swing.JFrame JavaDoc;
50 import javax.swing.JMenuBar JavaDoc;
51 import javax.swing.JMenu JavaDoc;
52 import javax.swing.JMenuItem JavaDoc;
53 import javax.swing.KeyStroke JavaDoc;
54
55 import de.qfs.lib.command.CommandDistributor;
56 import de.qfs.lib.gui.FocusFixer;
57 import de.qfs.lib.gui.Message;
58 import de.qfs.lib.gui.SwingUtil;
59 import de.qfs.lib.log.Log;
60 import de.qfs.lib.log.Logger;
61 import de.qfs.lib.config.Configurator;
62 import de.qfs.lib.config.ConfigWrapper;
63 import de.qfs.lib.option.Option;
64 import de.qfs.lib.option.OptionDialog;
65 import de.qfs.lib.option.OptionSet;
66 import de.qfs.lib.util.MapResourceBundle;
67
68 import de.qfs.apps.qflog.logview.command.CommandSaveConfiguration;
69 import de.qfs.apps.qflog.logview.command.CommandSaveLog;
70
71 // }}}
72

73 // {{{ doc
74

75 /**
76  * This is the Frame for a LogView. <p>
77  *
78  * The LogFrame must be initialized by a call to {@link #init init} after
79  * creation. It uses the LogView's resources for localization, which can be
80  * modified via {@link LogView#setResources setResources}. <p>
81  *
82  * The LogFrame has its own {@link de.qfs.lib.config.Configurator
83  * Configurator}, that must be registered separately.
84  *
85  * @author Gregor Schmid
86  * @version $Revision: 1.22 $
87  */

88
89 // }}}
90
public class LogFrame
91     extends JFrame JavaDoc
92     implements Observer JavaDoc
93 {
94     // {{{ variables
95

96     /**
97      * The Logger used for logging.
98      */

99     private static Logger logger = new Logger (LogFrame.class);
100
101     /**
102      * The frame's menu bar.
103      */

104     private transient JMenuBar JavaDoc menuBar;
105
106     /**
107      * The menu for the filter.
108      */

109     private transient JMenu JavaDoc filterMenu;
110
111     /**
112      * The menu for the levels.
113      */

114     private transient JMenu JavaDoc levelMenu;
115
116     /**
117      * The LogView contained in the Frame.
118      */

119     protected transient LogView view;
120
121     /**
122      * The Configurator for the Frame.
123      */

124     protected transient Configurator cfg;
125
126     /**
127      * The dialog for the options.
128      */

129     private transient OptionDialog optionDialog;
130
131     /**
132      * Whether the view has been initialized.
133      */

134     private transient boolean initialized;
135
136     /**
137      * Whether logging is enabled (true) or disabled (false);
138      */

139     private transient boolean logging = false;
140
141     //----------------------------------------------------------------------
142
// actions
143
//----------------------------------------------------------------------
144
/**
145      * Save the log messages to a file.
146      */

147     private transient Action JavaDoc actionFileSave;
148
149     /**
150      * Show keyboard help.
151      */

152     private transient Action JavaDoc actionHelpKeys;
153
154     /**
155      * Edit the options.
156      */

157     private transient Action JavaDoc actionEditOptions;
158
159     /**
160      * Save all log messages.
161      */

162     private transient Action JavaDoc actionSaveAll;
163
164     /**
165      * Save the visible messages.
166      */

167     private transient Action JavaDoc actionSaveVisible;
168
169     /**
170      * Load some log messages.
171      */

172     private transient Action JavaDoc actionLoadLog;
173
174     /**
175      * Save the configuration.
176      */

177     private transient Action JavaDoc actionSaveCfg;
178
179     /**
180      * Restore the configuration.
181      */

182     private transient Action JavaDoc actionLoadCfg;
183
184     // }}}
185

186     // {{{ constructors
187

188     /**
189      * Create a new LogFrame with a new LogView.
190      */

191     LogFrame ()
192     {
193         this (new LogView ());
194         view.setLoggingEnabled(logging);
195     }
196
197     /**
198      * Create a new LogFrame for a LogView.
199      *
200      * @param view The frame's LogView.
201      */

202     LogFrame (LogView view)
203     {
204         boolean excluded = ! logging;
205         if (excluded) {
206             Log.excludeThread();
207         }
208         try {
209             this.view = view;
210             cfg = new Configurator ("LogFrame");
211         } finally {
212             if (excluded) {
213                 Log.includeThread();
214             }
215         }
216     }
217
218     // }}}
219

220     //----------------------------------------------------------------------
221
// Initialization
222
//----------------------------------------------------------------------
223
// {{{ init
224

225     /**
226      * Initialize the frame and its view. This method is not called by the
227      * constructor to enable further configuration like setting the resources,
228      * before the view is initialized.
229      */

230     public void init ()
231     {
232         if (logging && logger.level >= Log.MTD) {
233             logger.log(Log.MTD, "init()", "");
234         }
235
236         // init only once
237
if (initialized) {
238             return;
239         }
240         initialized = true;
241
242         boolean excluded = ! logging;
243         if (excluded) {
244             Log.excludeThread();
245         }
246         try {
247             // ImageIcon icon = (ImageIcon)
248
// view.getResources().getIcon("logFrame.icon", null);
249
// if (icon != null && icon.getImage() != null) {
250
// setIconImage(icon.getImage());
251
// }
252
view.init();
253             setupActions();
254             initMenu();
255
256             OptionSet options = view.getOptions();
257             options.getOption("ShowFilterView").addObserver(this);
258             options.getOption("ShowLevelView").addObserver(this);
259             filterMenu.setEnabled(options.getBoolean("ShowFilterView", false));
260             levelMenu.setEnabled(options.getBoolean("ShowLevelView", false));
261
262             getContentPane().add((JComponent JavaDoc) view);
263             pack();
264             setLocation(new Point JavaDoc (0, 10));
265             setSize(new Dimension JavaDoc(1020, 750));
266
267             cfg.add(ConfigWrapper.makeWrapper(this, "frame"));
268
269             addKeyListener(new java.awt.event.KeyAdapter JavaDoc() {
270                 public void keyPressed(KeyEvent JavaDoc e) {
271                     if (e.getKeyCode() == e.VK_F12 && e.getModifiers() == 0) {
272                         System.err.println("" + javax.swing.SwingUtilities
273                                            .findFocusOwner(LogFrame.this));
274                     }
275                 }
276             });
277
278             FocusFixer.instance().addWindow(this);
279         } finally {
280             if (excluded) {
281                 Log.includeThread();
282             }
283         }
284     }
285
286     // }}}
287
// {{{ setVisible
288

289     /**
290      * Make the frame visible/invisible. Ensures that the frame and view have
291      * been initialized.
292      *
293      * @param visible True to make the frame visible.
294      */

295     public void setVisible(boolean visible)
296     {
297         if (logging && logger.level >= Log.MTD) {
298             logger.log(Log.MTD, "setVisible(boolean)",
299                        logger.level < Log.MTDDETAIL ? "" :
300                        "visible: " + visible);
301         }
302         if (visible) {
303             init();
304         }
305         super.setVisible(visible);
306     }
307
308
309     // }}}
310
// {{{ setVisible
311

312     /**
313      * Display the frame. Ensures that the frame and view have been
314      * initialized.
315      */

316     public void show()
317     {
318         if (logging && logger.level >= Log.MTD) {
319             logger.log(Log.MTD, "show()", "");
320         }
321         init();
322         super.show();
323     }
324
325
326     // }}}
327

328     //----------------------------------------------------------------------
329
// Termination
330
//----------------------------------------------------------------------
331
// {{{ dispose
332

333     /**
334      * Dispose the LogFrame.
335      */

336     public void dispose()
337     {
338         if (logging && logger.level >= Log.MTD) {
339             logger.log(Log.MTD, "dispose()", "");
340         }
341         boolean excluded = ! logging;
342         if (excluded) {
343             Log.excludeThread();
344         }
345
346         try {
347             if (cfg.isRegistered()) {
348                 cfg.unregister(true);
349                 cfg = null;
350             }
351
352             FocusFixer.instance().removeWindow(this);
353
354             OptionSet options = view.getOptions();
355             options.getOption("ShowFilterView").deleteObserver(this);
356             options.getOption("ShowLevelView").deleteObserver(this);
357
358             SwingUtil.cleanup(this);
359             view.cleanup();
360             view = null;
361
362             super.dispose();
363             removeNotify();
364
365
366             // javax.swing.RepaintManager rm =
367
// javax.swing.RepaintManager.currentManager(this);
368
// Dimension d = rm.getDoubleBufferMaximumSize();
369
// rm.setDoubleBufferMaximumSize(new Dimension (0, 0));
370
// rm.setDoubleBufferMaximumSize(d);
371
} finally {
372             if (excluded) {
373                 Log.includeThread();
374             }
375         }
376     }
377
378     // }}}
379
// {{{ finalize
380

381     /**
382      * Finalize the LogFrame.
383      */

384     public void finalize()
385     {
386         if (logging && logger.level >= Log.MTD) {
387             logger.log(Log.MTD, "finalize()", "");
388         }
389     }
390
391     // }}}
392

393     //----------------------------------------------------------------------
394
// Various getters and setters
395
//----------------------------------------------------------------------
396
// {{{ setLoggingEnabled
397

398     /**
399      * Enable or disable logging output caused directly or indirectly by
400      * LogFrame methods. If logging is disabled, all calls to methods that
401      * might create log messages will be protected with {@link
402      * de.qfs.lib.log.Log#excludeThread de.qfs.lib.log.Log.excludeThread}.
403      * This is necessary, if the LogFrame is used inside the application whose
404      * logs it is supposed to filter. <p>
405      *
406      * The default value is false.
407      *
408      * @param enable True to enable logging, false to disable it.
409      */

410     public final void setLoggingEnabled(boolean enable)
411     {
412         logging = enable;
413     }
414
415     // }}}
416
// {{{ getView
417

418     /**
419      * Get the LogView of the LogFrame.
420      *
421      * @return The view of the LogFrame.
422      */

423     public final LogView getView()
424     {
425         return view;
426     }
427
428     // }}}
429
// {{{ getConfigurator
430

431     /**
432      * Get the configurator of the LogFrame.
433      *
434      * @return The configurator of the LogFrame.
435      */

436     public final Configurator getConfigurator()
437     {
438         return cfg;
439     }
440
441     // }}}
442

443     //----------------------------------------------------------------------
444
// Helper methods
445
//----------------------------------------------------------------------
446
// {{{ setupActions
447

448     /**
449      * Set up the actions for the LogFrame.
450      */

451     private void setupActions()
452     {
453         actionFileSave = new AbstractAction JavaDoc () {
454             public void actionPerformed (ActionEvent JavaDoc e)
455             {
456             }
457         };
458
459         actionHelpKeys = new AbstractAction JavaDoc () {
460             public void actionPerformed (ActionEvent JavaDoc e)
461             {
462                 showKeyBindings();
463             }
464         };
465
466         actionEditOptions = new AbstractAction JavaDoc () {
467             public void actionPerformed (ActionEvent JavaDoc e)
468             {
469                 editOptions();
470             }
471         };
472
473         actionSaveAll = new AbstractAction JavaDoc () {
474             public void actionPerformed (ActionEvent JavaDoc e)
475             {
476                 CommandDistributor.getDefaultDistributor().assignCommand
477                 (new CommandSaveLog
478                  (LogFrame.this, LogFrame.this, null, true, true));
479             }
480         };
481
482         actionSaveVisible = new AbstractAction JavaDoc () {
483             public void actionPerformed (ActionEvent JavaDoc e)
484             {
485                 CommandDistributor.getDefaultDistributor().assignCommand
486                 (new CommandSaveLog
487                  (LogFrame.this, LogFrame.this, null, true, false));
488             }
489         };
490
491         actionLoadLog = new AbstractAction JavaDoc () {
492             public void actionPerformed (ActionEvent JavaDoc e)
493             {
494                 CommandDistributor.getDefaultDistributor().assignCommand
495                 (new CommandSaveLog
496                  (LogFrame.this, LogFrame.this, null, false, false));
497             }
498         };
499
500         actionSaveCfg = new AbstractAction JavaDoc () {
501             public void actionPerformed (ActionEvent JavaDoc e)
502             {
503                 CommandDistributor.getDefaultDistributor().assignCommand
504                 (new CommandSaveConfiguration
505                  (LogFrame.this, LogFrame.this, true));
506             }
507         };
508
509         actionLoadCfg = new AbstractAction JavaDoc () {
510             public void actionPerformed (ActionEvent JavaDoc e)
511             {
512                 CommandDistributor.getDefaultDistributor().assignCommand
513                 (new CommandSaveConfiguration
514                  (LogFrame.this, LogFrame.this, false));
515             }
516         };
517     }
518
519     // }}}
520
// {{{ initMenu
521

522     /**
523      * Initialize the menus of the frame.
524      */

525     protected void initMenu ()
526     {
527         boolean excluded = ! logging;
528         if (excluded) {
529             Log.excludeThread();
530         }
531         try {
532             menuBar = new JMenuBar JavaDoc ();
533             setJMenuBar(menuBar);
534
535             // File
536
JMenu JavaDoc mFile = makeMenu("file");
537             menuBar.add(mFile);
538
539             // JMenuItem mi = makeMenuItem("fileLoadLog", actionLoadLog);
540
// mFile.add(mi);
541
JMenuItem JavaDoc mi = makeMenuItem("fileSaveAll", actionSaveAll);
542             mFile.add(mi);
543             mi = makeMenuItem("fileSaveVis", actionSaveVisible);
544             mFile.add(mi);
545
546             mFile.addSeparator();
547
548             mi = makeMenuItem("fileLoadCfg", actionLoadCfg);
549             mFile.add(mi);
550             mi = makeMenuItem("fileSaveCfg", actionSaveCfg);
551             mFile.add(mi);
552
553             // Edit
554
// JMenu mEdit = makeMenu("edit");
555
// menuBar.add(mEdit);
556
// mi = makeMenuItem("editOptions", actionEditOptions);
557
// mEdit.add(mi);
558

559             // Messages
560
JMenu JavaDoc mMessages = makeMenu("messages");
561             menuBar.add(mMessages);
562             view.getTableView().fillMenu(mMessages);
563
564             // Filter
565
filterMenu = makeMenu("filter");
566             menuBar.add(filterMenu);
567             view.getFilterView().fillMenu(filterMenu);
568
569             // Level
570
levelMenu = makeMenu("level");
571             menuBar.add(levelMenu);
572             if (view.getLevelView() != null) {
573                 view.getLevelView().fillMenu(levelMenu);
574             } else {
575                 levelMenu.setEnabled(false);
576             }
577
578             // View
579
menuBar.add(view.makeViewMenu());
580
581             // Help
582
JMenu JavaDoc mHelp = makeMenu("help");
583             menuBar.add(mHelp);
584
585             mi = makeMenuItem("helpKeys", actionHelpKeys);
586             mHelp.add(mi);
587         } finally {
588             if (excluded) {
589                 Log.includeThread();
590             }
591         }
592     }
593
594     // }}}
595
// {{{ makeMenu
596

597     /**
598      * Make a menu.
599      *
600      * @param resource Part of the menu's resource id.
601      *
602      * @return The new menu.
603      */

604     protected JMenu JavaDoc makeMenu (String JavaDoc resource)
605     {
606         JMenu JavaDoc menu = new JMenu JavaDoc
607             (view.getResources().getString("logView.menu." + resource +
608                                            ".name",
609                                            "MISSING: " + resource));
610         String JavaDoc mnemo =
611             view.getResources().getString("logView.menu." + resource +
612                                           ".mnemonic",
613                                           null);
614         if (mnemo != null) {
615             menu.setMnemonic(mnemo.charAt(0));
616         }
617         return menu;
618     }
619
620     // }}}
621
// {{{ makeMenuItem
622

623     /**
624      * Make a menu item.
625      *
626      * @param resource Part of the menu item's resource id.
627      * @param action An action listener for the menu item.
628      *
629      * @return The new menu.
630      */

631     protected JMenuItem JavaDoc makeMenuItem (String JavaDoc resource, ActionListener JavaDoc action)
632     {
633         MapResourceBundle rb = view.getResources();
634
635         JMenuItem JavaDoc mi = new JMenuItem JavaDoc
636             (rb.getString("logView.action." + resource + ".name",
637                           "MISSING NAME: " + resource));
638         String JavaDoc mnemo = rb.getString("logView.action." + resource +
639                                     ".mnemonic", null);
640         if (mnemo != null) {
641             mi.setMnemonic(mnemo.charAt(0));
642         }
643         mi.setActionCommand
644             (rb.getString("logView.action." + resource + ".command",
645                           "MISSING COMMAND: " + resource));
646         mi.addActionListener(action);
647
648         return mi;
649
650     }
651
652     // }}}
653
// {{{ showKeyBindings
654

655     /**
656      * Display the key bingings for a LogView. This is a temporary hack until
657      * a true help is available.
658      */

659     private void showKeyBindings()
660     {
661         boolean excluded = ! logging;
662         if (excluded) {
663             Log.excludeThread();
664         }
665         try {
666             Message.showMessage(this, "keyBindings");
667         } finally {
668             if (excluded) {
669                 Log.includeThread();
670             }
671         }
672     }
673
674     // }}}
675
// {{{ editOptions
676

677     /**
678      * Bring up a dialog to edit the options for the LogFrame and LogView.
679      */

680     private void editOptions()
681     {
682         if (logging && logger.level >= Log.MTD) {
683             logger.log(Log.MTD, "editOptions()", "");
684         }
685
686         boolean excluded = ! logging;
687         if (excluded) {
688             Log.excludeThread();
689         }
690         try {
691             if (optionDialog == null) {
692                 optionDialog = new OptionDialog
693                     (this,
694                      view.getResources().getString
695                      ("logView.optionDialog.title"),
696                      view.getOptions(),
697                      view.getLevelView() == null ? "logview" : "logviewplus");
698             } else {
699                 optionDialog.update(view.getOptions());
700             }
701             optionDialog.doModal();
702         } finally {
703             if (excluded) {
704                 Log.includeThread();
705             }
706         }
707     }
708
709     // }}}
710

711     //----------------------------------------------------------------------
712
// Observer interface
713
//----------------------------------------------------------------------
714
// {{{ update
715

716     /**
717      * Notify the LogFrame that one of its Observables has changed.
718      *
719      * @param obj The Observable that changed.
720      * @param arg Details about the change.
721      */

722     public void update(Observable JavaDoc obj, Object JavaDoc arg)
723     {
724         if (logging && logger.level >= Log.MTD) {
725             logger.log(Log.MTD, "update(Observable,Object)",
726                        logger.level < Log.MTDDETAIL ? "" :
727                        "obj: " + obj + ", " +
728                        "arg: " + arg);
729         }
730         if (obj instanceof Option) {
731             boolean excluded = ! logging;
732             if (excluded) {
733                 Log.excludeThread();
734             }
735             try {
736                 Option option = (Option) obj;
737                 OptionSet options = view.getOptions();
738                 if (option.getName().equals("ShowFilterView")) {
739                     filterMenu.setEnabled(options.getBoolean
740                                           ("ShowFilterView", false));
741                 } else if (option.getName().equals("ShowLevelView")) {
742                     if (options.getBoolean("ShowLevelView", false)
743                         && view.getLevelView() != null
744                         && levelMenu.getItemCount() == 0) {
745                         view.getLevelView().fillMenu(levelMenu);
746                     }
747                     levelMenu.setEnabled(options.getBoolean
748                                          ("ShowLevelView", false));
749                 }
750             } finally {
751                 if (excluded) {
752                     Log.includeThread();
753                 }
754             }
755         }
756     }
757
758     // }}}
759

760     //----------------------------------------------------------------------
761
// Main method for logging test purposes
762
//----------------------------------------------------------------------
763
// {{{ main
764

765     /**
766      * Bring up a LogFrame to let the user fool around a bit and test whether
767      * logging is completely turned off.
768      *
769      * @param args Ignored.
770      */

771     public static void main(String JavaDoc[] args)
772     {
773         Log.setQueueing(false);
774         Log.setOutputLevel(10);
775         Log.setPreQueueLevel(10);
776         Logger.setDefaultLogLevel(10);
777
778         final LogFrame logFrame = new LogFrame ();
779
780         SwingUtil.invokeAndWait(new Runnable JavaDoc () {
781             public void run() {
782                 // logFrame.getView().startLogging();
783
logFrame.init();
784                 Log.excludeThread();
785                 try {
786                     logFrame.getConfigurator().register();
787                     logFrame.getView().getConfigurator().register();
788                 } finally {
789                     Log.includeThread();
790                 }
791                 LogLevelTreeModel levels = new LogLevelTreeModel ();
792                 Logger.addLogLevelListener(levels);
793                 levels.setLogLevelCallback
794                     (new InternalLogLevelCallback (levels));
795                 logFrame.getView().setLogLevels(levels);
796
797                 logFrame.setTitle("Logging selftest");
798
799                 logFrame.addWindowListener
800                     (new java.awt.event.WindowAdapter JavaDoc () {
801                         public void windowClosing
802                             (java.awt.event.WindowEvent JavaDoc e) {
803                             try {
804                                 java.io.FileOutputStream JavaDoc fos =
805                                     new java.io.FileOutputStream JavaDoc
806                                     ("/tmp/logtest.cfg");
807                                 de.qfs.lib.config.Configuration
808                                     .instance().save(fos);
809                                 fos.close();
810                             } catch (Exception JavaDoc ex) {
811                                 ex.printStackTrace();
812                             }
813                             System.exit(0);
814                         }
815                     });
816
817                 Log.excludeThread();
818                 try {
819                     de.qfs.lib.option.Option.setResources
820                         (logFrame.view.getResources());
821                     Message.setResources(logFrame.view.getResources());
822                     java.io.FileInputStream JavaDoc fis =
823                         new java.io.FileInputStream JavaDoc("/tmp/logtest.cfg");
824                     de.qfs.lib.config.Configuration.instance().restore(fis);
825                     fis.close();
826                 } catch (Exception JavaDoc ex) {
827                     ex.printStackTrace();
828                 } finally {
829                     Log.includeThread();
830                 }
831
832                 logFrame.show();
833             }
834         });
835
836         for (int i = 0; i < 100; i++) {
837             de.qfs.lib.log.LogEntry entry = new de.qfs.lib.log.LogEntry
838                 (i % 10 + 1, i, "Thread" + i % 3, "Class" + i % 7,
839                  "Method" + i % 11, "message");
840             logFrame.view.getTableView().getModel().filter(entry);
841         }
842
843         while (true) {
844             try {
845                 Thread.currentThread().sleep(10000);
846             } catch (InterruptedException JavaDoc ex) {
847             }
848         }
849     }
850
851     // }}}
852
}
853
Popular Tags