KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > izforge > izpack > installer > GUIInstaller


1 /*
2  * $Id: GUIInstaller.java 1708 2007-01-13 18:31:26Z jponge $
3  * IzPack - Copyright 2001-2007 Julien Ponge, All Rights Reserved.
4  *
5  * http://www.izforge.com/izpack/
6  * http://developer.berlios.de/projects/izpack/
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */

20
21 package com.izforge.izpack.installer;
22
23 import java.awt.Color JavaDoc;
24 import java.awt.Component JavaDoc;
25 import java.awt.Dimension JavaDoc;
26 import java.awt.Font JavaDoc;
27 import java.awt.GraphicsEnvironment JavaDoc;
28 import java.awt.GridBagConstraints JavaDoc;
29 import java.awt.GridBagLayout JavaDoc;
30 import java.awt.Insets JavaDoc;
31 import java.awt.Point JavaDoc;
32 import java.awt.Toolkit JavaDoc;
33 import java.awt.event.ActionEvent JavaDoc;
34 import java.awt.event.ActionListener JavaDoc;
35 import java.awt.event.WindowAdapter JavaDoc;
36 import java.awt.event.WindowEvent JavaDoc;
37 import java.io.InputStream JavaDoc;
38 import java.io.ObjectInputStream JavaDoc;
39 import java.lang.reflect.Method JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Locale JavaDoc;
44 import java.util.Map JavaDoc;
45 import java.util.TreeMap JavaDoc;
46
47 import javax.swing.GrayFilter JavaDoc;
48 import javax.swing.ImageIcon JavaDoc;
49 import javax.swing.JButton JavaDoc;
50 import javax.swing.JComboBox JavaDoc;
51 import javax.swing.JDialog JavaDoc;
52 import javax.swing.JFrame JavaDoc;
53 import javax.swing.JLabel JavaDoc;
54 import javax.swing.JList JavaDoc;
55 import javax.swing.JOptionPane JavaDoc;
56 import javax.swing.JPanel JavaDoc;
57 import javax.swing.ListCellRenderer JavaDoc;
58 import javax.swing.LookAndFeel JavaDoc;
59 import javax.swing.SwingConstants JavaDoc;
60 import javax.swing.SwingUtilities JavaDoc;
61 import javax.swing.UIManager JavaDoc;
62 import javax.swing.plaf.metal.MetalLookAndFeel JavaDoc;
63 import javax.swing.plaf.metal.MetalTheme JavaDoc;
64
65 import com.izforge.izpack.GUIPrefs;
66 import com.izforge.izpack.LocaleDatabase;
67 import com.izforge.izpack.gui.ButtonFactory;
68 import com.izforge.izpack.gui.IzPackMetalTheme;
69 import com.izforge.izpack.gui.LabelFactory;
70 import com.izforge.izpack.util.Debug;
71 import com.izforge.izpack.util.OsVersion;
72 import com.izforge.izpack.util.VariableSubstitutor;
73
74 /**
75  * The IzPack graphical installer class.
76  *
77  * @author Julien Ponge
78  */

