KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > editor > options > OptionUtilities


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.editor.options;
21
22 import java.awt.Color JavaDoc;
23 import java.awt.Font JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28 import javax.swing.KeyStroke JavaDoc;
29 import org.netbeans.editor.MultiKeyBinding;
30 import java.util.List JavaDoc;
31 import java.util.StringTokenizer JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.awt.Insets JavaDoc;
34 import org.w3c.dom.Document JavaDoc;
35 import org.openide.xml.XMLUtil;
36 import org.openide.filesystems.FileLock;
37 import java.io.IOException JavaDoc;
38 import org.openide.filesystems.FileObject;
39 import org.openide.loaders.DataObject;
40 import java.util.Enumeration JavaDoc;
41 import org.openide.cookies.InstanceCookie;
42 import org.openide.util.actions.SystemAction;
43 import java.util.Set JavaDoc;
44 import java.awt.Dimension JavaDoc;
45
46 /** Various utilities for Editor Options.
47  *
48  * @author Martin Roskanin
49  * @since 08/2001
50  */

51 public class OptionUtilities {
52
53     private static final Logger JavaDoc LOG = Logger.getLogger(OptionUtilities.class.getName());
54     
55     // the name of default folder for storing default maps such as macros, abbrevs...
56
public static final String JavaDoc DEFAULT_FOLDER = "Defaults"; //NOI18N
57

58     private OptionUtilities() {
59         // instantiation has no sense
60
}
61     
62     private static String JavaDoc wrap(String JavaDoc s){
63         return (s.length()==1)? "0"+s : s; // NOI18N
64
}
65     
66     /** Converts Color to hexadecimal String representation */
67     public static String JavaDoc color2String(Color JavaDoc c){
68         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
69         sb.append("#"); // NOI18N
70
sb.append(wrap(Integer.toHexString(c.getRed()).toUpperCase()));
71         sb.append(wrap(Integer.toHexString(c.getGreen()).toUpperCase()));
72         sb.append(wrap(Integer.toHexString(c.getBlue()).toUpperCase()));
73         return sb.toString();
74     }
75     
76     /** Converts a String to an integer and returns the specified opaque Color. */
77     public static Color JavaDoc string2Color(String JavaDoc s){
78         try{
79             return Color.decode(s);
80         }catch(NumberFormatException JavaDoc nfe){
81             return null;
82         }
83     }
84     
85     /** Converts String to integer */
86     public static int string2Int(String JavaDoc s){
87         try{
88             return Integer.parseInt(s);
89         }catch(NumberFormatException JavaDoc nfe){
90             return -1;
91         }
92     }
93     
94     /** Decodes font style from string representation */
95     public static int getFontStyle(String JavaDoc s){
96         s=s.toLowerCase();
97         int ret = Font.PLAIN;
98         if (s.indexOf("bold") != -1) ret |= Font.BOLD; //NOI18N
99
if (s.indexOf("italic") != -1) ret |= Font.ITALIC; //NOI18N
100
return ret;
101     }
102     
103     /** Encodes font style to string representation */
104     public static String JavaDoc style2String(int i){
105         if (Font.BOLD == i) return "bold"; // NOI18N
106
if (Font.ITALIC == i) return "italic"; // NOI18N
107
if ( (Font.BOLD+Font.ITALIC) == i ) return "bold-italic"; // NOI18N
108
return "plain"; // NOI18N
109
}
110     
111     
112     /** Gets changed values of newMap against the oldMap.
113      * If allowNewKey is false then diff will contain only
114      * changed oldMap keys
115      */

116     public static Map JavaDoc getMapDiff(Map JavaDoc oldMap, Map JavaDoc newMap, boolean allowNewKeys){
117         Map JavaDoc ret = new HashMap JavaDoc();
118
119         for( Iterator JavaDoc i = newMap.keySet().iterator(); i.hasNext(); ) {
120             Object JavaDoc key = (Object JavaDoc)i.next();
121             Object JavaDoc value = newMap.get( key );
122             // if value in newMap is different from oldMap, put it to return Map
123
if (!value.equals(oldMap.get(key)))
124                 ret.put(key,newMap.get(key));
125             // or we can add some new key if allowNewKeys is true
126
else if (allowNewKeys && !oldMap.containsKey(key))
127                 ret.put(key, newMap.get(key));
128         }
129         
130         for ( Iterator JavaDoc i = oldMap.keySet().iterator(); i.hasNext(); ) {
131             String JavaDoc key = (String JavaDoc)i.next();
132             Object JavaDoc value = oldMap.get( key );
133             // all deleted keys
134
if (!newMap.containsKey(key)) ret.put(key, "");
135         }
136         
137         return ret;
138     }
139     
140
141     /** Creates textual representation of KeyStroke[]. */
142     public static String JavaDoc keysToString(KeyStroke JavaDoc[] stroke){
143         if (stroke == null) return "NULL"; // NOI18N
144
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
145         
146         for (int i=0; i<stroke.length; i++){
147             sb.append(org.openide.util.Utilities.keyToString(stroke[i]));
148             if (i<stroke.length-1) sb.append("$"); // NOI18N
149
}
150         
151         return sb.toString();
152     }
153
154     /** Creates textual representation of KeyStroke. */
155     public static String JavaDoc keyToString(KeyStroke JavaDoc stroke){
156         if (stroke == null) return "NULL"; // NOI18N
157
return org.openide.util.Utilities.keyToString(stroke);
158     }
159     
160     /** Converts textual representatin of Keystroke */
161     public static KeyStroke JavaDoc stringToKey(String JavaDoc s){
162         if (s.equals("NULL")) return null; // NOI18N
163
return org.openide.util.Utilities.stringToKey(s);
164     }
165
166     /** Converts textual representatin of Keystroke[] */
167     public static KeyStroke JavaDoc[] stringToKeys(String JavaDoc s){
168         if (s.equals("NULL")) return null; // NOI18N
169

170         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s.toUpperCase(), "$"); // NOI18N
171
ArrayList JavaDoc arr = new ArrayList JavaDoc();
172         
173         while (st.hasMoreElements()) {
174             s = st.nextToken();
175             KeyStroke JavaDoc k = stringToKey(s);
176             if (k == null) return null;
177             arr.add(k);
178         }
179         
180         return (KeyStroke JavaDoc[])arr.toArray(new KeyStroke JavaDoc[arr.size()]);
181     }
182     
183     public static void printDefaultAbbrevs(Map JavaDoc map){
184         System.out.println("-----------------------------------------------------------"); // NOI18N
185
System.out.println("<?xml version=\"1.0\"?>"); // NOI18N
186
System.out.println("<!DOCTYPE catalog PUBLIC \""+AbbrevsMIMEProcessor.PUBLIC_ID+"\""); // NOI18N
187
System.out.println(" \""+AbbrevsMIMEProcessor.SYSTEM_ID+"\">"); // NOI18N
188
System.out.println("");
189         System.out.println("<"+AbbrevsMIMEOptionFile.TAG_ROOT+">"); // NOI18N
190
for ( Iterator JavaDoc i = map.keySet().iterator(); i.hasNext(); ) {
191             String JavaDoc key = (String JavaDoc)i.next();
192             String JavaDoc value = (String JavaDoc)map.get(key);
193             System.out.println("<"+AbbrevsMIMEOptionFile.TAG_ABBREV+" "+AbbrevsMIMEOptionFile.ATTR_KEY+"=\""+key+"\">" // NOI18N
194
+value+"</"+AbbrevsMIMEOptionFile.TAG_ABBREV+">"); // NOI18N
195
}
196         System.out.println("</"+AbbrevsMIMEOptionFile.TAG_ROOT+">"); // NOI18N
197
}
198     
199     /** Prints given Abbreviations Map to XML file with given FO */
200     public static void printDefaultAbbrevs(Map JavaDoc map, FileObject file){
201         Document JavaDoc doc = XMLUtil.createDocument(AbbrevsMIMEOptionFile.TAG_ROOT, null, AbbrevsMIMEProcessor.PUBLIC_ID, AbbrevsMIMEProcessor.SYSTEM_ID);
202         org.w3c.dom.Element JavaDoc rootElem = doc.getDocumentElement();
203         
204         // save XML
205
for( Iterator JavaDoc i = map.keySet().iterator(); i.hasNext(); ) {
206             String JavaDoc key = (String JavaDoc)i.next();
207             if (map.get(key) instanceof String JavaDoc){
208                 
209                 String JavaDoc action = (String JavaDoc) map.get(key);
210                 
211                 org.w3c.dom.Element JavaDoc abbrevElem = doc.createElement(AbbrevsMIMEOptionFile.TAG_ABBREV);
212                 abbrevElem.setAttribute(AbbrevsMIMEOptionFile.ATTR_KEY, key);
213                 abbrevElem.appendChild(doc.createTextNode(action));
214                 rootElem.appendChild(abbrevElem);
215                 
216             }
217         }
218         
219         doc.getDocumentElement().normalize();
220         
221         try{
222             FileLock lock = file.lock();
223             try {
224                 XMLUtil.write(doc, file.getOutputStream(lock), "UTF-8"); // NOI18N
225
} catch (Exception JavaDoc e){
226                 e.printStackTrace();
227             } finally {
228                 lock.releaseLock();
229             }
230         }catch (IOException JavaDoc ioe){
231             ioe.printStackTrace();
232         }
233     }
234     
235     
236     /** Prints given Macro Map to XML file with given FO */
237     public static void printDefaultMacros(Map JavaDoc map, FileObject file){
238         Document JavaDoc doc = XMLUtil.createDocument(MacrosMIMEOptionFile.TAG_ROOT, null, MacrosMIMEProcessor.PUBLIC_ID, MacrosMIMEProcessor.SYSTEM_ID);
239         org.w3c.dom.Element JavaDoc rootElem = doc.getDocumentElement();
240         
241         // save XML
242
for( Iterator JavaDoc i = map.keySet().iterator(); i.hasNext(); ) {
243             String JavaDoc key = (String JavaDoc)i.next();
244             if (map.get(key) instanceof String JavaDoc){
245                 
246                 String JavaDoc action = (String JavaDoc) map.get(key);
247                 
248                 org.w3c.dom.Element JavaDoc macroElem = doc.createElement(MacrosMIMEOptionFile.TAG_MACRO);
249                 macroElem.setAttribute(MacrosMIMEOptionFile.ATTR_NAME, key);
250                 macroElem.appendChild(doc.createTextNode(action));
251                 rootElem.appendChild(macroElem);
252             }
253         }
254         
255         doc.getDocumentElement().normalize();
256         
257         try{
258             FileLock lock = file.lock();
259             try {
260                 XMLUtil.write(doc, file.getOutputStream(lock), "UTF-8"); // NOI18N
261
} catch (Exception JavaDoc e){
262                 e.printStackTrace();
263             } finally {
264                 lock.releaseLock();
265             }
266         }catch (IOException JavaDoc ioe){
267             ioe.printStackTrace();
268         }
269     }
270
271     /** Prints given KeyBindings List to XML file with given FO */
272     public static void printDefaultKeyBindings(List JavaDoc list, FileObject file){
273         Map JavaDoc map = makeKeyBindingsMap(list);
274         Document JavaDoc doc = XMLUtil.createDocument(KeyBindingsMIMEOptionFile.TAG_ROOT, null, KeyBindingsMIMEProcessor.PUBLIC_ID, KeyBindingsMIMEProcessor.SYSTEM_ID);
275         org.w3c.dom.Element JavaDoc rootElem = doc.getDocumentElement();
276         
277         // save XML
278
for( Iterator JavaDoc i = map.keySet().iterator(); i.hasNext(); ) {
279             String JavaDoc key = (String JavaDoc)i.next();
280             if (map.get(key) instanceof MultiKeyBinding){
281                 
282                 MultiKeyBinding mkb = (MultiKeyBinding) map.get(key);
283                 if (mkb==null) continue;
284                 
285                 org.w3c.dom.Element JavaDoc keybElem = doc.createElement(KeyBindingsMIMEOptionFile.TAG_BIND);
286                 keybElem.setAttribute(KeyBindingsMIMEOptionFile.ATTR_KEY, key);
287                 keybElem.setAttribute(KeyBindingsMIMEOptionFile.ATTR_ACTION_NAME, mkb.actionName);
288                 rootElem.appendChild(keybElem);
289             }
290         }
291         
292         doc.getDocumentElement().normalize();
293         
294         try{
295             FileLock lock = file.lock();
296             try {
297                 XMLUtil.write(doc, file.getOutputStream(lock), "UTF-8"); // NOI18N
298
} catch (Exception JavaDoc e){
299                 e.printStackTrace();
300             } finally {
301                 lock.releaseLock();
302             }
303         }catch (IOException JavaDoc ioe){
304             ioe.printStackTrace();
305         }
306     }
307     
308     /** Coverts Insets to String representation */
309     public static String JavaDoc insetsToString(Insets JavaDoc ins){
310         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
311         sb.append(ins.top);
312         sb.append(',');
313         
314         sb.append(ins.left);
315         sb.append(',');
316         
317         sb.append(ins.bottom);
318         sb.append(',');
319         
320         sb.append(ins.right);
321         
322         return sb.toString();
323     }
324
325     /** Converts textual representation of Insets */
326     public static Insets JavaDoc parseInsets(String JavaDoc s){
327         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s, ","); // NOI18N
328

