KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > FormEditor


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.form;
21
22 import java.awt.Cursor JavaDoc;
23 import java.beans.*;
24 import java.io.IOException JavaDoc;
25 import java.util.*;
26 import java.util.prefs.PreferenceChangeEvent JavaDoc;
27 import java.util.prefs.PreferenceChangeListener JavaDoc;
28 import javax.swing.*;
29 import javax.swing.text.Document JavaDoc;
30 import org.netbeans.modules.form.assistant.AssistantModel;
31 import org.netbeans.modules.form.palette.PaletteUtils;
32 import org.netbeans.spi.palette.PaletteController;
33
34 import org.openide.*;
35 import org.openide.awt.UndoRedo;
36 import org.openide.awt.StatusDisplayer;
37 import org.openide.loaders.DataObject;
38 import org.openide.nodes.Node;
39 import org.openide.util.Mutex;
40 import org.openide.windows.*;
41
42 import org.netbeans.modules.form.project.ClassSource;
43 import org.netbeans.modules.form.project.ClassPathUtils;
44
45 /**
46  * Form editor.
47  *
48  * @author Jan Stola
49  */

50 public class FormEditor {
51     static final int LOADING = 1;
52     static final int SAVING = 2;
53
54     /** The FormModel instance holding the form itself */
55     private FormModel formModel;
56
57     /** The root node of form hierarchy presented in Component Inspector */
58     private FormRootNode formRootNode;
59
60     /** The designer component - the last active designer of the form
61      * (there can be more clones). May happen to be null if the active designer
62      * was closed and no other designer of given form was activated since then. */

63     private FormDesigner formDesigner;
64
65     /** The code generator for the form */
66     private CodeGenerator codeGenerator;
67
68     /** The FormJavaSource for the form */
69     private FormJavaSource formJavaSource;
70     
71     /** I18nSupport instance for the form */
72     private I18nSupport i18nSupport;
73
74     /** List of exceptions occurred during the last persistence operation */
75     private List persistenceErrors;
76     
77     /** Persistence manager responsible for saving the form */
78     private PersistenceManager persistenceManager;
79     
80     /** An indicator whether the form has been loaded (from the .form file) */
81     private boolean formLoaded = false;
82     
83     /** Table of opened FormModel instances (FormModel to FormEditor map) */
84     private static Map openForms = new Hashtable();
85
86     /* Maps form model to assistant model. */
87     private static Map formModelToAssistant = new WeakHashMap();
88     
89     /** List of floating windows - must be closed when the form is closed. */
90     private List floatingWindows;
91     
92     /** The DataObject of the form */
93     private FormDataObject formDataObject;
94     private PropertyChangeListener dataObjectListener;
95     private static PreferenceChangeListener JavaDoc settingsListener;
96     private PropertyChangeListener paletteListener;
97     
98     // listeners
99
private FormModelListener formListener;
100     
101     FormEditor(FormDataObject formDataObject) {
102         this.formDataObject = formDataObject;
103     }
104
105     /** @return root node representing the form (in pair with the class node) */
106     public final FormNode getFormRootNode() {
107         return formRootNode;
108     }
109
110     /** @return the FormModel of this form, null if the form is not loaded */
111     public final FormModel getFormModel() {
112         return formModel;
113     }
114     
115     public final FormDataObject getFormDataObject() {
116         return formDataObject;
117     }
118
119     private final FormJavaSource getFormJavaSource() {
120         return formJavaSource;
121     }
122     
123     CodeGenerator getCodeGenerator() {
124         if (!formLoaded)
125             return null;
126         if (codeGenerator == null)
127             codeGenerator = new JavaCodeGenerator();
128         return codeGenerator;
129     }
130
131     I18nSupport getI18nSupport() {
132         if (i18nSupport == null && formModel != null) {
133             i18nSupport = new I18nSupport(formModel);
134         }
135         return i18nSupport;
136     }
137
138     boolean isFormLoaded() {
139         return formLoaded;
140     }
141     
142     /** This methods loads the form, reports errors, creates the FormDesigner */
143     void loadFormDesigner() {
144         JFrame mainWin = (JFrame) WindowManager.getDefault().getMainWindow();
145
146         // set status text "Opening Form: ..."
147
StatusDisplayer.getDefault().setStatusText(
148             FormUtils.getFormattedBundleString(
149                 "FMT_OpeningForm", // NOI18N
150
new Object JavaDoc[] { formDataObject.getFormFile().getName() }));
151         javax.swing.RepaintManager.currentManager(mainWin).paintDirtyRegions();
152
153         // set wait cursor [is not very reliable, but...]
154
mainWin.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
155         mainWin.getGlassPane().setVisible(true);
156
157         // load form data and report errors
158
try {
159             loadFormData();
160         }
161         catch (PersistenceException ex) {
162             logPersistenceError(ex, 0);
163         }
164
165         // clear status text
166
StatusDisplayer.getDefault().setStatusText(""); // NOI18N
167

168         // clear wait cursor
169
mainWin.getGlassPane().setVisible(false);
170         mainWin.getGlassPane().setCursor(null);
171
172         // report errors during loading
173
reportErrors(LOADING);
174
175         // may do additional setup for just created form
176
postCreationUpdate();
177     }
178
179     boolean loadForm() {
180         if (formLoaded)
181             return true;
182
183         if (java.awt.EventQueue.isDispatchThread()) {
184             try {
185                 loadFormData();
186             }
187             catch (PersistenceException ex) {
188                 logPersistenceError(ex, 0);
189             }
190         }
191         else { // loading must be done in AWT event dispatch thread
192
try {
193                 java.awt.EventQueue.invokeAndWait(new Runnable JavaDoc() {
194                     public void run() {
195                         try {
196                             loadFormData();
197                         }
198                         catch (PersistenceException ex) {
199                             logPersistenceError(ex, 0);
200                         }
201                     }
202                 });
203             }
204             catch (Exception JavaDoc ex) {
205                 ex.printStackTrace();
206             }
207         }
208
209         return formLoaded;
210     }
211     
212     /** This method performs the form data loading. All open/load methods go
213      * through this one.
214      */

215     private void loadFormData() throws PersistenceException {
216         if (formLoaded)
217             return; // form already loaded
218

219         resetPersistenceErrorLog(); // clear log of errors
220

221         // first find PersistenceManager for loading the form
222
persistenceManager = recognizeForm(formDataObject);
223
224         // create and register new FormModel instance
225
formModel = new FormModel();
226         formModel.setName(formDataObject.getName());
227         formModel.setReadOnly(formDataObject.isReadOnly());
228         formJavaSource = new FormJavaSource(formDataObject);
229     formModel.getCodeStructure().setFormJavaSource(formJavaSource);
230     
231         openForms.put(formModel, this);
232
233         // load the form data (FormModel) and report errors
234
synchronized(persistenceManager) {
235             try {
236                 FormLAF.executeWithLookAndFeel(new Mutex.ExceptionAction() {
237                     public Object JavaDoc run() throws Exception JavaDoc {
238                         persistenceManager.loadForm(formDataObject,
239                                                     formModel,
240                                                     persistenceErrors);
241                         return null;
242                     }
243                 });
244             }
245             catch (PersistenceException ex) { // some fatal error occurred
246
persistenceManager = null;
247                 openForms.remove(formModel);
248                 formModel = null;
249                 throw ex;
250             }
251             catch (Exception JavaDoc ex) { // should not happen, but for sure...
252
ex.printStackTrace();
253                 persistenceManager = null;
254                 openForms.remove(formModel);
255                 formModel = null;
256                 return;
257             }
258         }
259                                 
260         // form is successfully loaded...
261
formLoaded = true;
262     
263         getCodeGenerator().initialize(formModel);
264         getI18nSupport(); // creates and inits I18nSupport
265

266         formModel.fireFormLoaded();
267         if (formModel.wasCorrected()) // model repaired or upgraded
268
formModel.fireFormChanged(false);
269
270         // create form nodes hierarchy and add it to SourceChildren
271
formRootNode = new FormRootNode(formModel);
272         formRootNode.getChildren().getNodes();
273         formDataObject.getNodeDelegate().getChildren()
274                                           .add(new Node[] { formRootNode });
275         
276         attachFormListener();
277         attachDataObjectListener();
278         attachSettingsListener();
279         attachPaletteListener();
280     }
281     
282     /** Public method for saving form data to file. Does not save the
283      * source code (document), does not report errors and does not throw
284      * any exceptions.
285      * @return whether there was not any fatal error during saving (true means
286      * everything was ok); returns true even if nothing was saved
287      * because form was not loaded or read-only, etc.
288      */

289     public boolean saveForm() {
290         try {
291             saveFormData();
292             return true;
293         }
294         catch (PersistenceException ex) {
295             logPersistenceError(ex, 0);
296             return false;
297         }
298     }
299     
300     void saveFormData() throws PersistenceException {
301         if (formLoaded && !formDataObject.formFileReadOnly() && !formModel.isReadOnly()) {
302             formModel.fireFormToBeSaved();
303
304             resetPersistenceErrorLog();
305
306             synchronized(persistenceManager) {
307                 persistenceManager.saveForm(formDataObject,
308                                             formModel,
309                                             persistenceErrors);
310             }
311         }
312     }
313     
314     private void resetPersistenceErrorLog() {
315         if (persistenceErrors != null)
316             persistenceErrors.clear();
317         else
318             persistenceErrors = new ArrayList();
319     }
320     
321     private void logPersistenceError(Throwable JavaDoc t, int index) {
322         if (persistenceErrors == null)
323             persistenceErrors = new ArrayList();
324
325         if (index < 0)
326             persistenceErrors.add(t);
327         else
328             persistenceErrors.add(index, t);
329     }
330     
331     /** Finds PersistenceManager that can load and save the form.
332      */

333     private PersistenceManager recognizeForm(FormDataObject formDO)
334         throws PersistenceException
335     {
336         Iterator it = PersistenceManager.getManagers();
337         if (!it.hasNext()) { // there's no PersistenceManager available
338
PersistenceException ex = new PersistenceException(
339                                       "No persistence manager registered"); // NOI18N
340
ErrorManager.getDefault().annotate(
341                 ex,
342                 ErrorManager.ERROR,
343                 null,
344                 FormUtils.getBundleString("MSG_ERR_NoPersistenceManager"), // NOI18N
345
null,
346                 null);
347             throw ex;
348         }
349
350         do {
351             PersistenceManager pm = (PersistenceManager)it.next();
352             synchronized(pm) {
353                 try {
354                     if (pm.canLoadForm(formDO)) {
355                         resetPersistenceErrorLog();
356                         return pm;
357                     }
358                 }
359                 catch (PersistenceException ex) {
360                     logPersistenceError(ex);
361                     // [continue on exception?]
362
}
363             }
364         }
365         while (it.hasNext());
366
367         // no PersistenceManager is able to load the form
368
PersistenceException ex;
369         if (!anyPersistenceError()) {
370             // no error occurred, the format is just unknown
371
ex = new PersistenceException("Form file format not recognized"); // NOI18N
372
ErrorManager.getDefault().annotate(
373                 ex,
374                 ErrorManager.ERROR,
375                 null,
376                 FormUtils.getBundleString("MSG_ERR_NotRecognizedForm"), // NOI18N
377
null,
378                 null);
379         }
380         else { // some errors occurred when recognizing the form file format
381
Throwable JavaDoc annotateT = null;
382             int n = persistenceErrors.size();
383             if (n == 1) { // just one exception occurred
384
ex = (PersistenceException) persistenceErrors.get(0);
385                 Throwable JavaDoc t = ex.getOriginalException();
386                 annotateT = t != null ? t : ex;
387                 n = 0;
388             }
389             else { // there were more exceptions
390
ex = new PersistenceException("Form file cannot be loaded"); // NOI18N
391
annotateT = ex;
392             }
393             ErrorManager.getDefault().annotate(
394                 annotateT,
395                 FormUtils.getBundleString("MSG_ERR_LoadingErrors") // NOI18N
396
);
397             for (int i=0; i < n; i++) {
398                 PersistenceException pe = (PersistenceException)
399                                           persistenceErrors.get(i);
400                 Throwable JavaDoc t = pe.getOriginalException();
401                 ErrorManager.getDefault().annotate(ex, (t != null ? t : pe));
402             }
403             // all the exceptions were attached to the main exception to
404
// be thrown, so the log can be cleared
405
resetPersistenceErrorLog();
406         }
407         throw ex;
408     }
409
410     private void logPersistenceError(Throwable JavaDoc t) {
411         logPersistenceError(t, -1);
412     }
413
414     private boolean anyPersistenceError() {
415         return persistenceErrors != null && !persistenceErrors.isEmpty();
416     }
417     
418     /** Reports errors occurred during loading or saving the form.
419      */

420     public void reportErrors(int operation) {
421         if (!anyPersistenceError())
422             return; // no errors or warnings logged
423

424         final ErrorManager errorManager = ErrorManager.getDefault();
425
426         boolean checkLoadingErrors = operation == LOADING && formLoaded;
427         boolean anyNonFatalLoadingError = false; // was there a real error?
428

429         for (Iterator it=persistenceErrors.iterator(); it.hasNext(); ) {
430             Throwable JavaDoc t = (Throwable JavaDoc) it.next();
431             if (t instanceof PersistenceException) {
432                 Throwable JavaDoc th = ((PersistenceException)t).getOriginalException();
433                 if (th != null)
434                     t = th;
435             }
436            
437             if (checkLoadingErrors && !anyNonFatalLoadingError) {
438                 // was there a real loading error (not just warnings) causing
439
// some data not loaded?
440
ErrorManager.Annotation[] annotations =
441                                             errorManager.findAnnotations(t);
442                 int severity = 0;
443                 if ((annotations != null) && (annotations.length != 0)) {
444                     for (int i=0; i < annotations.length; i++) {
445                         int s = annotations[i].getSeverity();
446                         if (s == ErrorManager.UNKNOWN)
447                             s = ErrorManager.EXCEPTION;
448                         if (s > severity)
449                             severity = s;
450                     }
451                 }
452                 else severity = ErrorManager.EXCEPTION;
453
454                 if (severity > ErrorManager.WARNING)
455                     anyNonFatalLoadingError = true;
456             }
457             errorManager.notify(ErrorManager.INFORMATIONAL, t);
458             errorManager.notify(ErrorManager.USER, t);
459         }
460         
461         if (checkLoadingErrors && anyNonFatalLoadingError) {
462             // the form was loaded with some non-fatal errors - some data
463
// was not loaded - show a warning about possible data loss
464
java.awt.EventQueue.invokeLater(new Runnable JavaDoc() {
465                 public void run() {
466                     // for some reason this would be displayed before the
467
// ErrorManager if not invoked later
468

469                     JButton viewOnly = new JButton(FormUtils.getBundleString("CTL_ViewOnly")); // NOI18N
470
JButton allowEditing = new JButton(FormUtils.getBundleString("CTL_AllowEditing")); // NOI18N
471

472                     Object JavaDoc ret = DialogDisplayer.getDefault().notify(new NotifyDescriptor(
473                         FormUtils.getBundleString("MSG_FormLoadedWithErrors"), // NOI18N
474
FormUtils.getBundleString("CTL_FormLoadedWithErrors"), // NOI18N
475
NotifyDescriptor.DEFAULT_OPTION,
476                         NotifyDescriptor.WARNING_MESSAGE,
477                         new Object JavaDoc[] { viewOnly, allowEditing, NotifyDescriptor.CANCEL_OPTION },
478                         viewOnly ));
479                    
480                     if(ret == viewOnly) {
481                         setFormReadOnly();
482                     } else if(ret == allowEditing) {
483                         destroyInvalidComponents();
484                     } else { // close form, switch to source editor
485
getFormDesigner().reset(FormEditor.this); // might be reused
486
closeForm();
487                         getFormDataObject().getFormEditorSupport().selectJavaEditor();
488                     }
489                 }
490             });
491         }
492
493         resetPersistenceErrorLog();
494     }
495     
496     /**
497      * Destroys all components from {@link #formModel} taged as invalid
498      */

499     private void destroyInvalidComponents() {
500         Collection<RADComponent> allComps = formModel.getAllComponents();
501         List<RADComponent> invalidComponents = new ArrayList(allComps.size());
502         // collect all invalid components
503
for (RADComponent comp : allComps) {
504             if(!comp.isValid()) {
505                 invalidComponents.add(comp);
506             }
507         }
508         // destroy all invalid components
509
for (RADComponent comp : invalidComponents) {
510             try {
511                 comp.getNodeReference().destroy();
512             }
513             catch (java.io.IOException JavaDoc ex) { // should not happen
514
ex.printStackTrace();
515             }
516         }
517     }
518     
519     /**
520      * Sets the FormEditor in Read-Only mode
521      */

522     private void setFormReadOnly() {
523         formModel.setReadOnly(true);
524         getFormDesigner().getHandleLayer().setViewOnly(true);
525         detachFormListener();
526         getFormDataObject().getFormEditorSupport().updateMVTCDisplayName();
527     }
528
529     boolean needPostCreationUpdate() {
530         return Boolean.TRUE.equals(formDataObject.getPrimaryFile().getAttribute("justCreatedByNewWizard")); // NOI18N
531
// see o.n.m.f.w.TemplateWizardIterator.instantiate()
532
}
533
534     /**
535      * Form just created by the user via the New wizard may need some additional
536      * setup that can't be ensured by the static template. For example the type
537      * of layout code generation needs to be honored.
538      */

539     private void postCreationUpdate() {
540         if (formLoaded && formModel != null && !formModel.isReadOnly()
541             && needPostCreationUpdate()) // just created via New wizard
542
{ // regenerate code according to actual settings and save
543
formModel.getSettings().getLayoutCodeTarget(); // make sure layout gen. target is detected
544
formModel.getSettings().getI18nAutoMode(); // make sure auto i18n is detected
545
formModel.fireFormChanged(true); // hack: regenerate code immediately
546
FormEditorSupport fes = formDataObject.getFormEditorSupport();
547             try { // save the form if changed
548
if (fes.isModified()) {
549                     saveFormData();
550                     fes.saveSourceOnly();
551                 }
552                 formDataObject.getPrimaryFile().setAttribute("justCreatedByNewWizard", null); // NOI18N
553
}
554             catch (Exception JavaDoc ex) { // no problem should happen for just created form
555
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
556             }
557         }
558     }
559
560     /** @return the last activated FormDesigner for this form */
561     FormDesigner getFormDesigner() {
562         if (!formLoaded)
563             return null;
564
565         return formDesigner;
566     }
567
568     /** Called by FormDesigner when activated. */
569     void setFormDesigner(FormDesigner designer) {
570         formDesigner = designer;
571     }
572     
573     /** Closes the form. Used when closing the form editor or reloading
574      * the form. */

575     void closeForm() {
576         if (formLoaded) {
577             formModel.fireFormToBeClosed();
578
579             openForms.remove(formModel);
580             formModelToAssistant.remove(formModel);
581             formLoaded = false;
582             
583             // remove nodes hierarchy
584
if (formDataObject.isValid()) {
585                 // Avoiding deadlock (issue 51796)
586
java.awt.EventQueue.invokeLater(new Runnable JavaDoc() {
587                     public void run() {
588                         formDataObject.getNodeDelegate().getChildren()
589                             .remove(new Node[] { formRootNode });
590                         formRootNode = null;
591                     }
592                 });
593             }
594             
595             // remove listeners
596
detachFormListener();
597             detachDataObjectListener();
598             detachPaletteListener();
599             if (openForms.isEmpty()) {
600                 ComponentInspector.getInstance().focusForm(null);
601                 detachSettingsListener();
602             }
603             else { // still any opened forms - focus some
604
FormEditor next = (FormEditor)openForms.values().iterator().next();
605                 ComponentInspector.getInstance().focusForm(next);
606             }
607             
608             // close the floating windows
609
if (floatingWindows != null) {
610                 if (floatingWindows.size() > 0) {
611                     List tempList = new LinkedList(floatingWindows);
612                     Iterator it = tempList.iterator();
613                     while (it.hasNext()) {
614                         java.awt.Window JavaDoc window = (java.awt.Window JavaDoc) it.next();
615                         if (window.isVisible())
616                             window.setVisible(false);
617                     }
618                 }
619                 floatingWindows = null;
620             }
621             
622             // reset references
623
formDesigner = null;
624             persistenceManager = null;
625             persistenceErrors = null;
626             formModel = null;
627             codeGenerator = null;
628         formJavaSource = null;
629             i18nSupport = null;
630         }
631     }
632     
633     private void attachFormListener() {
634         if (formListener != null || formDataObject.isReadOnly() || formModel.isReadOnly())
635             return;
636
637         // this listener ensures necessary updates of nodes according to
638
// changes in containers in form
639
formListener = new FormModelListener() {
640             public void formChanged(FormModelEvent[] events) {
641                 if (events == null)
642                     return;
643
644                 boolean modifying = false;
645                 Set changedContainers = events.length > 0 ?
646                                           new HashSet() : null;
647                 Set compsToSelect = null;
648                 FormNode nodeToSelect = null;
649
650                 for (int i=0; i < events.length; i++) {
651                     FormModelEvent ev = events[i];
652
653                     if (ev.isModifying())
654                         modifying = true;
655
656                     int type = ev.getChangeType();
657                     if (type == FormModelEvent.CONTAINER_LAYOUT_EXCHANGED
658                         || type == FormModelEvent.CONTAINER_LAYOUT_CHANGED
659                         || type == FormModelEvent.COMPONENT_ADDED
660                         || type == FormModelEvent.COMPONENT_REMOVED
661                         || type == FormModelEvent.COMPONENTS_REORDERED)
662                     {
663                         ComponentContainer cont = ev.getContainer();
664                         if (changedContainers == null
665                             || !changedContainers.contains(cont))
666                         {
667                             updateNodeChildren(cont);
668                             if (changedContainers != null)
669                                 changedContainers.add(cont);
670                         }
671
672                         if (type == FormModelEvent.COMPONENT_REMOVED) {
673                             FormNode select;
674                             if (cont instanceof RADComponent)
675                                 select = ((RADComponent)cont).getNodeReference();
676                             else
677                                 select = formRootNode.getOthersNode();
678
679                             if (!(nodeToSelect instanceof RADComponentNode)) {
680                                 if (nodeToSelect != formRootNode)
681                                     nodeToSelect = select;
682                             }
683                             else if (nodeToSelect != select)
684                                 nodeToSelect = formRootNode;
685                         }
686                         else if (type == FormModelEvent.CONTAINER_LAYOUT_EXCHANGED) {
687                             nodeToSelect = ((RADVisualContainer)cont)
688                                                 .getLayoutNodeReference();
689                         }
690                         else if (type == FormModelEvent.COMPONENT_ADDED
691                                  && ev.getComponent().isInModel())
692                         {
693                             if (compsToSelect == null)
694                                 compsToSelect = new HashSet();
695
696                             compsToSelect.add(ev.getComponent());
697                             compsToSelect.remove(ev.getContainer());
698                         }
699                     }
700                 }
701
702                 FormDesigner designer = getFormDesigner();
703                 if (designer != null) {
704                     if (compsToSelect != null) {
705                         designer.clearSelectionImpl();
706                         for (Iterator it=compsToSelect.iterator(); it.hasNext(); ) {
707                             designer.addComponentToSelectionImpl((RADComponent)it.next());
708                         }
709                         designer.updateComponentInspector();
710 // RADComponent[] comps =
711
// new RADComponent[compsToSelect.size()];
712
// compsToSelect.toArray(comps);
713
// designer.setSelectedComponents(comps);
714
}
715                     else if (nodeToSelect != null)
716                         designer.setSelectedNode(nodeToSelect);
717                 }
718
719                 if (modifying) { // mark the form document modified explicitly
720
FormDataObject formDO = getFormDataObject();
721                     formDO.getFormEditorSupport().markFormModified();
722                 }
723             }
724         };
725
726         formModel.addFormModelListener(formListener);
727     }
728
729     private void detachFormListener() {
730         if (formListener != null) {
731             formModel.removeFormModelListener(formListener);
732             formListener = null;
733         }
734     }
735     
736     /** Updates (sub)nodes of a container (in Component Inspector) after
737      * a change has been made (like component added or removed). */

738     void updateNodeChildren(ComponentContainer metacont) {
739         FormNode node;
740
741         if (metacont == null || metacont == formModel.getModelContainer())
742             node = formRootNode != null ?
743                        formRootNode.getOthersNode() : null;
744
745         else if (metacont instanceof RADComponent)
746             node = ((RADComponent)metacont).getNodeReference();
747
748         else node = null;
749
750         if (node != null)
751             node.updateChildren();
752     }
753     
754     private void attachDataObjectListener() {
755         if (dataObjectListener != null)
756             return;
757
758         dataObjectListener = new PropertyChangeListener() {
759             public void propertyChange(PropertyChangeEvent ev) {
760                 if (DataObject.PROP_NAME.equals(ev.getPropertyName())) {
761                     // FormDataObject's name has changed
762
String JavaDoc name = formDataObject.getName();
763                     formModel.setName(name);
764                     formRootNode.updateName(name);
765                     // multiview updated by FormEditorSupport
766
// formModel.fireFormChanged(); // [refactoring may choke if we change code...]
767
}
768                 else if (DataObject.PROP_COOKIE.equals(ev.getPropertyName())) {
769                     java.awt.EventQueue.invokeLater(new Runnable JavaDoc() {
770                         public void run() {
771                             Node[] nodes = ComponentInspector.getInstance()
772                                      .getExplorerManager().getSelectedNodes();
773                             for (int i=0; i < nodes.length; i++)
774                                 ((FormNode)nodes[i]).updateCookies();
775                         }
776                     });
777                 }
778             }
779         };
780
781         formDataObject.addPropertyChangeListener(dataObjectListener);
782     }
783
784     private void detachDataObjectListener() {
785         if (dataObjectListener != null) {
786             formDataObject.removePropertyChangeListener(dataObjectListener);
787             dataObjectListener = null;
788         }
789     }
790     
791     private static void attachSettingsListener() {
792         if (settingsListener != null)
793             return;
794
795         settingsListener = new PreferenceChangeListener JavaDoc() {
796
797             public void preferenceChange(PreferenceChangeEvent JavaDoc evt) {
798                 Iterator iter = openForms.keySet().iterator();
799
800                 while (iter.hasNext()) {
801                     FormModel formModel = (FormModel) iter.next();
802                     String JavaDoc propName = evt.getKey();
803
804                     if (FormLoaderSettings.PROP_USE_INDENT_ENGINE.equals(propName)) {
805                         formModel.fireSyntheticPropertyChanged(null, propName,
806                                                                null,
807                                                                evt.getNewValue());
808                     } else if (FormLoaderSettings.PROP_SELECTION_BORDER_SIZE.equals(propName) ||
809                                FormLoaderSettings.PROP_SELECTION_BORDER_COLOR.equals(propName) ||
810                                FormLoaderSettings.PROP_CONNECTION_BORDER_COLOR.equals(propName) ||
811                                FormLoaderSettings.PROP_FORMDESIGNER_BACKGROUND_COLOR.equals(propName) ||
812                                FormLoaderSettings.PROP_FORMDESIGNER_BORDER_COLOR.equals(propName)) {
813                         FormDesigner designer = getFormDesigner(formModel);
814
815                         if (designer != null)
816                             designer.updateVisualSettings();
817                     } else if (FormLoaderSettings.PROP_PALETTE_IN_TOOLBAR.equals(propName)) {
818                         FormDesigner designer = getFormDesigner(formModel);
819
820                         if (designer != null)
821                             designer.getFormToolBar().showPaletteButton(FormLoaderSettings.getInstance().isPaletteInToolBar());
822                     }
823                 }
824             }
825         };
826
827         FormLoaderSettings.getInstance().getPreferences().addPreferenceChangeListener(settingsListener);
828     }
829
830     private static void detachSettingsListener() {
831         if (settingsListener != null) {
832             FormLoaderSettings.getInstance().getPreferences().removePreferenceChangeListener(settingsListener);
833             settingsListener = null;
834         }
835     }
836     
837     private void attachPaletteListener() {
838         if (paletteListener != null)
839             return;
840
841         paletteListener = new PropertyChangeListener() {
842             public void propertyChange(PropertyChangeEvent evt) {
843                 if (PaletteController.PROP_SELECTED_ITEM.equals(evt.getPropertyName())) {
844                     Iterator iter = openForms.keySet().iterator();
845                     while (iter.hasNext()) {
846                         FormModel formModel = (FormModel)iter.next();
847                         if(formModel.isReadOnly()) {
848                             continue;
849                         }
850                         FormDesigner designer = getFormDesigner(formModel);
851                         if (designer != null) {
852                             // PENDING should be done for all cloned designers
853
if (evt.getNewValue() == null) {
854                                 if (designer.getDesignerMode() == FormDesigner.MODE_ADD)
855                                     designer.setDesignerMode(FormDesigner.MODE_SELECT);
856                             } else {
857                                 if (designer.getDesignerMode() == FormDesigner.MODE_ADD) {
858                                     // Change in the selected palette item means unselection
859
// of the old item and selection of the new one
860
designer.setDesignerMode(FormDesigner.MODE_SELECT);
861                                 }
862                                 designer.setDesignerMode(FormDesigner.MODE_ADD);
863                             }
864                             // TODO activate current designer?
865
}
866                     }
867                 }
868             }
869         };
870
871         PaletteUtils.addPaletteListener(paletteListener, formDataObject.getPrimaryFile());
872     }
873
874     private void detachPaletteListener() {
875         if (paletteListener != null) {
876             PaletteUtils.removePaletteListener(paletteListener, formDataObject.getPrimaryFile());
877             paletteListener = null;
878         }
879     }
880
881     void reinstallListener() {
882         if (formListener != null) {
883             formModel.removeFormModelListener(formListener);
884             formModel.addFormModelListener(formListener);
885         }
886     }
887
888     /** @return JEditorPane set up with the actuall forms java source*/
889     public static JEditorPane createCodeEditorPane(FormModel formModel) {
890         JEditorPane codePane = new JEditorPane();
891         codePane.setContentType("text/x-java"); // NOI18N
892
codePane.getDocument().putProperty(Document.StreamDescriptionProperty, getFormDataObject(formModel));
893         JavaCodeGenerator codeGen = (JavaCodeGenerator) FormEditor.getCodeGenerator(formModel);
894         codeGen.regenerateCode();
895         return codePane;
896     }
897
898     public static synchronized AssistantModel getAssistantModel(FormModel formModel) {
899         assert (formModel != null);
900         AssistantModel assistant = (AssistantModel)formModelToAssistant.get(formModel);
901         if (assistant == null) {
902             assistant = new AssistantModel();
903             formModelToAssistant.put(formModel, assistant);
904         }
905         return assistant;
906     }
907
908     /** @return FormDesigner for given form */
909     public static FormDesigner getFormDesigner(FormModel formModel) {
910         FormEditor formEditor = (FormEditor) openForms.get(formModel);
911         return formEditor != null ? formEditor.getFormDesigner() : null;
912     }
913
914     /** @return CodeGenerator for given form */
915     public static CodeGenerator getCodeGenerator(FormModel formModel) {
916         FormEditor formEditor = (FormEditor) openForms.get(formModel);
917         return formEditor != null ? formEditor.getCodeGenerator() : null;
918     }
919
920     /** @return FormDataObject of given form */
921     public static FormDataObject getFormDataObject(FormModel formModel) {
922         FormEditor formEditor = (FormEditor) openForms.get(formModel);
923         return formEditor != null ? formEditor.getFormDataObject() : null;
924     }
925
926     /** @return FormJavaSource of given form */
927     public static FormJavaSource getFormJavaSource(FormModel formModel) {
928         FormEditor formEditor = (FormEditor) openForms.get(formModel);
929         return formEditor != null ? formEditor.getFormJavaSource() : null;
930     }
931
932     /** @return I18nSupport of given form */
933     static I18nSupport getI18nSupport(FormModel formModel) {
934         FormEditor formEditor = (FormEditor) openForms.get(formModel);
935         return formEditor != null ? formEditor.getI18nSupport() : null;
936     }
937
938     /** @return FormEditor instance for given form */
939     public static FormEditor getFormEditor(FormModel formModel) {
940         return (FormEditor) openForms.get(formModel);
941     }
942     
943     UndoRedo.Manager getFormUndoRedoManager() {
944         return formModel != null ? formModel.getUndoRedoManager() : null;
945     }
946     
947     public void registerFloatingWindow(java.awt.Window JavaDoc window) {
948         if (floatingWindows == null)
949             floatingWindows = new ArrayList();
950         else
951             floatingWindows.remove(window);
952         floatingWindows.add(window);
953     }
954
955     public void unregisterFloatingWindow(java.awt.Window JavaDoc window) {
956         if (floatingWindows != null)
957             floatingWindows.remove(window);
958     }
959
960     /**
961      * Updates project classpath with the layout extensions library.
962      */

963     public boolean updateProjectForNaturalLayout() {
964         if (formModel.getSettings().getLayoutCodeTarget() == JavaCodeGenerator.LAYOUT_CODE_JDK6)
965             return false;
966         try {
967             // [TODO maybe we should check if the library isn't there already]
968
ClassSource cs = new ClassSource("org.jdesktop.layout.*", // class name actually not needed // NOI18N
969
new String JavaDoc[] { ClassSource.LIBRARY_SOURCE },
970                                              new String JavaDoc[] { "swing-layout" }); // NOI18N
971
return ClassPathUtils.updateProject(formDataObject.getFormFile(), cs);
972         }
973         catch (IOException JavaDoc ex) {
974             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
975         }
976         return false;
977     }
978
979     public static boolean isNonVisualTrayEnabled() {
980         return Boolean.getBoolean("netbeans.form.non_visual_tray"); // NOI18N
981
}
982 }
983
Popular Tags