79 public class GUIInstaller extends InstallerBase
80 {
81
82     /** The installation data. */
83     private InstallData installdata;
84
85     /** The L&F. */
86     protected String JavaDoc lnf;
87
88     /** defined modifier for language display type. */
89     private static final String JavaDoc[] LANGUAGE_DISPLAY_TYPES = { "iso3", "native", "default"};
90
91     private static final String JavaDoc[][] LANG_CODES = { { "cat", "ca"}, { "chn", "zh"}, { "cze", "cs"},
92             { "dan", "da"}, { "deu", "de"}, { "eng", "en"}, { "fin", "fi"}, { "fra", "fr"},
93             { "hun", "hu"}, { "ita", "it"}, { "jpn", "ja"}, { "mys", "ms"}, { "ned", "nl"},
94             { "nor", "no"}, { "pol", "pl"}, { "por", "pt"}, { "rom", "or"}, { "rus", "ru"},
95             { "spa", "es"}, { "svk", "sk"}, { "swe", "sv"}, { "tur", "tr"}, { "ukr", "uk"}};
96
97     /** holds language to ISO-3 language code translation */
98     private static HashMap JavaDoc isoTable;
99
100     /**
101      * The constructor.
102      *
103      * @exception Exception Description of the Exception
104      */

105     public GUIInstaller() throws Exception JavaDoc
106     {
107         this.installdata = new InstallData();
108
109         // Loads the installation data
110
loadInstallData(installdata);
111
112         // add the GUI install data
113
loadGUIInstallData();
114
115         // Sets up the GUI L&F
116
loadLookAndFeel();
117
118         // Checks the Java version
119
checkJavaVersion();
120
121         // Loads the suitable langpack
122
SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
123             public void run()
124             {
125                 try
126                 {
127                     loadLangPack();
128                 }
129                 catch (Exception JavaDoc e)
130                 {
131                     e.printStackTrace();
132                 }
133             }
134         });
135
136         // create the resource manager (after the language selection!)
137
ResourceManager.create(this.installdata);
138
139         // Load custom langpack if exist.
140
addCustomLangpack(installdata);
141
142         // We launch the installer GUI
143
SwingUtilities.invokeLater(new Runnable JavaDoc() {
144             public void run()
145             {
146                 try
147                 {
148                     loadGUI();
149                 }
150                 catch (Exception JavaDoc e)
151                 {
152                     e.printStackTrace();
153                 }
154             }
155         });
156     }
157
158     /**
159      * Load GUI preference information.
160      *
161      * @throws Exception
162      */

163     public void loadGUIInstallData() throws Exception JavaDoc
164     {
165         InputStream JavaDoc in = GUIInstaller.class.getResourceAsStream("/GUIPrefs");
166         ObjectInputStream JavaDoc objIn = new ObjectInputStream JavaDoc(in);
167         this.installdata.guiPrefs = (GUIPrefs) objIn.readObject();
168         objIn.close();
169     }
170
171     /**
172      * Checks the Java version.
173      *
174      * @exception Exception Description of the Exception
175      */

176     private void checkJavaVersion() throws Exception JavaDoc
177     {
178         String JavaDoc version = System.getProperty("java.version");
179         String JavaDoc required = this.installdata.info.getJavaVersion();
180         if (version.compareTo(required) < 0)
181         {
182             StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
183             msg.append("The application that you are trying to install requires a ");
184             msg.append(required);
185             msg.append(" version or later of the Java platform.\n");
186             msg.append("You are running a ");
187             msg.append(version);
188             msg.append(" version of the Java platform.\n");
189             msg.append("Please upgrade to a newer version.");
190
191             System.out.println(msg.toString());
192             JOptionPane.showMessageDialog(null, msg.toString(), "Error", JOptionPane.ERROR_MESSAGE);
193             System.exit(1);
194         }
195     }
196
197     /**
198      * Loads the suitable langpack.
199      *
200      * @exception Exception Description of the Exception
201      */

202     private void loadLangPack() throws Exception JavaDoc
203     {
204         // Initialisations
205
List JavaDoc availableLangPacks = getAvailableLangPacks();
206         int npacks = availableLangPacks.size();
207         if (npacks == 0) throw new Exception JavaDoc("no language pack available");
208         String JavaDoc selectedPack;
209
210         // Dummy Frame
211
JFrame JavaDoc frame = new JFrame JavaDoc();
212         frame.setIconImage(new ImageIcon JavaDoc(this.getClass().getResource("/img/JFrameIcon.png"))
213                 .getImage());
214
215         Dimension JavaDoc frameSize = frame.getSize();
216         Dimension JavaDoc screenSize = Toolkit.getDefaultToolkit().getScreenSize();
217         frame.setLocation((screenSize.width - frameSize.width) / 2,
218                 (screenSize.height - frameSize.height) / 2 - 10);
219
220         // We get the langpack name
221
if (npacks != 1)
222         {
223             LanguageDialog picker = new LanguageDialog(frame, availableLangPacks.toArray());
224             picker.setSelection(Locale.getDefault().getISO3Country().toLowerCase());
225             picker.setModal(true);
226             picker.toFront();
227             //frame.setVisible(true);
228
frame.setVisible(false);
229             picker.setVisible(true);
230
231             selectedPack = (String JavaDoc) picker.getSelection();
232             if (selectedPack == null) throw new Exception JavaDoc("installation canceled");
233         }
234         else
235             selectedPack = (String JavaDoc) availableLangPacks.get(0);
236
237         // We add an xml data information
238
this.installdata.xmlData.setAttribute("langpack", selectedPack);
239
240         // We load the langpack
241
installdata.localeISO3 = selectedPack;
242         installdata.setVariable(ScriptParser.ISO3_LANG, installdata.localeISO3);
243         InputStream JavaDoc in = getClass().getResourceAsStream("/langpacks/" + selectedPack + ".xml");
244         this.installdata.langpack = new LocaleDatabase(in);
245     }
246
247     /**
248      * Returns an ArrayList of the available langpacks ISO3 codes.
249      *
250      * @return The available langpacks list.
251      * @exception Exception Description of the Exception
252      */

