1 { Copyright (C) 2005 Bas Steendijk and Peter Green
\r
2 For conditions of distribution and use, see copyright notice in zlib_license.txt
\r
3 which is included in the package
\r
4 ----------------------------------------------------------------------------- }
\r
6 //this unit provides a rough approximation of windows messages on linux
\r
7 //it is usefull for multithreaded applications on linux to communicate back to
\r
8 //the main lcore thread
\r
9 //This unit is *nix only, on windows you should use the real thing
\r
12 //windows messages like system based on lcore tasks
\r
15 uses pgtypes,sysutils,bsearchtree,strings,syncobjs;
\r
24 hwnd=qword; //window handles are monotonically increasing 64 bit integers,
\r
25 //this should allow for a million windows per second for over half
\r
28 twndproc=function(ahWnd:HWND; auMsg:Integer; awParam:WPARAM; alParam:LPARAM):Integer; stdcall;
\r
33 lpfnwndproc : twndproc;
\r
34 cbclsextra : integer;
\r
35 cbwndextra : integer;
\r
36 hinstance : thinstance;
\r
39 hbrbackground : hbrush;
\r
40 lpszmenuname : pchar;
\r
41 lpszclassname : pchar;
\r
43 PWNDCLASS=^twndclass;
\r
47 tTIMERPROC = procedure (ahwnd:HWND; umsg:integer; idevent:taddrint;dwtime:taddrint);stdcall;
\r
67 THevent=TEventObject;
\r
69 WS_EX_TOOLWINDOW = $80;
\r
70 WS_POPUP = longint($80000000);
\r
75 INFINITE = syncobjs.infinite;
\r
76 function getwindowlongptr(ahwnd:hwnd;nindex:integer) : taddrint;
\r
77 function setwindowlongptr(ahwnd:hwnd;nindex:integer;dwNewLong : taddrint) : taddrint;
\r
78 function DefWindowProc(ahWnd:HWND; auMsg:Integer; awParam:WPARAM; alParam:LPARAM):Integer; stdcall;
\r
79 function RegisterClass(const lpWndClass:TWNDCLASS):ATOM;
\r
80 function CreateWindowEx(dwExStyle:DWORD; lpClassName:LPCSTR; lpWindowName:LPCSTR; dwStyle:DWORD; X:longint;Y:longint; nWidth:longint; nHeight:longint; hWndParent:HWND; hMenu:HMENU;hInstance:HINST; lpParam:LPVOID):HWND;
\r
81 function DestroyWindow(ahWnd:HWND):WINBOOL;
\r
82 function PostMessage(hWnd:HWND; Msg:UINT; wParam:WPARAM; lParam:LPARAM):WINBOOL;
\r
83 function PeekMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): WINBOOL;
\r
84 function DispatchMessage(const lpMsg: TMsg): Longint;
\r
85 function GetMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT): WINBOOL;
\r
86 function SetEvent(hEvent:THevent):WINBOOL;
\r
87 function CreateEvent(lpEventAttributes:PSECURITYATTRIBUTES; bManualReset:WINBOOL; bInitialState:WINBOOL; lpName:pchar):tHevent;
\r
88 function terminatethread(threadhandle : tthreadid;dummy:integer) : boolean;
\r
89 function waitforsingleevent(event:thevent;timeout:cardinal) : twaitresult;
\r
90 function SetTimer(ahWnd:HWND; nIDEvent:taddrint; uElapse:UINT; lpTimerFunc:tTIMERPROC):UINT;
\r
91 function KillTimer(ahWnd:HWND; uIDEvent:taddrint):WINBOOL;
\r
97 baseunix,unix,lcore,unixutil;//,safewriteln;
\r
101 tmessageintransit = class
\r
103 next : tmessageintransit;
\r
106 tthreaddata = class
\r
107 messagequeue : tmessageintransit;
\r
108 messageevent : teventobject;
\r
110 lcorethread : boolean;
\r
111 nexttimer : ttimeval;
\r
112 threadid : integer;
\r
116 extrawindowmemory : pointer;
\r
117 threadid : tthreadid;
\r
118 windowproc : twndproc;
\r
122 structurelock : tcriticalsection;
\r
123 threaddata : thashtable;
\r
124 windowclasses : thashtable;
\r
125 lcorelinkpipesend : integer;
\r
126 lcorelinkpiperecv : tlasio;
\r
127 windows : thashtable;
\r
128 //I would rather things crash immediately
\r
129 //if they use an insufficiant size type
\r
130 //than crash after over four billion
\r
131 //windows have been made ;)
\r
132 nextwindowhandle : qword = $100000000;
\r
133 {$i ltimevalstuff.inc}
\r
135 //findthreaddata should only be called while holding the structurelock
\r
136 function findthreaddata(threadid : integer) : tthreaddata;
\r
138 result := tthreaddata(findtree(@threaddata,inttostr(threadid)));
\r
139 if result = nil then begin
\r
140 result := tthreaddata.create;
\r
141 result.messageevent := teventobject.create(nil,false,false,inttostr(taddrint(result)));
\r
142 result.nexttimer := tv_invalidtimebig;
\r
143 result.threadid := threadid;
\r
144 addtree(@threaddata,inttostr(threadid),result);
\r
148 //deletethreaddataifunused should only be called while holding the structurelock
\r
149 procedure deletethreaddataifunused(athreaddata : tthreaddata);
\r
151 //writeln('in deletethreaddataifunused');
\r
152 if (athreaddata <> nil) then if (athreaddata.waiting=false) and (athreaddata.messagequeue=nil) and (athreaddata.lcorethread=false) and (athreaddata.nexttimer.tv_sec=tv_invalidtimebig.tv_sec) and (athreaddata.nexttimer.tv_usec=tv_invalidtimebig.tv_usec) then begin
\r
153 //writeln('threaddata is unused, freeing messageevent');
\r
154 athreaddata.messageevent.free;
\r
155 //writeln('freeing thread data object');
\r
157 //writeln('deleting thread data object from hashtable');
\r
158 deltree(@threaddata,inttostr(athreaddata.threadid));
\r
159 //writeln('finished deleting thread data');
\r
161 //writeln('thread data is not unused');
\r
165 function getwindowlongptr(ahwnd:hwnd;nindex:integer) : taddrint;
\r
169 structurelock.acquire;
\r
171 window := findtree(@windows,inttostr(ahwnd));
\r
172 if window <> nil then begin
\r
173 result := paddrint(taddrint(window.extrawindowmemory)+nindex)^;
\r
178 structurelock.release;
\r
182 function setwindowlongptr(ahwnd:hwnd;nindex:integer;dwNewLong : taddrint) : taddrint;
\r
186 structurelock.acquire;
\r
188 window := findtree(@windows,inttostr(ahwnd));
\r
189 if window <> nil then begin
\r
190 result := paddrint(taddrint(window.extrawindowmemory)+nindex)^;
\r
191 paddrint(taddrint(window.extrawindowmemory)+nindex)^ := dwnewlong;
\r
196 structurelock.release;
\r
202 function DefWindowProc(ahWnd:HWND; auMsg:Integer; awParam:WPARAM; alParam:LPARAM):Integer; stdcall;
\r
207 function strdup(s:pchar) : pchar;
\r
209 //swriteln('in strdup, about to allocate memory');
\r
210 result := getmem(strlen(s)+1);
\r
211 //swriteln('about to copy string');
\r
213 //swriteln('leaving strdup');
\r
216 function RegisterClass(const lpWndClass:TWNDCLASS):ATOM;
\r
218 storedwindowclass:pwndclass;
\r
220 structurelock.acquire;
\r
222 //swriteln('in registerclass, about to check for duplicate window class');
\r
223 storedwindowclass := findtree(@windowclasses, lpwndclass.lpszclassname);
\r
224 if storedwindowclass <> nil then begin
\r
226 if comparebyte(storedwindowclass^,lpwndclass,sizeof(twndclass)-sizeof(pchar)-sizeof(pchar)) <> 0 then begin
\r
227 //swriteln('duplicate window class registered with different settings');
\r
228 raise exception.create('duplicate window class registered with different settings');
\r
230 //swriteln('duplicate window class registered with same settings, tollerated');
\r
233 //swriteln('about to allocate memory for new windowclass');
\r
234 storedwindowclass := getmem(sizeof(twndclass));
\r
235 //swriteln('about to copy windowclass from parameter');
\r
236 move(lpwndclass,storedwindowclass^,sizeof(twndclass));
\r
237 //swriteln('about to copy strings');
\r
238 if lpwndclass.lpszmenuname <> nil then storedwindowclass.lpszmenuname := strdup(lpwndclass.lpszmenuname);
\r
239 if lpwndclass.lpszclassname <> nil then storedwindowclass.lpszclassname := strdup(lpwndclass.lpszclassname);
\r
240 //swriteln('about to add result to list of windowclasses');
\r
241 addtree(@windowclasses,lpwndclass.lpszclassname,storedwindowclass);
\r
243 //swriteln('about to return result');
\r
244 result := storedwindowclass;
\r
245 //swriteln('leaving registerclass');
\r
247 structurelock.release;
\r
251 function CreateWindowEx(dwExStyle:DWORD; lpClassName:LPCSTR; lpWindowName:LPCSTR; dwStyle:DWORD; X:longint;Y:longint; nWidth:longint; nHeight:longint; hWndParent:HWND; hMenu:HMENU;hInstance:HINST; lpParam:LPVOID):HWND;
\r
253 wndclass : pwndclass;
\r
254 tm : tthreadmanager;
\r
257 structurelock.acquire;
\r
259 window := twindow.create;
\r
260 window.hwnd := nextwindowhandle;
\r
261 result := window.hwnd;
\r
262 nextwindowhandle := nextwindowhandle + 1;
\r
263 addtree(@windows,inttostr(window.hwnd),window);
\r
264 wndclass := findtree(@windowclasses,lpclassname);
\r
265 window.extrawindowmemory := getmem(wndclass.cbwndextra);
\r
267 getthreadmanager(tm);
\r
268 window.threadid := tm.GetCurrentThreadId;
\r
269 window.windowproc := wndclass.lpfnwndproc;
\r
271 structurelock.release;
\r
274 function DestroyWindow(ahWnd:HWND):WINBOOL;
\r
277 windowthreaddata : tthreaddata;
\r
278 currentmessage : tmessageintransit;
\r
279 prevmessage : tmessageintransit;
\r
281 //writeln('started to destroy window');
\r
282 structurelock.acquire;
\r
284 window := twindow(findtree(@windows,inttostr(ahwnd)));
\r
285 if window <> nil then begin
\r
286 freemem(window.extrawindowmemory);
\r
287 //writeln('aboute to delete window from windows structure');
\r
288 deltree(@windows,inttostr(ahwnd));
\r
289 //writeln('deleted window from windows structure');
\r
290 windowthreaddata := tthreaddata(findtree(@threaddata,inttostr(window.threadid)));
\r
292 if windowthreaddata <> nil then begin
\r
293 //writeln('found thread data scanning for messages to clean up');
\r
294 currentmessage := windowthreaddata.messagequeue;
\r
295 prevmessage := nil;
\r
296 while currentmessage <> nil do begin
\r
297 while (currentmessage <> nil) and (currentmessage.msg.hwnd = ahwnd) do begin
\r
298 if prevmessage = nil then begin
\r
299 windowthreaddata.messagequeue := currentmessage.next;
\r
301 prevmessage.next := currentmessage.next;
\r
303 currentmessage.free;
\r
304 if prevmessage = nil then begin
\r
305 currentmessage := windowthreaddata.messagequeue;
\r
307 currentmessage := prevmessage.next;
\r
310 if currentmessage <> nil then begin
\r
311 prevmessage := currentmessage;
\r
312 currentmessage := currentmessage.next;
\r
315 //writeln('deleting thread data structure if it is unused');
\r
316 deletethreaddataifunused(windowthreaddata);
\r
318 //writeln('there is no thread data to search for messages to cleanup');
\r
320 //writeln('freeing window');
\r
327 structurelock.release;
\r
329 //writeln('window destroyed');
\r
334 function PostMessage(hWnd:HWND; Msg:UINT; wParam:WPARAM; lParam:LPARAM):WINBOOL;
\r
336 threaddata : tthreaddata;
\r
337 message : tmessageintransit;
\r
338 messagequeueend : tmessageintransit;
\r
341 structurelock.acquire;
\r
343 window := findtree(@windows,inttostr(hwnd));
\r
344 if window <> nil then begin
\r
345 threaddata := findthreaddata(window.threadid);
\r
346 message := tmessageintransit.create;
\r
347 message.msg.hwnd := hwnd;
\r
348 message.msg.message := msg;
\r
349 message.msg.wparam := wparam;
\r
350 message.msg.lparam := lparam;
\r
351 if threaddata.lcorethread then begin
\r
352 //swriteln('posting message to lcore thread');
\r
353 fdwrite(lcorelinkpipesend,message,sizeof(message));
\r
355 //writeln('posting message to non lcore thread');
\r
356 if threaddata.messagequeue = nil then begin
\r
357 threaddata.messagequeue := message;
\r
359 messagequeueend := threaddata.messagequeue;
\r
360 while messagequeueend.next <> nil do begin
\r
361 messagequeueend := messagequeueend.next;
\r
363 messagequeueend.next := message;
\r
366 //writeln('message added to queue');
\r
367 if threaddata.waiting then threaddata.messageevent.setevent;
\r
374 structurelock.release;
\r
379 function gettickcount : dword;
\r
385 result64 := (tv.tv_sec*1000)+(tv.tv_usec div 1000);
\r
386 result := result64;
\r
389 function DispatchMessage(const lpMsg: TMsg): Longint;
\r
391 timerproc : ttimerproc;
\r
393 windowproc : twndproc;
\r
395 ////swriteln('in dispatchmessage, msg.hwnd='+inttohex(taddrint(lpmsg.hwnd),16));
\r
396 if (lpmsg.lparam <> 0) and (lpmsg.message = WM_TIMER) then begin
\r
397 timerproc := ttimerproc(lpmsg.lparam);
\r
398 timerproc(lpmsg.hwnd,lpmsg.message,lpmsg.wparam,gettickcount);
\r
401 structurelock.acquire;
\r
403 window := findtree(@windows,inttostr(lpmsg.hwnd));
\r
404 //we have to get the window procedure while the structurelock
\r
405 //is still held as the window could be destroyed from another thread
\r
407 windowproc := window.windowproc;
\r
409 structurelock.release;
\r
411 if window <> nil then begin
\r
412 result := windowproc(lpmsg.hwnd,lpmsg.message,lpmsg.wparam,lpmsg.lparam);
\r
419 procedure processtimers;
\r
423 function GetMessageinternal(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT; wremovemsg : UINT;peek:boolean): WINBOOL;
\r
425 tm : tthreadmanager;
\r
426 threaddata : tthreaddata;
\r
427 message : tmessageintransit;
\r
429 timeouttv : ttimeval;
\r
433 if hwnd <> 0 then raise exception.create('getting messages for an individual window is not supported');
\r
434 if (wmsgfiltermin <> 0) or (wmsgfiltermax <> 0) then raise exception.create('message filtering is not supported');
\r
435 structurelock.acquire;
\r
438 getthreadmanager(tm);
\r
439 threaddata := findthreaddata(tm.GetCurrentThreadId);
\r
440 if threaddata.lcorethread then raise exception.create('get/peek message cannot be used in the lcore thread');
\r
441 message := threaddata.messagequeue;
\r
442 gettimeofday(nowtv);
\r
443 while (not peek) and (message=nil) and (not tv_compare(nowtv,threaddata.nexttimer)) do begin
\r
444 threaddata.waiting := true;
\r
445 structurelock.release;
\r
446 if (threaddata.nexttimer.tv_sec = TV_invalidtimebig.tv_sec) and (threaddata.nexttimer.tv_usec = TV_invalidtimebig.tv_usec) then begin
\r
447 threaddata.messageevent.waitfor(INFINITE);
\r
450 timeouttv := threaddata.nexttimer;
\r
451 timeoutms := (timeouttv.tv_sec * 1000)+(timeouttv.tv_usec div 1000);
\r
452 //i'm assuming the timeout is in milliseconds
\r
453 if (timeoutms > maxlongint) then timeoutms := maxlongint;
\r
454 threaddata.messageevent.waitfor(timeoutms);
\r
457 structurelock.acquire;
\r
458 threaddata.waiting := false;
\r
459 message := threaddata.messagequeue;
\r
460 gettimeofday(nowtv);
\r
462 if (message=nil) and tv_compare(nowtv,threaddata.nexttimer) then begin
\r
465 message := threaddata.messagequeue;
\r
466 if message <> nil then begin
\r
467 lpmsg := message.msg;
\r
468 if wremovemsg=PM_REMOVE then begin
\r
469 threaddata.messagequeue := message.next;
\r
475 deletethreaddataifunused(threaddata);
\r
477 structurelock.release;
\r
481 function GetMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT): WINBOOL;
\r
483 result := getmessageinternal(lpmsg,hwnd,wmsgfiltermin,wmsgfiltermax,PM_REMOVE,false);
\r
486 function PeekMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): WINBOOL;
\r
488 result := getmessageinternal(lpmsg,hwnd,wmsgfiltermin,wmsgfiltermax,PM_REMOVE,true);
\r
491 function SetEvent(hEvent:THevent):WINBOOL;
\r
497 function CreateEvent(lpEventAttributes:PSECURITYATTRIBUTES; bManualReset:WINBOOL; bInitialState:WINBOOL; lpName:pchar):tHevent;
\r
499 result := teventobject.create(lpeventattributes,bmanualreset,binitialstate,lpname);
\r
502 function terminatethread(threadhandle:tthreadid;dummy : integer) : boolean;
\r
504 tm : tthreadmanager;
\r
506 getthreadmanager(tm);
\r
507 tm.killthread(threadhandle);
\r
511 function waitforsingleevent(event:thevent;timeout:cardinal) : twaitresult;
\r
513 result := event.waitfor(timeout);
\r
516 procedure removefrombuffer(n : integer; var buffer:string);
\r
518 if n=length(buffer) then begin
\r
521 uniquestring(buffer);
\r
522 move(buffer[n+1],buffer[1],length(buffer)-n);
\r
523 setlength(buffer,length(buffer)-n);
\r
529 procedure available(sender:tobject;error:word);
\r
535 procedure tsc.available(sender:tobject;error:word);
\r
537 message : tmessageintransit;
\r
538 messagebytes : array[1..sizeof(tmessageintransit)] of char absolute message;
\r
541 //swriteln('received data on lcorelinkpipe');
\r
542 recvbuf := recvbuf + lcorelinkpiperecv.receivestr;
\r
543 while length(recvbuf) >= sizeof(tmessageintransit) do begin
\r
544 for i := 1 to sizeof(tmessageintransit) do begin
\r
545 messagebytes[i] := recvbuf[i];
\r
547 dispatchmessage(message.msg);
\r
549 removefrombuffer(sizeof(tmessageintransit),recvbuf);
\r
555 tm : tthreadmanager;
\r
556 threaddata : tthreaddata;
\r
557 pipeends : tfildes;
\r
560 structurelock := tcriticalsection.create;
\r
561 getthreadmanager(tm);
\r
562 threaddata := findthreaddata(tm.GetCurrentThreadId);
\r
563 threaddata.lcorethread := true;
\r
565 lcorelinkpipesend := pipeends[1];
\r
566 lcorelinkpiperecv := tlasio.create(nil);
\r
567 lcorelinkpiperecv.dup(pipeends[0]);
\r
568 lcorelinkpiperecv.ondataavailable := sc.available;
\r
573 lcorethreadtimers : thashtable;
\r
575 tltimerformsg = class(tltimer)
\r
579 procedure timer(sender : tobject);
\r
582 procedure tltimerformsg.timer(sender : tobject);
\r
586 ////swriteln('in tltimerformsg.timer');
\r
587 fillchar(msg,sizeof(msg),0);
\r
588 msg.message := WM_TIMER;
\r
592 dispatchmessage(msg);
\r
595 function SetTimer(ahWnd:HWND; nIDEvent:taddrint; uElapse:UINT; lpTimerFunc:tTIMERPROC):UINT;
\r
597 threaddata : tthreaddata;
\r
598 ltimer : tltimerformsg;
\r
599 tm : tthreadmanager;
\r
602 structurelock.acquire;
\r
604 window := findtree(@windows,inttostr(ahwnd));
\r
605 if window= nil then raise exception.create('invalid window');
\r
606 threaddata := findthreaddata(window.threadid);
\r
608 structurelock.release;
\r
610 if threaddata.lcorethread then begin
\r
611 getthreadmanager(tm);
\r
612 if tm.GetCurrentThreadId <> window.threadid then raise exception.create('timers on the lcore thread may only be added and removed from the lcore thread');
\r
613 if ahwnd = 0 then raise exception.create('timers on the lcore thread must be associated with a window handle');
\r
614 if @lptimerfunc <> nil then raise exception.create('seperate timer functions are not supported');
\r
616 //remove preexisting timer with same ID
\r
617 killtimer(ahwnd,nIDEvent);
\r
619 ltimer := tltimerformsg.create(nil);
\r
620 ltimer.interval := uelapse;
\r
621 ltimer.id := nidevent;
\r
622 ltimer.hwnd := ahwnd;
\r
623 ltimer.enabled := true;
\r
624 ltimer.ontimer := ltimer.timer;
\r
626 addtree(@lcorethreadtimers,inttostr(taddrint(ahwnd))+' '+inttostr(nIDEvent),ltimer);
\r
628 result := nidevent;
\r
630 raise exception.create('settimer not implemented for threads other than the lcore thread');
\r
634 function KillTimer(ahWnd:HWND; uIDEvent:taddrint):WINBOOL;
\r
636 threaddata : tthreaddata;
\r
637 ltimer : tltimerformsg;
\r
638 tm : tthreadmanager;
\r
641 structurelock.acquire;
\r
643 window := findtree(@windows,inttostr(ahwnd));
\r
644 if window= nil then raise exception.create('invalid window');
\r
645 threaddata := findthreaddata(window.threadid);
\r
647 structurelock.release;
\r
649 if threaddata.lcorethread then begin
\r
650 getthreadmanager(tm);
\r
651 if tm.GetCurrentThreadId <> window.threadid then raise exception.create('timers on the lcore thread may only be added and remove from the lcore thread');
\r
652 if ahwnd = 0 then raise exception.create('timers on the lcore thread must be associated with a window handle');
\r
653 ltimer := tltimerformsg(findtree(@lcorethreadtimers,inttostr(taddrint(ahwnd))+' '+inttostr(uIDEvent)));
\r
654 if ltimer <> nil then begin
\r
655 deltree(@lcorethreadtimers,inttostr(taddrint(ahwnd))+' '+inttostr(uIDEvent));
\r
662 raise exception.create('settimer not implemented for threads other than the lcore thread');
\r