KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > editor > ext > ExtKit


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.ext;
21
22 import java.awt.Rectangle JavaDoc;
23 import java.awt.event.ActionEvent JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import javax.swing.Action JavaDoc;
28 import javax.swing.JPopupMenu JavaDoc;
29 import javax.swing.JMenuItem JavaDoc;
30 import javax.swing.KeyStroke JavaDoc;
31 import javax.swing.text.Caret JavaDoc;
32 import javax.swing.text.Keymap JavaDoc;
33 import javax.swing.text.JTextComponent JavaDoc;
34 import javax.swing.text.TextAction JavaDoc;
35 import javax.swing.text.BadLocationException JavaDoc;
36 import org.netbeans.editor.BaseKit;
37 import org.netbeans.editor.EditorUI;
38 import org.netbeans.editor.BaseAction;
39 import org.netbeans.editor.Utilities;
40 import org.netbeans.editor.Settings;
41 import org.netbeans.editor.BaseDocument;
42 import org.netbeans.editor.SyntaxSupport;
43 import org.netbeans.editor.Formatter;
44 import org.netbeans.lib.editor.util.CharSequenceUtilities;
45 import org.netbeans.lib.editor.util.swing.DocumentUtilities;
46 import org.openide.util.NbBundle;
47
48
49 /**
50 * Extended kit offering advanced functionality
51 *
52 * @author Miloslav Metelka
53 * @version 1.00
54 */

