KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > apisupport > project > ui > UIUtil


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.apisupport.project.ui;
21
22 import java.awt.Component JavaDoc;
23 import java.awt.Dialog JavaDoc;
24 import java.awt.Dimension JavaDoc;
25 import java.awt.FlowLayout JavaDoc;
26 import java.awt.GridLayout JavaDoc;
27 import java.awt.Image JavaDoc;
28 import java.awt.event.InputEvent JavaDoc;
29 import java.awt.event.KeyEvent JavaDoc;
30 import java.io.File JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.lang.ref.Reference JavaDoc;
33 import java.lang.ref.WeakReference JavaDoc;
34 import java.net.MalformedURLException JavaDoc;
35 import java.text.Collator JavaDoc;
36 import java.text.MessageFormat JavaDoc;
37 import java.util.ArrayList JavaDoc;
38 import java.util.Collection JavaDoc;
39 import java.util.Collections JavaDoc;
40 import java.util.HashSet JavaDoc;
41 import java.util.List JavaDoc;
42 import java.util.Locale JavaDoc;
43 import java.util.Map JavaDoc;
44 import java.util.SortedSet JavaDoc;
45 import java.util.Stack JavaDoc;
46 import java.util.StringTokenizer JavaDoc;
47 import java.util.TreeSet JavaDoc;
48 import javax.swing.ComboBoxModel JavaDoc;
49 import javax.swing.DefaultComboBoxModel JavaDoc;
50 import javax.swing.DefaultListCellRenderer JavaDoc;
51 import javax.swing.Icon JavaDoc;
52 import javax.swing.ImageIcon JavaDoc;
53 import javax.swing.JButton JavaDoc;
54 import javax.swing.JComboBox JavaDoc;
55 import javax.swing.JFileChooser JavaDoc;
56 import javax.swing.JLabel JavaDoc;
57 import javax.swing.JList JavaDoc;
58 import javax.swing.JPanel JavaDoc;
59 import javax.swing.JTextField JavaDoc;
60 import javax.swing.KeyStroke JavaDoc;
61 import javax.swing.ListCellRenderer JavaDoc;
62 import javax.swing.UIManager JavaDoc;
63 import javax.swing.event.DocumentEvent JavaDoc;
64 import javax.swing.event.DocumentListener JavaDoc;
65 import javax.swing.filechooser.FileFilter JavaDoc;
66 import javax.swing.filechooser.FileView JavaDoc;
67 import javax.swing.plaf.UIResource JavaDoc;
68 import javax.swing.text.JTextComponent JavaDoc;
69 import org.netbeans.api.project.Project;
70 import org.netbeans.api.project.ProjectInformation;
71 import org.netbeans.api.project.ProjectManager;
72 import org.netbeans.api.project.ProjectUtils;
73 import org.netbeans.api.project.SourceGroup;
74 import org.netbeans.api.project.ui.OpenProjects;
75 import org.netbeans.modules.apisupport.project.NbModuleProject;
76 import org.netbeans.modules.apisupport.project.spi.NbModuleProvider;
77 import org.netbeans.modules.apisupport.project.Util;
78 import org.netbeans.modules.apisupport.project.layers.LayerUtils;
79 import org.netbeans.modules.apisupport.project.suite.SuiteProject;
80 import org.netbeans.modules.apisupport.project.ui.customizer.SuiteUtils;
81 import org.netbeans.modules.apisupport.project.ui.wizard.NewNbModuleWizardIterator;
82 import org.netbeans.spi.java.project.support.ui.PackageView;
83 import org.netbeans.spi.project.ui.support.ProjectChooser;
84 import org.openide.DialogDescriptor;
85 import org.openide.DialogDisplayer;
86 import org.openide.ErrorManager;
87 import org.openide.NotifyDescriptor;
88 import org.openide.WizardDescriptor;
89 import org.openide.awt.Mnemonics;
90 import org.openide.filesystems.FileObject;
91 import org.openide.filesystems.FileStateInvalidException;
92 import org.openide.filesystems.FileSystem;
93 import org.openide.filesystems.FileUtil;
94 import org.openide.util.NbBundle;
95 import org.openide.util.NbCollections;
96 import org.openide.util.Utilities;
97
98 /**
99  * UI related utility methods for the module.
100  *
101  * @author Martin Krauskopf
102  */

