KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > editor > example > JavaKit


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.editor.example;
21
22 import java.io.*;
23 import java.awt.event.KeyEvent JavaDoc;
24 import java.awt.event.InputEvent JavaDoc;
25 import java.awt.event.ActionEvent JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.text.MessageFormat JavaDoc;
28
29 import java.util.Map JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.ResourceBundle JavaDoc;
32 import java.util.MissingResourceException JavaDoc;
33 import javax.swing.KeyStroke JavaDoc;
34 import javax.swing.JEditorPane JavaDoc;
35 import javax.swing.JMenuItem JavaDoc;
36 import javax.swing.Action JavaDoc;
37 import javax.swing.text.Document JavaDoc;
38 import javax.swing.text.JTextComponent JavaDoc;
39 import javax.swing.text.TextAction JavaDoc;
40 import javax.swing.text.BadLocationException JavaDoc;
41 import org.netbeans.editor.*;
42 import org.netbeans.editor.ext.*;
43 import org.netbeans.editor.ext.java.*;
44
45 /**
46 * Java editor kit with appropriate document
47 *
48 * @author Miloslav Metelka
49 * @version 1.00
50 */

51
52 public class JavaKit extends ExtKit {
53
54     public static final String JavaDoc JAVA_MIME_TYPE = "text/x-java"; // NOI18N
55

56     private static final String JavaDoc[] getSetIsPrefixes = new String JavaDoc[] {
57                 "get", "set", "is" // NOI18N
58
};
59
60     /** Switch first letter of word to capital and insert 'get'
61     * at word begining.
62     */

63     public static final String JavaDoc makeGetterAction = "make-getter"; // NOI18N
64

65     /** Switch first letter of word to capital and insert 'set'
66     * at word begining.
67     */

68     public static final String JavaDoc makeSetterAction = "make-setter"; // NOI18N
69

70     /** Switch first letter of word to capital and insert 'is'
71     * at word begining.
72     */

73     public static final String JavaDoc makeIsAction = "make-is"; // NOI18N
74

75     /** Debug source and line number */
76     public static final String JavaDoc abbrevDebugLineAction = "abbrev-debug-line"; // NOI18N
77

78     static final long serialVersionUID =-5445829962533684922L;
79
80     static {
81         Settings.addInitializer( new JavaSettingsInitializer( JavaKit.class ) );
82         Settings.addInitializer( new SaJavaSettingsInitializer() );
83         Settings.reset();
84
85         ResourceBundle JavaDoc settings = ResourceBundle.getBundle( "settings" ); // NOI18N
86
String JavaDoc jcPath = null;
87         try {
88             jcPath = settings.getString( "Java_Completion" );
89         } catch( MissingResourceException JavaDoc exc ) {}
90
91         if( jcPath != null ) {
92         URL JavaDoc skeleton = JavaKit.class.getResource("/" + jcPath + ".jcs");
93         URL JavaDoc body = JavaKit.class.getResource("/" + jcPath + ".jcb");
94         
95         if (skeleton == null || body == null) {
96            System.err.println("Warning: Java parser databases not found. Ignoring.");
97         } else {
98             DAFileProvider provider = new DAFileProvider(
99             new URLAccessor(skeleton),
100             new URLAccessor(body)
101             );
102         
103                 JCBaseFinder finder = new JCBaseFinder();
104         
105                 finder.append( provider );
106                 JavaCompletion.setFinder( finder );
107         }
108         }
109     }
110
111     public String JavaDoc getContentType() {
112         return JAVA_MIME_TYPE;
113     }
114
115     /** Create new instance of syntax coloring scanner
116     * @param doc document to operate on. It can be null in the cases the syntax
117     * creation is not related to the particular document
118     */

119     public Syntax createSyntax(Document JavaDoc doc) {
120         return new JavaSyntax();
121     }
122
123     /** Create syntax support */
124     public SyntaxSupport createSyntaxSupport(BaseDocument doc) {
125         return new JavaSyntaxSupport(doc);
126     }
127
128     public Completion createCompletion(ExtEditorUI extEditorUI) {
129         return new JavaCompletion(extEditorUI);
130     }
131
132     /** Create the formatter appropriate for this kit */
133     public Formatter createFormatter() {
134         return new JavaFormatter(this.getClass());
135     }
136     
137     protected EditorUI createEditorUI() {
138         return new ExtEditorUI();
139     }
140
141     protected void initDocument(BaseDocument doc) {
142         doc.addLayer(new JavaDrawLayerFactory.JavaLayer(),
143                 JavaDrawLayerFactory.JAVA_LAYER_VISIBILITY);
144         doc.addDocumentListener(new JavaDrawLayerFactory.LParenWatcher());
145     }
146
147     protected Action JavaDoc[] createActions() {
148         Action JavaDoc[] javaActions = new Action JavaDoc[] {
149                                    new JavaDefaultKeyTypedAction(),
150                                    new PrefixMakerAction(makeGetterAction, "get", getSetIsPrefixes), // NOI18N
151
new PrefixMakerAction(makeSetterAction, "set", getSetIsPrefixes), // NOI18N
152
new PrefixMakerAction(makeIsAction, "is", getSetIsPrefixes), // NOI18N
153
new AbbrevDebugLineAction(),
154                                };
155         return TextAction.augmentList(super.createActions(), javaActions);
156     }
157
158
159     public static class JavaDefaultKeyTypedAction extends ExtDefaultKeyTypedAction {
160
161         protected void checkIndentHotChars(JTextComponent JavaDoc target, String JavaDoc typedText) {
162             boolean reindent = false;
163
164             BaseDocument doc = Utilities.getDocument(target);
165             int dotPos = target.getCaret().getDot();
166             if (doc != null) {
167                 /* Check whether the user has written the ending 'e'
168                  * of the first 'else' on the line.
169                  */

170                 if ("e".equals(typedText)) { // NOI18N
171
try {
172                         int fnw = Utilities.getRowFirstNonWhite(doc, dotPos);
173                         if (fnw >= 0 && fnw + 4 == dotPos
174                             && "else".equals(doc.getText(fnw, 4)) // NOI18N
175
) {
176                             reindent = true;
177                         }
178                     } catch (BadLocationException JavaDoc e) {
179                     }
180
181                 } else if (":".equals(typedText)) { // NOI18N
182
try {
183                         int fnw = Utilities.getRowFirstNonWhite(doc, dotPos);
184                         if (fnw >= 0 && fnw + 4 <= doc.getLength()
185                             && "case".equals(doc.getText(fnw, 4)) // NOI18N
186
) {
187                             reindent = true;
188                         }
189                     } catch (BadLocationException JavaDoc e) {
190                     }
191                 }
192
193                 // Reindent the line if necessary
194
if (reindent) {
195                     try {
196                         Utilities.reformatLine(doc, dotPos);
197                     } catch (BadLocationException JavaDoc e) {
198                     }
199                 }
200             }
201
202             super.checkIndentHotChars(target, typedText);
203         }
204
205     }
206
207
208
209     public static class AbbrevDebugLineAction extends BaseAction {
210
211         public AbbrevDebugLineAction() {
212             super(abbrevDebugLineAction);
213         }
214
215         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
216             if (target != null) {
217                 if (!target.isEditable() || !target.isEnabled()) {
218                     target.getToolkit().beep();
219                     return;
220                 }
221                 BaseDocument doc = (BaseDocument)target.getDocument();
222                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc("System.err.println(\""); // NOI18N
223
File file = (File)doc.getProperty( "file" );
224                 if (file != null) {
225                     sb.append( file.getAbsolutePath() );
226                     sb.append(':');
227                 }
228                 try {
229                     sb.append(Utilities.getLineOffset(doc, target.getCaret().getDot()) + 1);
230                 } catch (BadLocationException JavaDoc e) {
231                 }
232                 sb.append(' ');
233
234                 BaseKit kit = Utilities.getKit(target);
235                 Action JavaDoc a = kit.getActionByName(BaseKit.insertContentAction);
236                 if (a != null) {
237                     Utilities.performAction(
238                         a,
239                         new ActionEvent JavaDoc(target, ActionEvent.ACTION_PERFORMED, sb.toString()),
240                         target
241                     );
242                 }
243             }
244         }
245     }
246     
247     
248     private static class SaJavaSettingsInitializer extends Settings.AbstractInitializer {
249         public SaJavaSettingsInitializer() {
250             super( "sa-java-settings-initializer" ); // NOI18N
251
}
252         
253         
254         
255         public void updateSettingsMap(Class JavaDoc kitClass, Map JavaDoc settingsMap) {
256             if (kitClass == JavaKit.class) {
257                 SettingsUtil.updateListSetting(settingsMap, SettingsNames.KEY_BINDING_LIST, getJavaKeyBindings());
258             }
259
260         }
261
262         public MultiKeyBinding[] getJavaKeyBindings() {
263             return new MultiKeyBinding[] {
264                new MultiKeyBinding(
265                    new KeyStroke JavaDoc[] {
266                        KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.ALT_MASK),
267                        KeyStroke.getKeyStroke(KeyEvent.VK_G, 0)
268                    },
269                    JavaKit.makeGetterAction
270                ),
271                new MultiKeyBinding(
272                    new KeyStroke JavaDoc[] {
273                        KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.ALT_MASK),
274                        KeyStroke.getKeyStroke(KeyEvent.VK_S, 0)
275                    },
276                    JavaKit.makeSetterAction
277                ),
278                new MultiKeyBinding(
279                    new KeyStroke JavaDoc[] {
280                        KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.ALT_MASK),
281                        KeyStroke.getKeyStroke(KeyEvent.VK_I, 0)
282                    },
283                    JavaKit.makeIsAction
284                ),
285                new MultiKeyBinding(
286                    KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.ALT_MASK),
287                    JavaKit.abbrevDebugLineAction
288                )
289             };
290         }
291     }
292
293
294     /**
295      * DataAccessor for parser DB files via URL streams
296      *
297      * @author Petr Nejedly
298      */

