KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > commands > CommandService


1 /*******************************************************************************
2  * Copyright (c) 2005, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ui.internal.commands;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Collection JavaDoc;
15 import java.util.Collections JavaDoc;
16 import java.util.HashMap JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.Map JavaDoc;
20
21 import org.eclipse.core.commands.Category;
22 import org.eclipse.core.commands.Command;
23 import org.eclipse.core.commands.CommandManager;
24 import org.eclipse.core.commands.IExecutionListener;
25 import org.eclipse.core.commands.IHandler;
26 import org.eclipse.core.commands.ParameterType;
27 import org.eclipse.core.commands.ParameterizedCommand;
28 import org.eclipse.core.commands.SerializationException;
29 import org.eclipse.core.commands.State;
30 import org.eclipse.core.commands.common.NotDefinedException;
31 import org.eclipse.core.runtime.ISafeRunnable;
32 import org.eclipse.core.runtime.SafeRunner;
33 import org.eclipse.jface.commands.PersistentState;
34 import org.eclipse.ui.commands.IElementReference;
35 import org.eclipse.ui.commands.IElementUpdater;
36 import org.eclipse.ui.commands.ICommandService;
37 import org.eclipse.ui.internal.WorkbenchPlugin;
38 import org.eclipse.ui.internal.util.PrefUtil;
39 import org.eclipse.ui.menus.UIElement;
40
41 /**
42  * <p>
43  * Provides services related to the command architecture within the workbench.
44  * This service can be used to access the set of commands and handlers.
45  * </p>
46  *
47  * @since 3.1
48  */