103 public final class UIUtil {
104     
105     private static final String JavaDoc ICON_KEY_UIMANAGER = "Tree.closedIcon"; // NOI18N
106
private static final String JavaDoc OPENED_ICON_KEY_UIMANAGER = "Tree.openIcon"; // NOI18N
107
private static final String JavaDoc ICON_KEY_UIMANAGER_NB = "Nb.Explorer.Folder.icon"; // NOI18N
108
private static final String JavaDoc OPENED_ICON_KEY_UIMANAGER_NB = "Nb.Explorer.Folder.openedIcon"; // NOI18N
109
private static final String JavaDoc ICON_PATH = "org/netbeans/modules/apisupport/project/resources/defaultFolder.gif"; // NOI18N
110
private static final String JavaDoc OPENED_ICON_PATH = "org/netbeans/modules/apisupport/project/resources/defaultFolderOpen.gif"; // NOI18N
111

112     private UIUtil() {}
113     
114     public static String JavaDoc keyToLogicalString(KeyStroke JavaDoc keyStroke) {
115         String JavaDoc keyDesc = Utilities.keyToString(keyStroke);
116         int dash = keyDesc.indexOf('-');
117         return dash == -1 ? keyDesc :
118             keyDesc.substring(0, dash).replace('C', 'D').replace('A', 'O') + keyDesc.substring(dash);
119     }
120     
121     public static String JavaDoc keyStrokeToString(KeyStroke JavaDoc keyStroke) {
122         int modifiers = keyStroke.getModifiers();
123         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
124         if ((modifiers & InputEvent.CTRL_DOWN_MASK) > 0) {
125             sb.append("Ctrl+"); // NOI18N
126
}
127         if ((modifiers & InputEvent.ALT_DOWN_MASK) > 0) {
128             sb.append("Alt+"); // NOI18N
129
}
130         if ((modifiers & InputEvent.SHIFT_DOWN_MASK) > 0) {
131             sb.append("Shift+"); // NOI18N
132
}
133         if ((modifiers & InputEvent.META_DOWN_MASK) > 0) {
134             sb.append("Meta+"); // NOI18N
135
}
136         if (keyStroke.getKeyCode() != KeyEvent.VK_SHIFT &&
137                 keyStroke.getKeyCode() != KeyEvent.VK_CONTROL &&
138                 keyStroke.getKeyCode() != KeyEvent.VK_META &&
139                 keyStroke.getKeyCode() != KeyEvent.VK_ALT &&
140                 keyStroke.getKeyCode() != KeyEvent.VK_ALT_GRAPH) {
141             sb.append(Utilities.keyToString(
142                     KeyStroke.getKeyStroke(keyStroke.getKeyCode(), 0)));
143         }
144         return sb.toString();
145     }
146     
147     public static KeyStroke JavaDoc stringToKeyStroke(String JavaDoc keyStroke) {
148         int modifiers = 0;
149         if (keyStroke.startsWith("Ctrl+")) { // NOI18N
150
modifiers |= InputEvent.CTRL_DOWN_MASK;
151             keyStroke = keyStroke.substring(5);
152         }
153         if (keyStroke.startsWith("Alt+")) { // NOI18N
154
modifiers |= InputEvent.ALT_DOWN_MASK;
155             keyStroke = keyStroke.substring(4);
156         }
157         if (keyStroke.startsWith("Shift+")) { // NOI18N
158
modifiers |= InputEvent.SHIFT_DOWN_MASK;
159             keyStroke = keyStroke.substring(6);
160         }
161         if (keyStroke.startsWith("Meta+")) { // NOI18N
162
modifiers |= InputEvent.META_DOWN_MASK;
163             keyStroke = keyStroke.substring(5);
164         }
165         KeyStroke JavaDoc ks = Utilities.stringToKey(keyStroke);
166         if (ks == null) {
167             return null;
168         }
169         KeyStroke JavaDoc result = KeyStroke.getKeyStroke(ks.getKeyCode(), modifiers);
170         return result;
171     }
172     
173     /**
174      * Returns multi keystroke for given text representation of shortcuts
175      * (like Alt+A B). Returns null if text is not parsable, and empty array
176      * for empty string.
177      */

178     public static KeyStroke JavaDoc[] stringToKeyStrokes(String JavaDoc keyStrokes) {
179         String JavaDoc delim = " "; // NOI18N
180
if (keyStrokes.length() == 0) {
181             return new KeyStroke JavaDoc [0];
182         }
183         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(keyStrokes, delim);
184         List JavaDoc<KeyStroke JavaDoc> result = new ArrayList JavaDoc<KeyStroke JavaDoc>();
185         while (st.hasMoreTokens()) {
186             String JavaDoc ks = st.nextToken().trim();
187             KeyStroke JavaDoc keyStroke = stringToKeyStroke(ks);
188             if (keyStroke == null) { // text is not parsable
189
return null;
190             }
191             result.add(keyStroke);
192         }
193         return result.toArray(new KeyStroke JavaDoc[result.size()]);
194     }
195     
196     public static String JavaDoc keyStrokesToString(final KeyStroke JavaDoc[] keyStrokes) {
197         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(UIUtil.keyStrokeToString(keyStrokes [0]));
198         int i, k = keyStrokes.length;
199         for (i = 1; i < k; i++) {
200             sb.append(' ').append(UIUtil.keyStrokeToString(keyStrokes [i]));
201         }
202         String JavaDoc newShortcut = sb.toString();
203         return newShortcut;
204     }
205     
206     public static String JavaDoc keyStrokesToLogicalString(final KeyStroke JavaDoc[] keyStrokes) {
207         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(UIUtil.keyToLogicalString(keyStrokes [0]));
208         int i, k = keyStrokes.length;
209         for (i = 1; i < k; i++) {
210             sb.append(' ').append(UIUtil.keyToLogicalString((keyStrokes [i])));
211         }
212         String JavaDoc newShortcut = sb.toString();
213         return newShortcut;
214     }
215     
216     /**
217      * Calls in turn {@link ProjectChooser#setProjectsFolder} if the
218      * <code>folder</code> is not <code>null</code> and is a directory.
219      */

220     public static void setProjectChooserDir(File JavaDoc folder) {
221         if (folder == null || !folder.isDirectory()) {
222             return;
223         }
224         ProjectChooser.setProjectsFolder(folder);
225     }
226     
227     /**
228      * Calls {@link #setProjectChooserDir} with the <code>fileOrFolder</code>'s
229      * parent if it isn't <code>null</code>. Otherwise fallbacks to
230      * <code>fileOrFolder</code> itself if it is a directory.
231      */

232     public static void setProjectChooserDirParent(File JavaDoc fileOrFolder) {
233         if (fileOrFolder == null) {
234             return;
235         }
236         File JavaDoc parent = fileOrFolder.getParentFile();
237         setProjectChooserDir(parent != null ? parent :
238             (fileOrFolder.isDirectory() ? fileOrFolder : null));
239     }
240     
241     /**
242      * Set the <code>text</code> for the <code>textComp</code> and set its
243      * caret position to the end of the text.
244      */

245     public static void setText(JTextComponent JavaDoc textComp, String JavaDoc text) {
246         textComp.setText(text);
247         textComp.setCaretPosition(text == null ? 0 : text.length());
248     }
249     
250     /**
251      * Convenient class for listening on document changes. Use it if you do not
252      * care what exact change really happened. {@link #removeUpdate} and {@link
253      * #changedUpdate} just delegate to {@link #insertUpdate}. So everything
254      * what is needed in order to be notified about document changes is to
255      * override {@link #insertUpdate} method.
256      */

257     public abstract static class DocumentAdapter implements DocumentListener JavaDoc {
258         public void removeUpdate(DocumentEvent JavaDoc e) { insertUpdate(null); }
259         public void changedUpdate(DocumentEvent JavaDoc e) { insertUpdate(null); }
260     }
261     
262     private static Reference JavaDoc<JFileChooser JavaDoc> iconChooser;
263     
264     /**
265      * @param icon file representing icon
266      * @param expectedWidth expected width
267      * @param expectedHeight expected height
268      * @return warning or empty <code>String</code>
269      */

270     public static String JavaDoc getIconDimensionWarning(File JavaDoc icon, int expectedWidth, int expectedHeight) {
271         Dimension JavaDoc real = new Dimension JavaDoc(UIUtil.getIconDimension(icon));
272         if (real.height == expectedHeight && real.width == expectedWidth) {
273             return "";
274         }
275         return NbBundle.getMessage(UIUtil.class, "MSG_WrongIconSize",new Object JavaDoc[] {
276             real.width,
277             real.height,
278             expectedWidth,
279             expectedHeight
280         });
281     }
282
283     /**
284      * @param expectedWidth expected width
285      * @param expectedHeight expected height
286      * @return warning
287      */

288     public static String JavaDoc getNoIconSelectedWarning(int expectedWidth, int expectedHeight) {
289         return NbBundle.getMessage(UIUtil.class, "MSG_NoIconSelected", expectedWidth, expectedHeight);
290     }
291     
292     /**
293      * @param icon file representing icon
294      * @param expectedWidth expected width
295      * @param expectedHeight expected height
296      * @return true if icon corresponds to expected dimension
297      */

298     public static boolean isValidIcon(final File JavaDoc icon, int expectedWidth, int expectedHeight) {
299         Dimension JavaDoc iconDimension = UIUtil.getIconDimension(icon);
300         return (expectedWidth == iconDimension.getWidth() &&
301                 expectedHeight == iconDimension.getHeight());
302     }
303     
304     /**
305      * @param icon file representing icon
306      * @return width and height of icon encapsulated into {@link java.awt.Dimension}
307      */

308     public static Dimension JavaDoc getIconDimension(final File JavaDoc icon) {
309         try {
310             ImageIcon JavaDoc imc = new ImageIcon JavaDoc(icon.toURI().toURL());
311             return new Dimension JavaDoc(imc.getIconWidth(), imc.getIconHeight());
312         } catch (MalformedURLException JavaDoc ex) {
313             ErrorManager.getDefault().notify(ex);
314         }
315         return new Dimension JavaDoc(-1, -1);
316     }
317     
318     /**
319      * Returns an instance of {@link javax.swing.JFileChooser} permitting
320      * selection only a regular <em>icon</em>.
321      */

322     public static JFileChooser JavaDoc getIconFileChooser() {
323         if (iconChooser != null) {
324             JFileChooser JavaDoc choose = iconChooser.get();
325             if (choose != null) {
326                 return choose;
327             }
328         }
329         final JFileChooser JavaDoc chooser = new IconFileChooser();
330         iconChooser = new WeakReference JavaDoc<JFileChooser JavaDoc>(chooser);
331         return chooser;
332     }
333
334         
335     /**
336      * tries to set the selected file according to currently existing data.
337      * Will se it only if the String represents a file path that exists.
338      */

339     public static JFileChooser JavaDoc getIconFileChooser(String JavaDoc oldValue) {
340         JFileChooser JavaDoc chooser = getIconFileChooser();
341         String JavaDoc iconText = oldValue.trim();
342         if ( iconText.length() > 0) {
343             File JavaDoc fil = new File JavaDoc(iconText);
344             if (fil.exists()) {
345                 chooser.setSelectedFile(fil);
346             }
347         }
348         return chooser;
349     }
350     
351     /**
352      * Create combobox containing packages from the given {@link SourceGroup}.
353      */

354     public static JComboBox JavaDoc createPackageComboBox(SourceGroup srcRoot) {
355         JComboBox JavaDoc packagesComboBox = new JComboBox JavaDoc(PackageView.createListView(srcRoot));
356         packagesComboBox.setRenderer(PackageView.listRenderer());
357         return packagesComboBox;
358     }
359     
360     /**
361      * Returns true for valid package name.
362      */

363     public static boolean isValidPackageName(String JavaDoc str) {
364         if (str.length() > 0 && str.charAt(0) == '.') {
365             return false;
366         }
367         StringTokenizer JavaDoc tukac = new StringTokenizer JavaDoc(str, "."); // NOI18N
368
while (tukac.hasMoreTokens()) {
369             String JavaDoc token = tukac.nextToken();
370             if ("".equals(token)) {
371                 return false;
372             }
373             if (!Utilities.isJavaIdentifier(token)) {
374                 return false;
375             }
376         }
377         return true;
378     }
379     
380     /**
381      * Returns a string suitable for text areas respresenting content of {@link
382      * CreatedModifiedFiles} <em>paths</em>.
383      *
384      * @param relPaths should be either
385      * {@link CreatedModifiedFiles#getCreatedPaths()} or
386      * {@link CreatedModifiedFiles#getModifiedPaths()}.
387      */

388     public static String JavaDoc generateTextAreaContent(String JavaDoc[] relPaths) {
389         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
390         if (relPaths.length > 0) {
391             for (int i = 0; i < relPaths.length; i++) {
392                 if (i > 0) {
393                     sb.append('\n');
394                 }
395                 sb.append(relPaths[i]);
396             }
397         }
398         return sb.toString();
399     }
400     
401     /**
402      * Calls in turn {@link #createLayerPresenterComboModel(Project, String,
403      * Map)} with {@link Collections#EMPTY_MAP} as a third parameter.
404      */

405     public static ComboBoxModel JavaDoc createLayerPresenterComboModel(
406             final Project project, final String JavaDoc sfsRoot) {
407         return createLayerPresenterComboModel(project, sfsRoot, Collections.<String JavaDoc,Object JavaDoc>emptyMap());
408     }
409     
410     /**
411      * Returns {@link ComboBoxModel} containing {@link #LayerItemPresenter}s
412      * wrapping all folders under the given <code>sfsRoot</code>.
413      *
414      * @param excludeAttrs {@link Map} of pairs String - Object used to filter
415      * out folders which have one or more attribute(key)
416      * with a corresponding value.
417      */

418     public static ComboBoxModel JavaDoc createLayerPresenterComboModel(
419             final Project project, final String JavaDoc sfsRoot, final Map JavaDoc<String JavaDoc,Object JavaDoc> excludeAttrs) {
420         DefaultComboBoxModel JavaDoc model = new DefaultComboBoxModel JavaDoc();
421         try {
422             FileSystem sfs = LayerUtils.getEffectiveSystemFilesystem(project);
423             FileObject root = sfs.getRoot().getFileObject(sfsRoot);
424             if (root != null) {
425                 SortedSet JavaDoc<LayerItemPresenter> presenters = new TreeSet JavaDoc<LayerItemPresenter>();
426                 for (FileObject subFolder : getFolders(root, excludeAttrs)) {
427                     presenters.add(new LayerItemPresenter(subFolder, root));
428                 }
429                 for (LayerItemPresenter presenter : presenters) {
430                     model.addElement(presenter);
431                 }
432             }
433         } catch (IOException JavaDoc exc) {
434             Util.err.notify(exc);
435         }
436         return model;
437     }
438     
439     public static class LayerItemPresenter implements Comparable JavaDoc<LayerItemPresenter> {
440         
441         private String JavaDoc displayName;
442         private final FileObject item;
443         private final FileObject root;
444         private final boolean contentType;
445         
446         public LayerItemPresenter(final FileObject item,
447                 final FileObject root,
448                 final boolean contentType) {
449             this.item = item;
450             this.root = root;
451             this.contentType = contentType;
452         }
453         
454         public LayerItemPresenter(final FileObject item, final FileObject root) {
455             this(item, root, false);
456         }
457         
458         public FileObject getFileObject() {
459             return item;
460         }
461         
462         public String JavaDoc getFullPath() {
463             return item.getPath();
464         }
465         
466         public String JavaDoc getDisplayName() {
467             if (displayName == null) {
468                 displayName = computeDisplayName();
469             }
470             return displayName;
471         }
472         
473         public String JavaDoc toString() {
474             return getDisplayName();
475         }
476         
477         public int compareTo(LayerItemPresenter o) {
478             int res = Collator.getInstance().compare(getDisplayName(), o.getDisplayName());
479             if (res != 0) {
480                 return res;
481             } else {
482                 return getFullPath().compareTo(o.getFullPath());
483             }
484         }
485         
486         private static String JavaDoc getFileObjectName(FileObject fo) {
487             String JavaDoc name = null;
488             try {
489                 name = fo.getFileSystem().getStatus().annotateName(
490                         fo.getNameExt(), Collections.singleton(fo));
491             } catch (FileStateInvalidException ex) {
492                 name = fo.getName();
493             }
494             return name;
495         }
496         
497         private String JavaDoc computeDisplayName() {
498             FileObject displayItem = contentType ? item.getParent() : item;
499             String JavaDoc displaySeparator = contentType ? "/" : " | "; // NOI18N
500
Stack JavaDoc<String JavaDoc> s = new Stack JavaDoc<String JavaDoc>();
501             s.push(getFileObjectName(displayItem));
502             FileObject parent = displayItem.getParent();
503             while (!root.getPath().equals(parent.getPath())) {
504                 s.push(getFileObjectName(parent));
505                 parent = parent.getParent();
506             }
507             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
508             sb.append(s.pop());
509             while (!s.empty()) {
510                 sb.append(displaySeparator).append(s.pop());
511             }
512             return sb.toString();
513         }
514         
515     }
516     
517     /**
518      * Returns path relative to the root of the SFS. May return
519      * <code>null</code> for empty String or user's custom non-string items.
520      * Also see {@link Util#isValidSFSPath(String)}.
521      */

522     public static String JavaDoc getSFSPath(final JComboBox JavaDoc lpCombo, final String JavaDoc supposedRoot) {
523         Object JavaDoc editorItem = lpCombo.getEditor().getItem();
524         String JavaDoc path = null;
525         if (editorItem instanceof LayerItemPresenter) {
526             path = ((LayerItemPresenter) editorItem).getFullPath();
527         } else if (editorItem instanceof String JavaDoc) {
528             String JavaDoc editorItemS = ((String JavaDoc) editorItem).trim();
529             if (editorItemS.length() > 0) {
530                 path = searchLIPCategoryCombo(lpCombo, editorItemS);
531                 if (path == null) {
532                     // entered by user - absolute and relative are supported...
533
path = editorItemS.startsWith(supposedRoot) ? editorItemS :
534                         supposedRoot + '/' + editorItemS;
535                 }
536             }
537         }
538         return path;
539     }
540     
541     public static NbModuleProject chooseSuiteComponent(Component JavaDoc parent, SuiteProject suite) {
542         NbModuleProject suiteComponent = null;
543         Project project = chooseProject(parent);
544         if (project != null) {
545             if (SuiteUtils.getSubProjects(suite).contains(project)) {
546                 DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
547                         NbBundle.getMessage(UIUtil.class, "MSG_SuiteAlreadyContainsProject",
548                         ProjectUtils.getInformation(suite).getDisplayName(),
549                         ProjectUtils.getInformation(project).getDisplayName())));
550                 return null;
551             }
552             NbModuleProvider nmtp = project.getLookup().lookup(NbModuleProvider.class);
553             if (nmtp == null) { // not netbeans module
554
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
555                         NbBundle.getMessage(UIUtil.class, "MSG_TryingToAddNonNBModule",
556                         ProjectUtils.getInformation(project).getDisplayName())));
557             } else if (nmtp.getModuleType() == NbModuleProvider.SUITE_COMPONENT) {
558                 Object JavaDoc[] params = new Object JavaDoc[] {
559                     ProjectUtils.getInformation(project).getDisplayName(),
560                     getSuiteProjectName(project),
561                     getSuiteProjectDirectory(project),
562                     ProjectUtils.getInformation(suite).getDisplayName(),
563                 };
564                 NotifyDescriptor.Confirmation confirmation = new NotifyDescriptor.Confirmation(
565                         NbBundle.getMessage(UIUtil.class, "MSG_MoveFromSuiteToSuite", params),
566                         NotifyDescriptor.OK_CANCEL_OPTION);
567                 DialogDisplayer.getDefault().notify(confirmation);
568                 if (confirmation.getValue() == NotifyDescriptor.OK_OPTION) {
569                     suiteComponent = (NbModuleProject) project;
570                 }
571             } else if (nmtp.getModuleType() == NbModuleProvider.STANDALONE) {
572                 suiteComponent = (NbModuleProject) project;
573             } else if (nmtp.getModuleType() == NbModuleProvider.NETBEANS_ORG) {
574                 DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
575                         NbBundle.getMessage(UIUtil.class, "MSG_TryingToAddNBORGModule",
576                         ProjectUtils.getInformation(project).getDisplayName())));
577             }
578         }
579         return suiteComponent;
580     }
581     
582     /**
583      * Appropriately renders {@link Project}s. For others instances delegates
584      * to {@link DefaultListCellRenderer}.
585      */

