KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: InstallerFrame.java 1710 2007-01-15 07:39:53Z dreil $
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  * Copyright 2002 Jan Blok
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  */

22
23 package com.izforge.izpack.installer;
24
25 import java.awt.BorderLayout JavaDoc;
26 import java.awt.Color JavaDoc;
27 import java.awt.Component JavaDoc;
28 import java.awt.Cursor JavaDoc;
29 import java.awt.Dimension JavaDoc;
30 import java.awt.Font JavaDoc;
31 import java.awt.GraphicsEnvironment JavaDoc;
32 import java.awt.GridBagConstraints JavaDoc;
33 import java.awt.GridLayout JavaDoc;
34 import java.awt.Point JavaDoc;
35 import java.awt.Window JavaDoc;
36 import java.awt.event.ActionEvent JavaDoc;
37 import java.awt.event.ActionListener JavaDoc;
38 import java.awt.event.FocusAdapter JavaDoc;
39 import java.awt.event.KeyAdapter JavaDoc;
40 import java.awt.event.MouseAdapter JavaDoc;
41 import java.awt.event.MouseMotionAdapter JavaDoc;
42 import java.awt.event.WindowAdapter JavaDoc;
43 import java.awt.event.WindowEvent JavaDoc;
44 import java.io.BufferedWriter JavaDoc;
45 import java.io.ByteArrayOutputStream JavaDoc;
46 import java.io.File JavaDoc;
47 import java.io.FileNotFoundException JavaDoc;
48 import java.io.FileOutputStream JavaDoc;
49 import java.io.IOException JavaDoc;
50 import java.io.InputStream JavaDoc;
51 import java.io.ObjectOutputStream JavaDoc;
52 import java.io.OutputStream JavaDoc;
53 import java.io.OutputStreamWriter JavaDoc;
54 import java.lang.reflect.Constructor JavaDoc;
55 import java.net.URL JavaDoc;
56 import java.util.ArrayList JavaDoc;
57 import java.util.HashSet JavaDoc;
58 import java.util.Iterator JavaDoc;
59 import java.util.List JavaDoc;
60 import java.util.Map JavaDoc;
61 import java.util.Vector JavaDoc;
62 import java.util.zip.ZipEntry JavaDoc;
63 import java.util.zip.ZipException JavaDoc;
64 import java.util.zip.ZipOutputStream JavaDoc;
65
66 import javax.swing.BorderFactory JavaDoc;
67 import javax.swing.Box JavaDoc;
68 import javax.swing.BoxLayout JavaDoc;
69 import javax.swing.ImageIcon JavaDoc;
70 import javax.swing.JButton JavaDoc;
71 import javax.swing.JComponent JavaDoc;
72 import javax.swing.JFrame JavaDoc;
73 import javax.swing.JLabel JavaDoc;
74 import javax.swing.JOptionPane JavaDoc;
75 import javax.swing.JPanel JavaDoc;
76 import javax.swing.JProgressBar JavaDoc;
77 import javax.swing.JSeparator JavaDoc;
78 import javax.swing.SwingUtilities JavaDoc;
79 import javax.swing.UIManager JavaDoc;
80 import javax.swing.WindowConstants JavaDoc;
81 import javax.swing.border.TitledBorder JavaDoc;
82 import javax.swing.text.JTextComponent JavaDoc;
83
84 import net.n3.nanoxml.NonValidator;
85 import net.n3.nanoxml.StdXMLBuilder;
86 import net.n3.nanoxml.StdXMLParser;
87 import net.n3.nanoxml.StdXMLReader;
88 import net.n3.nanoxml.XMLElement;
89 import net.n3.nanoxml.XMLWriter;
90
91 import com.izforge.izpack.CustomData;
92 import com.izforge.izpack.ExecutableFile;
93 import com.izforge.izpack.LocaleDatabase;
94 import com.izforge.izpack.Panel;
95 import com.izforge.izpack.gui.ButtonFactory;
96 import com.izforge.izpack.gui.EtchedLineBorder;
97 import com.izforge.izpack.gui.IconsDatabase;
98 import com.izforge.izpack.rules.RulesEngine;
99 import com.izforge.izpack.util.AbstractUIProgressHandler;
100 import com.izforge.izpack.util.Debug;
101 import com.izforge.izpack.util.Housekeeper;
102 import com.izforge.izpack.util.IoHelper;
103 import com.izforge.izpack.util.OsConstraint;
104 import com.izforge.izpack.util.VariableSubstitutor;
105
106 /**
107  * The IzPack installer frame.
108  *
109  * @author Julien Ponge created October 27, 2002
110  * @author Fabrice Mirabile added fix for alert window on cross button, July 06 2005
111  * @author Dennis Reil, added RulesEngine November 10 2006, several changes in January 2007
112  */