329         int arr[] = new int[4];
330         int i=0;
331         while (st.hasMoreElements()) {
332             if (i>3) return null;
333             try{
334                 arr[i] = Integer.parseInt(st.nextToken());
335             }catch(NumberFormatException JavaDoc nfe){
336                 return null;
337             }
338             i++;
339         }
340         if (i!=4) return null;
341         return new Insets JavaDoc(arr[0],arr[1],arr[2],arr[3]);
342     }
343
344     /** Coverts Insets to String representation */
345     public static String JavaDoc dimensionToString(Dimension JavaDoc dim){
346         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
347         sb.append(dim.width);
348         sb.append(',');
349         
350         sb.append(dim.height);
351
352         return sb.toString();
353     }
354
355     /** Converts textual representation of Insets */
356     public static Dimension JavaDoc parseDimension(String JavaDoc s){
357         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s, ","); // NOI18N
358

359         int arr[] = new int[2];
360         int i=0;
361         while (st.hasMoreElements()) {
362             if (i>1) return null;
363             try{
364                 arr[i] = Integer.parseInt(st.nextToken());
365             }catch(NumberFormatException JavaDoc nfe){
366                 return null;
367             }
368             i++;
369         }
370         if (i!=2) return null;
371         return new Dimension JavaDoc(arr[0],arr[1]);
372     }
373     
374     
375     /** Converts KeyBings List to KeyBindings Map
376      * Map.key is the textual representation of keystroke(s) */