253     private List JavaDoc getAvailableLangPacks() throws Exception JavaDoc
254     {
255         // We read from the langpacks file in the jar
256
InputStream JavaDoc in = getClass().getResourceAsStream("/langpacks.info");
257         ObjectInputStream JavaDoc objIn = new ObjectInputStream JavaDoc(in);
258         List JavaDoc available = (List JavaDoc) objIn.readObject();
259         objIn.close();
260
261         return available;
262     }
263
264     /**
265      * Loads the suitable L&F.
266      *
267      * @exception Exception Description of the Exception
268      */

269     protected void loadLookAndFeel() throws Exception JavaDoc
270     {
271         // Do we have any preference for this OS ?
272
String JavaDoc syskey = "unix";
273         if (OsVersion.IS_WINDOWS)
274         {
275             syskey = "windows";
276         }
277         else if (OsVersion.IS_OSX)
278         {
279             syskey = "mac";
280         }
281         String JavaDoc laf = null;
282         if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
283         {
284             laf = (String JavaDoc) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
285         }
286
287         // Let's use the system LAF
288
// Resolve whether button icons should be used or not.
289
boolean useButtonIcons = true;
290         if (installdata.guiPrefs.modifier.containsKey("useButtonIcons")
291                 && "no".equalsIgnoreCase((String JavaDoc) installdata.guiPrefs.modifier.get("useButtonIcons"))) useButtonIcons = false;
292         ButtonFactory.useButtonIcons(useButtonIcons);
293         boolean useLabelIcons = true;
294         if (installdata.guiPrefs.modifier.containsKey("useLabelIcons")
295                 && "no".equalsIgnoreCase((String JavaDoc) installdata.guiPrefs.modifier.get("useLabelIcons"))) useLabelIcons = false;
296         LabelFactory.setUseLabelIcons(useLabelIcons);
297         if (laf == null)
298         {
299             if (!"mac".equals(syskey))
300             {
301                 String JavaDoc syslaf = UIManager.getSystemLookAndFeelClassName();
302                 UIManager.setLookAndFeel(syslaf);
303                 if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel JavaDoc)
304                 {
305                     MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
306                     ButtonFactory.useHighlightButtons();
307                     // Reset the use button icons state because
308
// useHighlightButtons
309
// make it always true.
310
ButtonFactory.useButtonIcons(useButtonIcons);
311                     installdata.buttonsHColor = new Color JavaDoc(182, 182, 204);
312                 }
313             }
314             lnf = "swing";
315             return;
316         }
317
318         // Kunststoff (http://www.incors.org/)
319
if ("kunststoff".equals(laf))
320         {
321             ButtonFactory.useHighlightButtons();
322             // Reset the use button icons state because useHighlightButtons
323
// make it always true.
324
ButtonFactory.useButtonIcons(useButtonIcons);
325             installdata.buttonsHColor = new Color JavaDoc(255, 255, 255);
326             Class JavaDoc lafClass = Class.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
327             Class JavaDoc mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
328             Class JavaDoc[] params = { mtheme};
329             Class JavaDoc theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
330             Method JavaDoc setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
331
332             // We invoke and place Kunststoff as our L&F
333
LookAndFeel JavaDoc kunststoff = (LookAndFeel JavaDoc) lafClass.newInstance();
334             MetalTheme JavaDoc ktheme = (MetalTheme JavaDoc) theme.newInstance();
335             Object JavaDoc[] kparams = { ktheme};
336             UIManager.setLookAndFeel(kunststoff);
337             setCurrentThemeMethod.invoke(kunststoff, kparams);
338
339             lnf = "kunststoff";
340             return;
341         }
342
343         // Liquid (http://liquidlnf.sourceforge.net/)
344
if ("liquid".equals(laf))
345         {
346             UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
347             lnf = "liquid";
348
349             Map JavaDoc params = (Map JavaDoc) installdata.guiPrefs.lookAndFeelParams.get(laf);
350             if (params.containsKey("decorate.frames"))
351             {
352                 String JavaDoc value = (String JavaDoc) params.get("decorate.frames");
353                 if ("yes".equals(value))
354                 {
355                     JFrame.setDefaultLookAndFeelDecorated(true);
356                 }
357             }
358             if (params.containsKey("decorate.dialogs"))
359             {
360                 String JavaDoc value = (String JavaDoc) params.get("decorate.dialogs");
361                 if ("yes".equals(value))
362                 {
363                     JDialog.setDefaultLookAndFeelDecorated(true);
364                 }
365             }
366
367             return;
368         }
369
370         // Metouia (http://mlf.sourceforge.net/)
371
if ("metouia".equals(laf))
372         {
373             UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
374             lnf = "metouia";
375             return;
376         }
377
378         // JGoodies Looks (http://looks.dev.java.net/)
379
if ("looks".equals(laf))
380         {
381             Map JavaDoc variants = new TreeMap JavaDoc();
382             variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
383             variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
384             variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
385             variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
386             String JavaDoc variant = (String JavaDoc) variants.get("plasticXP");
387
388             Map JavaDoc params = (Map JavaDoc) installdata.guiPrefs.lookAndFeelParams.get(laf);
389             if (params.containsKey("variant"))
390             {
391                 String JavaDoc param = (String JavaDoc) params.get("variant");
392                 if (variants.containsKey(param))
393                 {
394                     variant = (String JavaDoc) variants.get(param);
395                 }
396             }
397
398             UIManager.setLookAndFeel(variant);
399         }
400     }
401
402     /**
403      * Loads the GUI.
404      *
405      * @exception Exception Description of the Exception
406      */