113 public class InstallerFrame extends JFrame JavaDoc
114 {
115
116    
117     private static final long serialVersionUID = 3257852069162727473L;
118
119     /**
120      * VM version to use version dependent methods calls
121      */

122     private static final float JAVA_SPECIFICATION_VERSION = Float.parseFloat(System
123             .getProperty("java.specification.version"));
124
125     private static final String JavaDoc ICON_RESOURCE = "Installer.image";
126     
127     /**
128      * Name of the variable where to find an extension to the resource name of the icon resource
129      */

130     private static final String JavaDoc ICON_RESOURCE_EXT_VARIABLE_NAME = "installerimage.ext";
131
132
133     private static final String JavaDoc HEADING_ICON_RESOURCE = "Heading.image";
134
135     // private static final int HEADINGLINES = 1;
136

137     /**
138      * The language pack.
139      */

140     public LocaleDatabase langpack;
141
142     /**
143      * The installation data.
144      */

145     protected InstallData installdata;
146
147     /**
148      * The icons database.
149      */

150     public IconsDatabase icons;
151
152     /**
153      * The panels container.
154      */

155     protected JPanel JavaDoc panelsContainer;
156
157     /**
158      * The frame content pane.
159      */

160     protected JPanel JavaDoc contentPane;
161
162     /**
163      * The previous button.
164      */

165     protected JButton JavaDoc prevButton;
166
167     /**
168      * The next button.
169      */

170     protected JButton JavaDoc nextButton;
171
172     /**
173      * The quit button.
174      */

175     protected JButton JavaDoc quitButton;
176
177     /**
178      * Mapping from "raw" panel number to visible panel number.
179      */

180     protected ArrayList JavaDoc visiblePanelMapping;
181
182     /**
183      * Registered GUICreationListener.
184      */

185     protected ArrayList JavaDoc guiListener;
186
187     /**
188      * Heading major text.
189      */

190     protected JLabel JavaDoc[] headingLabels;
191
192     /**
193      * Panel which contains the heading text and/or icon
194      */

195     protected JPanel JavaDoc headingPanel;
196
197     /**
198      * The heading counter component.
199      */

200     protected JComponent JavaDoc headingCounterComponent;
201
202     /**
203      * Image
204      */

205     private JLabel JavaDoc iconLabel;
206
207     /**
208      * Count for discarded interrupt trials.
209      */

210     private int interruptCount = 1;
211
212     /**
213      * Maximum of discarded interrupt trials.
214      */

215     private static final int MAX_INTERRUPT = 3;
216
217     /**
218      * conditions
219      */

220     protected RulesEngine rules;
221
222     /**
223      * Resource name of the conditions specification
224      */

225     private static final String JavaDoc CONDITIONS_SPECRESOURCENAME = "conditions.xml";
226     /**
227      * Resource name for custom icons
228      */

229     private static final String JavaDoc CUSTOM_ICONS_RESOURCEFILE = "customicons.xml";
230
231     /**
232      * The constructor (normal mode).
233      *
234      * @param title The window title.
235      * @param installdata The installation data.
236      * @throws Exception Description of the Exception
237      */

238     public InstallerFrame(String JavaDoc title, InstallData installdata) throws Exception JavaDoc
239     {
240         super(title);
241         guiListener = new ArrayList JavaDoc();
242         visiblePanelMapping = new ArrayList JavaDoc();
243         this.installdata = installdata;
244         this.langpack = installdata.langpack;
245
246         // Sets the window events handler
247
addWindowListener(new WindowHandler());
248         setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
249
250         // initialize rules by loading the conditions
251
loadConditions();
252
253         // Builds the GUI
254
loadIcons();
255         loadCustomIcons();
256         loadPanels();
257         buildGUI();
258
259         // We show the frame
260
showFrame();
261         switchPanel(0);
262     }
263
264     /**
265      * Reads the conditions specification file and initializes the rules engine.
266      */

267     protected void loadConditions()
268     {
269         try
270         {
271             InputStream JavaDoc input = null;
272             input = this.getResource(CONDITIONS_SPECRESOURCENAME);
273             if (input == null)
274             {
275                 this.rules = new RulesEngine(null, installdata);
276                 return;
277             }
278
279             StdXMLParser parser = new StdXMLParser();
280             parser.setBuilder(new StdXMLBuilder());
281             parser.setValidator(new NonValidator());
282             parser.setReader(new StdXMLReader(input));
283
284             // get the data
285
XMLElement conditionsxml = (XMLElement) parser.parse();
286             this.rules = new RulesEngine(conditionsxml, installdata);
287         }
288         catch (Exception JavaDoc e)
289         {
290             Debug.trace("Can not find optional resource " + CONDITIONS_SPECRESOURCENAME);
291             // there seem to be no conditions
292
this.rules = new RulesEngine(null, installdata);
293         }
294     }
295
296     /**
297      * Loads the panels.
298      *
299      * @throws Exception Description of the Exception
300      */

301     private void loadPanels() throws Exception JavaDoc
302     {
303         // Initialisation
304
java.util.List JavaDoc panelsOrder = installdata.panelsOrder;
305         int i;
306         int size = panelsOrder.size();
307         String JavaDoc className;
308         Class JavaDoc objectClass;
309         Constructor JavaDoc constructor;
310         Object JavaDoc object;
311         IzPanel panel;
312         Class JavaDoc[] paramsClasses = new Class JavaDoc[2];
313         paramsClasses[0] = Class.forName("com.izforge.izpack.installer.InstallerFrame");
314         paramsClasses[1] = Class.forName("com.izforge.izpack.installer.InstallData");
315         Object JavaDoc[] params = { this, installdata};
316
317         // We load each of them
318
int curVisPanelNumber = 0;
319         int lastVis = 0;
320         int count = 0;
321         for (i = 0; i < size; i++)
322         {
323             // We add the panel
324
Panel JavaDoc p = (Panel JavaDoc) panelsOrder.get(i);
325             if (!OsConstraint.oneMatchesCurrentSystem(p.osConstraints)) continue;
326             className = p.className;
327             String JavaDoc praefix = "com.izforge.izpack.panels.";
328             if (className.indexOf('.') > -1)
329             // Full qualified class name
330
praefix = "";
331             objectClass = Class.forName(praefix + className);
332             constructor = objectClass.getDeclaredConstructor(paramsClasses);
333             installdata.currentPanel = p; // A hack to use meta data in IzPanel constructor
334
// Do not call constructor of IzPanel or it's derived at an other place else
335
// metadata will be not set.
336
object = constructor.newInstance(params);
337             panel = (IzPanel) object;
338             installdata.panels.add(panel);
339             if (panel.isHidden())
340                 visiblePanelMapping.add(count, new Integer JavaDoc(-1));
341             else
342             {
343                 visiblePanelMapping.add(count, new Integer JavaDoc(curVisPanelNumber));
344                 curVisPanelNumber++;
345                 lastVis = count;
346             }
347             count++;
348             // We add the XML data panel root
349
XMLElement panelRoot = new XMLElement(className);
350             installdata.xmlData.addChild(panelRoot);
351         }
352         visiblePanelMapping.add(count, new Integer JavaDoc(lastVis));
353     }
354
355     /**
356      * Loads the icons.
357      *
358      * @throws Exception Description of the Exception
359      */

360     private void loadIcons() throws Exception JavaDoc
361     {
362         // Initialisations
363
icons = new IconsDatabase();
364         URL JavaDoc url;
365         ImageIcon JavaDoc img;
366         XMLElement icon;
367         InputStream JavaDoc inXML = InstallerFrame.class
368                 .getResourceAsStream("/com/izforge/izpack/installer/icons.xml");
369
370         // Initialises the parser
371
StdXMLParser parser = new StdXMLParser();
372         parser.setBuilder(new StdXMLBuilder());
373         parser.setReader(new StdXMLReader(inXML));
374         parser.setValidator(new NonValidator());
375
376         // We get the data
377
XMLElement data = (XMLElement) parser.parse();
378
379         // We load the icons
380
Vector JavaDoc children = data.getChildrenNamed("icon");
381         int size = children.size();
382         for (int i = 0; i < size; i++)
383         {
384             icon = (XMLElement) children.get(i);
385             url = InstallerFrame.class.getResource(icon.getAttribute("res"));
386             img = new ImageIcon JavaDoc(url);
387             icons.put(icon.getAttribute("id"), img);
388         }
389
390         // We load the Swing-specific icons
391
children = data.getChildrenNamed("sysicon");
392         size = children.size();
393         for (int i = 0; i < size; i++)
394         {
395             icon = (XMLElement) children.get(i);
396             url = InstallerFrame.class.getResource(icon.getAttribute("res"));
397             img = new ImageIcon JavaDoc(url);
398             UIManager.put(icon.getAttribute("id"), img);
399         }
400     }
401     
402     /**
403      * Loads custom icons into the installer.
404      *
405      * @throws Exception
406      */

407     protected void loadCustomIcons() throws Exception JavaDoc {
408       // We try to load and add a custom langpack.
409
InputStream JavaDoc inXML = null;
410       try {
411         inXML = ResourceManager.getInstance().getInputStream(
412             CUSTOM_ICONS_RESOURCEFILE);
413       } catch (Throwable JavaDoc exception) {
414         Debug.trace("Resource " + CUSTOM_ICONS_RESOURCEFILE + " not defined. No custom icons available.");
415         return;
416       }
417       Debug.trace("Custom icons available.");
418       URL JavaDoc url;
419       ImageIcon JavaDoc img;
420       XMLElement icon;
421
422       // Initialises the parser
423
StdXMLParser parser = new StdXMLParser();
424       parser.setBuilder(new StdXMLBuilder());
425       parser.setReader(new StdXMLReader(inXML));
426       parser.setValidator(new NonValidator());
427
428       // We get the data
429
XMLElement data = (XMLElement) parser.parse();
430
431       // We load the icons
432
Vector JavaDoc children = data.getChildrenNamed("icon");
433       int size = children.size();
434       for (int i = 0; i < size; i++) {
435         icon = (XMLElement) children.get(i);
436         url = InstallerFrame.class.getResource(icon.getAttribute("res"));
437         img = new ImageIcon JavaDoc(url);
438         Debug.trace("Icon with id found: " + icon.getAttribute("id"));
439         icons.put(icon.getAttribute("id"), img);
440       }
441
442       // We load the Swing-specific icons
443
children = data.getChildrenNamed("sysicon");
444       size = children.size();
445       for (int i = 0; i < size; i++) {
446         icon = (XMLElement) children.get(i);
447         url = InstallerFrame.class.getResource(icon.getAttribute("res"));
448         img = new ImageIcon JavaDoc(url);
449         UIManager.put(icon.getAttribute("id"), img);
450       }
451     }
452
453     /**
454      * Builds the GUI.
455      */

456     private void buildGUI()
457     {
458         this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // patch 06/07/2005,
459
// Fabrice Mirabile
460
// Sets the frame icon
461
setIconImage(icons.getImageIcon("JFrameIcon").getImage());
462
463         // Prepares the glass pane to block the gui interaction when needed
464
JPanel JavaDoc glassPane = (JPanel JavaDoc) getGlassPane();
465         glassPane.addMouseListener(new MouseAdapter JavaDoc() {/* Nothing todo */
466         });
467         glassPane.addMouseMotionListener(new MouseMotionAdapter JavaDoc() {/* Nothing todo */
468         });
469         glassPane.addKeyListener(new KeyAdapter JavaDoc() {/* Nothing todo */
470         });
471         glassPane.addFocusListener(new FocusAdapter JavaDoc() {/* Nothing todo */
472         });
473
474         // We set the layout & prepare the constraint object
475
contentPane = (JPanel JavaDoc) getContentPane();
476         contentPane.setLayout(new BorderLayout JavaDoc()); // layout);
477

478         // We add the panels container
479
panelsContainer = new JPanel JavaDoc();
480         panelsContainer.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
481         panelsContainer.setLayout(new GridLayout JavaDoc(1, 1));
482         contentPane.add(panelsContainer, BorderLayout.CENTER);
483
484         // We put the first panel
485
installdata.curPanelNumber = 0;
486         IzPanel panel_0 = (IzPanel) installdata.panels.get(0);
487         panelsContainer.add(panel_0);
488
489         // We add the navigation buttons & labels
490

491         NavigationHandler navHandler = new NavigationHandler();
492
493         JPanel JavaDoc navPanel = new JPanel JavaDoc();
494         navPanel.setLayout(new BoxLayout JavaDoc(navPanel, BoxLayout.X_AXIS));
495         navPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(8, 8,
496                 8, 8), BorderFactory.createTitledBorder(new EtchedLineBorder(), langpack
497                 .getString("installer.madewith")
498                 + " ", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font JavaDoc(
499                 "Dialog", Font.PLAIN, 10))));
500         navPanel.add(Box.createHorizontalGlue());
501
502         prevButton = ButtonFactory.createButton(langpack.getString("installer.prev"), icons
503                 .getImageIcon("stepback"), installdata.buttonsHColor);
504         navPanel.add(prevButton);
505         prevButton.addActionListener(navHandler);
506
507         navPanel.add(Box.createRigidArea(new Dimension JavaDoc(5, 0)));
508
509         nextButton = ButtonFactory.createButton(langpack.getString("installer.next"), icons
510                 .getImageIcon("stepforward"), installdata.buttonsHColor);
511         navPanel.add(nextButton);
512         nextButton.addActionListener(navHandler);
513
514         navPanel.add(Box.createRigidArea(new Dimension JavaDoc(5, 0)));
515
516         quitButton = ButtonFactory.createButton(langpack.getString("installer.quit"), icons
517                 .getImageIcon("stop"), installdata.buttonsHColor);
518         navPanel.add(quitButton);
519         quitButton.addActionListener(navHandler);
520         contentPane.add(navPanel, BorderLayout.SOUTH);
521
522         try
523         {
524             ImageIcon JavaDoc icon = loadIcon(ICON_RESOURCE, 0, true);
525             if (icon != null)
526             {
527                 JPanel JavaDoc imgPanel = new JPanel JavaDoc();
528                 imgPanel.setLayout(new BorderLayout JavaDoc());
529                 imgPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 0));
530                 iconLabel = new JLabel JavaDoc(icon);
531                 iconLabel.setBorder(BorderFactory.createLoweredBevelBorder());
532                 imgPanel.add(iconLabel, BorderLayout.NORTH);
533                 contentPane.add(imgPanel, BorderLayout.WEST);
534             }
535         }
536         catch (Exception JavaDoc e)
537         {
538             // ignore
539
}
540
541         loadAndShowImage(0);
542         getRootPane().setDefaultButton(nextButton);
543         callGUIListener(GUIListener.GUI_BUILDED, navPanel);
544         createHeading(navPanel);
545     }
546
547     private void callGUIListener(int what)
548     {
549         callGUIListener(what, null);
550     }
551
552     private void callGUIListener(int what, Object JavaDoc param)
553     {
554         Iterator JavaDoc iter = guiListener.iterator();
555         while (iter.hasNext())
556             ((GUIListener) iter.next()).guiActionPerformed(what, param);
557     }
558
559     private ImageIcon JavaDoc loadIcon(String JavaDoc resPrefix, int PanelNo, boolean tryBaseIcon)
560             throws ResourceNotFoundException, IOException JavaDoc
561     {
562         ResourceManager rm = ResourceManager.getInstance();
563         ImageIcon JavaDoc icon = null;
564         String JavaDoc iconext = this.getIconResourceNameExtension();
565         if (tryBaseIcon)
566         {
567             try
568             {
569                 icon = rm.getImageIconResource(resPrefix);
570             }
571             catch (Exception JavaDoc e) // This is not that clean ...
572
{
573                 icon = rm.getImageIconResource(resPrefix + "." + PanelNo + iconext);
574             }
575         }
576         else
577             icon = rm.getImageIconResource(resPrefix + "." + PanelNo + iconext);
578         return (icon);
579     }
580
581     private ImageIcon JavaDoc loadIcon(String JavaDoc resPrefix, String JavaDoc panelid, boolean tryBaseIcon)
582             throws ResourceNotFoundException, IOException JavaDoc
583     {
584         ResourceManager rm = ResourceManager.getInstance();
585         ImageIcon JavaDoc icon = null;
586         String JavaDoc iconext = this.getIconResourceNameExtension();
587         if (tryBaseIcon)
588         {
589             try
590             {
591                 icon = rm.getImageIconResource(resPrefix);
592             }
593             catch (Exception JavaDoc e) // This is not that clean ...
594
{
595                 icon = rm.getImageIconResource(resPrefix + "." + panelid + iconext);
596             }
597         }
598         else
599             icon = rm.getImageIconResource(resPrefix + "." + panelid + iconext);
600         return (icon);
601     }
602     
603     /**
604      * Returns the current set extension to icon resource names. Can be used to change
605      * the static installer image based on user input
606      * @return a resource extension
607      * or an empty string if the variable was not set.
608      */