55 public class ExtKit extends BaseKit {
56
57     /** This action is searched and executed when the popup menu should
58     * be displayed to build the popup menu.
59     */

60     public static final String JavaDoc buildPopupMenuAction = "build-popup-menu"; // NOI18N
61

62     /** Show popup menu.
63     */

64     public static final String JavaDoc showPopupMenuAction = "show-popup-menu"; // NOI18N
65

66     /** This action is searched and executed when the tool-tip should
67     * be displayed by tool-tip support to build the tool-tip.
68     */

69     public static final String JavaDoc buildToolTipAction = "build-tool-tip"; // NOI18N
70

71     /** Open find dialog action - this action is defined in view package, but
72     * its name is defined here for clarity
73     */

74     public static final String JavaDoc findAction = "find"; // NOI18N
75

76     /** Open replace dialog action - this action is defined in view package, but
77     * its name is defined here for clarity
78     */

79     public static final String JavaDoc replaceAction = "replace"; // NOI18N
80

81     /** Open goto dialog action - this action is defined in view package, but
82     * its name is defined here for clarity
83     */

84     public static final String JavaDoc gotoAction = "goto"; // NOI18N
85

86     /** Goto declaration depending on the context under the caret */
87     public static final String JavaDoc gotoDeclarationAction = "goto-declaration"; // NOI18N
88

89     /** Goto source depending on the context under the caret */
90     public static final String JavaDoc gotoSourceAction = "goto-source"; // NOI18N
91

92     public static final String JavaDoc gotoSuperImplementationAction = "goto-super-implementation"; // NOI18N
93

94     /** Goto help depending on the context under the caret */
95     public static final String JavaDoc gotoHelpAction = "goto-help"; // NOI18N
96

97     /** Match brace */
98     public static final String JavaDoc matchBraceAction = "match-brace"; // NOI18N
99

100     /** Select the text to the matching bracket */
101     public static final String JavaDoc selectionMatchBraceAction = "selection-match-brace"; // NOI18N
102

103     /** Toggle the case for the first character of the word under caret */
104     public static final String JavaDoc toggleCaseIdentifierBeginAction = "toggle-case-identifier-begin"; // NOI18N
105

106     /** Advanced code selection technique
107      * @deprecated this action name is not actively used by ExtKit and will be removed in future releases.
108      */

109     public static final String JavaDoc codeSelectAction = "code-select"; // NOI18N
110

111     /** Action used when escape is pressed. By default it hides popup-menu
112      * @deprecated this action name is not actively used by ExtKit and will be removed in future releases.
113      */

114     public static final String JavaDoc escapeAction = "escape"; // NOI18N
115

116     /** Find the completion help and show it in the completion pane. */
117     public static final String JavaDoc completionShowAction = "completion-show"; // NOI18N
118
public static final String JavaDoc allCompletionShowAction = "all-completion-show"; // NOI18N
119

120     /** Show documentation popup panel */
121     public static final String JavaDoc documentationShowAction = "documentation-show"; // NOI18N
122

123     /** Show completion tooltip */
124     public static final String JavaDoc completionTooltipShowAction = "tooltip-show"; // NOI18N
125

126     /** Comment out the selected block */
127     public static final String JavaDoc commentAction = "comment"; // NOI18N
128

129     /** Uncomment the selected block */
130     public static final String JavaDoc uncommentAction = "uncomment"; // NOI18N
131

132     /** Toggle the toolbar */
133     public static final String JavaDoc toggleToolbarAction = "toggle-toolbar"; // NOI18N
134

135     /** Trimmed text for go to submenu*/
136     public static final String JavaDoc TRIMMED_TEXT = "trimmed-text"; //NOI18N
137

138     /** Shared suport for find and replace dialogs */
139     private static FindDialogSupport findDialogSupport;
140     
141     private static FindAction findActionDef = new FindAction();
142     private static ReplaceAction replaceActionDef = new ReplaceAction();
143     private static GotoAction gotoActionDef = new GotoAction();
144
145
146     /** Whether editor popup menu creation should be dumped to console */
147     private static final boolean debugPopupMenu
148             = Boolean.getBoolean("netbeans.debug.editor.popup.menu"); // NOI18N
149

150     public ExtKit() {
151     }
152
153     /** Create caret to navigate through document */
154     public Caret JavaDoc createCaret() {
155         return new ExtCaret();
156     }
157
158     public SyntaxSupport createSyntaxSupport(BaseDocument doc) {
159         return new ExtSyntaxSupport(doc);
160     }
161
162     public Completion createCompletion(ExtEditorUI extEditorUI) {
163         return null;
164     }
165     
166     public CompletionJavaDoc createCompletionJavaDoc(ExtEditorUI extEditorUI) {
167         return null;
168     }
169     
170     protected EditorUI createEditorUI() {
171         return new ExtEditorUI();
172     }
173
174     protected Action JavaDoc[] createActions() {
175         Action JavaDoc[] extActions = new Action JavaDoc[] {
176             new BuildPopupMenuAction(),
177             new ShowPopupMenuAction(),
178             new BuildToolTipAction(),
179             findActionDef,
180             replaceActionDef,
181             gotoActionDef,
182             //new GotoDeclarationAction(), the instance will be created in extending editor... i.e. JavaKit
183
new ToggleCaseIdentifierBeginAction(),
184             new MatchBraceAction(matchBraceAction, false),
185             new MatchBraceAction(selectionMatchBraceAction, true),
186 // new CodeSelectAction(), // the actionPerformed is empty and so I'm removing the action from the list
187
// new EscapeAction(),
188
new ExtDefaultKeyTypedAction(),
189             new CompletionShowAction(),
190             new AllCompletionShowAction(),
191             new DocumentationShowAction(),
192             new CompletionTooltipShowAction()
193         };
194         return TextAction.augmentList(super.createActions(), extActions);
195     }
196     
197     /**
198      * Action that is localized in org.netbeans.editor package.
199      * <br/>
200      * <code>BaseKit.class</code> is used as a bundle class.
201      */

202     private abstract static class BaseKitLocalizedAction extends BaseAction {
203         
204         public BaseKitLocalizedAction(String JavaDoc name) {
205             super(name);
206         }
207         
208         public BaseKitLocalizedAction(String JavaDoc name, int updateMask) {
209             super(name, updateMask);
210         }
211         
212         protected Class JavaDoc getShortDescriptionBundleClass() {
213             return BaseKit.class;
214         }
215         
216     }
217
218     /** Called before the popup menu is shown to possibly rebuild
219     * the popup menu.
220     */

221     public static class BuildPopupMenuAction extends BaseKitLocalizedAction {
222
223         static final long serialVersionUID =4257043398248915291L;
224
225         public BuildPopupMenuAction() {
226             super(buildPopupMenuAction, NO_RECORDING);
227             putValue(BaseAction.NO_KEYBINDING, Boolean.TRUE);
228         }
229
230         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
231             if (target != null) {
232                 if (debugPopupMenu) {
233                     /*DEBUG*/System.err.println("POPUP CREATION START <<<<<"); // NOI18N
234
}
235                 JPopupMenu JavaDoc pm = buildPopupMenu(target);
236                 if (debugPopupMenu) {
237                     /*DEBUG*/System.err.println("POPUP CREATION END >>>>>"); // NOI18N
238
}
239                 ExtUtilities.getExtEditorUI(target).setPopupMenu(pm);
240             }
241         }
242         
243         protected JPopupMenu JavaDoc createPopupMenu(JTextComponent JavaDoc target) {
244             return new JPopupMenu JavaDoc();
245         }
246
247         protected JPopupMenu JavaDoc buildPopupMenu(JTextComponent JavaDoc target) {
248             JPopupMenu JavaDoc pm = createPopupMenu(target);
249
250             EditorUI ui = Utilities.getEditorUI(target);
251             List JavaDoc l = (List JavaDoc)Settings.getValue(Utilities.getKitClass(target),
252                 (ui == null || ui.hasExtComponent())
253                     ? ExtSettingsNames.POPUP_MENU_ACTION_NAME_LIST
254                     : ExtSettingsNames.DIALOG_POPUP_MENU_ACTION_NAME_LIST
255             );
256
257             if (l != null) {
258                 Iterator JavaDoc i = l.iterator();
259                 while (i.hasNext()) {
260                     String JavaDoc an = (String JavaDoc)i.next();
261                     addAction(target, pm, an);
262                 }
263             }
264             return pm;
265         }
266
267         /** Add the action to the popup menu. This method is called
268          * for each action-name found in the action-name-list. It should
269          * add the appopriate menu item to the popup menu.
270          * @param target target component for which the menu is being
271          * constructed.
272          * @param popupMenu popup menu to which this method should add
273          * the item corresponding to the action-name.
274          * @param actionName name of the action to add. The real action
275          * can be retrieved from the kit by calling <tt>getActionByName()</tt>.
276          */

277         protected void addAction(JTextComponent JavaDoc target, JPopupMenu JavaDoc popupMenu,
278         String JavaDoc actionName) {
279             Action JavaDoc a = Utilities.getKit(target).getActionByName(actionName);
280             if (a != null) {
281                 JMenuItem JavaDoc item = null;
282                 if (a instanceof BaseAction) {
283                     item = ((BaseAction)a).getPopupMenuItem(target);
284                 }
285                 if (item == null) {
286                     String JavaDoc itemText = getItemText(target, actionName, a);
287                     if (itemText != null) {
288                         item = new JMenuItem JavaDoc(itemText);
289                         item.addActionListener(a);
290                         // Try to get the accelerator
291
Keymap JavaDoc km = target.getKeymap();
292                         if (km != null) {
293                             KeyStroke JavaDoc[] keys = km.getKeyStrokesForAction(a);
294                             if (keys != null && keys.length > 0) {
295                                 item.setAccelerator(keys[0]);
296                             }
297                         }
298                         item.setEnabled(a.isEnabled());
299                         Object JavaDoc helpID = a.getValue ("helpID"); // NOI18N
300
if (helpID != null && (helpID instanceof String JavaDoc))
301                             item.putClientProperty ("HelpID", helpID); // NOI18N
302
}
303                 }
304
305                 if (item != null) {
306                     debugPopupMenuItem(item, a);
307                     popupMenu.add(item);
308                 }
309
310             } else if (actionName == null){ // action-name is null, add the separator
311
if (popupMenu.getComponentCount()>0){
312                     debugPopupMenuItem(null, null);
313                     popupMenu.addSeparator();
314                 }
315             }
316         }
317         
318         protected final void debugPopupMenuItem(JMenuItem JavaDoc item, Action JavaDoc action) {
319             if (debugPopupMenu) {
320                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc("POPUP: "); // NOI18N
321
if (item != null) {
322                     sb.append('"');
323                     sb.append(item.getText());
324                     sb.append('"');;
325                     if (!item.isVisible()) {
326                         sb.append(", INVISIBLE"); // NOI18N
327
}
328                     if (action != null) {
329                         sb.append(", action="); // NOI18N
330
sb.append(action.getClass().getName());
331                     }
332                     
333                 } else { // null item means separator
334
sb.append("--Separator--"); // NOI18N
335
}
336
337                 /*DEBUG*/System.err.println(sb.toString());
338             }
339
340         }
341
342         protected String JavaDoc getItemText(JTextComponent JavaDoc target, String JavaDoc actionName, Action JavaDoc a) {
343             String JavaDoc itemText;
344             if (a instanceof BaseAction) {
345                 itemText = ((BaseAction)a).getPopupMenuText(target);
346             } else {
347                 itemText = actionName;
348             }
349             return itemText;
350         }
351
352     }
353
354     /** Show the popup menu.
355     */

