001    /*
002     *  $Id: LookAndFeelMenu.java 69 2007-10-24 21:57:43Z ringler $
003     *  This class is part of the de.mospace.swing library.
004     *  Copyright (C) 2005-2006 Moritz Ringler
005     *
006     *  This program is free software; you can redistribute it and/or
007     *  modify it under the terms of the GNU General Public License
008     *  as published by the Free Software Foundation; either version 2
009     *  of the License, or (at your option) any later version.
010     *
011     *  This program is distributed in the hope that it will be useful,
012     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
013     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014     *  GNU General Public License for more details.
015     *
016     *  You should have received a copy of the GNU General Public License
017     *  along with this program; if not, write to the Free Software
018     *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
019     */
020    package de.mospace.swing;
021    
022    import java.awt.Component;
023    import java.awt.Window;
024    import java.awt.event.ActionEvent;
025    import java.awt.event.ActionListener;
026    import java.awt.event.KeyEvent;
027    import java.beans.PropertyChangeEvent;
028    import java.beans.PropertyChangeListener;
029    import java.io.BufferedInputStream;
030    import java.io.File;
031    import java.io.FileInputStream;
032    import java.io.IOException;
033    import java.io.InputStream;
034    import java.util.Arrays;
035    import java.util.Comparator;
036    import java.util.Iterator;
037    import java.util.List;
038    import java.util.Properties;
039    import java.util.Set;
040    import java.util.TreeSet;
041    import java.util.Vector;
042    import java.util.prefs.Preferences;
043    import java.util.logging.Logger;
044    import javax.swing.ButtonGroup;
045    import javax.swing.JMenu;
046    import javax.swing.JMenuItem;
047    import javax.swing.JRadioButtonMenuItem;
048    import javax.swing.LookAndFeel;
049    import javax.swing.SwingUtilities;
050    import javax.swing.UIManager;
051    import javax.swing.UIManager.LookAndFeelInfo;
052    import de.mospace.lang.ClassLoaderProvider;
053    import de.mospace.lang.DefaultClassLoaderProvider;
054    
055    /**
056     * A JMenu that lets you change the LookAndFeel of a window. The default
057     * menutitle is LnF. Use <code>setText()</code> to change it.<p>
058     * An instance of this class will detect when the UIManager's lookAndFeel
059     * property changes and will select the corresponding menu item if it exists.
060     * No further action will be taken, in particular the LookAndFeelMenu will
061     * not update the application GUI. In general, once a client creates
062     * an instance of this class it should yield control over the LookAndFeel
063     * to the LookAndFeelMenu.<p>
064     * There should be no problem however to have several instances of this class.
065     *
066     * @see #LookAndFeelMenu(Preferences, Window, File, File, ClassLoader)
067     *
068     * @author Moritz Ringler
069     * @version $Revision: 69 $ ($Date: 2007-10-24 23:57:43 +0200 (Mi, 24 Okt 2007) $)
070     */
071    public class LookAndFeelMenu extends JMenu {
072        private static final Logger logger = Logger.getLogger(LookAndFeelMenu.class.getPackage().getName());
073        private List lafItems;
074        private Preferences node = null;
075        private Window win;
076        private Component dialogParent = null;
077        private ClassLoader cl = ClassLoader.getSystemClassLoader();
078        private ClassLoaderProvider clp;
079        private final ActionListener lnfListener =
080                new ActionListener() {
081                    public void actionPerformed(ActionEvent e) {
082                        switchLaF((LaFMenuItem) e.getSource());
083                        updateSelection(currentLaF());
084                    }
085                };
086    
087        private final PropertyChangeListener LaFListener = new PropertyChangeListener(){
088            public void propertyChange(PropertyChangeEvent e){
089                if(
090                    e.getPropertyName().equals("lookAndFeel") &&
091                   !e.getNewValue().equals(e.getOldValue())
092                ){
093                    updateSelection(e.getNewValue().getClass().getName());
094                }
095            }
096        };
097        ButtonGroup bg = new ButtonGroup();
098    
099    
100        /**
101         * Creates a new LookAndFeelMenu that does not remember the selected
102         * LookAndFeel between program starts.<p>
103         * Equivalent to
104         * <code>{@link #LookAndFeelMenu(Preferences, Window, File, File, ClassLoader)
105         * LookAndFeelMenu(null, w, null, null, null)}</code>.
106         *
107         * @param w the window so set the look and feel of. May be <code>null</code>.
108         */
109        public LookAndFeelMenu(Window w) {
110            win = w;
111            init(UIManager.getInstalledLookAndFeels(), null, null);
112        }
113    
114    
115    
116        /**
117         * Creates a new LookAndFeelMenu that remembers the selected LookAndFeel
118         * between program starts.<p>
119         * Equivalent to
120         * <code>{@link
121         * #LookAndFeelMenu(Preferences, Window, File, File, ClassLoader)
122         * LookAndFeelMenu(pref, w, null, null, null)}</code>.
123         *
124         *
125         * @param pref the preferences node to read from and write to
126         * @param w the window so set the look and feel of, may be null
127         */
128        public LookAndFeelMenu(Preferences pref, Window w) {
129            win = w;
130            node = pref;
131            init(UIManager.getInstalledLookAndFeels(), null, null);
132        }
133    
134    
135        /**
136         * Creates a new LookAndFeelMenu that remembers the selected LookAndFeel
137         * between program starts and uses a fallback mechanism if the user does not
138         * have write access to the JRE directories. Look and Feel libraries
139         * will be read from and installed as jar files in the parent directory
140         * of lafProperties.<p>
141         *
142         * @param pref the preferences node to read from and write to
143         * @param w the window so set the look and feel of, may be null
144         * @param lafProperties a fallback properties file.
145         * @see #LookAndFeelMenu(Preferences, Window, File, File, ClassLoader)
146         */
147        public LookAndFeelMenu(Preferences pref, Window w, File lafProperties) {
148           this(pref, w, lafProperties,
149                lafProperties.getAbsoluteFile().getParentFile(),
150                initCLP(lafProperties.getAbsoluteFile().getParentFile()));
151        }
152    
153        private static ClassLoaderProvider initCLP(File dir){
154            ClassLoaderProvider newclp = new DefaultClassLoaderProvider();
155            newclp.registerLibraryDirectories(new File[]{dir});
156            return newclp;
157        }
158    
159        /**
160         * Creates a new LookAndFeelMenu that remembers the selected LookAndFeel
161         * between program starts and uses a fallback mechanism if the user does not
162         * have write access to the JRE directories.<p>
163         * Note that if installdir is <code>null</code> the system class loader will
164         * be used. Consider using <code>{@link
165         *    #LookAndFeelMenu(Preferences pref, Window w, File lafProperties)}
166         * </code>
167         * in this case.<p>
168         * Equivalent to<pre>
169         * LookAndFeelMenu(pref,
170         *                 w,
171         *                 lafProperties,
172         *                 installdir,
173         *                 createLibClassLoader(installdir))</pre>
174         *
175         * @param pref the preferences node to read from and write to
176         * @param w the window so set the look and feel of, may be null
177         * @param lafProperties a fallback properties file. Can be <code>null</code>.
178         * @param installdir a fallback installation directory.
179         * @see #LookAndFeelMenu(Preferences, Window, File, File, ClassLoader)
180         */
181        public LookAndFeelMenu(Preferences pref, Window w, File lafProperties, File installdir) {
182          this(pref, w, lafProperties, installdir, initCLP(installdir));
183        }
184    
185    
186        private void updateSelection(String newLafClass){
187            Iterator it = lafItems.iterator();
188            LaFMenuItem item;
189            while(it.hasNext()){
190                item = (LaFMenuItem) it.next();
191                String itemclass = item.getLaFClassName();
192                if(itemclass.equals(newLafClass)){
193                    item.setSelected(true);
194                    break;
195                }
196            }
197        }
198    
199        /**
200         * Creates a new LookAndFeelMenu that remembers the selected LookAndFeel
201         * between program starts and uses a fallback mechanism if the user does not
202         * have write access to the JRE directories.<p>
203         *
204         * If possible LookAndFeel jar files will be installed to the first writable
205         * directory specified by the Java system property <tt>java.ext.dirs</tt> ,
206         * and information about the installed LookAndFeels will be saved in <tt>
207         * lib/swing.properties</tt> .<p>
208         *
209         * If the user does not have write access to the extension directories the
210         * jar files will be installed to <tt>installdir</tt> or the user will be
211         * asked for a target directory if both <tt>installdir</tt> and
212         * <tt>lafProperties</tt> are <code>null</code>. If only <tt>installdir</tt>
213         * is <code>null</code> the parent directory of <tt>lafProperties</tt> will
214         * be used as the installation target.<p>
215         *
216         * If <tt>lafProperties</tt> is not <code>null</code> information about the
217         * installed LookAndFeels will be read from both
218         * <tt>lib/swing.properties</tt> and <tt>lafProperties</tt> and saved to
219         * <tt>lib/swing.properties</tt> if possible and <tt>lafProperties</tt>
220         * otherwise.<p>
221         *
222         * In addition a custom class loader can be specified, which will be used
223         * exclusively to instantiate LookAndFeel classes. A suitable classloader
224         * can be created using a {@link
225         * de.mospace.lang.DefaultClassLoaderProvider ClassLoaderProvider}.
226         * This is necessary whenever newly
227         * installed jar files are not added to your classpath by some other
228         * mechanism outside this class.<p>
229         *
230         * If you save the current LookAndFeel to Preferences your Application
231         * should call {@link LookAndFeelMenu#setLookAndFeel(Preferences pref,
232         * ClassLoader loader)} before creating its GUI.
233         *
234         * @param pref the preference node from which to read and to which to save
235         *      the current LookAndFeel. If it is <code>null</code> the current
236         *      LookAndFeel will be forgotten when the JVM exits.
237         * @param w the window whose LookAndFeel this LookAndFeelMenu controls. Can
238         *      be <code>null</code>.
239         * @param lafProperties a fallback properties file. Can be <code>null</code>.
240         * @param installdir a fallback installation directory. Can be <code>null</code>.
241         * @param customCL Description of the Parameter
242         */
243        public LookAndFeelMenu(Preferences pref, Window w,
244                File lafProperties, File installdir, ClassLoader customCL) {
245            LookAndFeelInfo[] looks1 = UIManager.getInstalledLookAndFeels();
246            LookAndFeelInfo[] looks2 = readProperties(lafProperties);
247            LookAndFeelInfo[] looks;
248            if (looks2.length == 0) {
249                looks = looks1;
250            } else if (looks1.length == 0) {
251                looks = looks2;
252            } else {
253                Set looksSet = new TreeSet(
254                    new Comparator() {
255                        public int compare(Object o1, Object o2) {
256                            return
257                                    ((LookAndFeelInfo) o1).getName().compareTo(
258                                    ((LookAndFeelInfo) o2).getName());
259                        }
260                    });
261                looksSet.addAll(Arrays.asList(looks1));
262                looksSet.addAll(Arrays.asList(looks2));
263                looks = (LookAndFeelInfo[]) looksSet.toArray(
264                        new LookAndFeelInfo[looksSet.size()]);
265            }
266            win = w;
267            node = pref;
268            if(customCL != null){
269                cl = customCL;
270            }
271            init(looks, lafProperties, (lafProperties != null && installdir == null)
272                     ? lafProperties.getAbsoluteFile().getParentFile()
273                     : installdir);
274        }
275    
276        public LookAndFeelMenu(Preferences pref, Window w,
277                File lafProperties, File installdir, ClassLoaderProvider clp) {
278            this(pref, w, lafProperties, installdir, clp.getClassLoader());
279            this.clp = clp;
280        }
281    
282    
283        private void init(LookAndFeelInfo[] looks, final File lafProperties,
284                final File installdir) {
285            lafItems = new Vector(looks.length);
286            setText("LnF");
287            setMnemonic(KeyEvent.VK_L);
288    
289            JMenuItem installLaF = new LafInstallerMenuItem(lafProperties, installdir);
290            add(installLaF);
291    
292            Arrays.sort(looks,
293                new Comparator() {
294                    public int compare(Object o1, Object o2) {
295                        return ((LookAndFeelInfo) o1).getName().compareTo(((LookAndFeelInfo) o2).getName());
296                    }
297                });
298    
299            String currentLNF = currentLaF();
300            for (int k = 0; k < looks.length; k++) {
301                LaFMenuItem item = addLookAndFeel(looks[k]);
302                if (item.getLaFClassName().equals(currentLNF)) {
303                    item.setSelected(true);
304                }
305                item.addActionListener(lnfListener);
306            }
307    
308            if (node != null) {
309                String prefLaF = node.get("LookAndFeelClass", UIManager.getSystemLookAndFeelClassName());
310    
311                /*
312                 *  Select and switch to prefLaF
313                 */
314                int selectedIndex = lafItems.indexOf(new LaFMenuItem("", prefLaF));
315                if (selectedIndex != -1) {
316                    switchLaF((LaFMenuItem) lafItems.get(selectedIndex));
317                }
318            }
319            UIManager.addPropertyChangeListener(LaFListener);
320        }
321    
322    
323        private LaFMenuItem addLookAndFeel(LookAndFeelInfo laf) {
324            LaFMenuItem item = new LaFMenuItem(laf);
325            lafItems.add(item);
326            bg.add(item);
327            add(item);
328            return item;
329        }
330    
331    
332        private String currentLaF() {
333            return UIManager.getLookAndFeel().getClass().getName();
334        }
335    
336        public void setDialogParent(Component p){
337            dialogParent = p;
338        }
339    
340    
341        private void switchLaF(LaFMenuItem item) {
342            /*
343             *  get selected look and feel class name
344             */
345            String lafClass = item.getLaFClassName();
346    
347            /*
348             *  if it is not the current LaF try to switch
349             */
350            if (lafClass.equals(currentLaF())){
351                    return;
352            }
353            if(LookAndFeelMenu.setLookAndFeel(lafClass, cl)) {
354    
355                /*
356                *  if we did indeed switch update GUI and prefs
357                */
358                updateApplicationGui();
359                if (node != null) {
360                    save();
361                }
362            } else {
363                item.setSelected(false);
364                item.setEnabled(false);
365            }
366        }
367    
368    
369        private LookAndFeelInfo[] readProperties(File f) {
370            Properties p = new Properties();
371            if (f.isFile()) {
372                InputStream fips = null;
373                try {
374                    fips = new BufferedInputStream(new FileInputStream(f));
375                    p.load(fips);
376                } catch (IOException ex) {
377                    ex.printStackTrace();
378                } catch (IllegalArgumentException ex) {
379                    ex.printStackTrace();
380                } finally {
381                    if (fips != null) {
382                        try {
383                            fips.close();
384                        } catch (IOException ioex) {
385                            ioex.printStackTrace();
386                        }
387                    }
388                }
389            }
390            String silafs = p.getProperty("swing.installedlafs");
391            LookAndFeelInfo[] result = new LookAndFeelInfo[0];
392            if (silafs != null) {
393                String[] lafs = silafs.split("\\s*,\\s*");
394                result = new LookAndFeelInfo[lafs.length];
395                for (int i = 0; i < lafs.length; i++) {
396                    result[i] = new LookAndFeelInfo(
397                            p.getProperty("swing.installedlaf." + lafs[i] + ".name", lafs[i]),
398                            p.getProperty("swing.installedlaf." + lafs[i] + ".class"));
399                }
400            }
401            return result;
402        }
403    
404    
405        /**
406         * Constructs a new LookAndFeel object, calls
407         * UIManager.setLookAndFeel(LookAndFeel laf), and consumes all eventual
408         * exceptions. This method should be used by subclasses of LookAndFeelMenu
409         * only.
410         *
411         * @param classname the classname of the new LookAndFeel
412         * @return false if an exception occurred true otherwise
413         * @see UIManager#setLookAndFeel(LookAndFeel laf)
414         */
415        protected boolean setLookAndFeel(String classname) {
416            return setLookAndFeel(classname, cl);
417        }
418    
419    
420        /**
421         * Tries to create an instance of the specified LookAndFeel class using the
422         * provided ClassLoader and calls UIManager.setLookAndFeel(LookAndFeel laf).
423         * Consumes all eventual exceptions.<p>
424         * This method should be used from outside this class and its subclasses
425         * only when no GUI components and in particular no instances of this
426         * class have been created.
427         *
428         * @param classname the classname of the new LookAndFeel
429         * @param loader the classloader that will be used to create an instance of
430         * the LookAndFeel class. If loader is <code>null<code> the system class
431         * loader will be used instead.
432         * @return false if an exception occurred true otherwise
433         * @see UIManager#setLookAndFeel(LookAndFeel laf)
434         */
435        public static boolean setLookAndFeel(String classname, ClassLoader loader) {
436            boolean result = true;
437            LookAndFeel oldLAF = UIManager.getLookAndFeel();
438            try {
439                LookAndFeel newLAF = (LookAndFeel)
440                        Class.forName(classname,
441                                      true,
442                                      (loader == null)
443                                        ? ClassLoader.getSystemClassLoader()
444                                        : loader
445                        ).newInstance();
446                UIManager.setLookAndFeel(newLAF);
447            } catch (Exception ex) {
448                logger.warning("Error setting Look and Feel to " + classname);
449                try{
450                    UIManager.setLookAndFeel(oldLAF);
451                    logger.warning("Successfully switched back to " + oldLAF.toString());
452                } catch (Exception ignore){
453                    logger.severe(ignore.toString());
454                }
455                result = false;
456            }
457            return result;
458        }
459    
460    
461        /**
462         * Tries to load a previously saved current LookAndFeel. If none is found
463         * {@link UIManager#getSystemLookAndFeelClassName()} is used as a default.
464         * Consumes all eventual exceptions.<p>
465         * This method should be used from outside this class and its subclasses
466         * only when no GUI components and in particular no instances of this
467         * class have been created.
468         *
469         * @param pref the Preferences node to load the LookAndFeel from
470         * @param loader the classloader that will be used to create an instance of
471         * the LookAndFeel class. If loader is <code>null<code> the system class
472         * loader will be used instead.
473         * @return false if an exception occurred true otherwise
474         * @see UIManager#setLookAndFeel(LookAndFeel laf)
475         */
476        public static boolean setLookAndFeel(Preferences pref, ClassLoader loader) {
477            String lnf = pref.get("LookAndFeelClass",
478                    UIManager.getSystemLookAndFeelClassName());
479            boolean result = setLookAndFeel(lnf, loader);
480            if(!result){
481                pref.remove("LookAndFeelClass");
482            }
483            return result;
484        }
485    
486    
487        /**
488         * The default implementation updates the window provided to the
489         * constructor. Override this method according to your application-specific
490         * needs.
491         */
492        protected void updateApplicationGui() {
493            if (win != null) {
494                SwingUtilities.updateComponentTreeUI(win);
495                win.validate();
496            }
497        }
498    
499        private void save() {
500            node.put("LookAndFeelClass",
501                    currentLaF());
502        }
503    
504    
505        /**
506         * Description of the Class
507         *
508         * @author ringler
509         */
510        private static class LaFMenuItem extends JRadioButtonMenuItem {
511            private final LookAndFeelInfo lafInfo;
512    
513    
514            /**
515             * Constructs a new LaFMenuItem.
516             *
517             * @param info Description of the Parameter
518             */
519            public LaFMenuItem(LookAndFeelInfo info) {
520                super(info.getName());
521                lafInfo = info;
522            }
523    
524    
525            /**
526             * Constructs a new LaFMenuItem.
527             *
528             * @param name Description of the Parameter
529             * @param classname Description of the Parameter
530             */
531            public LaFMenuItem(String name, String classname) {
532                super(name);
533                lafInfo = new LookAndFeelInfo(name, classname);
534            }
535    
536    
537            /**
538             * Gets the lookandFeelInfo attribute of the LaFMenuItem object
539             *
540             * @return The lookandFeelInfo value
541             */
542            public LookAndFeelInfo getLookandFeelInfo() {
543                return lafInfo;
544            }
545    
546    
547            /**
548             * Gets the laFClassName attribute of the LaFMenuItem object
549             *
550             * @return The laFClassName value
551             */
552            public String getLaFClassName() {
553                return getLookandFeelInfo().getClassName();
554            }
555    
556    
557            /**
558             * Description of the Method
559             *
560             * @param o Description of the Parameter
561             * @return Description of the Return Value
562             */
563            public boolean equals(Object o) {
564                return (o instanceof LaFMenuItem) &&
565                        (((LaFMenuItem) o).getLaFClassName().equals(getLaFClassName()));
566            }
567    
568    
569            /**
570             * Description of the Method
571             *
572             * @return Description of the Return Value
573             */
574            public int hashCode() {
575                return getLaFClassName().hashCode();
576            }
577        }
578    
579    
580        /**
581         * Description of the Class
582         *
583         * @author ringler
584         */
585        private class LafInstallerMenuItem extends JMenuItem implements ActionListener {
586            private final File idir;
587            private final File iprops;
588    
589    
590            /**
591             * Constructs a new LafInstallerMenuItem.
592             *
593             * @param lafProperties Description of the Parameter
594             * @param installDir Description of the Parameter
595             */
596            public LafInstallerMenuItem(File lafProperties, File installDir) {
597                super(GLOBALS.getString("LAF_MENU_INST_NEW"));
598                idir = installDir;
599                iprops = lafProperties;
600                addActionListener(this);
601            }
602    
603    
604            /**
605             * Description of the Method
606             *
607             * @param e Description of the Parameter
608             */
609            public void actionPerformed(ActionEvent e) {
610                Component parent = (dialogParent == null)? win : dialogParent;
611                if (LaFInstaller.canInstall(iprops)) {
612                    try {
613                        LaFInstaller lafi = new LaFInstaller(
614                                parent,
615                                idir,
616                                iprops);
617                        LaFInstaller.LaFPackage laf = lafi.queryLaF();
618                        if (laf == null){
619                            logger.warning("No Look and Feel found.");
620                        } else {
621                            if(lafi.installLaF(laf, clp)) {
622                                JMenuItem item = addLookAndFeel(laf);
623                                if(clp == null){
624                                    item.setEnabled(false);
625                                } else {
626                                    cl = clp.getClassLoader();
627                                    item.addActionListener(lnfListener);
628                                    item.doClick();
629                                }
630                                logger.info(laf.toString() + " installed");
631                            } else {
632                                logger.info(laf.toString() + " not installed.");
633                            }
634                        }
635                    } catch (Exception ex) {
636                        logger.severe(ex.toString());
637                    }
638                } else {
639                    LaFInstaller.warnCannotInstall(parent, iprops);
640                }
641            }
642        }
643    
644    }