609     private String JavaDoc getIconResourceNameExtension()
610     {
611         try
612         {
613             String JavaDoc iconext = this.installdata.getVariable(ICON_RESOURCE_EXT_VARIABLE_NAME);
614             if (iconext == null){
615               iconext = "";
616             }
617             else {
618               
619               if ((iconext.length() > 0) && (iconext.charAt(0) != '.')){
620                 iconext = "." + iconext;
621               }
622             }
623             iconext = iconext.trim();
624             return iconext;
625         }
626         catch (Exception JavaDoc e)
627         {
628             // in case of error, return an empty string
629
return "";
630         }
631    }
632
633     private void loadAndShowImage(int panelNo)
634     {
635         loadAndShowImage(iconLabel, ICON_RESOURCE, panelNo);
636     }
637
638     private void loadAndShowImage(int panelNo, String JavaDoc panelid)
639     {
640         loadAndShowImage(iconLabel, ICON_RESOURCE, panelNo, panelid);
641     }
642
643     private void loadAndShowImage(JLabel JavaDoc iLabel, String JavaDoc resPrefix, int panelno, String JavaDoc panelid)
644     {
645         ImageIcon JavaDoc icon = null;
646         try
647         {
648             icon = loadIcon(resPrefix, panelid, false);
649         }
650         catch (Exception JavaDoc e)
651         {
652             try
653             {
654                 icon = loadIcon(resPrefix, panelno, false);
655             }
656             catch (Exception JavaDoc ex)
657             {
658                 try
659                 {
660                     icon = loadIcon(resPrefix, panelid, true);
661                 }
662                 catch (Exception JavaDoc e1)
663                 {
664                     // ignore
665
}
666             }
667         }
668         if (icon != null)
669         {
670             iLabel.setVisible(false);
671             iLabel.setIcon(icon);
672             iLabel.setVisible(true);
673         }
674     }
675
676     private void loadAndShowImage(JLabel JavaDoc iLabel, String JavaDoc resPrefix, int panelNo)
677     {
678         ImageIcon JavaDoc icon = null;
679         try
680         {
681             icon = loadIcon(resPrefix, panelNo, false);
682         }
683         catch (Exception JavaDoc e)
684         {
685             try
686             {
687                 icon = loadIcon(resPrefix, panelNo, true);
688             }
689             catch (Exception JavaDoc e1)
690             {
691                 // ignore
692
}
693         }
694         if (icon != null)
695         {
696             iLabel.setVisible(false);
697             iLabel.setIcon(icon);
698             iLabel.setVisible(true);
699         }
700     }
701
702     /**
703      * Shows the frame.
704      */

705     private void showFrame()
706     {
707         pack();
708         setSize(installdata.guiPrefs.width, installdata.guiPrefs.height);
709         setResizable(installdata.guiPrefs.resizable);
710         centerFrame(this);
711         setVisible(true);
712     }
713
714     private boolean isBack = false;
715
716     /**
717      * Switches the current panel.
718      *
719      * @param last Description of the Parameter
720      */