356     public static class ShowPopupMenuAction extends BaseKitLocalizedAction {
357
358         static final long serialVersionUID =4257043398248915291L;
359
360         public ShowPopupMenuAction() {
361             super(showPopupMenuAction, NO_RECORDING);
362         }
363
364         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
365             if (target != null) {
366                 try {
367                     int dotPos = target.getCaret().getDot();
368                     Rectangle JavaDoc r = target.getUI().modelToView(target, dotPos);
369                     if (r != null) {
370                         ExtEditorUI eui = ExtUtilities.getExtEditorUI(target);
371                         if (eui != null){
372                             eui.showPopupMenu(r.x, r.y + r.height);
373                         }
374                     }
375                 } catch (BadLocationException JavaDoc e) {
376                     target.getToolkit().beep();
377                 }
378             }
379         }
380
381     }
382
383     public static class BuildToolTipAction extends BaseAction {
384
385         static final long serialVersionUID =-2701131863705941250L;
386
387         public BuildToolTipAction() {
388             super(buildToolTipAction, NO_RECORDING);
389             putValue(BaseAction.NO_KEYBINDING, Boolean.TRUE);
390             putValue(Action.SHORT_DESCRIPTION, ""); // No explicit description NOI18N
391
}
392
393         protected String JavaDoc buildText(JTextComponent JavaDoc target) {
394             ToolTipSupport tts = ExtUtilities.getExtEditorUI(target).getToolTipSupport();
395             return (tts != null)
396                 ? target.getToolTipText(tts.getLastMouseEvent())
397                 : target.getToolTipText();
398         }
399
400         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
401             if (target != null) {
402                 ToolTipSupport tts = ExtUtilities.getExtEditorUI(target).getToolTipSupport();
403                 if (tts != null) {
404                     tts.setToolTipText(buildText(target));
405                 }
406             }
407         }
408
409     }
410
411     public static class FindAction extends BaseKitLocalizedAction {
412
413         static final long serialVersionUID =719554648887497427L;
414
415         public FindAction() {
416             super(findAction, ABBREV_RESET
417                   | MAGIC_POSITION_RESET | UNDO_MERGE_RESET | NO_RECORDING);
418             putValue(BaseAction.ICON_RESOURCE_PROPERTY,
419                     "org/netbeans/modules/editor/resources/find"); //NOI18N
420
}
421
422         public FindDialogSupport getSupport() {
423             return FindDialogSupport.getFindDialogSupport();
424         }
425
426         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
427             if (target != null) {
428                 getSupport().showFindDialog(new KeyEventBlocker(target, false));
429             }
430         }
431
432     }
433
434     public static class ReplaceAction extends BaseKitLocalizedAction {
435
436         static final long serialVersionUID =1828017436079834384L;
437
438         public ReplaceAction() {
439             super(replaceAction, ABBREV_RESET
440                   | MAGIC_POSITION_RESET | UNDO_MERGE_RESET | NO_RECORDING);
441         }
442
443         public FindDialogSupport getSupport() {
444             return FindDialogSupport.getFindDialogSupport();
445         }
446
447         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
448             if (target != null) {
449                 // make KeyEventBlocker to discard the first key typed event (Ctrl-H)
450
// because it is mapped to backspace in the replace dialog
451
getSupport().showReplaceDialog(new KeyEventBlocker(target, true));
452             }
453         }
454
455     }
456
457     public static class GotoAction extends BaseKitLocalizedAction {
458
459         static final long serialVersionUID =8425585413146373256L;
460
461         public GotoAction() {
462             super(gotoAction, ABBREV_RESET
463                   | MAGIC_POSITION_RESET | UNDO_MERGE_RESET);
464             String JavaDoc name = NbBundle.getBundle(BaseKit.class).getString("goto_trimmed");
465             putValue(TRIMMED_TEXT, name);
466             putValue(POPUP_MENU_TEXT, name);
467         }
468
469
470         /** This method is called by the dialog support
471         * to translate the line offset to the document position. This
472         * can be changed for example for the diff operations.
473         * @param doc document to operate over
474         * @param lineOffset the line offset to convert to position
475         * @return document offset that corresponds to the row-start
476         * of the line with the line-number equal to (lineOffset + 1).
477         */

478         protected int getOffsetFromLine(BaseDocument doc, int lineOffset) {
479             return Utilities.getRowStartFromLineOffset(doc, lineOffset);
480         }
481
482         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
483             if (target != null) {
484                 new GotoDialogSupport().showGotoDialog(new KeyEventBlocker(target, false));
485             }
486         }
487
488     }
489
490     /** Action to go to the declaration of the variable under the caret.
491     */