407     private void loadGUI() throws Exception JavaDoc
408     {
409         UIManager.put("OptionPane.yesButtonText", installdata.langpack.getString("installer.yes"));
410         UIManager.put("OptionPane.noButtonText", installdata.langpack.getString("installer.no"));
411         UIManager.put("OptionPane.cancelButtonText", installdata.langpack
412                 .getString("installer.cancel"));
413         String JavaDoc title;
414         // Use a alternate message if defined.
415
final String JavaDoc key = "installer.reversetitle";
416         String JavaDoc message = installdata.langpack.getString(key);
417         // message equal to key -> no message defined.
418
if (message.indexOf(key) > -1)
419             title = installdata.langpack.getString("installer.title")
420                     + installdata.info.getAppName();
421         else
422         { // Attention! The alternate message has to contain the hole message including
423
// $APP_NAME and may be $APP_VER.
424
VariableSubstitutor vs = new VariableSubstitutor(installdata.getVariables());
425             title = vs.substitute(message, null);
426         }
427         new InstallerFrame(title, this.installdata);
428     }
429
430     /**
431      * Returns whether flags should be used in the language selection dialog or not.
432      *
433      * @return whether flags should be used in the language selection dialog or not
434      */

435     protected boolean useFlags()
436     {
437         if (installdata.guiPrefs.modifier.containsKey("useFlags")
438                 && "no".equalsIgnoreCase((String JavaDoc) installdata.guiPrefs.modifier.get("useFlags")))
439             return (false);
440         return (true);
441     }
442
443     /**
444      * Returns the type in which the language should be displayed in the language selction dialog.
445      * Possible are "iso3", "native" and "usingDefault".
446      *
447      * @return language display type
448      */

449     protected String JavaDoc getLangType()
450     {
451         if (installdata.guiPrefs.modifier.containsKey("langDisplayType"))
452         {
453             String JavaDoc val = (String JavaDoc) installdata.guiPrefs.modifier.get("langDisplayType");
454             val = val.toLowerCase();
455             // Verify that the value is valid, else return the default.
456
for (int i = 0; i < LANGUAGE_DISPLAY_TYPES.length; ++i)
457                 if (val.equalsIgnoreCase(LANGUAGE_DISPLAY_TYPES[i])) return (val);
458             Debug.trace("Value for language display type not valid; value: " + val);
459         }
460         return (LANGUAGE_DISPLAY_TYPES[0]);
461     }
462
463     /**
464      * Used to prompt the user for the language. Languages can be displayed in iso3 or the native
465      * notation or the notation of the default locale. Revising to native notation is based on code
466      * from Christian Murphy (patch #395).
467      *
468      * @author Julien Ponge
469      * @author Christian Murphy
470      * @author Klaus Bartz
471      */

