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