1 /**
2 Copyright: Copyright (c) 2015-2016 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 module voxelman.input.keybindingmanager;
7 
8 import std.experimental.logger;
9 
10 import pluginlib;
11 import voxelman.config.configmanager;
12 import voxelman.utils.keynamemap;
13 public import voxelman.gui.plugin : KeyCode, PointerButton;
14 
15 
16 struct KeyBinding
17 {
18 	uint keyCode;
19 	string keyName;
20 	KeyHandler pressHandler;
21 	KeyHandler releaseHandler;
22 }
23 
24 alias KeyHandler = void delegate(string key);
25 
26 final class KeyBindingManager : IResourceManager
27 {
28 	KeyBinding*[uint] keyBindingsByCode;
29 	KeyBinding*[string] keyBindingsByName;
30 	private ConfigOption[string] options;
31 	private ConfigManager config;
32 
33 	override string id() @property { return "voxelman.managers.keybindingmanager"; }
34 
35 	override void init(IResourceManagerRegistry resmanRegistry)
36 	{
37 		config = resmanRegistry.getResourceManager!ConfigManager;
38 	}
39 
40 	// Load all keybindings from config
41 	override void postInit()
42 	{
43 		foreach(pair; options.byKeyValue)
44 		{
45 			string optionName = pair.key;
46 			ConfigOption option = pair.value;
47 			if (optionName !in keyBindingsByName) continue;
48 
49 			KeyBinding* binding = keyBindingsByName[optionName];
50 			string key = option.get!string;
51 			if (key !in stringToKeyMap) continue;
52 
53 			uint configKeyCode = stringToKeyMap[key];
54 			if (binding.keyCode != configKeyCode)
55 			{
56 				keyBindingsByCode.remove(binding.keyCode);
57 				keyBindingsByCode[configKeyCode] = binding;
58 				binding.keyCode = configKeyCode;
59 			}
60 		}
61 	}
62 
63 	// Called during IPlugin.registerResources calls.
64 	void registerKeyBinding(KeyBinding* binding)
65 	{
66 		assert(binding);
67 		auto option = config.registerOption!string(binding.keyName, keyToStringMap[binding.keyCode]);
68 		options[binding.keyName] = option;
69 		keyBindingsByCode[binding.keyCode] = binding;
70 		keyBindingsByName[binding.keyName] = binding;
71 	}
72 }