492     public static class GotoDeclarationAction extends BaseKitLocalizedAction {
493
494         static final long serialVersionUID =-6440495023918097760L;
495
496         public GotoDeclarationAction() {
497             super(gotoDeclarationAction,
498                   ABBREV_RESET | MAGIC_POSITION_RESET | UNDO_MERGE_RESET
499                   | SAVE_POSITION
500                  );
501             String JavaDoc name = NbBundle.getBundle(BaseKit.class).getString("goto-declaration-trimmed");
502             putValue(TRIMMED_TEXT, name); //NOI18N
503
putValue(POPUP_MENU_TEXT, name); //NOI18N
504
}
505
506         public boolean gotoDeclaration(JTextComponent JavaDoc target) {
507             try {
508                 Caret JavaDoc caret = target.getCaret();
509                 int dotPos = caret.getDot();
510                 BaseDocument doc = (BaseDocument)target.getDocument();
511                 int[] idBlk = Utilities.getIdentifierBlock(doc, dotPos);
512                 ExtSyntaxSupport extSup = (ExtSyntaxSupport)doc.getSyntaxSupport();
513                 if (idBlk != null) {
514                     int decPos = extSup.findDeclarationPosition(doc.getText(idBlk), idBlk[1]);
515                     if (decPos >= 0) {
516                         caret.setDot(decPos);
517                         return true;
518                     }
519                 }
520             } catch (BadLocationException JavaDoc e) {
521             }
522             return false;
523         }
524
525         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
526             if (target != null) {
527                 gotoDeclaration(target); // try to go to the declaration position
528
}
529         }
530     }
531
532     public static class ToggleCaseIdentifierBeginAction extends BaseKitLocalizedAction {
533
534         static final long serialVersionUID =584392193824931979L;
535
536         ToggleCaseIdentifierBeginAction() {
537             super(toggleCaseIdentifierBeginAction, ABBREV_RESET
538                   | MAGIC_POSITION_RESET | UNDO_MERGE_RESET | WORD_MATCH_RESET);
539         }
540
541         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
542             if (target != null) {
543                 if (!target.isEditable() || !target.isEnabled()) {
544                     target.getToolkit().beep();
545                     return;
546                 }
547
548                 try {
549                     Caret JavaDoc caret = target.getCaret();
550                     BaseDocument doc = (BaseDocument)target.getDocument();
551                     int[] idBlk = Utilities.getIdentifierBlock(doc, caret.getDot());
552                     if (idBlk != null) {
553                         Utilities.changeCase(doc, idBlk[0], 1, Utilities.CASE_SWITCH);
554                     }
555                 } catch (BadLocationException JavaDoc e) {
556                     target.getToolkit().beep();
557                 }
558             }
559         }
560     }
561
562     public static class MatchBraceAction extends BaseKitLocalizedAction {
563
564         boolean select;
565
566         static final long serialVersionUID =-184887499045886231L;
567
568         public MatchBraceAction(String JavaDoc name, boolean select) {
569             super(name, ABBREV_RESET
570                   | MAGIC_POSITION_RESET | UNDO_MERGE_RESET);
571             this.select = select;
572         }
573
574         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
575             if (target != null) {
576                 try {
577                     Caret JavaDoc caret = target.getCaret();
578                     BaseDocument doc = Utilities.getDocument(target);
579                     int dotPos = caret.getDot();
580                     ExtSyntaxSupport sup = (ExtSyntaxSupport)doc.getSyntaxSupport();
581                     if (dotPos > 0) {
582                         int[] matchBlk = sup.findMatchingBlock(dotPos - 1, false);
583                         if (matchBlk != null) {
584                             if (select) {
585                                 caret.moveDot(matchBlk[1]);
586                             } else {
587                                 caret.setDot(matchBlk[1]);
588                             }
589                         }
590                     }
591                 } catch (BadLocationException JavaDoc e) {
592                     target.getToolkit().beep();
593                 }
594             }
595         }
596     }
597
598     /**
599      * @deprecated this action is deprecated and will be removed in future releases.
600      */

