KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > i18n > InsertI18nStringAction


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
21 package org.netbeans.modules.i18n;
22
23
24 import java.awt.Dialog JavaDoc;
25 import java.io.IOException JavaDoc;
26 import javax.swing.JEditorPane JavaDoc;
27 import javax.swing.JPanel JavaDoc;
28 import javax.swing.text.BadLocationException JavaDoc;
29 import javax.swing.text.Position JavaDoc;
30 import org.openide.DialogDescriptor;
31 import org.openide.ErrorManager;
32
33 import org.openide.cookies.EditorCookie;
34 import org.openide.nodes.Node;
35 import org.openide.NotifyDescriptor;
36 import org.openide.DialogDisplayer;
37 import org.openide.loaders.DataObject;
38 import org.openide.text.NbDocument;
39 import org.openide.util.HelpCtx;
40 import org.openide.util.actions.CookieAction;
41 import org.netbeans.api.project.FileOwnerQuery;
42
43
44 /**
45  * Insert internationalized string at caret position (if it is not in guarded block).
46  * <p>
47  * Backported from <tt>prj40_prototype</tt> branch.
48  *
49  * @author Petr Jiricka, Peter Zavadsky
50  */

51 public class InsertI18nStringAction extends CookieAction {
52
53     /** Generated serial version UID. */
54     static final long serialVersionUID =-7002111874047983222L;
55
56     // lifetime performAction:
57

58     // Position where to insert the new i18n-string.
59
private transient Position JavaDoc position;
60
61     private transient I18nSupport support;
62
63     private transient I18nPanel i18nPanel;
64
65     private transient DataObject dataObject;
66
67     public InsertI18nStringAction() {
68         putValue("noIconInMenu", Boolean.TRUE);
69     }
70     
71     /**
72      * Open I18nPanel and grab user response then update Document.
73      * @param activatedNodes currently activated nodes
74      */

75     protected void performAction (final Node[] activatedNodes) {
76         try {
77             final EditorCookie editorCookie = (EditorCookie)(activatedNodes[0]).getCookie(EditorCookie.class);
78             if (editorCookie == null) {
79                 Util.debug(new IllegalArgumentException JavaDoc("Missing editor cookie!")); // NOI18N
80
return;
81             }
82
83             // Set data object.
84
dataObject = (DataObject)activatedNodes[0].getCookie(DataObject.class);
85             if (dataObject == null) {
86                 Util.debug(new IllegalArgumentException JavaDoc("Missing DataObject!")); // NOI18N
87
return;
88             }
89
90             JEditorPane JavaDoc[] panes = editorCookie.getOpenedPanes();
91
92             if (panes == null || panes.length == 0) {
93                 //??? should it be tools action at all, once launched
94
// from node it may raise this exception or it inserts
95
// string in latest caret position in possibly hidden source
96
Util.debug(new IllegalArgumentException JavaDoc("Missing editor pane!")); // NOI18N
97
return;
98             }
99
100             // Set insert position.
101
position = NbDocument.createPosition(panes[0].getDocument(), panes[0].getCaret().getDot(), Position.Bias.Backward);
102
103             // If there is a i18n action in run on the same editor, cancel it.
104
I18nManager.getDefault().cancel();
105
106             try {
107                 showModalPanel();
108             } catch(IOException JavaDoc ex) {
109                 String JavaDoc msg = "Document loading failure " + dataObject.getName(); // NOI18N
110
Util.debug(msg, ex);
111                 return;
112             }
113
114             // Ensure caret is visible.
115
panes[0].getCaret().setVisible(true);
116         } catch (BadLocationException JavaDoc blex) {
117             ErrorManager.getDefault().notify(blex);
118         } finally {
119             dataObject = null;
120             support = null;
121             i18nPanel = null;
122             position = null;
123         }
124     }
125
126
127     /**
128      * Implementation
129      */

130     private void insertI18nString() {
131         try {
132             I18nString i18nString = i18nPanel.getI18nString();
133
134             if(i18nString.key == null) {
135                 return;
136             }
137
138             // Try to add key to bundle.
139
support.getResourceHolder().addProperty(
140                 i18nString.getKey(),
141                 i18nString.getValue(),
142                 i18nString.getComment()
143             );
144
145             // Create field if necessary.
146
// PENDING, should not be performed here -> capability moves to i18n wizard.
147
if(support.hasAdditionalCustomizer())
148                 support.performAdditionalChanges();
149
150             // Replace string.
151
String JavaDoc code = i18nString.getReplaceString();
152             support.getDocument().insertString(position.getOffset(), code, null);
153
154         } catch (IllegalStateException JavaDoc e) {
155             NotifyDescriptor.Message msg = new NotifyDescriptor.Message(
156                 I18nUtil.getBundle().getString("EXC_BadKey"),
157                 NotifyDescriptor.ERROR_MESSAGE);
158             DialogDisplayer.getDefault().notify(msg);
159         } catch (BadLocationException JavaDoc e) {
160             DialogDisplayer.getDefault().notify(
161                 new NotifyDescriptor.Message(
162                     I18nUtil.getBundle().getString("MSG_CantInsertInGuarded"),
163                     NotifyDescriptor.INFORMATION_MESSAGE
164                 )
165             );
166         }
167     }
168
169
170     /**
171      * Create panel used for specifying i18n string.
172      */

173     private JPanel JavaDoc createPanel() throws IOException JavaDoc {
174         I18nSupport.Factory factory = FactoryRegistry.getFactory(dataObject.getClass());
175
176         if(factory == null)
177             throw new IllegalStateException JavaDoc("I18N: No factory registered for data object type="+dataObject.getClass().getName()); // NOI18N
178

179         support = factory.create(dataObject);
180
181         //If you decide for caching impl it must be invalidated on
182
//dataobject and document instabce change and update properties keys regularly.
183

184         i18nPanel = new I18nPanel(support.getPropertyPanel(), false, Util.getProjectFor(dataObject), dataObject.getPrimaryFile());
185         i18nPanel.setI18nString(support.getDefaultI18nString());
186         i18nPanel.setDefaultResource(dataObject);
187
188         return i18nPanel;
189     }
190
191
192     /**
193      * Basically I18nPanel wrapped by Ok, Cancel and Help buttons shown.
194      * Handles OK button.
195      */

196     private void showModalPanel() throws IOException JavaDoc {
197         DialogDescriptor dd = new DialogDescriptor(
198             createPanel(),
199             Util.getString("CTL_InsertI18nDialogTitle"),
200             true,
201             NotifyDescriptor.OK_CANCEL_OPTION,
202             NotifyDescriptor.OK_OPTION,
203             DialogDescriptor.DEFAULT_ALIGN,
204             new HelpCtx(InsertI18nStringAction.class),
205             null
206         );
207         Dialog JavaDoc dialog = DialogDisplayer.getDefault().createDialog(dd);
208         dialog.setVisible(true);
209         if (dd.getValue() == NotifyDescriptor.OK_OPTION) {
210             insertI18nString();
211         }
212     }
213
214
215     /** Overrides superclass method. Adds additional test if i18n module has registered factory
216      * for this data object to be able to perform i18n action. */

217     protected boolean enable(Node[] activatedNodes) {
218         if (!super.enable(activatedNodes)) return false;
219
220         // if has an open editor pane must not be in a guarded block
221
// PENDING>>
222
// It causes StackOverflowError
223
// I18nSupport.isGuardedPosittion() checks teh way it causes change cookies (remove add SaveCookie), what
224
// in turn calls back enable method, it calls isGuardedPosition again etc. etc.
225
/*final SourceCookie.Editor sec = (SourceCookie.Editor)(activatedNodes[0]).getCookie(SourceCookie.Editor.class);
226         if (sec != null) {
227             JEditorPane[] edits = sec.getOpenedPanes();
228             if (edits != null && edits.length > 0) {
229                 int position = edits[0].getCaret().getDot();
230                 StyledDocument doc = sec.getDocument();
231                 DataObject obj = (DataObject)sec.getSource().getCookie(DataObject.class);
232                 if(I18nSupport.getI18nSupport(doc, obj).isGuardedPosition(position))
233                     return false;
234             }
235         }*/

236         // PENDING<<
237

238         DataObject dataObject = (DataObject)activatedNodes[0].getCookie(DataObject.class);
239
240         if (dataObject == null) return false;
241
242     // check that the node has project
243
if (FileOwnerQuery.getOwner(dataObject.getPrimaryFile()) == null) return false;
244
245         if (FactoryRegistry.hasFactory(dataObject.getClass()) == false) return false;
246
247         EditorCookie sec = (EditorCookie)(activatedNodes[0]).getCookie(EditorCookie.class);
248         if (sec == null) return false;
249
250         JEditorPane JavaDoc[] edits = sec.getOpenedPanes();
251         return edits != null && edits.length > 0;
252     }
253
254     /** Implements superclass abstract method.
255      * @return MODE_EXACTLY_ONE.
256      */

257     protected int mode () {
258         return MODE_EXACTLY_ONE;
259     }
260
261     /** Implemenst superclass abstract method.
262      * @return <code>EditorCookie<code>.class
263      * #see org.openide.cookies.EditorCookie */

264     protected Class JavaDoc[] cookieClasses () {
265         return new Class JavaDoc [] {
266             EditorCookie.class,
267         };
268     }
269
270     /** Gets localized name of action. Overrides superclass method. */
271     public String JavaDoc getName() {
272         return I18nUtil.getBundle().getString("CTL_InsertI18nString");
273     }
274
275     /** Gets the action's help context. Implemenst superclass abstract method. */
276     public HelpCtx getHelpCtx() {
277         return new HelpCtx(I18nUtil.HELP_ID_MANINSERT);
278     }
279
280     protected boolean asynchronous() {
281       return false;
282     }
283 }
284
Popular Tags