586     public static ListCellRenderer JavaDoc createProjectRenderer() {
587         return new ProjectRenderer();
588     }
589     
590     private static class ProjectRenderer extends JLabel JavaDoc implements ListCellRenderer JavaDoc, UIResource JavaDoc {
591         
592         public ProjectRenderer () {
593             setOpaque(true);
594         }
595         
596         public Component JavaDoc getListCellRendererComponent(
597                 JList JavaDoc list, Object JavaDoc value, int index, boolean isSelected, boolean cellHasFocus) {
598             // #93658: GTK needs name to render cell renderer "natively"
599
setName("ComboBox.listRenderer"); // NOI18N
600

601             String JavaDoc text = null;
602             if (!(value instanceof Project)) {
603                 text = value.toString();
604             } else {
605                 ProjectInformation pi = ProjectUtils.getInformation((Project) value);
606                 text = pi.getDisplayName();
607                 setIcon(pi.getIcon());
608             }
609             setText(text);
610             
611             if ( isSelected ) {
612                 setBackground(list.getSelectionBackground());
613                 setForeground(list.getSelectionForeground());
614             }
615             else {
616                 setBackground(list.getBackground());
617                 setForeground(list.getForeground());
618             }
619             
620             return this;
621         }
622         
623         // #93658: GTK needs name to render cell renderer "natively"
624
public String JavaDoc getName() {
625             String JavaDoc name = super.getName();
626             return name == null ? "ComboBox.renderer" : name; // NOI18N
627
}
628         
629     }
630     
631     /**
632      * Returns default folder icon as {@link java.awt.Image}. Never returns
633      * <code>null</code>.
634      *
635      * @param opened wheter closed or opened icon should be returned.
636      */