601     public static class CodeSelectAction extends BaseKitLocalizedAction {
602
603         static final long serialVersionUID =4033474080778585860L;
604
605         public CodeSelectAction() {
606             super(codeSelectAction);
607         }
608
609         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
610 /* if (target != null) {
611                 BaseDocument doc = (BaseDocument)target.getDocument();
612                 SyntaxSupport sup = doc.getSyntaxSupport();
613                 Caret caret = target.getCaret();
614                 try {
615                     int bracketPos = sup.findUnmatchedBracket(caret.getDot(), sup.getRightBrackets());
616                     if (bracketPos >= 0) {
617                         caret.setDot(bracketPos);
618                         while (true) {
619                           int bolPos = Utilities.getRowStart(doc, bracketPos);
620                           boolean isWSC = sup.isCommentOrWhitespace(bolPos, bracketPos);
621                           if (isWSC) { // get previous line end
622                             
623                           }
624                         }
625                     }
626                 } catch (BadLocationException e) {
627                     target.getToolkit().beep();
628                 }
629             }
630 */

631         }
632     }
633
634     /** Prefix maker adds the prefix before the identifier under cursor.
635     * The prefix is not added if it's already present. The prefix to be
636     * added is specified in the constructor of the action together
637     * with the prefix group. If there's already any prefix from the prefix
638     * group at the begining of the identifier, that prefix is replaced
639     * by the actual prefix.
640     */