299     public static class URLAccessor implements DataAccessor {
300     
301         URL JavaDoc url;
302         InputStream stream;
303     int streamOff;
304         int actOff;
305
306         public URLAccessor(URL JavaDoc url) {
307             this.url = url;
308         }
309     
310         /** Not implemented
311          */

312         public void append(byte[] buffer, int off, int len) throws IOException {
313         throw new IllegalArgumentException JavaDoc("read only!"); // NOI18N
314
}
315     
316         /**
317          * Reads exactly <code>len</code> bytes from this file resource into the byte
318          * array, starting at the current file pointer. This method reads
319          * repeatedly from the file until the requested number of bytes are
320          * read. This method blocks until the requested number of bytes are
321          * read, the end of the inputStream is detected, or an exception is thrown.
322          *
323          * @param buffer the buffer into which the data is read.
324          * @param off the start offset of the data.
325          * @param len the number of bytes to read.
326          */

327         public void read(byte[] buffer, int off, int len) throws IOException {
328         InputStream str = getStream(actOff);
329         while (len > 0) {
330         int count = str.read(buffer, off, len);
331         streamOff += count;
332         off += count;
333         len -= count;
334         }
335         }
336     
337         /** Opens DataAccessor file resource
338          * @param requestWrite if true, file is opened for read/write operation.
339          */

340         public void open(boolean requestWrite) throws IOException {
341         if(requestWrite) throw new IllegalArgumentException JavaDoc("read only!"); // NOI18N
342
}
343     
344         /** Closes DataAccessor file resource */
345         public void close() throws IOException {
346             if (stream!=null) {
347                 stream.close();
348             stream = null;
349         }
350         }
351     
352         /**
353          * Returns the current offset in this file.
354          *
355          * @return the offset from the beginning of the file, in bytes,
356          * at which the next read or write occurs.
357          */

358         public long getFilePointer() throws IOException {
359            return actOff;
360         }
361     
362         /** Clears the file and sets the offset to 0 */
363         public void resetFile() throws IOException {
364             throw new IllegalArgumentException JavaDoc("read only!"); // NOI18N
365
}
366     
367         /**
368          * Sets the file-pointer offset, measured from the beginning of this
369          * file, at which the next read or write occurs.
370          */

371         public void seek(long pos) throws IOException {
372             actOff = (int)pos;
373         }
374
375         /** Gets InputStream prepared for reading from <code>off</code> offset position*/
376         private InputStream getStream(int off) throws IOException {
377         if (streamOff > off && stream != null) {
378         stream.close();
379         stream = null;
380         }
381         
382             if(stream == null) {
383         stream = url.openStream();
384         streamOff = 0;
385         }
386         
387         while (streamOff < off) {
388         long len = stream.skip(off - streamOff);
389         streamOff += (int)len;
390         if (len == 0) throw new IOException("EOF"); // NOI18N
391
}
392
393         return stream;
394         }
395     
396         public int getFileLength() {
397         try {
398         int l = url.openConnection().getContentLength();
399         return l;
400         } catch (IOException e) {
401         return 0;
402         }
403         }
404     
405         public String JavaDoc toString() {
406             return url.toString();
407         }
408     }
409 }
410
Popular Tags