637     public static Image JavaDoc getTreeFolderIcon(boolean opened) {
638         Image JavaDoc base = null;
639         Icon JavaDoc baseIcon = UIManager.getIcon(opened ? OPENED_ICON_KEY_UIMANAGER : ICON_KEY_UIMANAGER); // #70263
640
if (baseIcon != null) {
641             base = Utilities.icon2Image(baseIcon);
642         } else {
643             base = (Image JavaDoc) UIManager.get(opened ? OPENED_ICON_KEY_UIMANAGER_NB : ICON_KEY_UIMANAGER_NB); // #70263
644
if (base == null) { // fallback to our owns
645
base = Utilities.loadImage(opened ? OPENED_ICON_PATH : ICON_PATH, true);
646             }
647         }
648         assert base != null;
649         return base;
650     }
651     
652     public static NbModuleProject runLibraryWrapperWizard(final Project suiteProvider) {
653         NewNbModuleWizardIterator iterator = NewNbModuleWizardIterator.createLibraryModuleIterator(suiteProvider);
654         return UIUtil.runProjectWizard(iterator, "CTL_NewLibraryWrapperProject"); // NOI18N
655
}
656     
657     public static NbModuleProject runProjectWizard(
658             final NewNbModuleWizardIterator iterator, final String JavaDoc titleBundleKey) {
659         WizardDescriptor wd = new WizardDescriptor(iterator);
660         wd.setTitleFormat(new MessageFormat JavaDoc("{0}")); // NOI18N
661
wd.setTitle(NbBundle.getMessage(UIUtil.class, titleBundleKey));
662         Dialog JavaDoc dialog = DialogDisplayer.getDefault().createDialog(wd);
663         dialog.setVisible(true);
664         dialog.toFront();
665         NbModuleProject project = null;
666         boolean cancelled = wd.getValue() != WizardDescriptor.FINISH_OPTION;
667         if (!cancelled) {
668             FileObject folder = iterator.getCreateProjectFolder();
669             try {
670                 project = (NbModuleProject) ProjectManager.getDefault().findProject(folder);
671                 OpenProjects.getDefault().open(new Project[] { project }, false);
672                 if (wd.getProperty("setAsMain") == Boolean.TRUE) { // NOI18N
673
OpenProjects.getDefault().setMainProject(project);
674                 }
675             } catch (IOException JavaDoc e) {
676                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
677             }
678         }
679         return project;
680     }
681     
682     /**
683      * Searches LayerItemPresenter combobox by the item's display name.
684      */

