KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > options > colors > ColorModel


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.options.colors;
21
22 import java.awt.BorderLayout JavaDoc;
23 import java.awt.Color JavaDoc;
24 import java.awt.Component JavaDoc;
25 import java.awt.Cursor JavaDoc;
26 import java.awt.Image JavaDoc;
27 import java.awt.Toolkit JavaDoc;
28 import java.io.BufferedReader JavaDoc;
29 import java.io.FileNotFoundException JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.InputStream JavaDoc;
32 import java.io.InputStreamReader JavaDoc;
33 import java.net.URL JavaDoc;
34 import java.util.ArrayList JavaDoc;
35 import java.util.Collection JavaDoc;
36 import java.util.HashMap JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.List JavaDoc;
40 import java.util.Map JavaDoc;
41 import java.util.Set JavaDoc;
42 import javax.swing.ImageIcon JavaDoc;
43 import javax.swing.JEditorPane JavaDoc;
44 import javax.swing.JPanel JavaDoc;
45 import javax.swing.SwingUtilities JavaDoc;
46 import javax.swing.event.CaretEvent JavaDoc;
47 import javax.swing.event.CaretListener JavaDoc;
48 import javax.swing.text.AttributeSet JavaDoc;
49 import javax.swing.text.BadLocationException JavaDoc;
50 import javax.swing.text.Document JavaDoc;
51 import javax.swing.text.SimpleAttributeSet JavaDoc;
52 import javax.swing.text.StyleConstants JavaDoc;
53 import org.netbeans.api.editor.settings.EditorStyleConstants;
54 import org.netbeans.editor.AnnotationType;
55 import org.netbeans.editor.AnnotationTypes;
56 import org.netbeans.editor.EditorUI;
57 import org.netbeans.editor.SyntaxSupport;
58 import org.netbeans.editor.TokenItem;
59 import org.netbeans.editor.Utilities;
60 import org.netbeans.editor.ext.ExtSyntaxSupport;
61 import org.netbeans.modules.editor.settings.storage.api.EditorSettings;
62 import org.netbeans.modules.editor.settings.storage.api.FontColorSettingsFactory;
63 import org.openide.filesystems.FileObject;
64 import org.openide.filesystems.FileSystem;
65 import org.openide.filesystems.Repository;
66 import org.openide.text.CloneableEditorSupport;
67 import org.openide.util.NbBundle;
68
69 public final class ColorModel {
70     
71     /* package */ static final String JavaDoc ALL_LANGUAGES = NbBundle.getMessage(ColorModel.class, "CTL_All_Languages"); //NOI18N
72
private static final String JavaDoc HIGHLIGHTING_LANGUAGE = "Highlighting"; //NOI18N
73
private static final String JavaDoc [] EMPTY_MIMEPATH = new String JavaDoc[0];
74     
75     private EditorSettings editorSettings = EditorSettings.getDefault ();
76     
77     
78     
79     // schemes .................................................................
80

81     public Set JavaDoc /*<String>*/ getProfiles () {
82         return editorSettings.getFontColorProfiles ();
83     }
84     
85     public String JavaDoc getCurrentProfile () {
86         return editorSettings.getCurrentFontColorProfile ();
87     }
88     
89     public boolean isCustomProfile (String JavaDoc profile) {
90         return editorSettings.isCustomFontColorProfile (profile);
91     }
92     
93     public void setCurrentProfile (String JavaDoc profile) {
94         editorSettings.setCurrentFontColorProfile (profile);
95     }
96     
97     
98     // annotations .............................................................
99

100     public Collection JavaDoc /*<Category>*/ getAnnotations (String JavaDoc profile) {
101         Collection JavaDoc annotations = new ArrayList JavaDoc ();
102         for(Iterator JavaDoc it = AnnotationTypes.getTypes().getAnnotationTypeNames(); it.hasNext(); ) {
103             String JavaDoc name = (String JavaDoc) it.next ();
104             
105             AnnotationType annotationType = AnnotationTypes.getTypes().getType(name);
106             if (!annotationType.isVisible()) {
107                 continue;
108             }
109
110             String JavaDoc description = annotationType.getDescription();
111             if (description == null) {
112                 continue;
113             }
114
115             SimpleAttributeSet JavaDoc category = new SimpleAttributeSet JavaDoc();
116             category.addAttribute(EditorStyleConstants.DisplayName, description);
117             category.addAttribute(StyleConstants.NameAttribute, description);
118             
119             URL JavaDoc iconURL = annotationType.getGlyph ();
120             Image JavaDoc image = null;
121             if (iconURL.getProtocol ().equals ("nbresloc")) { // NOI18N
122
image = org.openide.util.Utilities.loadImage(iconURL.getPath().substring(1));
123             } else {
124                 image = Toolkit.getDefaultToolkit ().getImage (iconURL);
125             }
126             if (image != null) {
127                 category.addAttribute("icon", new ImageIcon JavaDoc(image)); //NOI18N
128
}
129             
130             Color JavaDoc bgColor = annotationType.getHighlight();
131             if (annotationType.isUseHighlightColor() && bgColor != null) {
132                 category.addAttribute(StyleConstants.Background, bgColor);
133             }
134             
135             Color JavaDoc fgColor = annotationType.getForegroundColor();
136             if (!annotationType.isInheritForegroundColor() && fgColor != null) {
137                 category.addAttribute(StyleConstants.Foreground, fgColor);
138             }
139
140             Color JavaDoc underColor = annotationType.getWaveUnderlineColor();
141             if (annotationType.isUseWaveUnderlineColor() && underColor != null) {
142                 category.addAttribute(EditorStyleConstants.WaveUnderlineColor, underColor);
143             }
144             
145             category.addAttribute("annotationType", annotationType); //NOI18N
146
annotations.add(category);
147     }
148         
149     return annotations;
150     }
151     
152     public void setAnnotations (
153     String JavaDoc profile,
154     Collection JavaDoc /*<Category>*/ annotations
155     ) {
156     Iterator JavaDoc it = annotations.iterator ();
157     //S ystem.out.println("ColorModelImpl.setAnnotations ");
158
while (it.hasNext ()) {
159         AttributeSet JavaDoc category = (AttributeSet JavaDoc) it.next ();
160         AnnotationType annotationType = (AnnotationType)
161         category.getAttribute ("annotationType");
162             
163         if (category.isDefined (StyleConstants.Background)) {
164         annotationType.setUseHighlightColor (true);
165         annotationType.setHighlight (
166                     (Color JavaDoc) category.getAttribute (StyleConstants.Background)
167                 );
168             } else
169         annotationType.setUseHighlightColor (false);
170         if (category.isDefined (StyleConstants.Foreground)) {
171         annotationType.setInheritForegroundColor (false);
172         annotationType.setForegroundColor (
173                     (Color JavaDoc) category.getAttribute (StyleConstants.Foreground)
174                 );
175             } else
176         annotationType.setInheritForegroundColor (true);
177         if (category.isDefined (EditorStyleConstants.WaveUnderlineColor)) {
178                 annotationType.setUseWaveUnderlineColor (true);
179                 annotationType.setWaveUnderlineColor (
180                     (Color JavaDoc) category.getAttribute (EditorStyleConstants.WaveUnderlineColor)
181                 );
182             } else
183                 annotationType.setUseWaveUnderlineColor (false);
184         //S ystem.out.println(" " + category.getDisplayName () + " : " + annotationType + " : " + annotationType.getHighlight() + " : " + annotationType.isUseHighlightColor());
185
}
186     }
187     
188     
189     // editor categories .......................................................
190

191     /**
192      * Returns Collection of AttributeSets or null, if the profile does
193      * not exists.
194      *
195      * @param profile a profile name
196      * @return Collection of AttributeSets or null
197      */

198     public Collection JavaDoc /*<Category>*/ getHighlightings (String JavaDoc profile) {
199         Map JavaDoc m = editorSettings.getHighlightings(profile);
200         if (m == null) {
201             return null;
202         }
203         return hideDummyCategories(m.values());
204     }
205     
206     public Collection JavaDoc /*<Category>*/ getHighlightingDefaults (String JavaDoc profile) {
207         Collection JavaDoc r = editorSettings.getHighlightingDefaults (profile).values ();
208         if (r == null) return null;
209         return hideDummyCategories (r);
210     }
211     
212     public void setHighlightings (
213     String JavaDoc profile,
214     Collection JavaDoc /*<Category>*/ highlihgtings
215     ) {
216     editorSettings.setHighlightings (
217         profile,
218         toMap (highlihgtings)
219     );
220     }
221
222     
223     // syntax coloring .........................................................
224

225     public Set JavaDoc /*<String>*/ getLanguages () {
226     return getLanguageToMimeTypeMap ().keySet ();
227     }
228     
229     public Collection JavaDoc /*<Category>*/ getCategories (
230     String JavaDoc profile,
231     String JavaDoc language
232     ) {
233         if (language.equals(ALL_LANGUAGES)) {
234             return editorSettings.getFontColorSettings(EMPTY_MIMEPATH).getAllFontColors(profile);
235         }
236         
237         String JavaDoc mimeType = getMimeType (language);
238     FontColorSettingsFactory fcs = EditorSettings.getDefault ().
239             getFontColorSettings (new String JavaDoc[] {mimeType});
240         return fcs.getAllFontColors (profile);
241     }
242     
243     public Collection JavaDoc /*<Category>*/ getDefaults (
244     String JavaDoc profile,
245     String JavaDoc language
246     ) {
247         if (language.equals(ALL_LANGUAGES)) {
248             return editorSettings.getFontColorSettings(EMPTY_MIMEPATH).getAllFontColorDefaults(profile);
249         }
250         
251         String JavaDoc mimeType = getMimeType (language);
252     FontColorSettingsFactory fcs = EditorSettings.getDefault ().
253             getFontColorSettings (new String JavaDoc[] {mimeType});
254         return fcs.getAllFontColorDefaults (profile);
255     }
256     
257     public void setCategories (
258         String JavaDoc profile,
259         String JavaDoc language,
260         Collection JavaDoc categories
261     ) {
262         if (language.equals (ALL_LANGUAGES)) {
263             editorSettings.getFontColorSettings(EMPTY_MIMEPATH).setAllFontColors(profile, categories);
264             return;
265         }
266         
267         String JavaDoc mimeType = getMimeType (language);
268         if (mimeType == null) {
269             if (System.getProperty ("org.netbeans.optionsDialog") != null)
270                 System.out.println("ColorModelImpl.setCategories - unknown language " + language);
271             return;
272         }
273     FontColorSettingsFactory fcs = EditorSettings.getDefault ().
274             getFontColorSettings (new String JavaDoc[] {mimeType});
275     fcs.setAllFontColors (
276             profile,
277         categories
278     );
279     }
280     
281     public Component JavaDoc getEditorPreviewComponent () {
282         return new Preview (HIGHLIGHTING_LANGUAGE);
283     }
284     
285     public Component JavaDoc getSyntaxColoringPreviewComponent (
286         String JavaDoc language
287     ) {
288         return new Preview (language);
289     }
290
291     class Preview extends JPanel JavaDoc {
292         
293         static final String JavaDoc PROP_CURRENT_ELEMENT = "currentAElement";
294         private JEditorPane JavaDoc editorPane;
295         private FontColorSettingsFactory fontColorSettings;
296         
297         
298         Preview (
299             final String JavaDoc language
300         ) {
301             super (new BorderLayout JavaDoc ());
302 // S ystem.out.println ("getPreviewComponent " + profile + " : " + language);
303
// T hread.dumpStack ();
304

305             SwingUtilities.invokeLater (new Runnable JavaDoc () {
306                 public void run () {
307                     editorPane = new JEditorPane JavaDoc ();
308                     updateMimeType (language);
309                     if (language == HIGHLIGHTING_LANGUAGE) {
310                         EditorUI editorUI = Utilities.getEditorUI (editorPane);
311                         if (editorUI != null) {
312                             editorUI.setLineNumberEnabled (true);
313                             editorUI.getExtComponent ();
314                             add (editorUI.getExtComponent (), BorderLayout.CENTER);
315                             return;
316                         }
317 // S ystem.out.println("no text ui " + editorPane);
318
}
319                     add (editorPane, BorderLayout.CENTER);
320                 }
321             });
322             setCursor (Cursor.getPredefinedCursor (Cursor.HAND_CURSOR));
323         }
324         
325         private String JavaDoc currentLanguage;
326         
327         public void setParameters (
328             final String JavaDoc language,
329             final Collection JavaDoc /*<Category>*/ defaults,
330             final Collection JavaDoc /*<Category>*/ highlightings,
331             final Collection JavaDoc /*<Category>*/ syntaxColorings
332         ) {
333             SwingUtilities.invokeLater (new Runnable JavaDoc () {
334                 public void run () {
335                     String JavaDoc internalMimeType = null;
336                     if (!language.equals (currentLanguage)) {
337                         updateMimeType (language);
338                         currentLanguage = language;
339                         internalMimeType = languageToInternalMimeType(language, false);
340                         fontColorSettings = EditorSettings.getDefault ().
341                             getFontColorSettings (new String JavaDoc[] {internalMimeType});
342                     }
343                     
344                     if (internalMimeType == null) {
345                         internalMimeType = languageToInternalMimeType(language, false);
346                     }
347                     if (defaults != null) {
348                         editorSettings.getFontColorSettings(EMPTY_MIMEPATH).setAllFontColors(
349                             "test" + ColorModel.this.hashCode(),
350                             defaults
351                         );
352                     }
353                     if (highlightings != null)
354                         editorSettings.setHighlightings (
355                             "test" + ColorModel.this.hashCode (),
356                             toMap (highlightings)
357                         );
358                     if (syntaxColorings != null)
359                         fontColorSettings.setAllFontColors (
360                             "test" + ColorModel.this.hashCode (),
361                             syntaxColorings
362                         );
363                 }
364             });
365         }
366         
367         /**
368          * Sets given mime type to preview and loads proper example text.
369          */

370         private void updateMimeType (String JavaDoc language) {
371             String JavaDoc internalMimeType = languageToInternalMimeType(language, true);
372
373             // XXX: There is several hacks in the few lines of code below.
374
// First, the 'mimeType' property on a Document is abused for
375
// injecting the name of a profile used for previewing changes in
376
// colors. This by itself causes several problems in other parts of
377
// the IDE that had to be worked around. Second, Document properties
378
// are normally not supposed to be changed during a lifetime of a Document
379
// and there is no way how to listen for those changes. Which means
380
// that we have to fire a property change on the JTextComponent containing
381
// the Document, so that the layers can get recalculated.
382

383             Document JavaDoc document = editorPane.getDocument ();
384             document.putProperty ("mimeType", internalMimeType);
385             editorPane.setEditorKit (CloneableEditorSupport.getEditorKit(internalMimeType));
386             document = editorPane.getDocument ();
387             document.putProperty ("mimeType", internalMimeType);
388             editorPane.firePropertyChange(null, 0, 1);
389             
390             editorPane.addCaretListener (new CaretListener JavaDoc () {
391                 public void caretUpdate (CaretEvent JavaDoc e) {
392                     int position = e.getDot ();
393                     EditorUI editorUI = Utilities.getEditorUI (editorPane);
394                     if (editorUI == null) return;
395                     SyntaxSupport ss = Utilities.getSyntaxSupport
396                         (editorUI.getComponent ());
397                     if (!(ss instanceof ExtSyntaxSupport)) return;
398                     try {
399                         TokenItem tokenItem = ((ExtSyntaxSupport) ss).
400                             getTokenChain (position, position + 1);
401                         if (tokenItem == null) return;
402                         String JavaDoc elementName = tokenItem.getTokenContextPath ().
403                                 getNamePrefix ();
404                         if (tokenItem.getTokenID ().getCategory () != null)
405                             elementName += tokenItem.getTokenID ().
406                                 getCategory ().getName ();
407                         else
408                             elementName += tokenItem.getTokenID ().getName ();
409                         firePropertyChange (PROP_CURRENT_ELEMENT, null, elementName);
410                     } catch (BadLocationException JavaDoc ex) {
411                         ex.printStackTrace ();
412                     }
413                 }
414             });
415             editorPane.setEnabled (false);
416             InputStream JavaDoc is = loadPreviewExample (language);
417             if (is == null) {
418                 assert true :
419                        "Example for " + language + " language not found.";
420                 is = loadPreviewExample ("Java");
421             }
422             BufferedReader JavaDoc r = new BufferedReader JavaDoc (new InputStreamReader JavaDoc (is));
423             StringBuffer JavaDoc sb = new StringBuffer JavaDoc ();
424             try {
425                 String JavaDoc line = r.readLine ();
426                 while (line != null) {
427                     sb.append (line).append ('\n');
428                     line = r.readLine ();
429                 }
430                 editorPane.setText (new String JavaDoc (sb));
431             } catch (IOException JavaDoc ex) {
432                 ex.printStackTrace ();
433             }
434         }
435         
436         private InputStream JavaDoc loadPreviewExample (String JavaDoc language) {
437             String JavaDoc mimeType = getMimeType (language);
438             FileSystem fs = Repository.getDefault ().getDefaultFileSystem ();
439             FileObject exampleFile = fs.findResource
440                 ("OptionsDialog/PreviewExamples/" + mimeType);
441             try {
442                 return exampleFile != null ?
443                     exampleFile.getInputStream () : null;
444             } catch (FileNotFoundException JavaDoc fnfe) {
445                 return null;
446             }
447         }
448
449         private String JavaDoc languageToInternalMimeType (String JavaDoc language, boolean encodeTestProfileName) {
450             String JavaDoc mimeType = (
451                 language == HIGHLIGHTING_LANGUAGE ||
452                 language == ALL_LANGUAGES
453             ) ?
454                 "text/x-java" : //NOI18N Highlighting & All Languages
455
getMimeType (language);
456             
457             if (encodeTestProfileName) {
458                 return "test" + ColorModel.this.hashCode () + "_" + mimeType; //NOI18N
459
} else {
460                 return mimeType;
461             }
462         }
463     }
464     
465     
466     // private implementation ..................................................
467

468     private String JavaDoc getMimeType (String JavaDoc language) {
469         return (String JavaDoc) getLanguageToMimeTypeMap ().get (language);
470     }
471     
472     private Map JavaDoc languageToMimeType;
473     private Map JavaDoc getLanguageToMimeTypeMap () {
474     if (languageToMimeType == null) {
475         languageToMimeType = new HashMap JavaDoc ();
476         Set JavaDoc mimeTypes = editorSettings.getMimeTypes ();
477         Iterator JavaDoc it = mimeTypes.iterator ();
478         while (it.hasNext ()) {
479         String JavaDoc mimeType = (String JavaDoc) it.next ();
480         languageToMimeType.put (
481             editorSettings.getLanguageName (mimeType),
482             mimeType
483         );
484         }
485             languageToMimeType.put (
486                 ALL_LANGUAGES,
487                 "Defaults"
488             );
489     }
490     return languageToMimeType;
491     }
492     
493     private Set JavaDoc hiddenCategories = new HashSet JavaDoc ();
494     {
495 // hiddenCategories.add ("status-bar");
496
// hiddenCategories.add ("status-bar-bold");
497
}
498     
499     private Collection JavaDoc hideDummyCategories (
500         Collection JavaDoc /*AttributeSet*/ categories
501     ) {
502         List JavaDoc result = new ArrayList JavaDoc ();
503         Iterator JavaDoc it = categories.iterator ();
504         while (it.hasNext ()) {
505             AttributeSet JavaDoc as = (AttributeSet JavaDoc) it.next ();
506             if (hiddenCategories.contains (
507                 as.getAttribute (StyleConstants.NameAttribute)
508             )) continue;
509             result.add (as);
510         }
511         return result;
512     }
513     
514     private static Map JavaDoc toMap (Collection JavaDoc categories) {
515         if (categories == null) return null;
516         Map JavaDoc result = new HashMap JavaDoc ();
517         Iterator JavaDoc it = categories.iterator ();
518         while (it.hasNext ()) {
519             AttributeSet JavaDoc as = (AttributeSet JavaDoc) it.next ();
520             result.put (
521                 as.getAttribute (StyleConstants.NameAttribute),
522                 as
523             );
524         }
525         return result;
526     }
527 }
528
Popular Tags