KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > apisupport > project > ui > wizard > BasicWizardIterator


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.wizard;
21
22 import java.awt.Component JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.HashSet JavaDoc;
27 import java.util.NoSuchElementException JavaDoc;
28 import java.util.Set JavaDoc;
29 import javax.swing.event.ChangeListener JavaDoc;
30 import javax.swing.text.Position JavaDoc;
31 import org.netbeans.api.java.project.JavaProjectConstants;
32 import org.netbeans.api.project.Project;
33 import org.netbeans.api.project.ProjectUtils;
34 import org.netbeans.api.project.SourceGroup;
35 import org.netbeans.api.project.Sources;
36 import org.netbeans.editor.BaseDocument;
37 import org.netbeans.editor.GuardedDocument;
38 import org.netbeans.modules.apisupport.project.CreatedModifiedFiles;
39 import org.netbeans.modules.apisupport.project.NbModuleProject;
40 import org.netbeans.modules.apisupport.project.Util;
41 import org.netbeans.modules.apisupport.project.spi.NbModuleProvider;
42 import org.netbeans.spi.project.ui.templates.support.Templates;
43 import org.openide.ErrorManager;
44 import org.openide.WizardDescriptor;
45 import org.openide.cookies.EditorCookie;
46 import org.openide.filesystems.FileObject;
47 import org.openide.filesystems.FileStateInvalidException;
48 import org.openide.filesystems.FileUtil;
49 import org.openide.loaders.DataObject;
50 import org.openide.loaders.DataObjectNotFoundException;
51 import org.openide.util.HelpCtx;
52 import org.openide.util.NbBundle;
53
54 /**
55  * Convenient class for implementing {@link org.openide.WizardDescriptor.InstantiatingIterator}.
56  *
57  * @author Radek Matous
58  */