377     public static Map JavaDoc makeKeyBindingsMap(List JavaDoc propList){
378         Map JavaDoc ret = new HashMap JavaDoc();
379
380         boolean output = true;
381         for (int i=0; i<propList.size(); i++){
382             Object JavaDoc obj = propList.get(i);
383             if (! (obj instanceof org.netbeans.editor.MultiKeyBinding)) {
384                 if (!org.netbeans.editor.MultiKeyBinding.class.getClassLoader().equals(obj.getClass().getClassLoader())){
385                     if (output) {
386                         System.err.println("Different classloaders:");
387                         System.err.println(org.netbeans.editor.MultiKeyBinding.class.getClassLoader());
388                         System.err.println(obj.getClass().getClassLoader());
389                         output = false;
390                     }
391                 }
392                 
393                 continue;
394             }
395             MultiKeyBinding mkb = (MultiKeyBinding)obj;
396             String JavaDoc fileName = (mkb.keys == null) ?
397             OptionUtilities.keyToString(mkb.key) : OptionUtilities.keysToString(mkb.keys);
398             if (fileName!=null){
399                 ret.put(fileName,mkb);
400             }
401         }
402         return ret;
403     }
404     
405     /** Gets a list of attributes defined in BaseOptions.BASE MultiPropertyFolder */
406     public static List JavaDoc getGlobalAttribs(String JavaDoc folderName){
407         MIMEOptionFolder mimeFolder = AllOptionsFolder.getDefault().getMIMEFolder();
408         if (mimeFolder == null) return new ArrayList JavaDoc();
409         MultiPropertyFolder mpf = mimeFolder.getMPFolder(folderName,false); //NOI18N
410
if ( mpf!=null ){
411             List JavaDoc retList = new ArrayList JavaDoc();
412             for (Enumeration JavaDoc e = mpf.getDataFolder().getPrimaryFile().getAttributes() ; e.hasMoreElements() ;) {
413                 String JavaDoc name = (String JavaDoc) e.nextElement();
414                 if (name.indexOf("/") != -1) { //NOI18N
415
Object JavaDoc value = mpf.getDataFolder().getPrimaryFile().getAttribute(name);
416                     if ((value instanceof Boolean JavaDoc) && ((Boolean JavaDoc) value).booleanValue()){
417                         retList.add(name);
418                     }
419                 }
420             }
421             return retList;
422         }
423         return new ArrayList JavaDoc();
424     }
425     
426     /** Gets attributes of base popup folder */
427     public static List JavaDoc getGlobalPopupAttribs(){
428         return getGlobalAttribs("Popup"); //NOI18N
429
}
430     
431     /** Gets popup menu items (DataObjects) stored in base popup folder
432      */

