aboutsummaryrefslogtreecommitdiffstats
path: root/mediaplugin/src/lua/UHookableEvent.pas
blob: 8ad7ea9c63d4c827ac9dbc3e6d6ca45d8292ae97 (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
{* UltraStar Deluxe - Karaoke Game
 *
 * UltraStar Deluxe is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING. If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 * $URL$
 * $Id$
 *}

unit UHookableEvent;

interface

{$IFDEF FPC}
  {$MODE Delphi}
{$ENDIF}

{$I switches.inc}

uses ULua;

type
  { Record holding information about a hook of an event }
  PHook = ^THook;
  THook = record
    Handle: Integer; //< Handle to identify the hook, e.g. for unhooking by plugin
    Parent: Integer; //< Lua Core Handle this hook belongs to

    Func: String;   //< Name of the global that holds the function

    Next: PHook; //< Next Hook in list (nil for the first)
  end;

  { procedure is called before each call to the hooking lua functions, to push values on stack
    returns the number of pushed arguments}
  PrepareStackProc = Function(L: PLua_State): Integer;

  { class representing a hookable event }
  THookableEvent = class
    private
      iHandle: Integer; //< used to unregister at lua core
      LastHook: PHook;  //< last hook in hook list, first to be called
      NextHookHandle: Integer;  //< handle to identify next hook

      sName: String;    //< the events name

      PrepareStack: PrepareStackProc; //< prepare stack procedure passed to constructor
      CallinProcess: boolean; //< true if a chain call is in process, to prepare unhooking during calls
      HooksToRemove: array of PHook; // hooks to delete after chaincall

      procedure RemoveWaitingHooks;
    public
      constructor Create(Name: String; const Proc: PrepareStackProc = nil);

      property Name: String read sName;             //< returns the events name
      property Handle: Integer read iHandle;        //< returns the events name

      procedure Hook(L: Plua_State; Parent: Integer; Func: String); //< pushes hook object/table to the lua stack
      procedure UnHook(L: Plua_State; hHook: Integer);              //< unhook by plugin. push true or error string to lua stack

      procedure UnHookByParent(Parent: Integer);     //< deletes all hooks by a specified parent (unhook by core)

      function CallHookChain(Breakable: Boolean): PLua_State;   //< calls the events hookchain. if breakable, plugin can breake the chain by returning a value != 0 or false or nil

      destructor Destroy; override;
  end;

{ the default function for THookableEvent.PrepareStack it don't pass any arguments }
function PrepareStack_Dummy(L: PLua_State): Integer;

{ function in resulting hook table. it calls the unhook command of the event on plugins demand }
function LuaHook_UnHook(L: Plua_State): Integer; cdecl;

implementation
uses ULuaCore;

constructor THookableEvent.Create(Name: String; const Proc: PrepareStackProc);
begin
  inherited Create;
  
  Self.sName := Name;

  if (@Proc = nil) then
    Self.PrepareStack := @PrepareStack_Dummy
  else
    Self.PrepareStack := Proc;

  //init LastHook pointer w/ nil
  LastHook := nil;
  NextHookHandle := 1;

  iHandle := LuaCore.RegisterEvent(Self);
end;

destructor THookableEvent.Destroy;
var
  Prev: PHook;
  Cur:  PHook;
begin
  //delete all hooks
  Cur := LastHook;
  While (Cur <> nil) do
  begin
    Prev := Cur;
    Cur := Prev.Next;

    Dispose(Prev);
  end;

  //remove from luacores list
  LuaCore.UnRegisterEvent(iHandle);

  inherited;
end;

{ adds hook to events list and pushes hook object/table to the lua stack }
procedure  THookableEvent.Hook(L: PLua_State; Parent: Integer; Func: String);
  var
    Item: PHook;
    P: TLuaPlugin;
begin
  P := LuaCore.GetPluginById(Parent);
  if (P <> nil) then
  begin
    // get mem and fill it w/ data
    New(Item);
    Item.Handle := NextHookHandle;
    Inc(NextHookHandle);

    Item.Parent := Parent;
    Item.Func := Func;

    // add at front of the hook chain
    Item.Next := LastHook;
    LastHook := Item;

    //we need 2 free stack slots
    lua_checkstack(L, 2);

    //create the hook table, we need 2 elements (event name and unhook function)
    lua_createtable(L, 0, 2);

    //push events name
    lua_pushstring(L, PAnsiChar(Name));

    //add the name to the table
    lua_setfield(L, -2, 'Event');

    //push hook id to the stack
    lua_pushinteger(L, Item.Handle);

    //create a c closure, append one value from stack(the id)
    //this will pop both, the function and the id
    lua_pushcclosure(L, LuaHook_UnHook, 1);

    //add the function to our table
    lua_setfield(L, -2, 'Unhook');

    //the table is left on the stack, it is our result
  end;
end;

{ removes hooks in HookstoRemove array from chain }
procedure THookableEvent.RemoveWaitingHooks;
  function IsInArray(Cur: PHook): boolean;
    var I: Integer;
  begin
    Result := false;
    for I := 0 to high(HooksToRemove) do
      if (HooksToRemove[I] = Cur) then
      begin
        Result := true;
        Break;
      end;
  end;

  var
    Cur, Prev: PHook;
begin
  Prev := nil;
  Cur := LastHook;

  while (Cur <> nil) do
  begin
    if (IsInArray(Cur)) then
    begin //we found the hook
      if (prev <> nil) then
        Prev.Next := Cur.Next
      else //last hook found
        LastHook := Cur.Next;

      //free hooks memory
      Dispose(Cur);

      if (prev <> nil) then
        Cur := Prev.Next
      else
        Cur := LastHook;
    end
    else
    begin
      Prev := Cur;
      Cur := Prev.Next;
    end;
  end;

  SetLength(HooksToRemove, 0);
end;

{ unhook by plugin. push true or error string to lua stack }
procedure  THookableEvent.UnHook(L: Plua_State; hHook: Integer);
  var
    Cur, Prev: PHook;
    Len: integer;
begin
  if (hHook < NextHookHandle) and (hHook > 0) then
  begin
    //Search for the Hook
    Prev := nil;
    Cur := LastHook;

    while (Cur <> nil) do
    begin
      if (Cur.Handle = hHook) then
      begin //we found the hook
        if not CallinProcess then
        begin // => remove it
          if (prev <> nil) then
            Prev.Next := Cur.Next
          else //last hook found
            LastHook := Cur.Next;

          //free hooks memory
          Dispose(Cur);
        end
        else
        begin // add to list of hooks to remove
          Len := Length(HooksToRemove);
          SetLength(HooksToRemove, Len + 1);
          HooksToRemove[Len] := Cur;
        end;
        
        //indicate success
        lua_pushboolean(L, True);
        exit; //break the chain and exit the function
      end;
      Prev := Cur;
      Cur := Prev.Next;
    end;

    lua_pushstring(L, PAnsiChar('handle already unhooked')); //the error description
  end
  else
    lua_pushstring(L, PAnsiChar('undefined hook handle')); //the error description
end;

{ deletes all hooks by a specified parent (unhook by core) }
procedure  THookableEvent.UnHookByParent(Parent: Integer);
  var
    Cur, Prev: PHook;
begin
  Prev := nil;
  Cur := LastHook;

  While (Cur <> nil) do
  begin
    if (Cur.Parent = Parent) then
    begin //found a hook from parent => remove it
      if (Prev <> nil) then
        Prev.Next := Cur.Next
      Else
        LastHook := Cur.Next;

      Dispose(Cur);

      if (Prev <> nil) then
        Cur := Prev.Next
      else
        Cur := LastHook;
    end
    else //move through the chain
    begin
      Prev := Cur;
      Cur := Prev.Next;
    end;
  end;
end;

{ calls the events hookchain. if breakable, plugin can breake the chain
  by returning a value
  breakable is pushed as the first parameter to the hooking functions
  if chain is broken the LuaStack is returned, with all results left
  you may call lua_clearstack }
function  THookableEvent.CallHookChain(Breakable: Boolean): Plua_State;
  var
    Cur: PHook;
    P: TLuaPlugin;
begin
  Result := nil;

  CallinProcess := true;
  
  Cur := LastHook;
  While (Cur <> nil) do
  begin
    P := LuaCore.GetPluginById(Cur.Parent);
    lua_pushboolean(P.LuaState, Breakable);

    if  (P.CallFunctionByName(Cur.Func, 1 + PrepareStack(P.LuaState), LUA_MULTRET))
    and Breakable
    and (lua_gettop(P.LuaState) > 0) then
    begin //Chain Broken
      Result := P.LuaState;
      Break;
    end;

    Cur := Cur.Next;
  end;

  RemoveWaitingHooks;
  CallinProcess := false;
end;

{ the default function for THookableEvent.PrepareStack it don't pass any arguments }
function PrepareStack_Dummy(L: PLua_State): Integer;
begin
  Result := 0;
end;

{ function in resulting hook table. it calls the unhook command of the event on plugins demand }
function LuaHook_UnHook(L: Plua_State): Integer; cdecl;
  var
    Name: string;
    Event: THookableEvent;
    hHook: integer;
begin
  Result := 0;

  if not lua_isTable(L, 1) then
    LuaL_Error(L, 'Can''t find hook table in LuaHook_Unhook. Please call Unhook with method seperator (colon) instead of a point.');

  // get event name
  Lua_GetField(L, 1, 'Event');
  if not lua_isString(L, -1) then
    LuaL_Error(L, 'Can''t get event name in LuaHook_Unhook');

  Name := Lua_ToString(L, -1);

  // get event by name
  Event := LuaCore.GetEventbyName(Name);

  // free stack slots
  Lua_pop(L, Lua_GetTop(L));

  if (Event = nil) then
    LuaL_Error(L, PAnsiChar('event ' + Name + ' does not exist (anymore?) in LuaHook_Unhook'));

  // get the hookid
  hHook := lua_ToInteger(L, lua_upvalueindex(1));

  Event.UnHook(L, hHook);
end;

end.