641     public static class PrefixMakerAction extends BaseKitLocalizedAction {
642
643         static final long serialVersionUID =-2305157963664484920L;
644
645         private String JavaDoc prefix;
646
647         private String JavaDoc[] prefixGroup;
648
649         public PrefixMakerAction(String JavaDoc name, String JavaDoc prefix, String JavaDoc[] prefixGroup) {
650             super(name);
651             this.prefix = prefix;
652             this.prefixGroup = prefixGroup;
653             
654             // [PENDING] This should be done in a better way
655
String JavaDoc iconRes = null;
656             if ("get".equals(prefix)) { // NOI18N
657
iconRes = "org/netbeans/modules/editor/resources/var_get.gif"; // NOI18N
658
} else if ("set".equals(prefix)) { // NOI18N
659
iconRes = "org/netbeans/modules/editor/resources/var_set.gif"; // NOI18N
660
} else if ("is".equals(prefix)) { // NOI18N
661
iconRes = "org/netbeans/modules/editor/resources/var_is.gif"; // NOI18N
662
}
663             if (iconRes != null) {
664                 putValue(BaseAction.ICON_RESOURCE_PROPERTY, iconRes);
665             }
666         }
667
668         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
669             if (target != null) {
670                 if (!target.isEditable() || !target.isEnabled()) {
671                     target.getToolkit().beep();
672                     return;
673                 }
674
675                 BaseDocument doc = (BaseDocument)target.getDocument();
676                 int dotPos = target.getCaret().getDot();
677                 try {
678                     // look for identifier around caret
679
int[] block = org.netbeans.editor.Utilities.getIdentifierBlock(doc, dotPos);
680
681                     // If there is no identifier around, warn user
682
if (block == null) {
683                         target.getToolkit().beep();
684                         return;
685                     }
686
687                     // Get the identifier to operate on
688
CharSequence JavaDoc identifier = DocumentUtilities.getText(doc, block[0], block[1] - block[0]);
689
690                     // Handle the case we already have the work done - e.g. if we got called over 'getValue'
691
if (CharSequenceUtilities.startsWith(identifier, prefix) &&
692                             Character.isUpperCase(identifier.charAt(prefix.length()))) return;
693
694                     // Handle the case we have other type of known xEr: eg isRunning -> getRunning
695
for (int i=0; i<prefixGroup.length; i++) {
696                         String JavaDoc actPref = prefixGroup[i];
697                         if (CharSequenceUtilities.startsWith(identifier, actPref)
698                                 && identifier.length() > actPref.length()
699                                 && Character.isUpperCase(identifier.charAt(actPref.length()))
700                            ) {
701                             doc.remove(block[0], actPref.length());
702                             doc.insertString(block[0], prefix, null);
703                             return;
704                         }
705                     }
706
707                     // Upcase the first letter
708
Utilities.changeCase(doc, block[0], 1, Utilities.CASE_UPPER);
709                     // Prepend the prefix before it
710
doc.insertString(block[0], prefix, null);
711                 } catch (BadLocationException JavaDoc e) {
712                     target.getToolkit().beep();
713                 }
714             }
715         }
716     }
717
718     public static class CommentAction extends BaseKitLocalizedAction {
719
720         static final long serialVersionUID =-1422954906554289179L;
721
722         private String JavaDoc lineCommentString;
723
724         public CommentAction(String JavaDoc lineCommentString) {
725             super(commentAction);
726             this.lineCommentString = lineCommentString;
727             putValue(BaseAction.ICON_RESOURCE_PROPERTY,
728                 "org/netbeans/modules/editor/resources/comment.png"); // NOI18N
729
}
730
731         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
732             if (target != null) {
733                 if (!target.isEditable() || !target.isEnabled()) {
734                     target.getToolkit().beep();
735                     return;
736                 }
737                 Caret JavaDoc caret = target.getCaret();
738                 BaseDocument doc = (BaseDocument)target.getDocument();
739                 try {
740                     if (caret.isSelectionVisible()) {
741                         int startPos = Utilities.getRowStart(doc, target.getSelectionStart());
742                         int endPos = target.getSelectionEnd();
743                         doc.atomicLock();
744                         try {
745
746                             if (endPos > 0 && Utilities.getRowStart(doc, endPos) == endPos) {
747                                 endPos--;
748                             }
749
750                             int pos = startPos;
751                             for (int lineCnt = Utilities.getRowCount(doc, startPos, endPos);
752                                     lineCnt > 0; lineCnt--
753                                 ) {
754                                 doc.insertString(pos, lineCommentString, null); // NOI18N
755
pos = Utilities.getRowStart(doc, pos, +1);
756                             }
757                         } finally {
758                             doc.atomicUnlock();
759                         }
760                     } else { // selection not visible
761
doc.insertString(Utilities.getRowStart(doc, target.getSelectionStart()),
762                                          lineCommentString, null); // NOI18N
763
}
764                 } catch (BadLocationException JavaDoc e) {
765                     target.getToolkit().beep();
766                 }
767             }
768         }
769     }
770
771     public static class UncommentAction extends BaseKitLocalizedAction {
772
773         static final long serialVersionUID =-7005758666529862034L;
774
775         private String JavaDoc lineCommentString;
776
777         public UncommentAction(String JavaDoc lineCommentString) {
778             super(uncommentAction);
779             this.lineCommentString = lineCommentString;
780             putValue(BaseAction.ICON_RESOURCE_PROPERTY,
781                 "org/netbeans/modules/editor/resources/uncomment.png"); // NOI18N
782
}
783
784         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
785             if (target != null) {
786                 if (!target.isEditable() || !target.isEnabled()) {
787                     target.getToolkit().beep();
788                     return;
789                 }
790                 Caret JavaDoc caret = target.getCaret();
791                 BaseDocument doc = (BaseDocument)target.getDocument();
792                 int commentLen = lineCommentString.length();
793                 try {
794                     doc.atomicLock();
795                     try {
796                         int startPos = target.getSelectionStart();
797                         int endPos = target.getSelectionEnd();
798                         
799                         for (int pos = startPos, lineCnt = Utilities.getRowCount(doc, startPos, endPos); lineCnt > 0; lineCnt--) {
800                             // Get the first non-whitespace char on the current line
801
int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, pos);
802
803                             // If there is any, check wheter it's the line-comment-chars and remove them
804
if (firstNonWhitePos != -1) {
805                                 if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= commentLen) {
806                                     CharSequence JavaDoc maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, commentLen);
807                                     if (CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
808                                         doc.remove(firstNonWhitePos, commentLen);
809                                     }
810                                 }
811                             }
812                             
813                             pos = Utilities.getRowStart(doc, pos, +1);
814                         }
815                     } finally {
816                         doc.atomicUnlock();
817                     }
818                 } catch (BadLocationException JavaDoc e) {
819                     target.getToolkit().beep();
820                 }
821             }
822         }
823     }
824
825
826
827     /** Executed when the Escape key is pressed. By default it hides
828     * the popup menu if visible.
829     */

