Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 36d74a36f8df67cff0ae5222289afdd0bbed477c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*******************************************************************************
 * Copyright (c) 2004, 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.ui.internal.themes;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.commands.common.EventManager;
import org.eclipse.core.runtime.Platform;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.css.swt.theme.IThemeEngine;
import org.eclipse.e4.ui.internal.css.swt.definition.IThemeElementDefinitionOverridable;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.services.IStylingEngine;
import org.eclipse.e4.ui.workbench.UIEvents;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.misc.StatusUtil;
import org.eclipse.ui.internal.util.PrefUtil;
import org.eclipse.ui.statushandlers.StatusManager;
import org.eclipse.ui.themes.ITheme;
import org.eclipse.ui.themes.IThemeManager;
import org.osgi.service.event.EventHandler;

/**
 * Theme manager for the Workbench.
 * 
 * @since 3.0
 */
public class WorkbenchThemeManager extends EventManager implements
		IThemeManager {

	private static final String SYSTEM_DEFAULT_THEME = "org.eclipse.ui.ide.systemDefault";//$NON-NLS-1$

	private static WorkbenchThemeManager instance;

	private IEclipseContext context;

	private IEventBroker eventBroker;

	/**
	 * Returns the singelton instance of the WorkbenchThemeManager
	 * 
	 * @return singleton instance
	 */
	public static WorkbenchThemeManager getInstance() {
		if (instance == null) {
			if (PlatformUI.getWorkbench().getDisplay() != null) {
				PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
					public void run() {
						getInternalInstance();
					}
				});
			}
		}
		return instance;
	}

	/**
	 * Initialize the singleton theme manager. Must be called in the UI thread.
	 * 
	 * @return the theme manager.
	 */
	private static synchronized WorkbenchThemeManager getInternalInstance() {
		if (instance == null) {
			instance = new WorkbenchThemeManager();
			instance.getCurrentTheme(); // initialize the current theme
		}
		return instance;
	}

	private ITheme currentTheme;

	private IPropertyChangeListener currentThemeListener = new IPropertyChangeListener() {

		public void propertyChange(PropertyChangeEvent event) {
			firePropertyChange(event);
			if (event.getSource() instanceof FontRegistry) {
				JFaceResources.getFontRegistry().put(event.getProperty(),
						(FontData[]) event.getNewValue());
			} else if (event.getSource() instanceof ColorRegistry) {
				JFaceResources.getColorRegistry().put(event.getProperty(),
						(RGB) event.getNewValue());
			}
		}
	};

	private ColorRegistry defaultThemeColorRegistry;

	private FontRegistry defaultThemeFontRegistry;

	private IThemeRegistry themeRegistry;

	private Map themes = new HashMap(7);

	private EventHandler themeChangedHandler = new WorkbenchThemeChangedHandler();

	/*
	 * Initialize the WorkbenchThemeManager.
	 * Determine the default theme according to the following rules:
	 *   1) If we're in HC mode then default to system default
	 *   2) Otherwise, if preference already set (e.g. via plugin_customization.ini), then observe that value
	 *   3) Otherwise, use our default
	 * Call dispose when we close.
	 */
	private WorkbenchThemeManager() {
		defaultThemeColorRegistry = new ColorRegistry(PlatformUI.getWorkbench()
				.getDisplay());

		defaultThemeFontRegistry = new FontRegistry(PlatformUI.getWorkbench()
				.getDisplay());

		// copy the font values from preferences.
		FontRegistry jfaceFonts = JFaceResources.getFontRegistry();
		for (Iterator i = jfaceFonts.getKeySet().iterator(); i.hasNext();) {
			String key = (String) i.next();
			defaultThemeFontRegistry.put(key, jfaceFonts.getFontData(key));
		}

		//Theme might be set via plugin_configuration.ini
		String themeId = PrefUtil.getAPIPreferenceStore().getDefaultString(IWorkbenchPreferenceConstants.CURRENT_THEME_ID);

		//If not set, use default
		if (themeId.length() == 0)
			themeId = IThemeManager.DEFAULT_THEME;

		final boolean highContrast = Display.getCurrent().getHighContrast();

		Display.getCurrent().addListener(SWT.Settings, new Listener() {
			public void handleEvent(Event event) {
				updateThemes();
			}
		});

		// If in HC, *always* use the system default.
		// This ignores any default theme set via plugin_customization.ini
		if (highContrast)
			themeId = SYSTEM_DEFAULT_THEME;

		PrefUtil.getAPIPreferenceStore().setDefault(
				IWorkbenchPreferenceConstants.CURRENT_THEME_ID, themeId);

		context = (IEclipseContext) Workbench.getInstance().getService(IEclipseContext.class);
		eventBroker = (IEventBroker) Workbench.getInstance().getService(IEventBroker.class);
		if (eventBroker != null) {
			eventBroker.subscribe(UIEvents.UILifeCycle.THEME_CHANGED, themeChangedHandler);
			eventBroker.subscribe(IThemeEngine.Events.THEME_CHANGED, themeChangedHandler);
		}
	}

	/*
	 * Update existing theme contents, descriptors, and registries.
	 * Reread the themes and recompute the registries.
	 */	
	private void updateThemes() {
		//reread the themes since their descriptors have changed in value
        ThemeRegistryReader reader = new ThemeRegistryReader();
        reader.readThemes(Platform.getExtensionRegistry(),(ThemeRegistry) getThemeRegistry());   

        //DEFAULT_THEME is not in getThemes() list so must be handled special
        ThemeElementHelper.populateRegistry(getTheme(IThemeManager.DEFAULT_THEME), getThemeRegistry().getColors(), PrefUtil.getInternalPreferenceStore());			
        
        IThemeDescriptor[] themeDescriptors = getThemeRegistry().getThemes();

       	for (int i=0; i < themeDescriptors.length; i++) {
        	IThemeDescriptor themeDescriptor = themeDescriptors[i];
    		ITheme theme = (ITheme) themes.get(themeDescriptor);
    		//If theme is in our themes table then its already been populated
    		if (theme != null) {
                ColorDefinition[] colorDefinitions = themeDescriptor.getColors();
              
               if (colorDefinitions.length > 0) {
                	ThemeElementHelper.populateRegistry(theme, colorDefinitions,PrefUtil.getInternalPreferenceStore());
                }
    		}
		}
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.themes.IThemeManager#addPropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener)
	 */
	public void addPropertyChangeListener(IPropertyChangeListener listener) {
		addListenerObject(listener);
	}

	/**
	 * Disposes all ThemeEntries.
	 */
	public void dispose() {
		if (eventBroker != null) {
			eventBroker.unsubscribe(themeChangedHandler);
		}

		for (Iterator i = themes.values().iterator(); i.hasNext();) {
			ITheme theme = (ITheme) i.next();
			theme.removePropertyChangeListener(currentThemeListener);
			theme.dispose();
		}
		themes.clear();
	}

	private boolean doSetCurrentTheme(String id) {
		ITheme oldTheme = currentTheme;
		ITheme newTheme = getTheme(id);
		if (oldTheme != newTheme && newTheme != null) {
			currentTheme = newTheme;
			return true;
		}

		return false;
	}

	protected void firePropertyChange(PropertyChangeEvent event) {
		Object[] listeners = getListeners();

		for (int i = 0; i < listeners.length; i++) {
			((IPropertyChangeListener) listeners[i]).propertyChange(event);
		}
	}

	protected void firePropertyChange(String changeId, ITheme oldTheme,
			ITheme newTheme) {

		PropertyChangeEvent event = new PropertyChangeEvent(this, changeId,
				oldTheme, newTheme);
		firePropertyChange(event);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.themes.IThemeManager#getCurrentTheme()
	 */
	public ITheme getCurrentTheme() {
		if (currentTheme == null) {
			String themeId = PrefUtil.getAPIPreferenceStore().getString(
					IWorkbenchPreferenceConstants.CURRENT_THEME_ID);

			if (themeId == null) // missing preference
				setCurrentTheme(IThemeManager.DEFAULT_THEME);
			else {
				setCurrentTheme(themeId);
				if (currentTheme == null) { // still null - the preference
											// didn't resolve to a proper theme
					setCurrentTheme(IThemeManager.DEFAULT_THEME);
					StatusManager
							.getManager()
							.handle(
									StatusUtil
											.newStatus(
													PlatformUI.PLUGIN_ID,
													"Could not restore current theme: " + themeId, null)); //$NON-NLS-1$
				}
			}			
		}
		return currentTheme;
	}

	/**
	 * Return the default color registry.
	 * 
	 * @return the default color registry
	 */
	public ColorRegistry getDefaultThemeColorRegistry() {
		return defaultThemeColorRegistry;
	}

	/**
	 * Return the default font registry.
	 * 
	 * @return the default font registry
	 */
	public FontRegistry getDefaultThemeFontRegistry() {
		return defaultThemeFontRegistry;
	}

	private ITheme getTheme(IThemeDescriptor td) {
		ITheme theme = (ITheme) themes.get(td);
		if (theme == null) {
			theme = new Theme(td);
			themes.put(td, theme);
		}
		return theme;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.themes.IThemeManager#getTheme(java.lang.String)
	 */
	public ITheme getTheme(String id) {
		if (id.equals(IThemeManager.DEFAULT_THEME)) {
			return getTheme((IThemeDescriptor) null);
		}

		IThemeDescriptor td = getThemeRegistry().findTheme(id);
		if (td == null) {
			return null;
		}
		return getTheme(td);
	}

	/**
	 * Answer the IThemeRegistry for the Workbench
	 */
	private IThemeRegistry getThemeRegistry() {
		if (themeRegistry == null) {
			themeRegistry = WorkbenchPlugin.getDefault().getThemeRegistry();
		}
		return themeRegistry;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.themes.IThemeManager#removePropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener)
	 */
	public void removePropertyChangeListener(IPropertyChangeListener listener) {
		removeListenerObject(listener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.themes.IThemeManager#setCurrentTheme(java.lang.String)
	 */
	public void setCurrentTheme(String id) {
		ITheme oldTheme = currentTheme;
		if (WorkbenchThemeManager.getInstance().doSetCurrentTheme(id)) {
			firePropertyChange(CHANGE_CURRENT_THEME, oldTheme,
					getCurrentTheme());
			if (oldTheme != null) {
				oldTheme.removePropertyChangeListener(currentThemeListener);
			}
			currentTheme.addPropertyChangeListener(currentThemeListener);

			// update the preference if required.
			if (!PrefUtil.getAPIPreferenceStore().getString(
					IWorkbenchPreferenceConstants.CURRENT_THEME_ID).equals(id)) {
				PrefUtil.getAPIPreferenceStore().setValue(
						IWorkbenchPreferenceConstants.CURRENT_THEME_ID, id);
				PrefUtil.saveAPIPrefs();
			}

			// update the jface registries
			{
				ColorRegistry jfaceColors = JFaceResources.getColorRegistry();
				ColorRegistry themeColors = currentTheme.getColorRegistry();
				for (Iterator i = themeColors.getKeySet().iterator(); i
						.hasNext();) {
					String key = (String) i.next();
					jfaceColors.put(key, themeColors.getRGB(key));
				}
			}
			{
				FontRegistry jfaceFonts = JFaceResources.getFontRegistry();
				FontRegistry themeFonts = currentTheme.getFontRegistry();
				for (Iterator i = themeFonts.getKeySet().iterator(); i
						.hasNext();) {
					String key = (String) i.next();
					jfaceFonts.put(key, themeFonts.getFontData(key));
				}
			}
			{
				if (oldTheme != null && eventBroker != null) {
					eventBroker.send(UIEvents.UILifeCycle.THEME_CHANGED, null);
					eventBroker.send(UIEvents.UILifeCycle.THEME_DEFINITION_CHANGED,
							context.get(MApplication.class.getName()));
				}
			}
		}
	}
	
	public static class WorkbenchThemeChangedHandler implements EventHandler {
		public void handleEvent(org.osgi.service.event.Event event) {
			IStylingEngine engine = getStylingEngine();
			ThemeRegistry themeRegistry = getThemeRegistry();
			FontRegistry fontRegistry = getFontRegistry();
			ColorRegistry colorRegistry = getColorRegistry();

			resetThemeRegistries(themeRegistry);
			overrideAlreadyExistingDefinitions(engine, themeRegistry, fontRegistry, colorRegistry);
			addNewDefinitions(engine, themeRegistry, fontRegistry, colorRegistry);
		}

		protected IStylingEngine getStylingEngine() {
			return (IStylingEngine) getContext().get(IStylingEngine.SERVICE_NAME);
		}

		protected ThemeRegistry getThemeRegistry() {
			return (ThemeRegistry) getContext().get(IThemeRegistry.class.getName());
		}

		protected FontRegistry getFontRegistry() {
			return getCurrentTheme().getFontRegistry();
		}

		protected ColorRegistry getColorRegistry() {
			return getCurrentTheme().getColorRegistry();
		}

		private ITheme getCurrentTheme() {
			return WorkbenchThemeManager.getInstance().getCurrentTheme();
		}

		private IEclipseContext getContext() {
			return WorkbenchThemeManager.getInstance().context;
		}

		// At this moment we don't remove the definitions added by CSS since we
		// don't want to modify the 3.x theme registries api
		private void resetThemeRegistries(ThemeRegistry themeRegistry) {
			for (FontDefinition fontDefinition : themeRegistry.getFonts()) {
				if (fontDefinition.isOverridden()) {
					fontDefinition.resetToDefaultValue();
				}
			}
			for (ColorDefinition colorDefinition : themeRegistry.getColors()) {
				if (colorDefinition.isOverridden()) {
					colorDefinition.resetToDefaultValue();
				}
			}
		}

		private void overrideAlreadyExistingDefinitions(IStylingEngine engine,
				ThemeRegistry themeRegistry, FontRegistry fontRegistry, ColorRegistry colorRegistry) {
			for (FontDefinition fontDefinition : themeRegistry.getFonts()) {
				engine.style(fontDefinition);
				if (fontDefinition.isOverridden()) {
					fontRegistry.put(fontDefinition.getId(), fontDefinition.getValue());
				}
			}
			for (ColorDefinition colorDefinition : themeRegistry.getColors()) {
				engine.style(colorDefinition);
				if (colorDefinition.isOverridden()) {
					colorRegistry.put(colorDefinition.getId(), colorDefinition.getValue());
				}
			}
		}

		private void addNewDefinitions(IStylingEngine engine, ThemeRegistry themeRegistry,
				FontRegistry fontRegistry, ColorRegistry colorRegistry) {
			ThemesExtension themesExtension = createThemesExtension();
			engine.style(themesExtension);

			for (IThemeElementDefinitionOverridable<?> definition : themesExtension
					.getDefinitions()) {
				engine.style(definition);
				if (definition.isOverridden() && definition instanceof FontDefinition) {
					addFontDefinition((FontDefinition) definition, themeRegistry, fontRegistry);
				} else if (definition.isOverridden() && definition instanceof ColorDefinition) {
					addColorDefinition((ColorDefinition) definition, themeRegistry, colorRegistry);
				}
			}
		}

		private void addFontDefinition(FontDefinition definition, ThemeRegistry themeRegistry,
				FontRegistry fontRegistry) {
			themeRegistry.add(definition);
			fontRegistry.put(definition.getId(), definition.getValue());
		}

		private void addColorDefinition(ColorDefinition definition, ThemeRegistry themeRegistry,
				ColorRegistry colorRegistry) {
			themeRegistry.add(definition);
			colorRegistry.put(definition.getId(), definition.getValue());
		}

		protected ThemesExtension createThemesExtension() {
			return new ThemesExtension();
		}
	}

}

Back to the top