472     private final class LanguageDialog extends JDialog JavaDoc implements ActionListener JavaDoc
473     {
474
475         private static final long serialVersionUID = 3256443616359887667L;
476
477         /** The combo box. */
478         private JComboBox JavaDoc comboBox;
479
480         /** The ISO3 to ISO2 HashMap */
481         private HashMap JavaDoc iso3Toiso2 = null;
482
483         /** iso3Toiso2 expanded ? */
484         private boolean isoMapExpanded = false;
485
486         /**
487          * The constructor.
488          *
489          * @param items The items to display in the box.
490          */

491         public LanguageDialog(JFrame JavaDoc frame, Object JavaDoc[] items)
492         {
493             super(frame);
494
495             try
496             {
497                 loadLookAndFeel();
498             }
499             catch (Exception JavaDoc err)
500             {
501                 err.printStackTrace();
502             }
503
504             // We build the GUI
505
addWindowListener(new WindowHandler());
506             JPanel JavaDoc contentPane = (JPanel JavaDoc) getContentPane();
507             setTitle("Language selection");
508             GridBagLayout JavaDoc layout = new GridBagLayout JavaDoc();
509             contentPane.setLayout(layout);
510             GridBagConstraints JavaDoc gbConstraints = new GridBagConstraints JavaDoc();
511             gbConstraints.anchor = GridBagConstraints.CENTER;
512             gbConstraints.insets = new Insets JavaDoc(5, 5, 5, 5);
513             gbConstraints.fill = GridBagConstraints.NONE;
514             gbConstraints.gridx = 0;
515             gbConstraints.weightx = 1.0;
516             gbConstraints.weighty = 1.0;
517
518             ImageIcon JavaDoc img = getImage();
519             JLabel JavaDoc imgLabel = new JLabel JavaDoc(img);
520             gbConstraints.gridy = 0;
521             contentPane.add(imgLabel);
522
523             gbConstraints.fill = GridBagConstraints.HORIZONTAL;
524             String JavaDoc firstMessage = "Please select your language";
525             if (getLangType().equals(LANGUAGE_DISPLAY_TYPES[0]))
526             // iso3
527
firstMessage = "Please select your language (ISO3 code)";
528
529             JLabel JavaDoc label1 = new JLabel JavaDoc(firstMessage, SwingConstants.CENTER);
530             gbConstraints.gridy = 1;
531             gbConstraints.insets = new Insets JavaDoc(5, 5, 0, 5);
532             layout.addLayoutComponent(label1, gbConstraints);
533             contentPane.add(label1);
534             JLabel JavaDoc label2 = new JLabel JavaDoc("for install instructions:", SwingConstants.CENTER);
535             gbConstraints.gridy = 2;
536             gbConstraints.insets = new Insets JavaDoc(0, 5, 5, 5);
537             layout.addLayoutComponent(label2, gbConstraints);
538             contentPane.add(label2);
539             gbConstraints.insets = new Insets JavaDoc(5, 5, 5, 5);
540
541             items = reviseItems(items);
542
543             comboBox = new JComboBox JavaDoc(items);
544             if (useFlags()) comboBox.setRenderer(new FlagRenderer());
545             gbConstraints.fill = GridBagConstraints.HORIZONTAL;
546             gbConstraints.gridy = 3;
547             layout.addLayoutComponent(comboBox, gbConstraints);
548             contentPane.add(comboBox);
549
550             JButton JavaDoc okButton = new JButton JavaDoc("OK");
551             okButton.addActionListener(this);
552             gbConstraints.fill = GridBagConstraints.NONE;
553             gbConstraints.gridy = 4;
554             gbConstraints.anchor = GridBagConstraints.CENTER;
555             layout.addLayoutComponent(okButton, gbConstraints);
556             contentPane.add(okButton);
557             getRootPane().setDefaultButton(okButton);
558
559             // Packs and centers
560
// Fix for bug "Installer won't show anything on OSX"
561
if (System.getProperty("mrj.version") == null)
562                 pack();
563             else
564                 setSize(getPreferredSize());
565
566             Dimension JavaDoc frameSize = getSize();
567             Point JavaDoc center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
568             setLocation(center.x - frameSize.width / 2,
569                     center.y - frameSize.height / 2 - 10);
570             setResizable(true);
571         }
572
573         /**
574          * Revises iso3 language items depending on the language display type.
575          *
576          * @param items item array to be revised
577          * @return the revised array
578          */

579         private Object JavaDoc[] reviseItems(Object JavaDoc[] items)
580         {
581             String JavaDoc langType = getLangType();
582             // iso3: nothing todo.
583
if (langType.equals(LANGUAGE_DISPLAY_TYPES[0])) return (items);
584             // native: get the names as they are written in that language.
585
if (langType.equals(LANGUAGE_DISPLAY_TYPES[1]))
586                 return (expandItems(items, (new JComboBox JavaDoc()).getFont()));
587             // default: get the names as they are written in the default
588
// language.
589
if (langType.equals(LANGUAGE_DISPLAY_TYPES[2])) return (expandItems(items, null));
590             // Should never be.
591
return (items);
592         }
593
594         /**
595          * Expands the given iso3 codes to language names. If a testFont is given, the codes are
596          * tested whether they can displayed or not. If not, or no font given, the language name
597          * will be returned as written in the default language of this VM.
598          *
599          * @param items item array to be expanded to the language name
600          * @param testFont font to test wheter a name is displayable
601          * @return aray of expanded items
602          */

603         private Object JavaDoc[] expandItems(Object JavaDoc[] items, Font JavaDoc testFont)
604         {
605             int i;
606             if (iso3Toiso2 == null)
607             { // Loasd predefined langs into HashMap.
608
iso3Toiso2 = new HashMap JavaDoc(32);
609                 isoTable = new HashMap JavaDoc();
610                 for (i = 0; i < LANG_CODES.length; ++i)
611                     iso3Toiso2.put(LANG_CODES[i][0], LANG_CODES[i][1]);
612             }
613             for (i = 0; i < items.length; i++)
614             {
615                 Object JavaDoc it = expandItem(items[i], testFont);
616                 isoTable.put(it, items[i]);
617                 items[i] = it;
618             }
619             return items;
620         }
621
622         /**
623          * Expands the given iso3 code to a language name. If a testFont is given, the code will be
624          * tested whether it is displayable or not. If not, or no font given, the language name will
625          * be returned as written in the default language of this VM.
626          *
627          * @param item item to be expanded to the language name
628          * @param testFont font to test wheter the name is displayable
629          * @return expanded item
630          */

631         private Object JavaDoc expandItem(Object JavaDoc item, Font JavaDoc testFont)
632         {
633             Object JavaDoc iso2Str = iso3Toiso2.get(item);
634             int i;
635             if (iso2Str == null && !isoMapExpanded)
636             { // Expand iso3toiso2 only if needed because it needs some time.
637
isoMapExpanded = true;
638                 Locale JavaDoc[] loc = Locale.getAvailableLocales();
639                 for (i = 0; i < loc.length; ++i)
640                     iso3Toiso2.put(loc[i].getISO3Language(), loc[i].getLanguage());
641                 iso2Str = iso3Toiso2.get(item);
642             }
643             if (iso2Str == null)
644             // Unknown item, return it self.
645
return (item);
646             Locale JavaDoc locale = new Locale JavaDoc((String JavaDoc) iso2Str);
647             if (testFont == null)
648             // Return the language name in the spelling of the default locale.
649
return (locale.getDisplayLanguage());
650             // Get the language name in the spelling of that language.
651
String JavaDoc str = locale.getDisplayLanguage(locale);
652             int cdut = testFont.canDisplayUpTo(str);
653             if (cdut > -1)
654             // Test font cannot render it;
655
// use language name in the spelling of the default locale.
656
str = locale.getDisplayLanguage();
657             return (str);
658         }
659
660         /**
661          * Loads an image.
662          *
663          * @return The image icon.
664          */

665         public ImageIcon JavaDoc getImage()
666         {
667             ImageIcon JavaDoc img;
668             try
669             {
670                 img = new ImageIcon JavaDoc(LanguageDialog.class.getResource("/res/installer.langsel.img"));
671             }
672             catch (NullPointerException JavaDoc err)
673             {
674                 img = null;
675             }
676             return img;
677         }
678
679         /**
680          * Gets the selected object.
681          *
682          * @return The selected item.
683          */

684         public Object JavaDoc getSelection()
685         {
686             Object JavaDoc retval = null;
687             if (isoTable != null) retval = isoTable.get(comboBox.getSelectedItem());
688             return (retval != null) ? retval : comboBox.getSelectedItem();
689         }
690
691         /**
692          * Sets the selection.
693          *
694          * @param item The item to be selected.
695          */

696         public void setSelection(Object JavaDoc item)
697         {
698             Object JavaDoc mapped = null;
699             if (isoTable != null)
700             {
701                 Iterator JavaDoc iter = isoTable.keySet().iterator();
702                 while (iter.hasNext())
703                 {
704                     Object JavaDoc key = iter.next();
705                     if (isoTable.get(key).equals(item))
706                     {
707                         mapped = key;
708                         break;
709                     }
710                 }
711             }
712             if (mapped == null) mapped = item;
713             comboBox.setSelectedItem(mapped);
714         }
715
716         /**
717          * Closer.
718          *
719          * @param e The event.
720          */

721         public void actionPerformed(ActionEvent JavaDoc e)
722         {
723             dispose();
724         }
725
726         /**
727          * The window events handler.
728          *
729          * @author Julien Ponge
730          */

731         private class WindowHandler extends WindowAdapter JavaDoc
732         {
733
734             /**
735              * We can't avoid the exit here, so don't call exit anywhere else.
736              *
737              * @param e the event.
738              */

739             public void windowClosing(WindowEvent JavaDoc e)
740             {
741                 System.exit(0);
742             }
743         }
744     }
745
746     /**
747      * A list cell renderer that adds the flags on the display.
748      *
749      * @author Julien Ponge
750      */