721     protected void switchPanel(int last)
722     {
723         try
724         {
725             if (installdata.curPanelNumber < last)
726             {
727                 isBack = true;
728             }
729             panelsContainer.setVisible(false);
730             IzPanel panel = (IzPanel) installdata.panels.get(installdata.curPanelNumber);
731             IzPanel l_panel = (IzPanel) installdata.panels.get(last);
732             // instead of writing data here which leads to duplicated entries in
733
// auto-installation script (bug # 4551), let's make data only immediately before
734
// writing out that script.
735
// l_panel.makeXMLData(installdata.xmlData.getChildAtIndex(last));
736
// No previos button in the first visible panel
737
if (((Integer JavaDoc) visiblePanelMapping.get(installdata.curPanelNumber)).intValue() == 0)
738             {
739                 prevButton.setVisible(false);
740                 lockPrevButton();
741                 unlockNextButton(); // if we push the button back at the license
742
// panel
743
}
744             // Only the exit button in the last panel.
745
else if (((Integer JavaDoc) visiblePanelMapping.get(installdata.panels.size())).intValue() == installdata.curPanelNumber)
746             {
747                 prevButton.setVisible(false);
748                 nextButton.setVisible(false);
749                 lockNextButton();
750             }
751             else
752             {
753                 prevButton.setVisible(true);
754                 nextButton.setVisible(true);
755                 unlockPrevButton();
756                 unlockNextButton();
757             }
758             // With VM version >= 1.5 setting default button one time will not work.
759
// Therefore we set it every panel switch and that also later. But in
760
// the moment it seems so that the quit button will not used as default button.
761
// No idea why... (Klaus Bartz, 06.09.25)
762
SwingUtilities.invokeLater(new Runnable JavaDoc() {
763
764                 public void run()
765                 {
766                    JButton JavaDoc cdb = null;
767                    if (nextButton.isEnabled()) {
768                      cdb = nextButton;
769                      quitButton.setDefaultCapable(false);
770                      prevButton.setDefaultCapable(false);
771                      nextButton.setDefaultCapable(true);
772                    } else if (quitButton.isEnabled()) {
773                      cdb = quitButton;
774                      quitButton.setDefaultCapable(true);
775                      prevButton.setDefaultCapable(false);
776                      nextButton.setDefaultCapable(false);
777                    }
778                    getRootPane().setDefaultButton(cdb);
779                  }
780             });
781
782             // Change panels container to the current one.
783
panelsContainer.remove(l_panel);
784             l_panel.panelDeactivate();
785             panelsContainer.add(panel);
786
787             if (panel.getInitialFocus() != null)
788             { // Initial focus hint should be performed after current panel
789
// was added to the panels container, else the focus hint will
790
// be ignored.
791
// Give a hint for the initial focus to the system.
792
final Component JavaDoc inFoc = panel.getInitialFocus();
793                 if (JAVA_SPECIFICATION_VERSION < 1.35)
794                 {
795                     inFoc.requestFocus();
796                 }
797                 else
798                 { // On java VM version >= 1.5 it works only if
799
// invoke later will be used.
800
SwingUtilities.invokeLater(new Runnable JavaDoc() {
801
802                         public void run()
803                         {
804                             inFoc.requestFocusInWindow();
805                         }
806                     });
807                 }
808                 /*
809                  * On editable text components position the caret to the end of the cust existent
810                  * text.
811                  */

812                 if (inFoc instanceof JTextComponent JavaDoc)
813                 {
814                     JTextComponent JavaDoc inText = (JTextComponent JavaDoc) inFoc;
815                     if (inText.isEditable() && inText.getDocument() != null)
816                     {
817                         inText.setCaretPosition(inText.getDocument().getLength());
818                     }
819                 }
820             }
821             performHeading(panel);
822             performHeadingCounter(panel);
823             panel.panelActivate();
824             panelsContainer.setVisible(true);
825             Panel JavaDoc metadata = panel.getMetadata();
826             if ((metadata != null) && (!"UNKNOWN".equals(metadata.getPanelid())))
827             {
828                 loadAndShowImage(((Integer JavaDoc) visiblePanelMapping.get(installdata.curPanelNumber))
829                         .intValue(), metadata.getPanelid());
830             }
831             else
832             {
833                 loadAndShowImage(((Integer JavaDoc) visiblePanelMapping.get(installdata.curPanelNumber))
834                         .intValue());
835             }
836             isBack = false;
837             callGUIListener(GUIListener.PANEL_SWITCHED);
838         }
839         catch (Exception JavaDoc err)
840         {
841             err.printStackTrace();
842         }
843     }
844
845     /**
846      * Writes the uninstalldata.
847      */

