1 /**
2 * Copyright (c) 2006-2016 LOVE Development Team
3 *
4 * This software is provided 'as-is', without any express or implied
5 * warranty. In no event will the authors be held liable for any damages
6 * arising from the use of this software.
7 *
8 * Permission is granted to anyone to use this software for any purpose,
9 * including commercial applications, and to alter it and redistribute it
10 * freely, subject to the following restrictions:
11 *
12 * 1. The origin of this software must not be misrepresented; you must not
13 * claim that you wrote the original software. If you use this software
14 * in a product, an acknowledgment in the product documentation would be
15 * appreciated but is not required.
16 * 2. Altered source versions must be plainly marked as such, and must not be
17 * misrepresented as being the original software.
18 * 3. This notice may not be removed or altered from any source distribution.
19 **/
20
21 #include "Event.h"
22
23 using love::thread::Mutex;
24 using love::thread::Lock;
25
26 namespace love
27 {
28 namespace event
29 {
30
Message(const std::string & name,const std::vector<Variant> & vargs)31 Message::Message(const std::string &name, const std::vector<Variant> &vargs)
32 : name(name)
33 , args(vargs)
34 {
35 }
36
~Message()37 Message::~Message()
38 {
39 }
40
toLua(lua_State * L)41 int Message::toLua(lua_State *L)
42 {
43 luax_pushstring(L, name);
44
45 for (const Variant &v : args)
46 v.toLua(L);
47
48 return (int) args.size() + 1;
49 }
50
fromLua(lua_State * L,int n)51 Message *Message::fromLua(lua_State *L, int n)
52 {
53 std::string name = luax_checkstring(L, n);
54 std::vector<Variant> vargs;
55
56 int count = lua_gettop(L) - n;
57 n++;
58
59 Variant varg;
60
61 for (int i = 0; i < count; i++)
62 {
63 if (lua_isnoneornil(L, n+i))
64 break;
65
66 vargs.push_back(Variant::fromLua(L, n+i));
67
68 if (vargs.back().getType() == Variant::UNKNOWN)
69 {
70 vargs.clear();
71 luaL_error(L, "Argument %d can't be stored safely\nExpected boolean, number, string or userdata.", n+i);
72 return nullptr;
73 }
74 }
75
76 return new Message(name, vargs);
77 }
78
~Event()79 Event::~Event()
80 {
81 }
82
push(Message * msg)83 void Event::push(Message *msg)
84 {
85 Lock lock(mutex);
86 msg->retain();
87 queue.push(msg);
88 }
89
poll(Message * & msg)90 bool Event::poll(Message *&msg)
91 {
92 Lock lock(mutex);
93 if (queue.empty())
94 return false;
95 msg = queue.front();
96 queue.pop();
97 return true;
98 }
99
clear()100 void Event::clear()
101 {
102 Lock lock(mutex);
103 while (!queue.empty())
104 {
105 // std::queue::pop will remove the first (front) element.
106 queue.front()->release();
107 queue.pop();
108 }
109 }
110
111 } // event
112 } // love
113