830     public static class EscapeAction extends BaseKitLocalizedAction {
831
832         public EscapeAction() {
833             super(escapeAction);
834         }
835
836         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
837             if (target != null) {
838                 ExtUtilities.getExtEditorUI(target).hidePopupMenu();
839             }
840         }
841     }
842
843
844     // Completion customized actions
845
public static class ExtDefaultKeyTypedAction extends DefaultKeyTypedAction {
846
847         static final long serialVersionUID =5273032708909044812L;
848
849         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
850             String JavaDoc cmd = evt.getActionCommand();
851             int mod = evt.getModifiers();
852
853             // Dirty fix for Completion shortcut on Unix !!!
854
if (cmd != null && cmd.equals(" ") && (mod == ActionEvent.CTRL_MASK)) { // NOI18N
855
// Ctrl + SPACE
856
} else {
857                 Caret JavaDoc caret = target.getCaret();
858                 if (caret instanceof ExtCaret) {
859                     ((ExtCaret)caret).requestMatchBraceUpdateSync(); // synced bracket update
860
}
861                 super.actionPerformed(evt, target);
862             }
863
864             if ((target != null) && (evt != null)) {
865                 if ((cmd != null) && (cmd.length() == 1) &&
866                         ((mod & ActionEvent.ALT_MASK) == 0
867                          && (mod & ActionEvent.CTRL_MASK) == 0)
868                    ) {
869                     // Check whether char that should reindent the line was inserted
870
checkIndentHotChars(target, cmd);
871
872                     // Check the completion
873
checkCompletion(target, cmd);
874                 }
875             }
876         }
877
878         /** Check the characters that should cause reindenting the line. */
879         protected void checkIndentHotChars(JTextComponent JavaDoc target, String JavaDoc typedText) {
880             BaseDocument doc = Utilities.getDocument(target);
881             if (doc != null) {
882                 Caret JavaDoc caret = target.getCaret();
883                 Formatter f = doc.getFormatter();
884                 if (f instanceof ExtFormatter) {
885                     ExtFormatter ef = (ExtFormatter)f;
886                     int[] fmtBlk = ef.getReformatBlock(target, typedText);
887
888                     if (fmtBlk != null) {
889                         try {
890                             fmtBlk[0] = Utilities.getRowStart(doc, fmtBlk[0]);
891                             fmtBlk[1] = Utilities.getRowEnd(doc, fmtBlk[1]);
892
893                             //this was the of #18922, that causes the bug #20198
894
//ef.reformat(doc, fmtBlk[0], fmtBlk[1]);
895

896                             //bugfix of the bug #20198. Bug #18922 is fixed too as well as #6968
897
ef.reformat(doc, fmtBlk[0], fmtBlk[1], true);
898                             
899                         } catch (BadLocationException JavaDoc e) {
900                         } catch (IOException JavaDoc e) {
901                         }
902                     }
903                 }
904             }
905         }
906
907
908         /** Check and possibly popup, hide or refresh the completion */
909         protected void checkCompletion(JTextComponent JavaDoc target, String JavaDoc typedText) {
910             Completion completion = ExtUtilities.getCompletion(target);
911
912             BaseDocument doc = (BaseDocument)target.getDocument();
913             ExtSyntaxSupport extSup = (ExtSyntaxSupport)doc.getSyntaxSupport();
914             
915             if (completion != null && typedText.length() > 0) {
916                 if( !completion.isPaneVisible() ) {
917                     if (completion.isAutoPopupEnabled()) {
918                         int result = extSup.checkCompletion( target, typedText, false );
919                         if ( result == ExtSyntaxSupport.COMPLETION_POPUP ) {
920                             completion.popup(true);
921                         } else if ( result == ExtSyntaxSupport.COMPLETION_CANCEL ) {
922                             completion.cancelRequest();
923                         }
924                     }
925                 } else {
926                     int result = extSup.checkCompletion( target, typedText, true );
927                     switch( result ) {
928                         case ExtSyntaxSupport.COMPLETION_HIDE:
929                             completion.setPaneVisible(false);
930                             break;
931                         case ExtSyntaxSupport.COMPLETION_REFRESH:
932                             completion.refresh(false);
933                             break;
934                         case ExtSyntaxSupport.COMPLETION_POST_REFRESH:
935                             completion.refresh(true);
936                             break;
937                     }
938                 }
939             }
940         }
941     }
942
943     public static class CompletionShowAction extends BaseKitLocalizedAction {
944
945         static final long serialVersionUID =1050644925893851146L;
946
947         public CompletionShowAction() {
948             super(completionShowAction);
949         }
950
951         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
952         }
953
954     }
955
956     public static class AllCompletionShowAction extends BaseKitLocalizedAction {
957
958         public AllCompletionShowAction() {
959             super(allCompletionShowAction);
960         }
961
962         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
963         }
964
965     }
966
967     public static class DocumentationShowAction extends BaseKitLocalizedAction {
968
969         public DocumentationShowAction() {
970             super(documentationShowAction);
971         }
972
973         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
974         }
975
976     }
977
978     public static class CompletionTooltipShowAction extends BaseKitLocalizedAction {
979
980         public CompletionTooltipShowAction() {
981             super(completionTooltipShowAction);
982         }
983
984         public void actionPerformed(ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
985         }
986
987     }
988
989   public static class ExtDeleteCharAction extends DeleteCharAction {
990
991     public ExtDeleteCharAction(String JavaDoc nm, boolean nextChar) {
992       super(nm, nextChar);
993     }
994     
995   }
996
997
998 }
999
Popular Tags