848     private void writeUninstallData()
849     {
850         // Show whether a separated logfile should be also written or not.
851
String JavaDoc logfile = installdata.getVariable("InstallerFrame.logfilePath");
852         BufferedWriter JavaDoc extLogWriter = null;
853         if (logfile != null)
854         {
855             if (logfile.toLowerCase().startsWith("default"))
856                 logfile = "$INSTALL_PATH/Uninstaller/install.log";
857             logfile = IoHelper.translatePath(logfile, new VariableSubstitutor(installdata
858                     .getVariables()));
859             File JavaDoc outFile = new File JavaDoc(logfile);
860             if (!outFile.getParentFile().exists()) outFile.getParentFile().mkdirs();
861             FileOutputStream JavaDoc out = null;
862             try
863             {
864                 out = new FileOutputStream JavaDoc(outFile);
865             }
866             catch (FileNotFoundException JavaDoc e)
867             {
868                 Debug.trace("Cannot create logfile!");
869                 Debug.error(e);
870             }
871             if (out != null) extLogWriter = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(out));
872         }
873         try
874         {
875             // We get the data
876
UninstallData udata = UninstallData.getInstance();
877             List JavaDoc files = udata.getFilesList();
878             ZipOutputStream JavaDoc outJar = installdata.uninstallOutJar;
879
880             if (outJar == null) return;
881
882             // We write the files log
883
outJar.putNextEntry(new ZipEntry JavaDoc("install.log"));
884             BufferedWriter JavaDoc logWriter = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(outJar));
885             logWriter.write(installdata.getInstallPath());
886             logWriter.newLine();
887             Iterator JavaDoc iter = files.iterator();
888             if (extLogWriter != null)
889             { // Write intern (in uninstaller.jar) and extern log file.
890
while (iter.hasNext())
891                 {
892                     String JavaDoc txt = (String JavaDoc) iter.next();
893                     logWriter.write(txt);
894                     extLogWriter.write(txt);
895                     if (iter.hasNext())
896                     {
897                         logWriter.newLine();
898                         extLogWriter.newLine();
899                     }
900                 }
901                 logWriter.flush();
902                 extLogWriter.flush();
903                 extLogWriter.close();
904             }
905             else
906             {
907                 while (iter.hasNext())
908                 {
909                     logWriter.write((String JavaDoc) iter.next());
910                     if (iter.hasNext()) logWriter.newLine();
911                 }
912                 logWriter.flush();
913             }
914             outJar.closeEntry();
915
916             // We write the uninstaller jar file log
917
outJar.putNextEntry(new ZipEntry JavaDoc("jarlocation.log"));
918             logWriter = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(outJar));
919             logWriter.write(udata.getUninstallerJarFilename());
920             logWriter.newLine();
921             logWriter.write(udata.getUninstallerPath());
922             logWriter.flush();
923             outJar.closeEntry();
924
925             // Write out executables to execute on uninstall
926
outJar.putNextEntry(new ZipEntry JavaDoc("executables"));
927             ObjectOutputStream JavaDoc execStream = new ObjectOutputStream JavaDoc(outJar);
928             iter = udata.getExecutablesList().iterator();
929             execStream.writeInt(udata.getExecutablesList().size());
930             while (iter.hasNext())
931             {
932                 ExecutableFile file = (ExecutableFile) iter.next();
933                 execStream.writeObject(file);
934             }
935             execStream.flush();
936             outJar.closeEntry();
937
938             // Write out additional uninstall data
939
// Do not "kill" the installation if there is a problem
940
// with custom uninstall data. Therefore log it to Debug,
941
// but do not throw.
942
Map JavaDoc additionalData = udata.getAdditionalData();
943             if (additionalData != null && !additionalData.isEmpty())
944             {
945                 Iterator JavaDoc keys = additionalData.keySet().iterator();
946                 HashSet JavaDoc exist = new HashSet JavaDoc();
947                 while (keys != null && keys.hasNext())
948                 {
949                     String JavaDoc key = (String JavaDoc) keys.next();
950                     Object JavaDoc contents = additionalData.get(key);
951                     if ("__uninstallLibs__".equals(key))
952                     {
953                         Iterator JavaDoc nativeLibIter = ((List JavaDoc) contents).iterator();
954                         while (nativeLibIter != null && nativeLibIter.hasNext())
955                         {
956                             String JavaDoc nativeLibName = (String JavaDoc) ((List JavaDoc) nativeLibIter.next()).get(0);
957                             byte[] buffer = new byte[5120];
958                             long bytesCopied = 0;
959                             int bytesInBuffer;
960                             outJar.putNextEntry(new ZipEntry JavaDoc("native/" + nativeLibName));
961                             InputStream JavaDoc in = getClass().getResourceAsStream(
962                                     "/native/" + nativeLibName);
963                             while ((bytesInBuffer = in.read(buffer)) != -1)
964                             {
965                                 outJar.write(buffer, 0, bytesInBuffer);
966                                 bytesCopied += bytesInBuffer;
967                             }
968                             outJar.closeEntry();
969                         }
970                     }
971                     else if ("uninstallerListeners".equals(key) || "uninstallerJars".equals(key))
972                     { // It is a ArrayList of ArrayLists which contains the
973
// full
974
// package paths of all needed class files.
975
// First we create a new ArrayList which contains only
976
// the full paths for the uninstall listener self; thats
977
// the first entry of each sub ArrayList.
978
ArrayList JavaDoc subContents = new ArrayList JavaDoc();
979
980                         // Secound put the class into uninstaller.jar
981
Iterator JavaDoc listenerIter = ((List JavaDoc) contents).iterator();
982                         while (listenerIter.hasNext())
983                         {
984                             byte[] buffer = new byte[5120];
985                             long bytesCopied = 0;
986                             int bytesInBuffer;
987                             CustomData customData = (CustomData) listenerIter.next();
988                             // First element of the list contains the listener
989
// class path;
990
// remind it for later.
991
if (customData.listenerName != null)
992                                 subContents.add(customData.listenerName);
993                             Iterator JavaDoc liClaIter = customData.contents.iterator();
994                             while (liClaIter.hasNext())
995                             {
996                                 String JavaDoc contentPath = (String JavaDoc) liClaIter.next();
997                                 if (exist.contains(contentPath)) continue;
998                                 exist.add(contentPath);
999                                 try
1000                                {
1001                                    outJar.putNextEntry(new ZipEntry JavaDoc(contentPath));
1002                                }
1003                                catch (ZipException JavaDoc ze)
1004                                { // Ignore, or ignore not ?? May be it is a
1005
// exception because
1006
// a doubled entry was tried, then we should
1007
// ignore ...
1008
Debug.trace("ZipException in writing custom data: "
1009                                            + ze.getMessage());
1010                                    continue;
1011                                }
1012                                InputStream JavaDoc in = getClass().getResourceAsStream("/" + contentPath);
1013                                if (in != null)
1014                                {
1015                                    while ((bytesInBuffer = in.read(buffer)) != -1)
1016                                    {
1017                                        outJar.write(buffer, 0, bytesInBuffer);
1018                                        bytesCopied += bytesInBuffer;
1019                                    }
1020                                }
1021                                else
1022                                    Debug.trace("custom data not found: " + contentPath);
1023                                outJar.closeEntry();
1024
1025                            }
1026                        }
1027                        // Third we write the list into the
1028
// uninstaller.jar
1029
outJar.putNextEntry(new ZipEntry JavaDoc(key));
1030                        ObjectOutputStream JavaDoc objOut = new ObjectOutputStream JavaDoc(outJar);
1031                        objOut.writeObject(subContents);
1032                        objOut.flush();
1033                        outJar.closeEntry();
1034
1035                    }
1036                    else
1037                    {
1038                        outJar.putNextEntry(new ZipEntry JavaDoc(key));
1039                        if (contents instanceof ByteArrayOutputStream JavaDoc)
1040                        {
1041                            ((ByteArrayOutputStream JavaDoc) contents).writeTo(outJar);
1042                        }
1043                        else
1044                        {
1045                            ObjectOutputStream JavaDoc objOut = new ObjectOutputStream JavaDoc(outJar);
1046                            objOut.writeObject(contents);
1047                            objOut.flush();
1048                        }
1049                        outJar.closeEntry();
1050                    }
1051                }
1052            }
1053            // write the files which should be deleted by root for another user
1054

1055            outJar.putNextEntry(new ZipEntry JavaDoc(UninstallData.ROOTSCRIPT));
1056            ObjectOutputStream JavaDoc rootStream = new ObjectOutputStream JavaDoc(outJar);
1057
1058            String JavaDoc rootScript = udata.getRootScript();
1059
1060            rootStream.writeUTF(rootScript);
1061
1062            rootStream.flush();
1063            outJar.closeEntry();
1064
1065            // Cleanup
1066
outJar.flush();
1067            outJar.close();
1068        }
1069        catch (Exception JavaDoc err)
1070        {
1071            err.printStackTrace();
1072        }
1073    }
1074
1075    /**
1076     * Gets the stream to a resource.
1077     *
1078     * @param res The resource id.
1079     * @return The resource value, null if not found
1080     * @throws Exception
1081     */

1082    public InputStream JavaDoc getResource(String JavaDoc res) throws Exception JavaDoc
1083    {
1084        InputStream JavaDoc result;
1085        String JavaDoc basePath = "";
1086        ResourceManager rm = null;
1087
1088        try
1089        {
1090            rm = ResourceManager.getInstance();
1091            basePath = rm.resourceBasePath;
1092        }
1093        catch (Exception JavaDoc e)
1094        {
1095            e.printStackTrace();
1096        }
1097
1098        result = this.getClass().getResourceAsStream(basePath + res);
1099
1100        if (result == null) { throw new ResourceNotFoundException("Warning: Resource not found: "
1101                + res); }
1102        return result;
1103    }
1104
1105    /**
1106     * Centers a window on screen.
1107     *
1108     * @param frame The window tp center.
1109     */

1110    public void centerFrame(Window JavaDoc frame)
1111    {
1112        Point JavaDoc center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
1113        Dimension JavaDoc frameSize = frame.getSize();
1114        frame.setLocation(center.x - frameSize.width / 2, center.y - frameSize.height / 2 - 10);
1115    }
1116
1117    /**
1118     * Returns the panels container size.
1119     *
1120     * @return The panels container size.
1121     */

1122    public Dimension JavaDoc getPanelsContainerSize()
1123    {
1124        return panelsContainer.getSize();
1125    }
1126
1127    /**
1128     * Sets the parameters of a GridBagConstraints object.
1129     *
1130     * @param gbc The constraints object.
1131     * @param gx The x coordinates.
1132     * @param gy The y coordinates.
1133     * @param gw The width.
1134     * @param wx The x wheight.
1135     * @param wy The y wheight.
1136     * @param gh Description of the Parameter
1137     */

1138    public void buildConstraints(GridBagConstraints JavaDoc gbc, int gx, int gy, int gw, int gh, double wx,
1139            double wy)
1140    {
1141        gbc.gridx = gx;
1142        gbc.gridy = gy;
1143        gbc.gridwidth = gw;
1144        gbc.gridheight = gh;
1145        gbc.weightx = wx;
1146        gbc.weighty = wy;
1147    }
1148
1149    /**
1150     * Makes a clean closing.
1151     */

