Line data Source code
1 : /* Copyright (C) 2020 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #ifndef INCLUDED_SCRIPTENGINE
19 : #define INCLUDED_SCRIPTENGINE
20 :
21 : #include "ScriptTypes.h"
22 : #include "ps/Singleton.h"
23 :
24 : #include "js/Initialization.h"
25 :
26 : #include <list>
27 :
28 : /**
29 : * A class using the RAII (Resource Acquisition Is Initialization) idiom to manage initialization
30 : * and shutdown of the SpiderMonkey script engine. It also keeps a count of active script contexts
31 : * in order to validate the following constraints:
32 : * 1. JS_Init must be called before any ScriptContexts are initialized
33 : * 2. JS_Shutdown must be called after all ScriptContexts have been destroyed
34 : */
35 :
36 : class ScriptEngine : public Singleton<ScriptEngine>
37 : {
38 : public:
39 1 : ScriptEngine()
40 1 : {
41 1 : ENSURE(m_Contexts.empty() && "JS_Init must be called before any contexts are created!");
42 1 : JS_Init();
43 1 : }
44 :
45 1 : ~ScriptEngine()
46 1 : {
47 1 : ENSURE(m_Contexts.empty() && "All contexts must be destroyed before calling JS_ShutDown!");
48 1 : JS_ShutDown();
49 1 : }
50 :
51 1 : void RegisterContext(const JSContext* cx) { m_Contexts.push_back(cx); }
52 1 : void UnRegisterContext(const JSContext* cx) { m_Contexts.remove(cx); }
53 :
54 : private:
55 : std::list<const JSContext*> m_Contexts;
56 : };
57 :
58 : #endif // INCLUDED_SCRIPTENGINE
|