01: package fr.aliacom.commands;
02:
03: import java.util.ArrayList;
04: import java.util.HashMap;
05:
06: import org.apache.log4j.Logger;
07:
08: import fr.aliacom.form.common.FormContext;
09: import fr.aliacom.form.common.IForm;
10:
11: /**
12: * Ensures that PythonCommands running on the same formcontext (reference comparison)
13: * with the same script are the same objects.
14: *
15: * This is necessary to be able to disable a command from the menu and the
16: * toolbar at the same time.
17: *
18: * @author tom
19: *
20: * (C) 2001, 2003 Thomas Cataldo
21: */
22: public final class CommandPool {
23:
24: private static CommandPool singleton;
25:
26: static {
27: singleton = new CommandPool();
28: }
29:
30: private HashMap pool;
31: private Logger log;
32:
33: public static CommandPool getInstance() {
34: return singleton;
35: }
36:
37: private CommandPool() {
38: pool = new HashMap();
39: log = Logger.getLogger(getClass());
40: }
41:
42: /**
43: * Returns the python command that matches a given form, a given
44: * context and a given script.
45: *
46: * @param f the form on which the command will apply
47: * @param ctx the context used in command execution
48: * @param script the script that is going to be executed
49: * @return a command.
50: */
51: public PythonCommand getCommand(IForm f, FormContext ctx,
52: String script) {
53: PythonCommand ret = findCommand(ctx, script);
54: if (ret == null) {
55: log.debug("cache miss");
56: ArrayList coms = (ArrayList) pool.get(script);
57: ret = new PythonCommand(f, script, ctx);
58: coms.add(ret);
59: }
60: ret.setForm(f);
61: return ret;
62: }
63:
64: private PythonCommand findCommand(FormContext ctx, String script) {
65: ArrayList coms = (ArrayList) pool.get(script);
66: PythonCommand ret = null;
67: if (coms == null) {
68: coms = new ArrayList();
69: pool.put(script, coms);
70: } else {
71: for (int i = 0, n = coms.size(); i < n && ret == null; i++) {
72: PythonCommand tmp = (PythonCommand) coms.get(i);
73: if (tmp.getContext() == ctx) {
74: ret = tmp;
75: }
76: }
77: }
78: return ret;
79: }
80:
81: public void setEnabled(FormContext ctx, String script,
82: boolean enabled) {
83: PythonCommand com = getCommand(null, ctx, script);
84: if (com == null) {
85: throw new RuntimeException("Command not found for script '"
86: + script + "'");
87: }
88: com.setEnabled(enabled);
89: }
90: }
|