1152    public void exit()
1153    {
1154        if (installdata.canClose)
1155        {
1156            // this does nothing if the uninstaller was not included
1157
writeUninstallData();
1158            Housekeeper.getInstance().shutDown(0);
1159        }
1160        else
1161        {
1162            // The installation is not over
1163
if (Unpacker.isDiscardInterrupt() && interruptCount < MAX_INTERRUPT)
1164            { // But we should not interrupt.
1165
interruptCount++;
1166                return;
1167            }
1168            // Use a alternate message and title if defined.
1169
final String JavaDoc mkey = "installer.quit.reversemessage";
1170            final String JavaDoc tkey = "installer.quit.reversetitle";
1171            String JavaDoc message = langpack.getString(mkey);
1172            String JavaDoc title = langpack.getString(tkey);
1173            // message equal to key -> no alternate message defined.
1174
if (message.indexOf(mkey) > -1) message = langpack.getString("installer.quit.message");
1175            // title equal to key -> no alternate title defined.
1176
if (title.indexOf(tkey) > -1) title = langpack.getString("installer.quit.title");
1177            // Now replace variables in message or title.
1178
VariableSubstitutor vs = new VariableSubstitutor(installdata.getVariables());
1179            message = vs.substitute(message, null);
1180            title = vs.substitute(title, null);
1181            int res = JOptionPane
1182                    .showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION);
1183            if (res == JOptionPane.YES_OPTION)
1184            {
1185                wipeAborted();
1186                Housekeeper.getInstance().shutDown(0);
1187            }
1188        }
1189    }
1190
1191    /**
1192     * Wipes the written files when you abort the installation.
1193     */

1194    protected void wipeAborted()
1195    {
1196        Iterator JavaDoc it;
1197
1198        // We set interrupt to all running Unpacker and wait 40 sec for maximum.
1199
// If interrupt is discarded (return value false), return immediately:
1200
if (!Unpacker.interruptAll(40000)) return;
1201
1202        // Wipes them all in 2 stages
1203
UninstallData u = UninstallData.getInstance();
1204        it = u.getFilesList().iterator();
1205        if (!it.hasNext()) return;
1206        while (it.hasNext())
1207        {
1208            String JavaDoc p = (String JavaDoc) it.next();
1209            File JavaDoc f = new File JavaDoc(p);
1210            f.delete();
1211        }
1212        String JavaDoc fullCleanup = installdata.getVariable("InstallerFrame.cleanAllAtInterrupt");
1213        if (fullCleanup == null || !"no".equalsIgnoreCase(fullCleanup))
1214            cleanWipe(new File JavaDoc(installdata.getInstallPath()));
1215    }
1216
1217    /**
1218     * Recursive files wiper.
1219     *
1220     * @param file The file to wipe.
1221     */

1222    private void cleanWipe(File JavaDoc file)
1223    {
1224        if (file.isDirectory())
1225        {
1226            File JavaDoc[] files = file.listFiles();
1227            int size = files.length;
1228            for (int i = 0; i < size; i++)
1229                cleanWipe(files[i]);
1230        }
1231        file.delete();
1232    }
1233
1234    /**
1235     * Launches the installation.
1236     *
1237     * @param listener The installation listener.
1238     */

1239    public void install(AbstractUIProgressHandler listener)
1240    {
1241        IUnpacker unpacker = UnpackerFactory.getUnpacker(this.installdata.info.getUnpackerClassName(), installdata, listener);
1242        Thread JavaDoc unpackerthread = new Thread JavaDoc(unpacker, "IzPack - Unpacker thread");
1243        unpackerthread.start();
1244        /*
1245        Unpacker unpacker = new Unpacker(installdata, listener);
1246        unpacker.start();
1247        */

1248    }
1249
1250    /**
1251     * Writes an XML tree.
1252     *
1253     * @param root The XML tree to write out.
1254     * @param out The stream to write on.
1255     * @throws Exception Description of the Exception
1256     */

1257    public void writeXMLTree(XMLElement root, OutputStream JavaDoc out) throws Exception JavaDoc
1258    {
1259        XMLWriter writer = new XMLWriter(out);
1260        // fix bug# 4551
1261
// writer.write(root);
1262
for (int i = 0; i < installdata.panels.size(); i++)
1263        {
1264            IzPanel panel = (IzPanel) installdata.panels.get(i);
1265            panel.makeXMLData(installdata.xmlData.getChildAtIndex(i));
1266        }
1267        writer.write(installdata.xmlData);
1268    }
1269
1270    /**
1271     * Changes the quit button text. If <tt>text</tt> is null, the default quit text is used.
1272     *
1273     * @param text text to be used for changes
1274     */

1275    public void setQuitButtonText(String JavaDoc text)
1276    {
1277        String JavaDoc text1 = text;
1278        if (text1 == null) text1 = langpack.getString("installer.quit");
1279        quitButton.setText(text1);
1280    }
1281
1282    /**
1283     * Sets a new icon into the quit button if icons should be used, else nothing will be done.
1284     *
1285     * @param iconName name of the icon to be used
1286     */

1287    public void setQuitButtonIcon(String JavaDoc iconName)
1288    {
1289        String JavaDoc useButtonIcons = (String JavaDoc) installdata.guiPrefs.modifier.get("useButtonIcons");
1290
1291        if (useButtonIcons == null || "yes".equalsIgnoreCase(useButtonIcons))
1292        {
1293            quitButton.setIcon(icons.getImageIcon(iconName));
1294        }
1295    }
1296
1297    /*
1298     * FocusTraversalPolicy objects to handle keybord blocking; the declaration os Object allows to
1299     * use a pre version 1.4 VM.
1300     */

1301    private Object JavaDoc usualFTP = null;
1302
1303    private Object JavaDoc blockFTP = null;
1304
1305    /**
1306     * Blocks GUI interaction.
1307     */

1308    public void blockGUI()
1309    {
1310        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
1311        getGlassPane().setVisible(true);
1312        getGlassPane().setEnabled(true);
1313        // No traversal handling before VM version 1.4
1314
if (JAVA_SPECIFICATION_VERSION < 1.35) return;
1315        if (usualFTP == null) usualFTP = getFocusTraversalPolicy();
1316        if (blockFTP == null) blockFTP = new BlockFocusTraversalPolicy();
1317        setFocusTraversalPolicy((java.awt.FocusTraversalPolicy JavaDoc) blockFTP);
1318        getGlassPane().requestFocus();
1319        callGUIListener(GUIListener.GUI_BLOCKED);
1320
1321    }
1322
1323    /**
1324     * Releases GUI interaction.
1325     */

1326    public void releaseGUI()
1327    {
1328        getGlassPane().setEnabled(false);
1329        getGlassPane().setVisible(false);
1330        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
1331        // No traversal handling before VM version 1.4
1332
if (JAVA_SPECIFICATION_VERSION < 1.35) return;
1333        setFocusTraversalPolicy((java.awt.FocusTraversalPolicy JavaDoc) usualFTP);
1334        callGUIListener(GUIListener.GUI_RELEASED);
1335    }
1336
1337    /**
1338     * Locks the 'previous' button.
1339     */

1340    public void lockPrevButton()
1341    {
1342        prevButton.setEnabled(false);
1343    }
1344
1345    /**
1346     * Locks the 'next' button.
1347     */

1348    public void lockNextButton()
1349    {
1350        nextButton.setEnabled(false);
1351    }
1352
1353    /**
1354     * Unlocks the 'previous' button.
1355     */

1356    public void unlockPrevButton()
1357    {
1358        prevButton.setEnabled(true);
1359    }
1360
1361    /**
1362     * Unlocks the 'next' button.
1363     */

1364    public void unlockNextButton()
1365    {
1366        nextButton.setEnabled(true);
1367        nextButton.requestFocus();
1368    }
1369
1370    /**
1371     * Allows a panel to ask to be skipped.
1372     */

1373    public void skipPanel()
1374    {
1375        if (installdata.curPanelNumber < installdata.panels.size() - 1)
1376        {
1377            if (isBack)
1378            {
1379                installdata.curPanelNumber--;
1380                switchPanel(installdata.curPanelNumber + 1);
1381            }
1382            else
1383            {
1384                installdata.curPanelNumber++;
1385                switchPanel(installdata.curPanelNumber - 1);
1386            }
1387
1388        }
1389    }
1390
1391    public boolean canShow(int panelnumber)
1392    {
1393        IzPanel panel = (IzPanel) installdata.panels.get(panelnumber);
1394        String JavaDoc panelid = panel.getMetadata().getPanelid();
1395        Debug.trace("Current Panel: " + panelid);
1396
1397        if (!this.getRules().canShowPanel(panelid, this.installdata.variables))
1398        {
1399            // skip panel, if conditions for panel aren't met
1400
Debug.log("Skip panel with panelid=" + panelid);
1401            // panel should be skipped, so we have to decrement panelnumber for skipping
1402
return false;
1403        }
1404        else
1405        {
1406            return true;
1407        }
1408    }
1409
1410    /**
1411     * This function moves to the next panel
1412     */