685     private static String JavaDoc searchLIPCategoryCombo(final JComboBox JavaDoc lpCombo, final String JavaDoc displayName) {
686         String JavaDoc path = null;
687         for (int i = 0; i < lpCombo.getItemCount(); i++) {
688             Object JavaDoc item = lpCombo.getItemAt(i);
689             if (!(item instanceof LayerItemPresenter)) {
690                 continue;
691             }
692             LayerItemPresenter presenter = (LayerItemPresenter) lpCombo.getItemAt(i);
693             if (displayName.equals(presenter.getDisplayName())) {
694                 path = presenter.getFullPath();
695                 break;
696             }
697         }
698         return path;
699     }
700     
701     private static Project chooseProject(Component JavaDoc parent) {
702         JFileChooser JavaDoc chooser = ProjectChooser.projectChooser();
703         int option = chooser.showOpenDialog(parent);
704         Project project = null;
705         if (option == JFileChooser.APPROVE_OPTION) {
706             File JavaDoc projectDir = chooser.getSelectedFile();
707             UIUtil.setProjectChooserDirParent(projectDir);
708             try {
709                 project = ProjectManager.getDefault().findProject(
710                         FileUtil.toFileObject(projectDir));
711             } catch (IOException JavaDoc e) {
712                 ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
713             }
714         }
715         return project;
716     }
717     
718     private static File JavaDoc getSuiteDirectory(Project suiteComp) {
719         File JavaDoc suiteDir = SuiteUtils.getSuiteDirectory(suiteComp);
720         assert suiteDir != null : "Invalid suite provider for: "
721                 + suiteComp.getProjectDirectory();
722         return suiteDir;
723     }
724     
725     private static String JavaDoc getSuiteProjectDirectory(Project suiteComp) {
726         return getSuiteDirectory(suiteComp).getAbsolutePath();
727     }
728     
729     private static String JavaDoc getSuiteProjectName(Project suiteComp) {
730         FileObject suiteDir = FileUtil.toFileObject(getSuiteDirectory(suiteComp));
731         if (suiteDir == null) {
732             // #94915
733
return "???"; // NOI18N
734
}
735         return Util.getDisplayName(suiteDir);
736     }
737     
738     private static Collection JavaDoc<FileObject> getFolders(final FileObject root, final Map JavaDoc<String JavaDoc,Object JavaDoc> excludeAttrs) {
739         Collection JavaDoc<FileObject> folders = new HashSet JavaDoc<FileObject>();
740         SUBFOLDERS: for (FileObject subFolder : NbCollections.iterable(root.getFolders(false))) {
741             for (Map.Entry JavaDoc<String JavaDoc,Object JavaDoc> entry : excludeAttrs.entrySet()) {
742                 if (entry.getValue().equals(subFolder.getAttribute(entry.getKey()))) {
743                     continue SUBFOLDERS;
744                 }
745             }
746             folders.add(subFolder);
747             folders.addAll(getFolders(subFolder, excludeAttrs));
748         }
749         return folders;
750     }
751     
752     private static final class IconFilter extends FileFilter JavaDoc {
753         public boolean accept(File JavaDoc pathname) {
754             return pathname.isDirectory() ||
755                     pathname.getName().toLowerCase(Locale.ENGLISH).endsWith("gif") || // NOI18N
756
pathname.getName().toLowerCase(Locale.ENGLISH).endsWith("png"); // NOI18N
757
}
758         public String JavaDoc getDescription() {
759             return "*.gif, *.png"; // NOI18N
760
}
761     }
762     
763     /**
764      * Show an OK/cancel-type dialog with customized button texts.
765      * Only a separate method because it is otherwise cumbersome to replace
766      * the OK button with a button that is set as the default.
767      * @param title the dialog title
768      * @param message the body of the message (usually HTML text)
769      * @param acceptButton a label for the default accept button; should not use mnemonics
770      * @param cancelButton a label for the cancel button (or null for default); should not use mnemonics
771      * @param messageType {@link NotifyDescriptor#WARNING_MESSAGE} or similar
772      * @return true if user accepted the dialog
773      */

