001 package de.mospace.swing;
002 /*
003 * $Id: LaFInstaller.java 69 2007-10-24 21:57:43Z ringler $
004 * This class is part of the de.mospace.swing library.
005 * Copyright (C) 2006 Moritz Ringler
006 *
007 * This program is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU General Public License
009 * as published by the Free Software Foundation; either version 2
010 * of the License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program; if not, write to the Free Software
019 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
020 */
021 import java.awt.Component;
022 import java.io.BufferedInputStream;
023 import java.io.BufferedOutputStream;
024 import java.io.File;
025 import java.io.FileInputStream;
026 import java.io.FileOutputStream;
027 import java.io.IOException;
028 import java.io.InputStream;
029 import java.io.OutputStream;
030 import java.net.URL;
031 import java.net.URLClassLoader;
032 import java.util.Arrays;
033 import java.util.Collections;
034 import java.util.Enumeration;
035 import java.util.HashSet;
036 import java.util.Iterator;
037 import java.util.logging.Logger;
038 import java.util.List;
039 import java.util.Properties;
040 import java.util.Set;
041 import java.util.Vector;
042 import java.util.logging.ConsoleHandler;
043 import java.util.logging.Handler;
044 import java.util.logging.Level;
045 import java.util.zip.ZipEntry;
046 import java.util.zip.ZipFile;
047 import javax.swing.JFileChooser;
048 import javax.swing.JOptionPane;
049 import javax.swing.LookAndFeel;
050 import javax.swing.UIManager;
051 import javax.swing.UIManager.LookAndFeelInfo;
052 import de.mospace.lang.RTSI;
053 import de.mospace.lang.ClassLoaderProvider;
054
055 /**
056 * This class provides a convenient way to install new LookAndFeels in a Sun
057 * JRE. Given an archive with a LookAndFeel it will try to copy the jar file to
058 * a java extensions directory as per the system property <code>java.ext.dirs</code>
059 * or a client specified directory and add an entry to the property file
060 * <code>swing.properties</code>.<br>
061 * If the installation was succesfull, the LookAndFeel will be accessible
062 * through {@link UIManager#getInstalledLookAndFeels} with the next invocation
063 * of the JVM. In particular, applications can let the user switch to the new
064 * LookAndFeel with a {@link LookAndFeelMenu}.
065 *
066 * @author Moritz Ringler
067 */
068 public final class LaFInstaller extends ExtensionInstaller {
069 private static final Logger logger = Logger.getLogger(LaFInstaller.class.getPackage().getName());
070 private static String javahome = System.getProperty("java.home");
071 private final Properties swingp =
072 new Properties() {
073 /*
074 * This hack causes sorted output, if store()
075 * uses keys() to iterate over properties.
076 * Since this is not necessarily so, this is
077 * just a hack and it would be cleaner (but
078 * much lengthier) to overwrite store().
079 * It will do no harm, if keys() is not used.
080 */
081 public Enumeration keys() {
082 Enumeration ken = super.keys();
083 List kli = Collections.list(ken);
084 Collections.sort(kli);
085 return Collections.enumeration(kli);
086 }
087
088 /*
089 * This hack causes sorted output, if store()
090 * uses keySet() to iterate over properties
091 * (as GNU Classpath 0.91 does).
092 * Since this is not necessarily so, this is
093 * just a hack and it would be cleaner (but
094 * much lengthier) to overwrite store().
095 * /Breaks the general contract of keySet which requires
096 * /that changes in the Hashtable must reflect in the Set
097 * /returned by keySet
098 * public Set keySet(){
099 * return new TreeSet(super.keySet());
100 * }
101 */
102 };
103 private static File swingpf = new File(new File(javahome, "lib"), "swing.properties");
104 private final Set installedlafs = new HashSet();
105 private File fallbackProps = null;
106
107
108 /**
109 * Constructs a new LaFInstaller with a <code>null</code> parent component.
110 */
111 public LaFInstaller() {
112 this(null);
113 }
114
115
116 /**
117 * Constructs a new LaFInstaller.
118 *
119 * @param parent The parent component to use for dialogs. Can be <code>null</code>
120 */
121 public LaFInstaller(Component parent) {
122 super(parent);
123 init();
124 //System.out.println("installedlafs:" + installedlafs.toString());
125 }
126
127 public LaFInstaller(Component parent, File installdir, File lafProperties){
128 super(parent);
129 fallbackProps = lafProperties;
130 setFallbackTargetDirectory(installdir);
131 init();
132 }
133
134 private void init(){
135 readProps(swingpf);
136 readProps(fallbackProps);
137 if(installedlafs.isEmpty()){
138 LookAndFeelInfo[] lafi = UIManager.getInstalledLookAndFeels();
139 for (int i = 0; i < lafi.length; i++) {
140 installedlafs.add(new LaFPackage(lafi[i]));
141 }
142 }
143 updateProperties();
144 }
145
146 private void readProps(File propf){
147 if (propf != null && propf.isFile()) {
148 InputStream fips = null;
149 try {
150 fips = new BufferedInputStream(new FileInputStream(propf));
151 swingp.load(fips);
152 } catch (IOException ex) {
153 logger.warning("Error reading Look and Feel properties from file " + propf);
154 logger.warning(ex.toString());
155 } catch (IllegalArgumentException ex) {
156 logger.warning("Error reading Look and Feel properties from file " + propf);
157 logger.warning(ex.toString());
158 } finally {
159 if (fips != null) {
160 try {
161 fips.close();
162 } catch (IOException ioex) {
163 ioex.printStackTrace();
164 }
165 }
166 }
167 }
168 String silafs = swingp.getProperty("swing.installedlafs");
169 if (silafs != null) {
170 String[] lafs = silafs.split("\\s*,\\s*");
171 for (int i = 0; i < lafs.length; i++) {
172 installedlafs.add(new LaFPackage(null,
173 swingp.getProperty("swing.installedlaf." + lafs[i] +
174 ".class"),
175 swingp.getProperty("swing.installedlaf." + lafs[i] +
176 ".name",
177 lafs[i])));
178 }
179 }
180 }
181
182
183 /**
184 * Allows direct invocation of the LaFInstaller from the command line.
185 *
186 * @param argv No arguments are expected.
187 * @throws IOException if an I/O error occurred during modification
188 * of swing.properties.
189 */
190 public static void main(String[] argv) throws IOException {
191 Handler lh = new ConsoleHandler();
192 lh.setLevel(Level.SEVERE);
193 RTSI.addLogHandler(lh);
194 LaFInstaller me = new LaFInstaller();
195 me.installLaF(me.queryLaF());
196 /*
197 * The explicit exit is necessary in J2RE 1.4.1_02
198 */
199 System.exit(0);
200 }
201
202
203 /**
204 * Returns whether we can install new LookAndFeels.
205 *
206 * @return a boolean indicating whether we can modify the swing.properties
207 * file.
208 */
209 public static boolean canInstall(File props) {
210 return canWrite(swingpf) ||
211 (props != null) && canWrite(props) ;
212 }
213
214 /**
215 * Returns whether we can install new LookAndFeels.
216 *
217 * @return a boolean indicating whether we can modify the swing.properties
218 * file.
219 */
220 public static boolean canInstall() {
221 return canInstall(null);
222 }
223
224
225 /**
226 * Checks whether we can install new LookAndFeels and displays a dialog with
227 * an error message if not.
228 *
229 * @param pparent Description of the Parameter
230 */
231 public static void warnCannotInstall(Component pparent, File iprops) {
232 if (!canInstall(iprops)) {
233 JOptionPane.showMessageDialog(pparent,
234 GLOBALS.getMessage("LAF_INST_CANNOT_INSTALL_WARNING",
235 swingpf.getAbsolutePath()),
236 GLOBALS.getString("LAF_INST_CANNOT_INSTALL_TITLE"),
237 JOptionPane.WARNING_MESSAGE);
238 }
239 }
240
241
242 /**
243 * Aks the user to specify an archive wich will be searched for
244 * LookAndFeels as per {@link LaFPackage#fromJar} and
245 * {@link LaFPackage#fromZip}. If no LaF is found displays a warning
246 * message and returns. If more than one LookandFeel is found
247 * asks the user to pick one.
248 *
249 * @return the LookAndFeel specified by the user or null if no LookAndFeel
250 * has been found, the user cancelled a dialog or an I/O error occurred.
251 */
252 public LaFPackage queryLaF(){
253 LaFPackage result = null;
254 try{
255 File in = queryFile(GLOBALS.getMessage("LAF_INST_PACKAGE_PROMPT", System.getProperty("java.version")),
256 GLOBALS.getString("LAF_INST_PACKAGE_TITLE"),
257 JFileChooser.FILES_ONLY);
258 if (in == null) {
259 return null;
260 }
261 String ppath = in.getPath();
262 if (!in.isFile()) {
263 warn(GLOBALS.getMessage("LAF_INST_INVALID_PACKAGE", ppath),
264 GLOBALS.getString("LAF_INST_INVALID_FILE_TITLE"));
265 return null;
266 }
267 LaFPackage[] lafp = null;
268 if (ppath.endsWith(".zip")) {
269 lafp = LaFPackage.fromZip(in);
270 //System.err.println(Arrays.asList(lafp));
271 } else if (ppath.endsWith(".jar")) {
272 lafp = LaFPackage.fromJar(in);
273 } else {
274 warn(GLOBALS.getMessage("LAF_INST_NO_ZIP", ppath),
275 GLOBALS.getString("LAF_INST_INVALID_FILE_TITLE"));
276 }
277 if (lafp != null) {
278 if (lafp.length == 0) {
279 warn(GLOBALS.getMessage("LAF_INST_NO_LAF", ppath),
280 GLOBALS.getString("LAF_INST_NO_LAF_TITLE"));
281 } else {
282 result = (lafp.length > 1) ? pickLaF(lafp) : lafp[0];
283 }
284 }
285 } catch (Exception ioerror){
286 logger.severe(ioerror.toString());
287 }
288 return result;
289 }
290
291
292 /**
293 * Asks the user to pick one of several LookAndFeels.
294 *
295 * @param lafs the LookAndFeels to choose from.
296 * @return the selected LookAndFeel or <code>null</code> if the user
297 * cancelled the dialog.
298 */
299 public LaFPackage pickLaF(LaFPackage[] lafs) {
300 String[] names = new String[lafs.length];
301 for (int i = 0; i < lafs.length; i++) {
302 names[i] = lafs[i].getName() + " (" +
303 lafs[i].getClassName() + " in " + lafs[i].getJar().getName() + ")";
304 }
305 String lafname = (String) JOptionPane.showInputDialog(parent,
306 GLOBALS.getString("LAF_INST_PICK_LAF_PROMPT"),
307 GLOBALS.getString("LAF_INST_PICK_LAF_TITLE"),
308 JOptionPane.QUESTION_MESSAGE, null, names, names[0]);
309 return (lafname == null) ? null : lafs[Arrays.asList(names).indexOf(lafname)];
310 }
311
312
313 /**
314 * Tries to install the specified LookAndFeel and returns whether the
315 * installation was successful. More specifically, installs the jar file
316 * returned by {@link LaFPackage#getJar laf.getJar()} to this installer's
317 * target directory and modifies <code>swing.properties</code> to include
318 * the LookAndFeel referenced by <code>jar</code>.
319 *
320 * @param laf The LookAndFeel to install. May be <code>null</code>.
321 * @return whether the jar file was copied and swing.properties was modified
322 * to include the new LookAndFeel.
323 * @exception IOException when an error occurs during modification of <code>swing.properties</code>
324 * .
325 */
326 public boolean installLaF(LaFPackage laf) throws IOException {
327 return installLaF(laf, null);
328 }
329
330 public boolean installLaF(LaFPackage laf, ClassLoaderProvider clp) throws IOException {
331 warnCannotInstall(parent, fallbackProps);
332 boolean result = false;
333 if (laf != null) {
334 if (installedlafs.contains(laf)) {
335 warn(GLOBALS.getMessage("LAF_INST_LAF_ALREADY_INSTALLED",
336 new Object[]{laf.toString(), laf.getName()}),
337 GLOBALS.getString(
338 "LAF_INST_LAF_ALREADY_INSTALLED_TITLE"));
339 } else if (installLaFJar(laf.getJar(), clp)) {
340 installedlafs.add(laf);
341 dump();
342 result = true;
343 }
344 }
345 return result;
346 }
347
348
349 /**
350 * Calling this method on a LafInstaller will cause an
351 * UnsupportedOperationException. Use {@link #installLaF} if you want to
352 * install a LookAndFeel or a generic {@link ExtensionInstaller} if you want
353 * to install a different kind of extension.
354 *
355 * @param jarFile ...
356 * @return ...
357 * @throws UnsupportedOperationException
358 */
359 public boolean installExtension(File jarFile) {
360 throw new UnsupportedOperationException();
361 }
362
363
364 /**
365 * Calling this method on a LafInstaller will cause an
366 * UnsupportedOperationException. Use {@link #installLaF} if you want to
367 * install a LookAndFeel or a generic {@link ExtensionInstaller} if you want
368 * to install a different kind of extension.
369 *
370 * @param zip ...
371 * @param extjars ...
372 * @return ...
373 * @throws UnsupportedOperationException
374 */
375 public boolean installExtension(File zip, String extjars) {
376 throw new UnsupportedOperationException();
377 }
378
379
380 /**
381 * Description of the Method
382 *
383 * @param lafJar Description of the Parameter
384 * @return Description of the Return Value
385 * @exception IOException Description of the Exception
386 */
387 private boolean installLaFJar(File lafJar, ClassLoaderProvider clp)
388 throws IOException {
389 return (lafJar == null) ? false : super.installExtension(lafJar, clp);
390 }
391
392
393 /** Updates swingp with the current state of installedlafs. */
394 private void updateProperties() {
395 LaFPackage lp;
396 String laf;
397 StringBuffer ilprop = new StringBuffer(installedlafs.size() * 20);
398 Iterator it = installedlafs.iterator();
399 while (it.hasNext()) {
400 lp = (LaFPackage) it.next();
401 laf = lp.toString();
402 ilprop.append(laf).append(',');
403 swingp.setProperty("swing.installedlaf." + laf + ".class",
404 lp.getClassName());
405 swingp.setProperty("swing.installedlaf." + laf + ".name",
406 lp.getName());
407 }
408 ilprop.deleteCharAt(ilprop.length() - 1);
409 swingp.setProperty("swing.installedlafs", ilprop.toString());
410 }
411
412
413 /** Updates UIManagers installedLookAndFeels with the current state of installedlafs. */
414 public void updateUIManagerInstalledLafs() {
415 UIManager.setInstalledLookAndFeels(
416 (LookAndFeelInfo[]) installedlafs.toArray(
417 new LookAndFeelInfo[installedlafs.size()]
418 )
419 );
420 }
421
422
423 /**
424 * Updates swing.properties from the current state of installedlafs.
425 *
426 * @exception IOException Description of the Exception
427 */
428 private void dump() throws IOException {
429 updateProperties();
430 OutputStream fops = null;
431 File target = null;
432 if(canWrite(swingpf)){
433 target = swingpf;
434 } else if (fallbackProps != null && canWrite(fallbackProps)){
435 target = fallbackProps;
436 }
437 try {
438 fops = new BufferedOutputStream(new FileOutputStream(target));
439 swingp.store(fops, "swing.properties");
440 } finally {
441 if (fops != null) {
442 fops.close();
443 }
444 }
445 }
446
447
448 /**
449 * Description of the Class
450 *
451 * @author ringler
452 */
453 public final static class LaFPackage extends UIManager.LookAndFeelInfo {
454 private final File lafjar;
455
456
457 /**
458 * Constructs a new LaFPackage.
459 *
460 * @param jar Description of the Parameter
461 * @param mainclass Description of the Parameter
462 * @param name Description of the Parameter
463 */
464 public LaFPackage(File jar, String mainclass, String name) {
465 super(name, mainclass.replaceFirst("\\.class$", ""));
466 lafjar = jar;
467 }
468
469
470 /**
471 * Constructs a new LaFPackage.
472 *
473 * @param info Description of the Parameter
474 */
475 public LaFPackage(LookAndFeelInfo info) {
476 super(info.getName(), info.getClassName());
477 lafjar = null;
478 }
479
480
481 /**
482 * Description of the Method
483 *
484 * @param obj Description of the Parameter
485 * @return Description of the Return Value
486 */
487 public boolean equals(Object obj) {
488 return (obj instanceof LaFPackage) && (obj.toString().equals(this.toString()));
489 }
490
491
492 /**
493 * Description of the Method
494 *
495 * @return Description of the Return Value
496 */
497 public int hashCode() {
498 return this.toString().hashCode();
499 }
500
501
502 /**
503 * Gets the jar attribute of the LaFPackage object. It is not guaranteed
504 * that the File object returned actually exists.
505 *
506 * @return The jar value
507 */
508 public File getJar() {
509 return lafjar;
510 }
511
512
513 /**
514 * Description of the Method
515 *
516 * @return Description of the Return Value
517 */
518 public String toString() {
519 String result = getClassName();
520 result.replaceFirst("\\.class$", "");
521 //unnecessary but does no harm!
522 int a = result.lastIndexOf('.');
523 if (a >= 0) {
524 result = result.substring(a + 1).replaceFirst("LookAndFeel", "");
525 }
526 return result.toLowerCase();
527 }
528
529
530 /**
531 * Searches the given jar file for all LaFs it contains. As a side
532 * effect the jar file may become write protected until the jvm exits.
533 * Use {@link File#deleteOnExit deleteonExit} if a simple delete fails.
534 * <pre>
535 * if(! jar.delete()){
536 * jar.deleteOnExit();
537 * }
538 * </pre> Note that deleteOnExit might block memory that is released
539 * only when the JVM exits.
540 *
541 * @param jar the jar file to search
542 * @return all LookAndFeels found in the jar file
543 */
544 public static LaFPackage[] fromJar(File jar) {
545 List result = new Vector();
546 ZipFile zip = null;
547 URLClassLoader myCl;
548 try {
549 /*
550 * make a class loader that reads from the jar file
551 */
552 myCl = new URLClassLoader(new URL[]{jar.toURI().toURL()});
553 //System.out.println(Arrays.asList(myCl.getURLs()));
554
555 /*
556 * initialize a new RTSI with this class loader
557 */
558 RTSI myRTSI = new RTSI(myCl);
559
560 /*
561 * search the jarfile
562 */
563 zip = new ZipFile(jar);
564 Enumeration entries = zip.entries();
565
566 while (entries.hasMoreElements()) {
567
568 /*
569 * look for packages/directories
570 */
571 ZipEntry dir = (ZipEntry) entries.nextElement();
572 String dirName = dir.getName();
573 if (dir.isDirectory()) {
574 String packageName = dirName.substring(0, dirName.length() - 1).replaceAll("/", ".");
575
576 /*
577 * look for LookAndFeels in a package
578 */
579 String[] lafclasses = myRTSI.find(packageName, LookAndFeel.class);
580 LaFPackage[] xresult = new LaFPackage[lafclasses.length];
581 for (int i = 0; i < xresult.length; i++) {
582 LookAndFeel laf = (LookAndFeel)
583 Class.forName(lafclasses[i], true, myCl).newInstance();
584 xresult[i] = new LaFPackage(jar, lafclasses[i], laf.getName());
585 }
586
587 /*
588 * store the LookAndFeels we have found in the result list
589 */
590 result.addAll(Arrays.asList(xresult));
591 }
592 }
593 } catch (Exception ex) {
594 ex.printStackTrace();
595 return null;
596 } finally {
597 myCl = null;
598 if (zip != null) {
599 try {
600 zip.close();
601 } catch (IOException ex) {
602 logger.warning("Error closing jar file " + jar);
603 logger.warning(ex.toString());
604 }
605 }
606 }
607
608 return (LaFPackage[]) result.toArray(new LaFPackage[result.size()]);
609 }
610
611
612 //method LaFPackage.fromJar
613
614 /**
615 * The returned LaFPackage's freeResources() method should be called
616 * when none of them is needed any more.
617 *
618 * @param zipfile Description of the Parameter
619 * @return Description of the Return Value
620 * @exception IOException Description of the Exception
621 */
622 public static LaFPackage[] fromZip(File zipfile) throws IOException {
623 List result = new Vector();
624 BufferedInputStream is = null;
625 BufferedOutputStream dest = null;
626
627 /*
628 * IO config
629 */
630 int BUFFER = 2048;
631 byte data[] = new byte[BUFFER];
632 int count;
633
634 /*
635 * create temporary directory
636 */
637 String zipname = zipfile.getName();
638 if (zipname.length() < 7) {
639 zipname = "xxxxxxx" + zipname;
640 }
641
642 File target = null;
643
644 /*
645 * read zip file
646 */
647 ZipFile zip = new ZipFile(zipfile);
648 Enumeration entries = zip.entries();
649 ZipEntry jar;
650 String jarName;
651
652 while (entries.hasMoreElements()) {
653 jar = (ZipEntry) entries.nextElement();
654 jarName = jar.getName();
655
656 if (jarName.endsWith(".jar")) {
657
658 /*
659 * extract jar file to temporary directory
660 */
661 /*
662 * get rid of jar directory structure
663 */
664 target = new File(jarName);
665 String jFileName = target.getName();
666
667 /*
668 * construct tmp jarfile
669 */
670 /*
671 * get the temporary directory
672 */
673 target = File.createTempFile("xxx", null);
674 target.delete();
675 target = target.getParentFile();
676
677 /*
678 * construct the tmp jarfile name
679 */
680 target = new File(target, jFileName);
681 for (int i = 1; target.exists(); i++) {
682 target = new File(target.getParent(), jFileName.replaceFirst(".jar$", "-" + i + ".jar"));
683 }
684
685 target.deleteOnExit();
686
687 try {
688 is = new BufferedInputStream(zip.getInputStream(jar));
689 FileOutputStream fos = new FileOutputStream(target);
690 dest = new BufferedOutputStream(fos, BUFFER);
691 while ((count = is.read(data, 0, BUFFER)) != -1) {
692 dest.write(data, 0, count);
693 }
694 } finally {
695 if (dest != null) {
696 dest.close();
697 }
698 if (is != null) {
699 is.close();
700 }
701 }
702
703 /*
704 * look for LookAndFeels in jar
705 */
706 LaFPackage[] foundInJar = LaFPackage.fromJar(target);
707 if (foundInJar == null || foundInJar.length == 0) {
708 /*
709 * if none are found delete the extracted jar
710 * from the temporary directory ...
711 */
712 if (target != null) {
713 target.delete();
714 target = null;
715 }
716 } else {
717 /*
718 * otherwise add the found LaFs to the result list
719 */
720 result.addAll(Arrays.asList(foundInJar));
721 }
722 }
723 }
724 return (LaFPackage[]) result.toArray(new LaFPackage[result.size()]);
725 }
726
727
728 // method LaFPackage.fromZip
729
730 /**
731 * Description of the Method
732 *
733 * @param f Description of the Parameter
734 * @return Description of the Return Value
735 */
736 private static boolean deleteRecursively(File f) {
737 if (f.isDirectory()) {
738 File[] ff = f.listFiles();
739 for (int i = 0; i < ff.length; i++) {
740 deleteRecursively(ff[i]);
741 }
742 }
743 return f.delete();
744 }
745 }
746 // Class LaFPackage
747
748
749 }