1 /*
2    Copyright (C) 2014 - 2018 by Chris Beck <render787@gmail.com>
3    Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY.
11 
12    See the COPYING file for more details.
13 */
14 
15 /**
16  * Manages the availability of wesnoth callbacks to plug-ins while the
17  * application is context switching.
18  */
19 
20 #pragma once
21 
22 #include "utils/functional.hpp"
23 
24 #include <map>
25 #include <string>
26 #include <vector>
27 
28 class config;
29 
30 class plugins_context {
31 
32 public:
33 	typedef std::function<bool(config)> callback_function;
34 	struct Reg { char const * name; callback_function func; };
35 
36 	typedef std::function<config(config)> accessor_function;
37 	struct aReg { char const * name; accessor_function func; };
38 
39 	plugins_context( const std::string & name );
40 	plugins_context( const std::string & name, const std::vector<Reg>& callbacks, const std::vector<aReg>& accessors);
41 	template<int N, int M>
plugins_context(const std::string & name,const Reg (& callbacks)[N],const aReg (& accessors)[M])42 	plugins_context( const std::string & name, const Reg (& callbacks)[N], const aReg (& accessors)[M])
43 		: name_(name)
44 	{
45 		std::vector<Reg> l;
46 		std::vector<aReg> r;
47 		l.reserve(N);
48 		r.reserve(M);
49 		for(int i = 0; i < N; i++) {
50 			l.push_back(callbacks[i]);
51 		}
52 		for(int i = 0; i < M; i++) {
53 			r.push_back(accessors[i]);
54 		}
55 		initialize(l, r);
56 	}
57 
58 	void play_slice();
59 
60 	void set_callback(const std::string & name, callback_function);
61 	void set_callback(const std::string & name, std::function<void(config)> function, bool preserves_context);
62 	size_t erase_callback(const std::string & name);
63 	size_t clear_callbacks();
64 
65 	void set_accessor(const std::string & name, accessor_function);
66 	void set_accessor_string(const std::string & name, std::function<std::string(config)>);	//helpers which create a config from a simple type
67 	void set_accessor_int(const std::string & name, std::function<int(config)>);
68 	size_t erase_accessor(const std::string & name);
69 	size_t clear_accessors();
70 
71 	friend class application_lua_kernel;
72 
73 private:
74 	typedef std::map<std::string, callback_function > callback_list;
75 	typedef std::map<std::string, accessor_function > accessor_list;
76 
77 	void initialize(const std::vector<Reg>& callbacks, const std::vector<aReg>& accessors);
78 
79 	callback_list callbacks_;
80 	accessor_list accessors_;
81 	std::string name_;
82 };
83