774     public static boolean showAcceptCancelDialog(String JavaDoc title, String JavaDoc message, String JavaDoc acceptButton, String JavaDoc cancelButton, int messageType) {
775         DialogDescriptor d = new DialogDescriptor(message, title);
776         d.setModal(true);
777         JButton JavaDoc accept = new JButton JavaDoc(acceptButton);
778         accept.setDefaultCapable(true);
779         d.setOptions(new Object JavaDoc[] {
780             accept,
781             cancelButton != null ? new JButton JavaDoc(cancelButton) : NotifyDescriptor.CANCEL_OPTION,
782         });
783         d.setMessageType(messageType);
784         return DialogDisplayer.getDefault().notify(d).equals(accept);
785     }
786     
787     private static class IconFileChooser extends JFileChooser JavaDoc {
788         private final JTextField JavaDoc iconInfo = new JTextField JavaDoc();
789         private IconFileChooser() {
790             JPanel JavaDoc accessoryPanel = getAccesoryPanel(iconInfo);
791             setDialogTitle(NbBundle.getMessage(UIUtil.class, "TITLE_IconDialog"));//NOI18N
792
setAccessory(accessoryPanel);
793             setAcceptAllFileFilterUsed(false);
794             setFileSelectionMode(JFileChooser.FILES_ONLY);
795             setMultiSelectionEnabled(false);
796             addChoosableFileFilter(new IconFilter());
797             setFileView(new FileView JavaDoc() {
798                 public Icon JavaDoc getIcon(File JavaDoc f) {
799                     // Show icons right in the chooser, to make it easier to find
800
// the right one.
801
if (f.getName().endsWith(".gif") || f.getName().endsWith(".png")) { // NOI18N
802
Icon JavaDoc icon = new ImageIcon JavaDoc(f.getAbsolutePath());
803                         if (icon.getIconWidth() == 16 && icon.getIconHeight() == 16) {
804                             return icon;
805                         }
806                     }
807                     return null;
808                 }
809                 public String JavaDoc getName(File JavaDoc f) {
810                     File JavaDoc f2 = getSelectedFile();
811                     if (f2 != null && (f2.getName().endsWith(".gif") || f2.getName().endsWith(".png"))) { // NOI18N
812
Icon JavaDoc icon = new ImageIcon JavaDoc(f2.getAbsolutePath());
813                         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
814                         sb.append(f2.getName()).append(" [");//NOI18N
815
sb.append(icon.getIconWidth()).append('x').append(icon.getIconHeight());
816                         sb.append(']');
817                         setApproveButtonToolTipText(sb.toString());
818                         iconInfo.setText(sb.toString());
819                     } else {
820                         iconInfo.setText("");
821                     }
822                     return super.getName(f);
823                 }
824                 
825             });
826         }
827         
828         private static JPanel JavaDoc getAccesoryPanel(final JTextField JavaDoc iconInfo) {
829             iconInfo.setColumns(15);
830             iconInfo.setEditable(false);
831             
832             JPanel JavaDoc accessoryPanel = new JPanel JavaDoc();
833             JPanel JavaDoc inner = new JPanel JavaDoc();
834             JLabel JavaDoc iconInfoLabel = new JLabel JavaDoc();
835             accessoryPanel.setLayout(new FlowLayout JavaDoc(FlowLayout.LEFT, 6, 0));
836             
837             inner.setLayout(new GridLayout JavaDoc(2, 1, 0, 6));
838             
839             iconInfoLabel.setLabelFor(iconInfo);
840             Mnemonics.setLocalizedText(iconInfoLabel, NbBundle.getMessage(UIUtil.class, "LBL_IconInfo"));
841             inner.add(iconInfoLabel);
842             
843             inner.add(iconInfo);
844             
845             accessoryPanel.add(inner);
846             return accessoryPanel;
847         }
848     }
849 }
850
Popular Tags