751     private static class FlagRenderer extends JLabel JavaDoc implements ListCellRenderer JavaDoc
752     {
753
754         private static final long serialVersionUID = 3832899961942782769L;
755
756         /** Icons cache. */
757         private TreeMap JavaDoc icons = new TreeMap JavaDoc();
758
759         /** Grayed icons cache. */
760         private TreeMap JavaDoc grayIcons = new TreeMap JavaDoc();
761
762         public FlagRenderer()
763         {
764             setOpaque(true);
765         }
766
767         /**
768          * Returns a suitable cell.
769          *
770          * @param list The list.
771          * @param value The object.
772          * @param index The index.
773          * @param isSelected true if it is selected.
774          * @param cellHasFocus Description of the Parameter
775          * @return The cell.
776          */

777         public Component JavaDoc getListCellRendererComponent(JList JavaDoc list, Object JavaDoc value, int index,
778                 boolean isSelected, boolean cellHasFocus)
779         {
780             // We put the label
781
String JavaDoc iso3 = (String JavaDoc) value;
782             setText(iso3);
783             if (isoTable != null) iso3 = (String JavaDoc) isoTable.get(iso3);
784             if (isSelected)
785             {
786                 setForeground(list.getSelectionForeground());
787                 setBackground(list.getSelectionBackground());
788             }
789             else
790             {
791                 setForeground(list.getForeground());
792                 setBackground(list.getBackground());
793             }
794             // We put the icon
795

796             if (!icons.containsKey(iso3))
797             {
798                 ImageIcon JavaDoc icon;
799                 icon = new ImageIcon JavaDoc(this.getClass().getResource("/res/flag." + iso3));
800                 icons.put(iso3, icon);
801                 icon = new ImageIcon JavaDoc(GrayFilter.createDisabledImage(icon.getImage()));
802                 grayIcons.put(iso3, icon);
803             }
804             if (isSelected || index == -1)
805                 setIcon((ImageIcon JavaDoc) icons.get(iso3));
806             else
807                 setIcon((ImageIcon JavaDoc) grayIcons.get(iso3));
808
809             // We return
810
return this;
811         }
812     }
813 }
814
Popular Tags