49 public final class CommandService implements ICommandService {
50
51     /**
52      * The preference key prefix for all handler state.
53      */

54     private static final String JavaDoc PREFERENCE_KEY_PREFIX = "org.eclipse.ui.commands/state"; //$NON-NLS-1$
55

56     /**
57      * Creates a preference key for the given piece of state on the given
58      * command.
59      *
60      * @param command
61      * The command for which the preference key should be created;
62      * must not be <code>null</code>.
63      * @param stateId
64      * The identifier of the state for which the preference key
65      * should be created; must not be <code>null</code>.
66      * @return A suitable preference key; never <code>null</code>.
67      */

68     static final String JavaDoc createPreferenceKey(final Command command,
69             final String JavaDoc stateId) {
70         return PREFERENCE_KEY_PREFIX + '/' + command.getId() + '/' + stateId;
71     }
72
73     /**
74      * The command manager that supports this service. This value is never
75      * <code>null</code>.
76      */

77     private final CommandManager commandManager;
78
79     /**
80      * The persistence class for this command service.
81      */

82     private final CommandPersistence commandPersistence;
83
84     /**
85      * Constructs a new instance of <code>CommandService</code> using a
86      * command manager.
87      *
88      * @param commandManager
89      * The command manager to use; must not be <code>null</code>.
90      */

91     public CommandService(final CommandManager commandManager) {
92         if (commandManager == null) {
93             throw new NullPointerException JavaDoc(
94                     "Cannot create a command service with a null manager"); //$NON-NLS-1$
95
}
96         this.commandManager = commandManager;
97         this.commandPersistence = new CommandPersistence(this);
98     }
99
100     public final void addExecutionListener(final IExecutionListener listener) {
101         commandManager.addExecutionListener(listener);
102     }
103
104     public final void defineUncategorizedCategory(final String JavaDoc name,
105             final String JavaDoc description) {
106         commandManager.defineUncategorizedCategory(name, description);
107     }
108
109     public final ParameterizedCommand deserialize(
110             final String JavaDoc serializedParameterizedCommand)
111             throws NotDefinedException, SerializationException {
112         return commandManager.deserialize(serializedParameterizedCommand);
113     }
114
115     public final void dispose() {
116         commandPersistence.dispose();
117
118         /*
119          * All state on all commands neeeds to be disposed. This is so that the
120          * state has a chance to persist any changes.
121          */

122         final Command[] commands = commandManager.getAllCommands();
123         for (int i = 0; i < commands.length; i++) {
124             final Command command = commands[i];
125             final String JavaDoc[] stateIds = command.getStateIds();
126             for (int j = 0; j < stateIds.length; j++) {
127                 final String JavaDoc stateId = stateIds[j];
128                 final State state = command.getState(stateId);
129                 if (state instanceof PersistentState) {
130                     final PersistentState persistentState = (PersistentState) state;
131                     if (persistentState.shouldPersist()) {
132                         persistentState.save(PrefUtil
133                                 .getInternalPreferenceStore(),
134                                 createPreferenceKey(command, stateId));
135                     }
136                 }
137             }
138         }
139         commandCallbacks = null;
140     }
141
142     public final Category getCategory(final String JavaDoc categoryId) {
143         return commandManager.getCategory(categoryId);
144     }
145
146     public final Command getCommand(final String JavaDoc commandId) {
147         return commandManager.getCommand(commandId);
148     }
149
150     public final Category[] getDefinedCategories() {
151         return commandManager.getDefinedCategories();
152     }
153
154     public final Collection JavaDoc getDefinedCategoryIds() {
155         return commandManager.getDefinedCategoryIds();
156     }
157
158     public final Collection JavaDoc getDefinedCommandIds() {
159         return commandManager.getDefinedCommandIds();
160     }
161
162     public final Command[] getDefinedCommands() {
163         return commandManager.getDefinedCommands();
164     }
165
166     public Collection JavaDoc getDefinedParameterTypeIds() {
167         return commandManager.getDefinedParameterTypeIds();
168     }
169
170     public ParameterType[] getDefinedParameterTypes() {
171         return commandManager.getDefinedParameterTypes();
172     }
173
174     public final String JavaDoc getHelpContextId(final Command command)
175             throws NotDefinedException {
176         return commandManager.getHelpContextId(command);
177     }
178
179     public final String JavaDoc getHelpContextId(final String JavaDoc commandId)
180             throws NotDefinedException {
181         final Command command = getCommand(commandId);
182         return commandManager.getHelpContextId(command);
183     }
184
185     public ParameterType getParameterType(final String JavaDoc parameterTypeId) {
186         return commandManager.getParameterType(parameterTypeId);
187     }
188
189     public final void readRegistry() {
190         commandPersistence.read();
191     }
192
193     public final void removeExecutionListener(final IExecutionListener listener) {
194         commandManager.removeExecutionListener(listener);
195     }
196
197     public final void setHelpContextId(final IHandler handler,
198             final String JavaDoc helpContextId) {
199         commandManager.setHelpContextId(handler, helpContextId);
200     }
201
202     /**
203      * This is a map of commandIds to a list containing currently registered
204      * callbacks, in the form of ICallbackReferences.
205      */

206     private Map JavaDoc commandCallbacks = new HashMap JavaDoc();
207
208     /*
209      * (non-Javadoc)
210      *
211      * @see org.eclipse.ui.commands.ICommandService#refreshElements(java.lang.String,
212      * java.util.Map)
213      */

214     public final void refreshElements(String JavaDoc commandId, Map JavaDoc filter) {
215         Command cmd = getCommand(commandId);
216
217         if (!cmd.isDefined() || !(cmd.getHandler() instanceof IElementUpdater)) {
218             return;
219         }
220         final IElementUpdater updater = (IElementUpdater) cmd.getHandler();
221
222         if (commandCallbacks == null) {
223             return;
224         }
225
226         List JavaDoc callbackRefs = (List JavaDoc) commandCallbacks.get(commandId);
227         if (callbackRefs == null) {
228             return;
229         }
230
231         for (Iterator JavaDoc i = callbackRefs.iterator(); i.hasNext();) {
232             final IElementReference callbackRef = (IElementReference) i.next();
233             final Map JavaDoc parms = Collections.unmodifiableMap(callbackRef
234                     .getParameters());
235             ISafeRunnable run = new ISafeRunnable() {
236                 public void handleException(Throwable JavaDoc exception) {
237                     WorkbenchPlugin.log("Failed to update callback: " //$NON-NLS-1$
238
+ callbackRef.getCommandId(), exception);
239                 }
240
241                 public void run() throws Exception JavaDoc {
242                     updater.updateElement(callbackRef.getElement(), parms);
243                 }
244             };
245             if (filter == null) {
246                 SafeRunner.run(run);
247             } else {
248                 boolean match = true;
249                 for (Iterator JavaDoc j = filter.entrySet().iterator(); j.hasNext()
250                         && match;) {
251                     Map.Entry JavaDoc parmEntry = (Map.Entry JavaDoc) j.next();
252                     Object JavaDoc value = parms.get(parmEntry.getKey());
253                     if (!parmEntry.getValue().equals(value)) {
254                         match = false;
255                     }
256                 }
257                 if (match) {
258                     SafeRunner.run(run);
259                 }
260             }
261         }
262     }
263
264     /*
265      * (non-Javadoc)
266      *
267      * @see org.eclipse.ui.commands.ICommandService#registerElementForCommand(org.eclipse.core.commands.ParameterizedCommand,
268      * org.eclipse.ui.menus.UIElement)
269      */

270     public final IElementReference registerElementForCommand(
271             ParameterizedCommand command, UIElement element)
272             throws NotDefinedException {
273         if (!command.getCommand().isDefined()) {
274             throw new NotDefinedException(
275                     "Cannot define a callback for undefined command " //$NON-NLS-1$
276
+ command.getCommand().getId());
277         }
278         if (element == null) {
279             throw new NotDefinedException("No callback defined for command " //$NON-NLS-1$
280
+ command.getCommand().getId());
281         }
282
283         ElementReference ref = new ElementReference(command.getId(), element,
284                 command.getParameterMap());
285         registerElement(ref);
286         return ref;
287     }
288
289     /*
290      * (non-Javadoc)
291      *
292      * @see org.eclipse.ui.commands.ICommandService#registerElement(org.eclipse.ui.commands.IElementReference)
293      */

294     public void registerElement(IElementReference elementReference) {
295         List JavaDoc parameterizedCommands = (List JavaDoc) commandCallbacks
296                 .get(elementReference.getCommandId());
297         if (parameterizedCommands == null) {
298             parameterizedCommands = new ArrayList JavaDoc();
299             commandCallbacks.put(elementReference.getCommandId(),
300                     parameterizedCommands);
301         }
302         parameterizedCommands.add(elementReference);
303
304         // If the active handler wants to update the callback, it can do
305
// so now
306
Command command = getCommand(elementReference.getCommandId());
307         if (command.isDefined()) {
308             if (command.getHandler() instanceof IElementUpdater) {
309                 ((IElementUpdater) command.getHandler()).updateElement(
310                         elementReference.getElement(), elementReference
311                                 .getParameters());
312             }
313         }
314     }
315
316     /*
317      * (non-Javadoc)
318      *
319      * @see org.eclipse.ui.commands.ICommandService#unregisterElement(org.eclipse.ui.commands.IElementReference)
320      */

321     public void unregisterElement(IElementReference elementReference) {
322         List JavaDoc parameterizedCommands = (List JavaDoc) commandCallbacks
323                 .get(elementReference.getCommandId());
324         if (parameterizedCommands != null) {
325             parameterizedCommands.remove(elementReference);
326             if (parameterizedCommands.isEmpty()) {
327                 commandCallbacks.remove(elementReference.getCommandId());
328             }
329         }
330     }
331 }
332
Popular Tags