59 public abstract class BasicWizardIterator implements WizardDescriptor.AsynchronousInstantiatingIterator {
60     
61     private int position = 0;
62     private BasicWizardIterator.PrivateWizardPanel[] wizardPanels;
63     
64     /** Create a new wizard iterator. */
65     protected BasicWizardIterator() {}
66     
67     /** @return all panels provided by this {@link org.openide.WizardDescriptor.InstantiatingIterator} */
68     protected abstract BasicWizardIterator.Panel[] createPanels(WizardDescriptor wiz);
69     
70     /** Basic visual panel.*/
71     public abstract static class Panel extends BasicVisualPanel {
72         
73         protected Panel(WizardDescriptor wiz) {
74             super(wiz);
75         }
76         
77         /**
78          * Returned name is used by a wizard. e.g. on its left side in the
79          * <em>step list</em>.
80          * @return name of panel
81          */

82         protected abstract String JavaDoc getPanelName();
83         
84         /**
85          * Gives a chance to store an instance of {@link
86          * BasicWizardIterator.BasicDataModel}. It is called when a panel is
87          * going to be <em>hidden</em> (e.g. when switching to next/previous
88          * panel).
89          */

90         protected abstract void storeToDataModel();
91         
92         /**
93          * Gives a chance to refresh a panel (usually by reading a state of an
94          * instance of {@link BasicWizardIterator.BasicDataModel}. It is called
95          * when a panel is going to be <em>displayed</em> (e.g. when switching
96          * from next/previous panel).
97          */

98         protected abstract void readFromDataModel();
99         
100         protected abstract HelpCtx getHelp();
101         
102     }
103     
104     /** DataModel that is passed through individual panels.*/
105     public static class BasicDataModel {
106         
107         private Project project;
108         private NbModuleProvider module;
109         private SourceGroup sourceRootGroup;
110         private String JavaDoc packageName;
111         
112         /** Creates a new instance of NewFileDescriptorData */
113         public BasicDataModel(WizardDescriptor wiz) {
114             Project tmpProject = Templates.getProject(wiz);
115             
116             if (tmpProject == null) {
117                 throw new IllegalArgumentException JavaDoc();
118             }
119             module = tmpProject.getLookup().lookup(NbModuleProvider.class);
120             if (module == null) {
121                 throw new IllegalArgumentException JavaDoc(tmpProject.getClass().toString());
122             }
123             
124             project = tmpProject;
125             // #66339 need to prefetch the packagename and populate data with it..
126
FileObject fo = Templates.getTargetFolder(wiz);
127             if (fo != null) {
128                 Sources srcs = ProjectUtils.getSources(project); // #63247: don't use lookup directly
129
SourceGroup[] grps = srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
130                 for (int i = 0; i < grps.length; i++) {
131                     if (FileUtil.isParentOf(grps[i].getRootFolder(), fo)) {
132                         String JavaDoc relPath = FileUtil.getRelativePath(grps[i].getRootFolder(), fo);
133                         relPath = relPath.replace('/', '.');
134                         setPackageName(relPath);
135                         break;
136                     }
137                 }
138             }
139         }
140         
141         public Project getProject() {
142             return project;
143         }
144         
145         public NbModuleProvider getModuleInfo() {
146             return module;
147         }
148         
149         public String JavaDoc getPackageName() {
150             return packageName;
151         }
152         
153         public void setPackageName(String JavaDoc packageName) {
154             this.packageName = packageName;
155         }
156         
157         public SourceGroup getSourceRootGroup() {
158             if (sourceRootGroup == null) {
159                 FileObject tempSrcRoot = getModuleInfo().getSourceDirectory();
160                 assert tempSrcRoot != null;
161                 
162                 Sources sources = ProjectUtils.getSources(project);
163                 SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
164                 for (int i = 0; sourceRootGroup == null && i < groups.length; i++) {
165                     if (groups[i].getRootFolder().equals(tempSrcRoot)) {
166                         sourceRootGroup = groups[i];
167                     }
168                 }
169             }
170             return sourceRootGroup;
171         }
172         
173         public String JavaDoc getDefaultPackagePath(String JavaDoc fileName, boolean resource) {
174             return (resource ? getModuleInfo().getResourceDirectoryPath(false) : getModuleInfo().getSourceDirectoryPath()) + '/' +
175                     getPackageName().replace('.','/') + '/' + fileName;
176         }
177         
178         /**
179          * Conditionally adds an operation to the given {@link
180          * CreatedModifiedFiles}. Result of the operation, after given
181          * CreatedModifiedFiles are run, is copied (into the package) icon
182          * representing given <code>origIconPath</code>. If the origIconPath is
183          * already inside the project's source directory nothing happens.
184          *
185          * @return path of the icon relative to the project's source directory
186          */

187         public String JavaDoc addCreateIconOperation(CreatedModifiedFiles cmf, String JavaDoc origIconPath) {
188             FileObject origIconFO = FileUtil.toFileObject(new File JavaDoc(origIconPath));
189             String JavaDoc relativeIconPath = null;
190             if (!FileUtil.isParentOf(Util.getResourceDirectory(getProject()), origIconFO)) {
191                 String JavaDoc iconPath = getDefaultPackagePath(origIconFO.getNameExt(), true);
192                 try {
193                     cmf.add(cmf.createFile(iconPath, origIconFO.getURL()));
194                     relativeIconPath = getPackageName().replace('.', '/') + '/' + origIconFO.getNameExt();
195                 } catch (FileStateInvalidException exc) {
196                     Util.err.notify(exc);
197                 }
198             } else {
199                 relativeIconPath = FileUtil.getRelativePath(Util.getResourceDirectory(getProject()), origIconFO);
200             }
201             return relativeIconPath;
202         }
203         
204     }
205     
206     public void initialize(WizardDescriptor wiz) {
207         // mkleint: copied from the NewJavaFileWizardIterator.. there must be something painfully wrong..
208
String JavaDoc[] beforeSteps = null;
209         Object JavaDoc prop = wiz.getProperty("WizardPanel_contentData"); // NOI18N
210
if (prop != null && prop instanceof String JavaDoc[]) {
211             beforeSteps = (String JavaDoc[])prop;
212         }
213         position = 0;
214         BasicWizardIterator.Panel[] panels = createPanels(wiz);
215         String JavaDoc[] steps = BasicWizardIterator.createSteps(beforeSteps, panels);
216         wizardPanels = new BasicWizardIterator.PrivateWizardPanel[panels.length];
217         
218         for (int i = 0; i < panels.length; i++) {
219             wizardPanels[i] = new BasicWizardIterator.PrivateWizardPanel(panels[i], steps, i);
220         }
221     }
222     
223     // mkleint: copied from the NewJavaFileWizardIterator.. there must be something painfully wrong..
224
private static String JavaDoc[] createSteps(String JavaDoc[] before, BasicWizardIterator.Panel[] panels) {
225         assert panels != null;
226         // hack to use the steps set before this panel processed
227
int diff = 0;
228         if (before == null) {
229             before = new String JavaDoc[0];
230         } else if (before.length > 0) {
231             diff = ("...".equals(before[before.length - 1])) ? 1 : 0; // NOI18N
232
}
233         String JavaDoc[] res = new String JavaDoc[ (before.length - diff) + panels.length];
234         for (int i = 0; i < res.length; i++) {
235             if (i < (before.length - diff)) {
236                 res[i] = before[i];
237             } else {
238                 res[i] = panels[i - before.length + diff].getPanelName();
239             }
240         }
241         return res;
242     }
243     
244     public void uninitialize(WizardDescriptor wiz) {
245         wizardPanels = null;
246     }
247     
248     public String JavaDoc name() {
249         return ((BasicWizardIterator.PrivateWizardPanel)
250         current()).getPanel().getPanelName();
251     }
252     
253     public boolean hasNext() {
254         return position < (wizardPanels.length - 1);
255     }
256     
257     public boolean hasPrevious() {
258         return position > 0;
259     }
260     
261     public void nextPanel() {
262         if (!hasNext()) {
263             throw new NoSuchElementException JavaDoc();
264         }
265         position++;
266     }
267     
268     public void previousPanel() {
269         if (!hasPrevious()) {
270             throw new NoSuchElementException JavaDoc();
271         }
272         position--;
273     }
274     
275     public WizardDescriptor.Panel current() {
276         return wizardPanels[position];
277     }
278     
279     /**
280      * Convenience method for accessing Bundle resources from this package.
281      */

282     protected final String JavaDoc getMessage(String JavaDoc key) {
283         return NbBundle.getMessage(getClass(), key);
284     }
285     
286     public final void addChangeListener(ChangeListener JavaDoc l) {}
287     public final void removeChangeListener(ChangeListener JavaDoc l) {}
288     
289     protected Set JavaDoc getCreatedFiles(final CreatedModifiedFiles cmf, final Project project) throws IOException JavaDoc {
290         Collection JavaDoc toBeShown = new HashSet JavaDoc();
291         String JavaDoc[] paths = cmf.getCreatedPaths();
292         Set JavaDoc set = new HashSet JavaDoc();
293         for (int i = 0; i < paths.length; i++) {
294             FileObject fo = project.getProjectDirectory().getFileObject(paths[i]);
295             formatFile(fo);
296             DataObject dObj = DataObject.find(fo);
297             if (dObj != null && toBeShown.size() < 10 && toBeShown.add(dObj)) {
298                 set.add(fo);
299             }
300         }
301         return set;
302     }
303     
304     private static BaseDocument getDocument(final FileObject fo) throws DataObjectNotFoundException, IOException JavaDoc {
305         BaseDocument doc = null;
306         DataObject dObj = DataObject.find(fo);
307         if (dObj != null) {
308             EditorCookie editor = (EditorCookie) dObj.getCookie(EditorCookie.class);
309             if (editor != null) {
310                 doc = (BaseDocument) editor.openDocument();
311             }
312         }
313         return doc;
314     }
315     
316     // copy-pasted-adjusted from org.netbeans.editor.ActionFactory.FormatAction
317
private static void formatFile(final FileObject fo) {
318         assert fo != null;
319         BaseDocument doc = null;
320         boolean saved = false;
321         try {
322             doc = BasicWizardIterator.getDocument(fo);
323             if (doc == null) {
324                 return;
325             }
326             GuardedDocument gdoc = (doc instanceof GuardedDocument) ? (GuardedDocument) doc : null;
327             doc.atomicLock();
328             int startPos = 0;
329             Position JavaDoc endPosition = doc.createPosition(doc.getLength());
330             int pos = startPos;
331             if (gdoc != null) {
332                 pos = gdoc.getGuardedBlockChain().adjustToBlockEnd(pos);
333             }
334             
335             while (pos < endPosition.getOffset()) {
336                 int stopPos = endPosition.getOffset();
337                 if (gdoc != null) { // adjust to start of the next guarded block
338
stopPos = gdoc.getGuardedBlockChain().adjustToNextBlockStart(pos);
339                     if (stopPos == -1) {
340                         stopPos = endPosition.getOffset();
341                     }
342                 }
343                 int reformattedLen = doc.getFormatter().reformat(doc, pos, stopPos);
344                 pos = pos + reformattedLen;
345                 if (gdoc != null) { // adjust to end of current block
346
pos = gdoc.getGuardedBlockChain().adjustToBlockEnd(pos);
347                 }
348             }
349             saved = true;
350         } catch (Exception JavaDoc ex) {
351             // no disaster
352
ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot reformat the file: " + fo.getPath()); // NOI18N
353
} finally {
354             if (doc != null) {
355                 doc.atomicUnlock();
356                 if (saved) {
357                     try {
358                         ((EditorCookie) DataObject.find(fo).getCookie(EditorCookie.class)).saveDocument();
359                     } catch (IOException JavaDoc e) {
360                         Util.err.notify(ErrorManager.INFORMATIONAL, e);
361                     }
362                 }
363             }
364         }
365     }
366     
367     private static final class PrivateWizardPanel extends BasicWizardPanel {
368         
369         private BasicWizardIterator.Panel panel;
370         
371         PrivateWizardPanel(BasicWizardIterator.Panel panel, String JavaDoc[] allSteps, int stepIndex) {
372             super(panel.getSettings());
373             panel.addPropertyChangeListener(this);
374             panel.setName(panel.getPanelName()); // NOI18N
375
this.panel = panel;
376             panel.putClientProperty("WizardPanel_contentSelectedIndex", new Integer JavaDoc(stepIndex)); // NOI18N
377
// names of currently used steps
378
panel.putClientProperty("WizardPanel_contentData", allSteps); // NOI18N
379
}
380         
381         private BasicWizardIterator.Panel getPanel() {
382             return panel;
383         }
384         
385         public Component JavaDoc getComponent() {
386             return getPanel();
387         }
388         
389         public void storeSettings(Object JavaDoc settings) {
390             WizardDescriptor wiz = (WizardDescriptor) settings;
391             if (WizardDescriptor.NEXT_OPTION.equals(wiz.getValue()) ||
392                     WizardDescriptor.FINISH_OPTION.equals(wiz.getValue())) {
393                 panel.storeToDataModel();
394             }
395             //XXX hack
396
((WizardDescriptor) settings).putProperty("NewFileWizard_Title", null); // NOI18N
397
}
398         
399         public void readSettings(Object JavaDoc settings) {
400             WizardDescriptor wiz = (WizardDescriptor) settings;
401             // mkleint - copied from someplace.. is definitely weird..
402
// XXX hack, TemplateWizard in final setTemplateImpl() forces new wizard's title
403
// this name is used in NewProjectWizard to modify the title
404
Object JavaDoc substitute = getPanel().getClientProperty("NewFileWizard_Title"); // NOI18N
405
if (substitute != null) {
406                 wiz.putProperty("NewFileWizard_Title", substitute); // NOI18N
407
}
408             
409             if (WizardDescriptor.NEXT_OPTION.equals(wiz.getValue()) || wiz.getValue() == null) {
410                 panel.readFromDataModel();
411             }
412         }
413         
414         public HelpCtx getHelp() {
415             return getPanel().getHelp();
416         }
417         
418     }
419     
420 }
421
422
Popular Tags