1413    public void navigateNext()
1414    {
1415        // If the button is inactive this indicates that we cannot move
1416
// so we don't do the move
1417
if (!nextButton.isEnabled()) return;
1418        this.navigateNext(installdata.curPanelNumber);
1419    }
1420
1421    public void navigateNext(int last)
1422    {
1423        if ((installdata.curPanelNumber < installdata.panels.size() - 1))
1424        {
1425            installdata.curPanelNumber++;
1426            if (!canShow(installdata.curPanelNumber))
1427            {
1428                this.navigateNext(last);
1429                return;
1430            }
1431            else
1432            {
1433                if (((IzPanel) installdata.panels.get(last)).isValidated())
1434                {
1435                    switchPanel(last);
1436                }
1437                else {
1438                    installdata.curPanelNumber--;
1439                }
1440            }
1441        }
1442    }
1443
1444    /**
1445     * This function moves to the previous panel
1446     */

1447    public void navigatePrevious()
1448    {
1449        // If the button is inactive this indicates that we cannot move
1450
// so we don't do the move
1451
if (!prevButton.isEnabled()) return;
1452        this.navigatePrevious(installdata.curPanelNumber);
1453    }
1454
1455    public void navigatePrevious(int last)
1456    {
1457        if ((installdata.curPanelNumber > 0))
1458        {
1459            installdata.curPanelNumber--;
1460            if (!canShow(installdata.curPanelNumber))
1461            {
1462                this.navigatePrevious(last);
1463                return;
1464            }
1465            else
1466            {
1467                switchPanel(last);
1468            }
1469        }
1470    }
1471
1472    /**
1473     * Handles the events from the navigation bar elements.
1474     *
1475     * @author Julien Ponge
1476     */

1477    class NavigationHandler implements ActionListener JavaDoc
1478    {
1479
1480        /**
1481         * Actions handler.
1482         *
1483         * @param e The event.
1484         */

1485        public void actionPerformed(ActionEvent JavaDoc e)
1486        {
1487            Object JavaDoc source = e.getSource();
1488            if (source == prevButton)
1489            {
1490                navigatePrevious();
1491            }
1492            else if (source == nextButton)
1493            {
1494                navigateNext();
1495            }
1496            else if (source == quitButton) exit();
1497
1498        }
1499    }
1500
1501    /**
1502     * The window events handler.
1503     *
1504     * @author julien created October 27, 2002
1505     */

1506    class WindowHandler extends WindowAdapter JavaDoc
1507    {
1508
1509        /**
1510         * Window close is pressed,
1511         *
1512         * @param e The event.
1513         */

1514        public void windowClosing(WindowEvent JavaDoc e)
1515        {
1516            // We ask for confirmation
1517
exit();
1518        }
1519
1520        /**
1521         * OLD VERSION We can't avoid the exit here, so don't call exit anywhere else.
1522         *
1523         * @param e The event.
1524         *
1525         * public void windowClosing(WindowEvent e) { if (Unpacker.isDiscardInterrupt() &&
1526         * interruptCount < MAX_INTERRUPT) { // But we should not interrupt. interruptCount++;
1527         * return; } // We show an alert anyway if (!installdata.canClose)
1528         * JOptionPane.showMessageDialog(null, langpack.getString("installer.quit.message"),
1529         * langpack.getString("installer.warning"), JOptionPane.ERROR_MESSAGE); wipeAborted();
1530         * Housekeeper.getInstance().shutDown(0); }
1531         */

1532    }
1533
1534    /**
1535     * A FocusTraversalPolicy that only allows the block panel to have the focus
1536     */

1537    private class BlockFocusTraversalPolicy extends java.awt.DefaultFocusTraversalPolicy JavaDoc
1538    {
1539
1540        private static final long serialVersionUID = 3258413928261169209L;
1541
1542        /**
1543         * Only accepts the block panel
1544         *
1545         * @param aComp the component to check
1546         * @return true if aComp is the block panel
1547         */

1548        protected boolean accept(Component JavaDoc aComp)
1549        {
1550            return aComp == getGlassPane();
1551        }
1552    }
1553
1554    /**
1555     * Returns the gui creation listener list.
1556     *
1557     * @return the gui creation listener list
1558     */

1559    public List JavaDoc getGuiListener()
1560    {
1561        return guiListener;
1562    }
1563
1564    /**
1565     * Add a listener to the listener list.
1566     *
1567     * @param listener to be added as gui creation listener
1568     */

