KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > project > ui > ExitDialog


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.project.ui;
21
22 import java.awt.BorderLayout JavaDoc;
23 import java.awt.Component JavaDoc;
24 import java.awt.Dialog JavaDoc;
25 import java.awt.Dimension JavaDoc;
26 import java.awt.event.ActionEvent JavaDoc;
27 import java.awt.event.ActionListener JavaDoc;
28 import java.beans.BeanInfo JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.util.HashSet JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.ResourceBundle JavaDoc;
33 import java.util.Set JavaDoc;
34 import javax.swing.*;
35 import javax.swing.border.Border JavaDoc;
36 import javax.swing.border.CompoundBorder JavaDoc;
37 import javax.swing.border.EmptyBorder JavaDoc;
38 import javax.swing.border.LineBorder JavaDoc;
39 import javax.swing.event.ListSelectionEvent JavaDoc;
40 import javax.swing.event.ListSelectionListener JavaDoc;
41 import org.openide.DialogDescriptor;
42 import org.openide.DialogDisplayer;
43 import org.openide.ErrorManager;
44 import org.openide.NotifyDescriptor;
45 import org.openide.awt.Mnemonics;
46 import org.openide.cookies.EditorCookie;
47 import org.openide.cookies.SaveCookie;
48 import org.openide.loaders.DataObject;
49 import org.openide.nodes.Node;
50 import org.openide.util.NbBundle;
51
52
53 // XXX This code is stolen from core/ExitDialog.
54
/** Dialog which lets the user select which open files to close.
55  *
56  * @author Ian Formanek, Petr Hrebejk
57  */

