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
18 {$if (fpc_version < 2) or ((fpc_version=2) and ((fpc_release < 2) or ((fpc_release = 2) and (fpc_patch < 2)) ))}
\r
19 {$error this code is only supported under fpc 2.2.2 and above due to bugs in the eventobject code in older versions}
\r
29 hwnd=qword; //window handles are monotonically increasing 64 bit integers,
\r
30 //this should allow for a million windows per second for over half
\r
33 twndproc=function(ahWnd:HWND; auMsg:Integer; awParam:WPARAM; alParam:LPARAM):Integer; stdcall;
\r
38 lpfnwndproc : twndproc;
\r
39 cbclsextra : integer;
\r
40 cbwndextra : integer;
\r
41 hinstance : thinstance;
\r
44 hbrbackground : hbrush;
\r
45 lpszmenuname : pchar;
\r
46 lpszclassname : pchar;
\r
48 PWNDCLASS=^twndclass;
\r
52 tTIMERPROC = procedure (ahwnd:HWND; umsg:integer; idevent:taddrint;dwtime:taddrint);stdcall;
\r
72 THevent=TEventObject;
\r
74 WS_EX_TOOLWINDOW = $80;
\r
75 WS_POPUP = longint($80000000);
\r
80 INFINITE = syncobjs.infinite;
\r
81 function getwindowlongptr(ahwnd:hwnd;nindex:integer) : taddrint;
\r
82 function setwindowlongptr(ahwnd:hwnd;nindex:integer;dwNewLong : taddrint) : taddrint;
\r
83 function DefWindowProc(ahWnd:HWND; auMsg:Integer; awParam:WPARAM; alParam:LPARAM):Integer; stdcall;
\r
84 function RegisterClass(const lpWndClass:TWNDCLASS):ATOM;
\r
85 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
86 function DestroyWindow(ahWnd:HWND):WINBOOL;
\r
87 function PostMessage(hWnd:HWND; Msg:UINT; wParam:WPARAM; lParam:LPARAM):WINBOOL;
\r
88 function PeekMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): WINBOOL;
\r
89 function DispatchMessage(const lpMsg: TMsg): Longint;
\r
90 function GetMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT): WINBOOL;
\r
91 function SetEvent(hEvent:THevent):WINBOOL;
\r
92 function CreateEvent(lpEventAttributes:PSECURITYATTRIBUTES; bManualReset:WINBOOL; bInitialState:WINBOOL; lpName:pchar):tHevent;
\r
93 function terminatethread(threadhandle : tthreadid;dummy:integer) : boolean;
\r
94 function waitforsingleevent(event:thevent;timeout:cardinal) : twaitresult;
\r
95 function SetTimer(ahWnd:HWND; nIDEvent:taddrint; uElapse:UINT; lpTimerFunc:tTIMERPROC):UINT;
\r
96 function KillTimer(ahWnd:HWND; uIDEvent:taddrint):WINBOOL;
\r
102 baseunix,unix,lcore,unixutil,ltimevalstuff,sockets;//,safewriteln;
\r
106 tmessageintransit = class
\r
108 next : tmessageintransit;
\r
111 tthreaddata = class
\r
112 messagequeue : tmessageintransit;
\r
113 messageevent : teventobject;
\r
115 lcorethread : boolean;
\r
116 nexttimer : ttimeval;
\r
117 threadid : integer;
\r
121 extrawindowmemory : pointer;
\r
122 threadid : tthreadid;
\r
123 windowproc : twndproc;
\r
127 structurelock : tcriticalsection;
\r
128 threaddata : thashtable;
\r
129 windowclasses : thashtable;
\r
130 lcorelinkpipesend : integer;
\r
131 lcorelinkpiperecv : tlasio;
\r
132 windows : thashtable;
\r
133 //I would rather things crash immediately
\r
134 //if they use an insufficiant size type
\r
135 //than crash after over four billion
\r
136 //windows have been made ;)
\r
137 nextwindowhandle : qword = $100000000;
\r
140 //findthreaddata should only be called while holding the structurelock
\r
141 function findthreaddata(threadid : integer) : tthreaddata;
\r
143 result := tthreaddata(findtree(@threaddata,inttostr(threadid)));
\r
144 if result = nil then begin
\r
145 result := tthreaddata.create;
\r
146 result.messageevent := teventobject.create(nil,false,false,inttostr(taddrint(result)));
\r
147 result.nexttimer := tv_invalidtimebig;
\r
148 result.threadid := threadid;
\r
149 addtree(@threaddata,inttostr(threadid),result);
\r
153 //deletethreaddataifunused should only be called while holding the structurelock
\r
154 procedure deletethreaddataifunused(athreaddata : tthreaddata);
\r
156 //writeln('in deletethreaddataifunused');
\r
157 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
158 //writeln('threaddata is unused, freeing messageevent');
\r
159 athreaddata.messageevent.free;
\r
160 //writeln('freeing thread data object');
\r
162 //writeln('deleting thread data object from hashtable');
\r
163 deltree(@threaddata,inttostr(athreaddata.threadid));
\r
164 //writeln('finished deleting thread data');
\r
166 //writeln('thread data is not unused');
\r
170 function getwindowlongptr(ahwnd:hwnd;nindex:integer) : taddrint;
\r
174 structurelock.acquire;
\r
176 window := findtree(@windows,inttostr(ahwnd));
\r
177 if window <> nil then begin
\r
178 result := paddrint(taddrint(window.extrawindowmemory)+nindex)^;
\r
183 structurelock.release;
\r
187 function setwindowlongptr(ahwnd:hwnd;nindex:integer;dwNewLong : taddrint) : taddrint;
\r
191 structurelock.acquire;
\r
193 window := findtree(@windows,inttostr(ahwnd));
\r
194 if window <> nil then begin
\r
195 result := paddrint(taddrint(window.extrawindowmemory)+nindex)^;
\r
196 paddrint(taddrint(window.extrawindowmemory)+nindex)^ := dwnewlong;
\r
201 structurelock.release;
\r
207 function DefWindowProc(ahWnd:HWND; auMsg:Integer; awParam:WPARAM; alParam:LPARAM):Integer; stdcall;
\r
212 function strdup(s:pchar) : pchar;
\r
214 //swriteln('in strdup, about to allocate memory');
\r
215 result := getmem(strlen(s)+1);
\r
216 //swriteln('about to copy string');
\r
218 //swriteln('leaving strdup');
\r
221 function RegisterClass(const lpWndClass:TWNDCLASS):ATOM;
\r
223 storedwindowclass:pwndclass;
\r
225 structurelock.acquire;
\r
227 //swriteln('in registerclass, about to check for duplicate window class');
\r
228 storedwindowclass := findtree(@windowclasses, lpwndclass.lpszclassname);
\r
229 if storedwindowclass <> nil then begin
\r
231 if comparebyte(storedwindowclass^,lpwndclass,sizeof(twndclass)-sizeof(pchar)-sizeof(pchar)) <> 0 then begin
\r
232 //swriteln('duplicate window class registered with different settings');
\r
233 raise exception.create('duplicate window class registered with different settings');
\r
235 //swriteln('duplicate window class registered with same settings, tollerated');
\r
238 //swriteln('about to allocate memory for new windowclass');
\r
239 storedwindowclass := getmem(sizeof(twndclass));
\r
240 //swriteln('about to copy windowclass from parameter');
\r
241 move(lpwndclass,storedwindowclass^,sizeof(twndclass));
\r
242 //swriteln('about to copy strings');
\r
243 if lpwndclass.lpszmenuname <> nil then storedwindowclass.lpszmenuname := strdup(lpwndclass.lpszmenuname);
\r
244 if lpwndclass.lpszclassname <> nil then storedwindowclass.lpszclassname := strdup(lpwndclass.lpszclassname);
\r
245 //swriteln('about to add result to list of windowclasses');
\r
246 addtree(@windowclasses,lpwndclass.lpszclassname,storedwindowclass);
\r
248 //swriteln('about to return result');
\r
249 result := storedwindowclass;
\r
250 //swriteln('leaving registerclass');
\r
252 structurelock.release;
\r
256 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
258 wndclass : pwndclass;
\r
259 tm : tthreadmanager;
\r
262 structurelock.acquire;
\r
264 window := twindow.create;
\r
265 window.hwnd := nextwindowhandle;
\r
266 result := window.hwnd;
\r
267 nextwindowhandle := nextwindowhandle + 1;
\r
268 addtree(@windows,inttostr(window.hwnd),window);
\r
269 wndclass := findtree(@windowclasses,lpclassname);
\r
270 window.extrawindowmemory := getmem(wndclass.cbwndextra);
\r
272 getthreadmanager(tm);
\r
273 window.threadid := tm.GetCurrentThreadId;
\r
274 window.windowproc := wndclass.lpfnwndproc;
\r
276 structurelock.release;
\r
279 function DestroyWindow(ahWnd:HWND):WINBOOL;
\r
282 windowthreaddata : tthreaddata;
\r
283 currentmessage : tmessageintransit;
\r
284 prevmessage : tmessageintransit;
\r
286 //writeln('started to destroy window');
\r
287 structurelock.acquire;
\r
289 window := twindow(findtree(@windows,inttostr(ahwnd)));
\r
290 if window <> nil then begin
\r
291 freemem(window.extrawindowmemory);
\r
292 //writeln('aboute to delete window from windows structure');
\r
293 deltree(@windows,inttostr(ahwnd));
\r
294 //writeln('deleted window from windows structure');
\r
295 windowthreaddata := tthreaddata(findtree(@threaddata,inttostr(window.threadid)));
\r
297 if windowthreaddata <> nil then begin
\r
298 //writeln('found thread data scanning for messages to clean up');
\r
299 currentmessage := windowthreaddata.messagequeue;
\r
300 prevmessage := nil;
\r
301 while currentmessage <> nil do begin
\r
302 while (currentmessage <> nil) and (currentmessage.msg.hwnd = ahwnd) do begin
\r
303 if prevmessage = nil then begin
\r
304 windowthreaddata.messagequeue := currentmessage.next;
\r
306 prevmessage.next := currentmessage.next;
\r
308 currentmessage.free;
\r
309 if prevmessage = nil then begin
\r
310 currentmessage := windowthreaddata.messagequeue;
\r
312 currentmessage := prevmessage.next;
\r
315 if currentmessage <> nil then begin
\r
316 prevmessage := currentmessage;
\r
317 currentmessage := currentmessage.next;
\r
320 //writeln('deleting thread data structure if it is unused');
\r
321 deletethreaddataifunused(windowthreaddata);
\r
323 //writeln('there is no thread data to search for messages to cleanup');
\r
325 //writeln('freeing window');
\r
332 structurelock.release;
\r
334 //writeln('window destroyed');
\r
339 function PostMessage(hWnd:HWND; Msg:UINT; wParam:WPARAM; lParam:LPARAM):WINBOOL;
\r
341 threaddata : tthreaddata;
\r
342 message : tmessageintransit;
\r
343 messagequeueend : tmessageintransit;
\r
346 structurelock.acquire;
\r
348 window := findtree(@windows,inttostr(hwnd));
\r
349 if window <> nil then begin
\r
350 threaddata := findthreaddata(window.threadid);
\r
351 message := tmessageintransit.create;
\r
352 message.msg.hwnd := hwnd;
\r
353 message.msg.message := msg;
\r
354 message.msg.wparam := wparam;
\r
355 message.msg.lparam := lparam;
\r
356 if threaddata.lcorethread then begin
\r
357 //swriteln('posting message to lcore thread');
\r
358 fdwrite(lcorelinkpipesend,message,sizeof(message));
\r
360 //writeln('posting message to non lcore thread');
\r
361 if threaddata.messagequeue = nil then begin
\r
362 threaddata.messagequeue := message;
\r
364 messagequeueend := threaddata.messagequeue;
\r
365 while messagequeueend.next <> nil do begin
\r
366 messagequeueend := messagequeueend.next;
\r
368 messagequeueend.next := message;
\r
371 //writeln('message added to queue');
\r
372 if threaddata.waiting then threaddata.messageevent.setevent;
\r
379 structurelock.release;
\r
384 function gettickcount : dword;
\r
390 result64 := (tv.tv_sec*1000)+(tv.tv_usec div 1000);
\r
391 result := result64;
\r
394 function DispatchMessage(const lpMsg: TMsg): Longint;
\r
396 timerproc : ttimerproc;
\r
398 windowproc : twndproc;
\r
400 ////swriteln('in dispatchmessage, msg.hwnd='+inttohex(taddrint(lpmsg.hwnd),16));
\r
401 if (lpmsg.lparam <> 0) and (lpmsg.message = WM_TIMER) then begin
\r
402 timerproc := ttimerproc(lpmsg.lparam);
\r
403 timerproc(lpmsg.hwnd,lpmsg.message,lpmsg.wparam,gettickcount);
\r
406 structurelock.acquire;
\r
408 window := findtree(@windows,inttostr(lpmsg.hwnd));
\r
409 //we have to get the window procedure while the structurelock
\r
410 //is still held as the window could be destroyed from another thread
\r
412 if window <> nil then begin
\r
413 windowproc := window.windowproc;
\r
418 structurelock.release;
\r
420 if assigned(windowproc) then begin
\r
421 result := windowproc(lpmsg.hwnd,lpmsg.message,lpmsg.wparam,lpmsg.lparam);
\r
428 procedure processtimers;
\r
432 function GetMessageinternal(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT; wremovemsg : UINT;peek:boolean): WINBOOL;
\r
434 tm : tthreadmanager;
\r
435 threaddata : tthreaddata;
\r
436 message : tmessageintransit;
\r
438 timeouttv : ttimeval;
\r
442 if hwnd <> 0 then raise exception.create('getting messages for an individual window is not supported');
\r
443 if (wmsgfiltermin <> 0) or (wmsgfiltermax <> 0) then raise exception.create('message filtering is not supported');
\r
444 structurelock.acquire;
\r
447 getthreadmanager(tm);
\r
448 threaddata := findthreaddata(tm.GetCurrentThreadId);
\r
449 if threaddata.lcorethread then raise exception.create('get/peek message cannot be used in the lcore thread');
\r
450 message := threaddata.messagequeue;
\r
451 gettimeofday(nowtv);
\r
452 while (not peek) and (message=nil) and (not tv_compare(nowtv,threaddata.nexttimer)) do begin
\r
453 threaddata.waiting := true;
\r
454 structurelock.release;
\r
455 if (threaddata.nexttimer.tv_sec = TV_invalidtimebig.tv_sec) and (threaddata.nexttimer.tv_usec = TV_invalidtimebig.tv_usec) then begin
\r
456 threaddata.messageevent.waitfor(INFINITE);
\r
459 timeouttv := threaddata.nexttimer;
\r
460 timeoutms := (timeouttv.tv_sec * 1000)+(timeouttv.tv_usec div 1000);
\r
461 //i'm assuming the timeout is in milliseconds
\r
462 if (timeoutms > maxlongint) then timeoutms := maxlongint;
\r
463 threaddata.messageevent.waitfor(timeoutms);
\r
466 structurelock.acquire;
\r
467 threaddata.waiting := false;
\r
468 message := threaddata.messagequeue;
\r
469 gettimeofday(nowtv);
\r
471 if (message=nil) and tv_compare(nowtv,threaddata.nexttimer) then begin
\r
474 message := threaddata.messagequeue;
\r
475 if message <> nil then begin
\r
476 lpmsg := message.msg;
\r
477 if wremovemsg=PM_REMOVE then begin
\r
478 threaddata.messagequeue := message.next;
\r
484 deletethreaddataifunused(threaddata);
\r
486 structurelock.release;
\r
490 function GetMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax: UINT): WINBOOL;
\r
492 result := getmessageinternal(lpmsg,hwnd,wmsgfiltermin,wmsgfiltermax,PM_REMOVE,false);
\r
495 function PeekMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): WINBOOL;
\r
497 result := getmessageinternal(lpmsg,hwnd,wmsgfiltermin,wmsgfiltermax,wRemoveMsg,true);
\r
500 function SetEvent(hEvent:THevent):WINBOOL;
\r
506 function CreateEvent(lpEventAttributes:PSECURITYATTRIBUTES; bManualReset:WINBOOL; bInitialState:WINBOOL; lpName:pchar):tHevent;
\r
508 result := teventobject.create(lpeventattributes,bmanualreset,binitialstate,lpname);
\r
511 function terminatethread(threadhandle:tthreadid;dummy : integer) : boolean;
\r
513 tm : tthreadmanager;
\r
515 getthreadmanager(tm);
\r
516 tm.killthread(threadhandle);
\r
520 function waitforsingleevent(event:thevent;timeout:cardinal) : twaitresult;
\r
522 result := event.waitfor(timeout);
\r
525 procedure removefrombuffer(n : integer; var buffer:string);
\r
527 if n=length(buffer) then begin
\r
530 uniquestring(buffer);
\r
531 move(buffer[n+1],buffer[1],length(buffer)-n);
\r
532 setlength(buffer,length(buffer)-n);
\r
538 procedure available(sender:tobject;error:word);
\r
544 procedure tsc.available(sender:tobject;error:word);
\r
546 message : tmessageintransit;
\r
547 messagebytes : array[1..sizeof(tmessageintransit)] of char absolute message;
\r
550 //swriteln('received data on lcorelinkpipe');
\r
551 recvbuf := recvbuf + lcorelinkpiperecv.receivestr;
\r
552 while length(recvbuf) >= sizeof(tmessageintransit) do begin
\r
553 for i := 1 to sizeof(tmessageintransit) do begin
\r
554 messagebytes[i] := recvbuf[i];
\r
556 dispatchmessage(message.msg);
\r
558 removefrombuffer(sizeof(tmessageintransit),recvbuf);
\r
564 tm : tthreadmanager;
\r
565 threaddata : tthreaddata;
\r
566 pipeends : tfildes;
\r
569 structurelock := tcriticalsection.create;
\r
570 getthreadmanager(tm);
\r
571 threaddata := findthreaddata(tm.GetCurrentThreadId);
\r
572 threaddata.lcorethread := true;
\r
574 lcorelinkpipesend := pipeends[1];
\r
575 lcorelinkpiperecv := tlasio.create(nil);
\r
576 lcorelinkpiperecv.dup(pipeends[0]);
\r
577 lcorelinkpiperecv.ondataavailable := sc.available;
\r
582 lcorethreadtimers : thashtable;
\r
584 tltimerformsg = class(tltimer)
\r
588 procedure timer(sender : tobject);
\r
591 procedure tltimerformsg.timer(sender : tobject);
\r
595 ////swriteln('in tltimerformsg.timer');
\r
596 fillchar(msg,sizeof(msg),0);
\r
597 msg.message := WM_TIMER;
\r
601 dispatchmessage(msg);
\r
604 function SetTimer(ahWnd:HWND; nIDEvent:taddrint; uElapse:UINT; lpTimerFunc:tTIMERPROC):UINT;
\r
606 threaddata : tthreaddata;
\r
607 ltimer : tltimerformsg;
\r
608 tm : tthreadmanager;
\r
611 structurelock.acquire;
\r
613 window := findtree(@windows,inttostr(ahwnd));
\r
614 if window= nil then raise exception.create('invalid window');
\r
615 threaddata := findthreaddata(window.threadid);
\r
617 structurelock.release;
\r
619 if threaddata.lcorethread then begin
\r
620 getthreadmanager(tm);
\r
621 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
622 if ahwnd = 0 then raise exception.create('timers on the lcore thread must be associated with a window handle');
\r
623 if @lptimerfunc <> nil then raise exception.create('seperate timer functions are not supported');
\r
625 //remove preexisting timer with same ID
\r
626 killtimer(ahwnd,nIDEvent);
\r
628 ltimer := tltimerformsg.create(nil);
\r
629 ltimer.interval := uelapse;
\r
630 ltimer.id := nidevent;
\r
631 ltimer.hwnd := ahwnd;
\r
632 ltimer.enabled := true;
\r
633 ltimer.ontimer := ltimer.timer;
\r
635 addtree(@lcorethreadtimers,inttostr(taddrint(ahwnd))+' '+inttostr(nIDEvent),ltimer);
\r
637 result := nidevent;
\r
639 raise exception.create('settimer not implemented for threads other than the lcore thread');
\r
643 function KillTimer(ahWnd:HWND; uIDEvent:taddrint):WINBOOL;
\r
645 threaddata : tthreaddata;
\r
646 ltimer : tltimerformsg;
\r
647 tm : tthreadmanager;
\r
650 structurelock.acquire;
\r
652 window := findtree(@windows,inttostr(ahwnd));
\r
653 if window= nil then raise exception.create('invalid window');
\r
654 threaddata := findthreaddata(window.threadid);
\r
656 structurelock.release;
\r
658 if threaddata.lcorethread then begin
\r
659 getthreadmanager(tm);
\r
660 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
661 if ahwnd = 0 then raise exception.create('timers on the lcore thread must be associated with a window handle');
\r
662 ltimer := tltimerformsg(findtree(@lcorethreadtimers,inttostr(taddrint(ahwnd))+' '+inttostr(uIDEvent)));
\r
663 if ltimer <> nil then begin
\r
664 deltree(@lcorethreadtimers,inttostr(taddrint(ahwnd))+' '+inttostr(uIDEvent));
\r
671 raise exception.create('settimer not implemented for threads other than the lcore thread');
\r