1569    public void addGuiListener(GUIListener listener)
1570    {
1571        guiListener.add(listener);
1572    }
1573
1574    private void createHeadingLabels(int headingLines, Color JavaDoc back)
1575    {
1576        // headingLabels are an array which contains the labels for header (0),
1577
// description lines and the icon (last).
1578
headingLabels = new JLabel JavaDoc[headingLines + 1];
1579        headingLabels[0] = new JLabel JavaDoc("");
1580        // First line ist the "main heading" which should be bold.
1581
headingLabels[0].setFont(headingLabels[0].getFont().deriveFont(Font.BOLD));
1582        if (installdata.guiPrefs.modifier.containsKey("headingFontSize"))
1583        {
1584            float fontSize = Float.parseFloat((String JavaDoc) installdata.guiPrefs.modifier
1585                    .get("headingFontSize"));
1586            if (fontSize > 0.0 && fontSize <= 5.0)
1587            {
1588                float currentSize = headingLabels[0].getFont().getSize2D();
1589                headingLabels[0].setFont(headingLabels[0].getFont().deriveFont(
1590                        currentSize * fontSize));
1591            }
1592        }
1593        for (int i = 1; i < headingLines; ++i)
1594        {
1595            headingLabels[i] = new JLabel JavaDoc();
1596            // Minor headings should be a little bit more to the right.
1597
headingLabels[i].setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0));
1598        }
1599
1600    }
1601
1602    private void createHeadingCounter(Color JavaDoc back, JPanel JavaDoc navPanel, JPanel JavaDoc leftHeadingPanel)
1603    {
1604        int i;
1605        String JavaDoc counterPos = "inHeading";
1606        if (installdata.guiPrefs.modifier.containsKey("headingPanelCounterPos"))
1607            counterPos = (String JavaDoc) installdata.guiPrefs.modifier.get("headingPanelCounterPos");
1608        // Do not create counter if it should be in the heading, but no heading should be used.
1609
if (leftHeadingPanel == null && "inHeading".equalsIgnoreCase(counterPos)) return;
1610        if (installdata.guiPrefs.modifier.containsKey("headingPanelCounter"))
1611        {
1612            headingCounterComponent = null;
1613            if ("progressbar".equalsIgnoreCase((String JavaDoc) installdata.guiPrefs.modifier
1614                    .get("headingPanelCounter")))
1615            {
1616                JProgressBar JavaDoc headingProgressBar = new JProgressBar JavaDoc();
1617                headingProgressBar.setStringPainted(true);
1618                headingProgressBar.setString("");
1619                headingProgressBar.setValue(0);
1620                headingCounterComponent = headingProgressBar;
1621            }
1622            else if ("text".equalsIgnoreCase((String JavaDoc) installdata.guiPrefs.modifier
1623                    .get("headingPanelCounter")))
1624            {
1625                JLabel JavaDoc headingCountPanels = new JLabel JavaDoc(" ");
1626                headingCounterComponent = headingCountPanels;
1627                headingCounterComponent.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0));
1628            }
1629            if ("inHeading".equals(counterPos))
1630            {
1631                leftHeadingPanel.add(headingCounterComponent);
1632            }
1633            else if ("inNavigationPanel".equals(counterPos))
1634            {
1635                Component JavaDoc[] comps = navPanel.getComponents();
1636                for (i = 0; i < comps.length; ++i)
1637                {
1638                    if (comps[i].equals(prevButton)) break;
1639                }
1640                if (i <= comps.length)
1641                {
1642                    navPanel.add(Box.createHorizontalGlue(), i);
1643                    navPanel.add(headingCounterComponent, i);
1644                }
1645
1646            }
1647        }
1648    }
1649
1650    private JPanel JavaDoc createHeadingIcon(Color JavaDoc back)
1651    {
1652        // the icon
1653
ImageIcon JavaDoc icon = null;
1654        try
1655        {
1656            icon = loadIcon(HEADING_ICON_RESOURCE, 0, true);
1657        }
1658        catch (Exception JavaDoc e)
1659        {
1660            // ignore
1661
}
1662        JPanel JavaDoc imgPanel = new JPanel JavaDoc();
1663        imgPanel.setLayout(new BoxLayout JavaDoc(imgPanel, BoxLayout.Y_AXIS));
1664        imgPanel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
1665        if (back != null) imgPanel.setBackground(back);
1666        JLabel JavaDoc iconLab = new JLabel JavaDoc(icon);
1667        imgPanel.add(iconLab, BorderLayout.EAST);
1668        headingLabels[headingLabels.length - 1] = iconLab;
1669        return (imgPanel);
1670
1671    }
1672
1673    private void createHeading(JPanel JavaDoc navPanel)
1674    {
1675        headingPanel = null;
1676        int headingLines = 1;
1677        // The number of lines can be determined in the config xml file.
1678
// The first is the header, additonals are descriptions for the header.
1679
if (installdata.guiPrefs.modifier.containsKey("headingLineCount"))
1680            headingLines = Integer.parseInt((String JavaDoc) installdata.guiPrefs.modifier
1681                    .get("headingLineCount"));
1682        Color JavaDoc back = null;
1683        int i = 0;
1684        // It is possible to determine the used background color of the heading panel.
1685
if (installdata.guiPrefs.modifier.containsKey("headingBackgroundColor"))
1686            back = Color.decode((String JavaDoc) installdata.guiPrefs.modifier
1687                    .get("headingBackgroundColor"));
1688        // Try to create counter if no heading should be used.
1689
if (!isHeading(null))
1690        {
1691            createHeadingCounter(back, navPanel, null);
1692            return;
1693        }
1694
1695        // We create the text labels and the needed panels. From inner to outer.
1696
// Labels
1697
createHeadingLabels(headingLines, back);
1698        // Panel which contains the labels
1699
JPanel JavaDoc leftHeadingPanel = new JPanel JavaDoc();
1700        if (back != null) leftHeadingPanel.setBackground(back);
1701        leftHeadingPanel.setLayout(new BoxLayout JavaDoc(leftHeadingPanel, BoxLayout.Y_AXIS));
1702        for (i = 0; i < headingLines; ++i)
1703            leftHeadingPanel.add(headingLabels[i]);
1704        // HeadingPanel counter: this is a label or a progress bar which can be placed
1705
// in the leftHeadingPanel or in the navigation bar. It is facultative. If
1706
// exist, it shows the current panel number and the amount of panels.
1707
createHeadingCounter(back, navPanel, leftHeadingPanel);
1708        // It is possible to place an icon on the right side of the heading panel.
1709
JPanel JavaDoc imgPanel = createHeadingIcon(back);
1710
1711        // The panel for text and icon.
1712
JPanel JavaDoc northPanel = new JPanel JavaDoc();
1713        if (back != null) northPanel.setBackground(back);
1714        northPanel.setLayout(new BoxLayout JavaDoc(northPanel, BoxLayout.X_AXIS));
1715        northPanel.setBorder(BorderFactory.createEmptyBorder(0, 12, 0, 0));
1716        northPanel.add(leftHeadingPanel);
1717        northPanel.add(Box.createHorizontalGlue());
1718        northPanel.add(imgPanel);
1719        headingPanel = new JPanel JavaDoc(new BorderLayout JavaDoc());
1720        headingPanel.add(northPanel);
1721        headingPanel.add(new JSeparator JavaDoc(), BorderLayout.SOUTH);
1722
1723        // contentPane.add(northPanel, BorderLayout.NORTH);
1724
contentPane.add(headingPanel, BorderLayout.NORTH);
1725
1726    }
1727
1728    /**
1729     * Returns whether this installer frame uses with the given panel a separated heading panel or
1730     * not. Be aware, this is an other heading as given by the IzPanel which will be placed in the
1731     * IzPanel. This heading will be placed if the gui preferences contains an modifier with the key
1732     * "useHeadingPanel" and the value "yes" and there is a message with the key "&lt;class
1733     * name&gt;.headline".
1734     *
1735     * @param caller the IzPanel for which heading should be resolved
1736     * @return whether an heading panel will be used or not
1737     */

1738    public boolean isHeading(IzPanel caller)
1739    {
1740        if (!installdata.guiPrefs.modifier.containsKey("useHeadingPanel")
1741                || !((String JavaDoc) installdata.guiPrefs.modifier.get("useHeadingPanel"))
1742                        .equalsIgnoreCase("yes")) return (false);
1743        if (caller == null) return (true);
1744        return (caller.getI18nStringForClass("headline", null) != null);
1745
1746    }
1747
1748    private void performHeading(IzPanel panel)
1749    {
1750        int i;
1751        int headingLines = 1;
1752        if (installdata.guiPrefs.modifier.containsKey("headingLineCount"))
1753            headingLines = Integer.parseInt((String JavaDoc) installdata.guiPrefs.modifier
1754                    .get("headingLineCount"));
1755
1756        if (headingLabels == null) return;
1757        String JavaDoc headline = panel.getI18nStringForClass("headline");
1758        if (headline == null)
1759        {
1760            headingPanel.setVisible(false);
1761            return;
1762        }
1763        for (i = 0; i <= headingLines; ++i)
1764            if (headingLabels[i] != null) headingLabels[i].setVisible(false);
1765        String JavaDoc info;
1766        for (i = 0; i < headingLines - 1; ++i)
1767        {
1768            info = panel.getI18nStringForClass("headinfo" + Integer.toString(i));
1769            if (info == null) info = " ";
1770            if (info.endsWith(":"))
1771            {
1772                info = info.substring(0, info.length() - 1) + ".";
1773            }
1774            headingLabels[i + 1].setText(info);
1775            headingLabels[i + 1].setVisible(true);
1776        }
1777        // Do not forgett the first headline.
1778
headingLabels[0].setText(headline);
1779        headingLabels[0].setVisible(true);
1780        int curPanelNo = ((Integer JavaDoc) visiblePanelMapping.get(installdata.curPanelNumber)).intValue();
1781        if (headingLabels[headingLines] != null)
1782        {
1783            loadAndShowImage(headingLabels[headingLines], HEADING_ICON_RESOURCE, curPanelNo);
1784            headingLabels[headingLines].setVisible(true);
1785        }
1786        headingPanel.setVisible(true);
1787
1788    }
1789
1790    private void performHeadingCounter(IzPanel panel)
1791    {
1792        if (headingCounterComponent != null)
1793        {
1794            int curPanelNo = ((Integer JavaDoc) visiblePanelMapping.get(installdata.curPanelNumber))
1795                    .intValue();
1796            int visPanelsCount = ((Integer JavaDoc) visiblePanelMapping.get(((Integer JavaDoc) visiblePanelMapping
1797                    .get(installdata.panels.size())).intValue())).intValue();
1798
1799            StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1800            buf.append(langpack.getString("installer.step")).append(" ").append(curPanelNo + 1)
1801                    .append(" ").append(langpack.getString("installer.of")).append(" ").append(
1802                            visPanelsCount + 1);
1803            if (headingCounterComponent instanceof JProgressBar JavaDoc)
1804            {
1805                JProgressBar JavaDoc headingProgressBar = (JProgressBar JavaDoc) headingCounterComponent;
1806                headingProgressBar.setMaximum(visPanelsCount + 1);
1807                headingProgressBar.setValue(curPanelNo + 1);
1808                headingProgressBar.setString(buf.toString());
1809            }
1810            else
1811                ((JLabel JavaDoc) headingCounterComponent).setText(buf.toString());
1812        }
1813    }
1814
1815    /**
1816     * @return the rules
1817     */

1818    public RulesEngine getRules()
1819    {
1820        return this.rules;
1821    }
1822
1823    /**
1824     * @param rules the rules to set
1825     */

1826    public void setRules(RulesEngine rules)
1827    {
1828        this.rules = rules;
1829    }
1830}
1831
Popular Tags