433     public static List JavaDoc getGlobalPopupMenuItems(){
434         return getGlobalMenuItems("Popup"); //NOI18N
435
}
436
437     /** Retrieves a list of BaseOptions.BASE MultiPropertyFolder items */
438     public static List JavaDoc getGlobalMenuItems(String JavaDoc folderName){
439         MIMEOptionFolder mimeFolder = AllOptionsFolder.getDefault().getMIMEFolder();
440         if (mimeFolder == null) return new ArrayList JavaDoc();
441         MultiPropertyFolder mpf = mimeFolder.getMPFolder(folderName,false); //NOI18N
442
if ( mpf!=null ){
443             return mpf.getProperties();
444         }
445         return new ArrayList JavaDoc();
446     }
447
448     public static List JavaDoc getPopupStrings(List JavaDoc popup){
449         return getPopupStrings(popup, false);
450     }
451     
452     /** Creates String representation of popup from DO representation
453      * @param addSeparatorInstance if true the result list will use instance of JSeparator in case of separator,
454      * if false null will be used
455      */

456     public static List JavaDoc getPopupStrings(List JavaDoc popup, boolean addSeparatorInstance){
457         List JavaDoc retList = new ArrayList JavaDoc();
458         for (int i=0; i<popup.size(); i++){
459             if (!(popup.get(i) instanceof DataObject)) continue;
460             
461             DataObject dob = (DataObject) popup.get(i);
462             InstanceCookie ic = (InstanceCookie)dob.getCookie(InstanceCookie.class);
463             
464             if (ic!=null){
465                 
466                 try{
467                     if (SystemAction.class.isAssignableFrom(ic.instanceClass())){
468                         retList.add(ic.instanceName());
469                     }else if (javax.swing.Action JavaDoc.class.isAssignableFrom(ic.instanceClass())){
470                         retList.add(ic.instanceCreate());
471                     }
472                     if(javax.swing.JSeparator JavaDoc.class.isAssignableFrom(ic.instanceClass())){
473                         retList.add(addSeparatorInstance?new javax.swing.JSeparator JavaDoc():null);
474                     }
475                 }catch(IOException JavaDoc ioe){
476                     ioe.printStackTrace();
477                 }catch(ClassNotFoundException JavaDoc cnfe){
478                     cnfe.printStackTrace();
479                 }
480             }else{
481                 if ("org-openide-windows-TopComponent".equals(dob.getName())){ //NOI18N
482
retList.add(dob.getName().replace('-','.'));
483                 }else{
484                     retList.add(dob.getName());
485                 }
486             }
487         }
488         
489         return retList;
490     }
491     
492     /** Provides ordering of folder items in accordance with folder attributes */
493     public static List JavaDoc arrangeMergedFolderObjects(Set JavaDoc/*<DataObject>*/ items, Set JavaDoc/*<String>*/ attribs){
494         // init returnList with unsorted collection
495
List JavaDoc/*<DataObject>*/ retList = new ArrayList JavaDoc/*<DataObject>*/(items);
496         
497         // prepare name list of instance files
498
List JavaDoc/*<String>*/ nameList = new ArrayList JavaDoc/*<String>*/();
499         for (int i = 0; i<retList.size(); i++){
500             DataObject dob = (DataObject) retList.get(i);
501             nameList.add(dob.getPrimaryFile().getNameExt());
502         }
503         
504         // sort items
505
for (int i=0; i<attribs.size(); i++){
506             Iterator JavaDoc j = attribs.iterator();
507             while (j.hasNext()){
508                 String JavaDoc attr = (String JavaDoc) j.next();
509                 int idx = attr.indexOf('/');
510                 if (idx == -1) {
511                     // ignore invalid attribute (#78020)
512
LOG.warning("Ignoring invalid ordering attribute: '" + attr + "'"); //NOI18N
513
continue;
514                 }
515                 String JavaDoc firstItem = attr.substring(0,idx);
516                 String JavaDoc secondItem = attr.substring(idx+1);
517                 int first = nameList.indexOf(firstItem);
518                 int second = nameList.indexOf(secondItem);
519                 if ( (first>second) && (second>-1)){
520                     // move first item before the second
521
nameList.add(second,nameList.remove(first));
522                     retList.add(second,retList.remove(first));
523                 }
524             }
525         }
526         return retList;
527     }
528     
529     /** Provides sorting of merged popup elements according to sort instructions in folder attribs */
530     public static List JavaDoc arrangeMergedPopup(Set JavaDoc items, Set JavaDoc attribs){
531         List JavaDoc list = arrangeMergedFolderObjects(items, attribs);
532         //return sorted result
533
return getPopupStrings(list);
534     }
535     
536 }
537
Popular Tags