58 final public class ExitDialog extends JPanel implements ActionListener JavaDoc {
59
60     /*for tests only!*/static boolean SAVE_ALL_UNCONDITIONALLY = false;
61
62     private static Object JavaDoc[] exitOptions;
63
64     /** The dialog */
65     private static Dialog JavaDoc exitDialog;
66
67     /** Result of the dialog */
68     private static boolean result = false;
69
70     JList list;
71     DefaultListModel listModel;
72
73     /** Constructs new dlg for unsaved files in filesystems marked
74      * for unmount.
75     */

76     private ExitDialog (Set JavaDoc<DataObject> openedFiles) {
77         setLayout (new BorderLayout JavaDoc ());
78
79         listModel = new DefaultListModel();
80         
81         Set JavaDoc<DataObject> set = getModifiedFiles (openedFiles);
82         if (!set.isEmpty ()) {
83             Iterator JavaDoc iter = set.iterator ();
84             while (iter.hasNext ()) {
85                 DataObject obj = (DataObject) iter.next ();
86                 listModel.addElement(obj);
87             }
88             draw ();
89         }
90     }
91     
92     
93     /** Constructs rest of dialog.
94     */

95     private void draw () {
96         list = new JList(listModel);
97         list.setBorder(new EmptyBorder JavaDoc(2, 2, 2, 2));
98         list.addListSelectionListener (new ListSelectionListener JavaDoc () {
99                                            public void valueChanged (ListSelectionEvent JavaDoc evt) {
100                                                updateSaveButton ();
101                                            }
102                                        }
103                                       );
104         // bugfix 37941, select first item in list
105
if (!listModel.isEmpty ()) {
106             list.setSelectedIndex (0);
107         } else {
108             updateSaveButton ();
109         }
110         JScrollPane scroll = new JScrollPane (list);
111         scroll.setBorder (new CompoundBorder JavaDoc (new EmptyBorder JavaDoc (12, 12, 11, 0), scroll.getBorder ()));
112         add(scroll, BorderLayout.CENTER);
113         list.setCellRenderer(new ExitDlgListCellRenderer());
114         list.getAccessibleContext().setAccessibleName((NbBundle.getBundle(ExitDialog.class)).getString("ACSN_ListOfChangedFiles"));
115         list.getAccessibleContext().setAccessibleDescription((NbBundle.getBundle(ExitDialog.class)).getString("ACSD_ListOfChangedFiles"));
116         this.getAccessibleContext().setAccessibleDescription((NbBundle.getBundle(ExitDialog.class)).getString("ACSD_ExitDialog"));
117     }
118     
119     private void updateSaveButton () {
120         ((JButton)exitOptions [0]).setEnabled (list.getSelectedIndex () != -1);
121     }
122
123     /** @return preffered size */
124     public Dimension JavaDoc getPreferredSize() {
125         Dimension JavaDoc prev = super.getPreferredSize();
126         return new Dimension JavaDoc(Math.max(300, prev.width), Math.max(150, prev.height));
127     }
128
129     /** This method is called when is any of buttons pressed
130     */

131     public void actionPerformed (final ActionEvent JavaDoc evt) {
132         if (exitOptions[0].equals (evt.getSource ())) {
133             save(false);
134         } else if (exitOptions[1].equals (evt.getSource ())) {
135             save(true);
136         } else if (exitOptions[2].equals (evt.getSource ())) {
137             theEnd();
138         } else if (NotifyDescriptor.CANCEL_OPTION.equals (evt.getSource ())) {
139             exitDialog.setVisible (false);
140         }
141     }
142
143     /** Save the files from the listbox
144     * @param all true- all files, false - just selected
145     */

146     private void save(boolean all) {
147         Object JavaDoc array[] = ((all) ? listModel.toArray() : list.getSelectedValues());
148         int i, count = ((array == null) ? 0 : array.length);
149         int index = 0; // index of last removed item
150

151         for (i = 0; i < count; i++) {
152             DataObject nextObject = (DataObject)array[i];
153             index = listModel.indexOf(nextObject);
154             save(nextObject);
155         }
156
157         if (listModel.isEmpty())
158             theEnd();
159         else { // reset selection to new item at the same index if available
160
if (index < 0)
161                 index = 0;
162             else if (index > listModel.size() - 1) {
163                 index = listModel.size() - 1;
164             }
165             list.setSelectedIndex(index);
166         }
167     }
168
169     /** Tries to save given data object using its save cookie.
170      * Notifies user if excetions appear.
171      */

172     private void save (DataObject dataObject) {
173         try {
174             SaveCookie sc = (SaveCookie)dataObject.getCookie(SaveCookie.class);
175             if (sc != null) {
176                 sc.save();
177             }
178             listModel.removeElement(dataObject);
179         } catch (IOException JavaDoc exc) {
180             ErrorManager em = ErrorManager.getDefault();
181             Throwable JavaDoc t = em.annotate(
182                 exc, NbBundle.getBundle(ExitDialog.class).getString("EXC_Save")
183             );
184             em.notify(ErrorManager.EXCEPTION, t);
185         }
186     }
187  
188     public static void doSave (DataObject dataObject) {
189         try {
190             SaveCookie sc = (SaveCookie)dataObject.getCookie(SaveCookie.class);
191             if (sc != null) {
192                 sc.save();
193             }
194         } catch (IOException JavaDoc exc) {
195             ErrorManager em = ErrorManager.getDefault();
196             Throwable JavaDoc t = em.annotate(
197                 exc, NbBundle.getBundle(ExitDialog.class).getString("EXC_Save")
198             );
199             em.notify(ErrorManager.EXCEPTION, t);
200         }
201     }
202     
203     /** Exit the IDE
204     */

205     private void theEnd() {
206         // XXX(-ttran) result must be set before calling setVisible(false)
207
// because this will unblock the thread which called Dialog.show()
208

209         for (int i = listModel.size() - 1; i >= 0; i--) {
210             DataObject obj = (DataObject) listModel.getElementAt(i);
211             obj.setModified(false);
212         }
213
214         result = true;
215         exitDialog.setVisible (false);
216         exitDialog.dispose();
217     }
218
219     /** Opens the ExitDialog for unsaved files in filesystems marked
220      * for unmount and blocks until it's closed. If dialog doesm't
221      * exists it creates new one. Returns true if the IDE should be closed.
222      */

223     public static boolean showDialog (Set JavaDoc<DataObject> openedFiles) {
224         return innerShowDialog (getModifiedFiles (openedFiles));
225     }
226     
227     private static Set JavaDoc<DataObject> getModifiedFiles (Set JavaDoc<DataObject> openedFiles) {
228         Set JavaDoc<DataObject> set = new HashSet JavaDoc<DataObject> (openedFiles.size ());
229     for (DataObject obj: openedFiles) {
230             if (obj.isModified ()) {
231                 set.add (obj);
232             }
233         }
234         return set;
235     }
236
237
238     /** Opens the ExitDialog for activated nodes or for
239      * whole repository.
240      */

241     private static boolean innerShowDialog (Set JavaDoc<DataObject> openedFiles) {
242         if (!openedFiles.isEmpty()) {
243             if (SAVE_ALL_UNCONDITIONALLY) {
244                 //this section should be invoked only by tests!
245
for (DataObject d: openedFiles) {
246                     doSave(d);
247                 }
248                 
249                 return true;
250             }
251
252             // XXX(-ttran) caching this dialog is fatal. If the user
253
// cancels the Exit action, modifies some more files and tries to
254
// Exit again the list of modified DataObject's is not updated,
255
// changes made by the user after the first aborted Exit will be
256
// lost.
257
exitDialog = null;
258             
259             if (exitDialog == null) {
260                 ResourceBundle JavaDoc bundle = NbBundle.getBundle(ExitDialog.class);
261                 JButton buttonSave = new JButton();
262                 buttonSave.getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_Save"));
263                 JButton buttonSaveAll = new JButton();
264                 buttonSaveAll.getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_SaveAll"));
265                 JButton buttonDiscardAll = new JButton();
266                 buttonDiscardAll.getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_DiscardAll"));
267                 
268                 Mnemonics.setLocalizedText(buttonSave, bundle.getString("CTL_Save"));
269                 Mnemonics.setLocalizedText(buttonSaveAll, bundle.getString ("CTL_SaveAll"));
270                 Mnemonics.setLocalizedText(buttonDiscardAll, bundle.getString ("CTL_DiscardAll"));
271                 
272                 exitOptions = new Object JavaDoc[] {
273                                   buttonSave,
274                                   buttonSaveAll,
275                                   buttonDiscardAll,
276                               };
277                 ExitDialog exitComponent = null;
278                 exitComponent = new ExitDialog (openedFiles);
279                 DialogDescriptor exitDlgDescriptor = new DialogDescriptor (
280                                                          exitComponent, // inside component
281
bundle.getString("CTL_ExitTitle"), // title
282
true, // modal
283
exitOptions, // options
284
NotifyDescriptor.CANCEL_OPTION, // initial value
285
DialogDescriptor.RIGHT_ALIGN, // option align
286
null, // no help
287
exitComponent // Action Listener
288
);
289                 exitDlgDescriptor.setAdditionalOptions (new Object JavaDoc[] {NotifyDescriptor.CANCEL_OPTION});
290                 exitDialog = DialogDisplayer.getDefault ().createDialog (exitDlgDescriptor);
291             }
292
293             result = false;
294             exitDialog.setVisible (true); // Show the modal Save dialog
295
return result;
296
297         }
298         else
299             return true;
300     }
301
302     /** Renderer used in list box of exit dialog
303      */

304     private class ExitDlgListCellRenderer extends JLabel implements ListCellRenderer {
305
306         protected Border JavaDoc hasFocusBorder;
307         protected Border JavaDoc noFocusBorder;
308
309         public ExitDlgListCellRenderer() {
310             this.setOpaque(true);
311             this.setBorder(noFocusBorder);
312             hasFocusBorder = new LineBorder JavaDoc(UIManager.getColor("List.focusCellHighlight")); // NOI18N
313
noFocusBorder = new EmptyBorder JavaDoc(1, 1, 1, 1);
314         }
315
316         public Component JavaDoc getListCellRendererComponent (JList list, Object JavaDoc value, int index, boolean isSelected, boolean cellHasFocus) // the list and the cell have the focus
317
{
318             final DataObject obj = (DataObject)value;
319             if (!obj.isValid()) {
320                 // #17059: it might be invalid already.
321
// #18886: but if so, remove it later, otherwise BasicListUI gets confused.
322
SwingUtilities.invokeLater(new Runnable JavaDoc() {
323                     public void run() {
324                         listModel.removeElement(obj);
325                     }
326                 });
327                 setText("");
328                 return this;
329             }
330
331             Node node = obj.getNodeDelegate();
332
333             ImageIcon icon = new ImageIcon(node.getIcon(BeanInfo.ICON_COLOR_16x16));
334             super.setIcon(icon);
335
336             setText(node.getDisplayName());
337             if (isSelected){
338                 this.setBackground(UIManager.getColor("List.selectionBackground")); // NOI18N
339
this.setForeground(UIManager.getColor("List.selectionForeground")); // NOI18N
340
}
341             else {
342                 this.setBackground(list.getBackground());
343                 this.setForeground(list.getForeground());
344             }
345
346             this.setBorder(cellHasFocus ? hasFocusBorder : noFocusBorder);
347
348             return this;
349         }
350     }
351 }
352
Popular Tags