]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.ui/src/org/simantics/ui/workbench/ContextUtil.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.ui / src / org / simantics / ui / workbench / ContextUtil.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.ui.workbench;\r
13 \r
14 import org.eclipse.swt.events.FocusEvent;\r
15 import org.eclipse.swt.events.FocusListener;\r
16 import org.eclipse.swt.widgets.Control;\r
17 import org.eclipse.ui.IWorkbenchSite;\r
18 import org.eclipse.ui.contexts.IContextActivation;\r
19 import org.eclipse.ui.contexts.IContextService;\r
20 \r
21 /**\r
22  * @author Tuukka Lehtonen\r
23  */\r
24 public final class ContextUtil {\r
25 \r
26     /**\r
27      * Associate a workbench context specified by id with the focus state of the specified control.\r
28      * \r
29      * @param site any workbench site\r
30      * @param control the control whose focus to track for context activation\r
31      * @param contextId the ID of the context to use\r
32      */\r
33     public static void associateContext(final IWorkbenchSite site, Control control, final String contextId) {\r
34         control.addFocusListener(new FocusListener() {\r
35             IContextActivation contextActivation;\r
36 \r
37             IContextService getService() {\r
38                 if (site == null)\r
39                     return null;\r
40                 return (IContextService) site.getService(IContextService.class);\r
41             }\r
42 \r
43             @Override\r
44             public void focusGained(FocusEvent e) {\r
45                 IContextService contextService = getService();\r
46                 String ctx = contextId;\r
47                 if (contextService != null && ctx != null)\r
48                     contextActivation = contextService.activateContext(ctx);\r
49             }\r
50 \r
51             @Override\r
52             public void focusLost(FocusEvent e) {\r
53                 IContextService contextService = getService();\r
54                 if (contextService != null && contextActivation != null)\r
55                     contextService.deactivateContext(contextActivation);\r
56             }\r
57         });\r
58     }\r
59 \r
60 }\r