-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Messages.ahk
637 lines (464 loc) · 17.3 KB
/
Messages.ahk
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Modular Simulator Controller System - Inter Process Messages ;;;
;;; ;;;
;;; Author: Oliver Juwig (TheBigO) ;;;
;;; License: (2024) Creative Commons - BY-NC-SA ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;-------------------------------------------------------------------------;;;
;;; Global Include Section ;;;
;;;-------------------------------------------------------------------------;;;
#Include "..\Framework\Framework.ahk"
;;;-------------------------------------------------------------------------;;;
;;; Local Include Section ;;;
;;;-------------------------------------------------------------------------;;;
#Include "..\Libraries\Task.ahk"
;;;-------------------------------------------------------------------------;;;
;;; Public Constant Section ;;;
;;;-------------------------------------------------------------------------;;;
global kLocalMessage := 0
global kWindowMessage := 1
global kPipeMessage := 2
global kFileMessage := 3
;;;-------------------------------------------------------------------------;;;
;;; Public Classes Section ;;;
;;;-------------------------------------------------------------------------;;;
;;;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -;;;
;;; Class MessageManager ;;;
;;;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -;;;
class MessageManager extends PeriodicTask {
static sPriority := getMultiMapValue(readMultiMap(getFileName("Core Settings.ini", kUserConfigDirectory, kConfigDirectory)), "Messages", "Schedule", 200)
static sMessageHandlers := false
static sOutgoingMessages := []
iPaused := false
class MessageHandler {
iHandler := false
Handler {
Get {
return this.iHandler
}
}
__New(handler := false) {
this.iHandler := handler
}
call(category, data) {
throw "Virtual method MessageHandler.call must be implemented in a subclass..."
}
}
class FunctionMessageHandler extends MessageManager.MessageHandler {
call(category, data) {
local handler := this.Handler
if handler
handler.Call(category, data)
else if InStr(data, ":") {
data := StrSplit(data, ":", , 2)
withProtection(%data[1]%, string2Values(";", data[2])*)
}
else
withProtection(%data%)
return false
}
}
class MethodMessageHandler extends MessageManager.MessageHandler {
iObject := false
Object {
Get {
return this.iObject
}
}
__New(object, handler := false) {
this.iObject := object
super.__New(handler)
}
call(category, data) {
local handler := this.Handler
if handler
handler.Call(category, this.Object, data)
else if InStr(data, ":") {
data := StrSplit(data, ":", , 2)
return withProtection(ObjBindMethod(this.Object, data[1], string2Values(";", data[2])*))
}
else
return withProtection(ObjBindMethod(this.Object, data))
return false
}
}
class MessagesDispatcher extends Task {
static sWait := getMultiMapValue(readMultiMap(getFileName("Core Settings.ini", kUserConfigDirectory, kConfigDirectory)), "Messages", "Dispatch", 100)
iMessages := false
__New(messages) {
this.iMessages := messages
super.__New(false, MessageManager.MessagesDispatcher.sWait)
}
run() {
local ignore, message
for ignore, message in this.iMessages
try {
withProtection(ObjBindMethod(message[1], "call", message[2], message[3]))
}
catch Any as exception {
logError(exception, true)
}
return false
}
}
Paused {
Get {
return this.iPaused
}
}
static MessageHandlers[key?] {
Get {
MessageManager.initializeMessageHandlers()
return (isSet(key) ? MessageManager.sMessageHandlers[key] : MessageManager.sMessageHandlers)
}
Set {
MessageManager.initializeMessageHandlers()
return (key ? (MessageManager.sMessageHandlers[key] := value) : (MessageManager.sMessageHandlers := value))
}
}
OutgoingMessages[key?] {
Get {
return (isSet(key) ? MessageManager.sOutgoingMessages[key] : MessageManager.sOutgoingMessages)
}
Set {
return (isSet(key) ? (MessageManager.sOutgoingMessages[key] := value) : (MessageManager.sOutgoingMessages := value))
}
}
__New() {
MessageManager.Instance := this
super.__New(false, 4000, kHighPriority)
}
static initializeMessageHandlers() {
if !MessageManager.sMessageHandlers {
local cMap := Map()
cMap.CaseSens := false
MessageManager.sMessageHandlers := cMap
}
}
static isPaused() {
return MessageManager.Instance.Paused
}
static pause() {
MessageManager.Instance.iPaused := true
}
static resume() {
MessageManager.Instance.iPaused := false
}
receivePipeMessages() {
local messageHandlers := MessageManager.MessageHandlers
local result := []
local messageHandler, category, data, handler, pipeName
for category, handler in messageHandlers {
if (category = "*")
continue
pipeName := "\\.\pipe\SC." . category
if DllCall("WaitNamedPipe", "Str", pipeName, "UInt", 0xF)
loop Read, pipeName {
data := StrSplit(A_LoopReadLine, ":", , 2)
category := data[1]
messageHandler := (messageHandlers.Has(category) ? messageHandlers[category] : messageHandlers["*"])
logMessage(kLogInfo, translate("Dispatching message `"") . category . translate("`": ") . data[2])
result.Push(Array(messageHandler, category, decode(data[2])))
}
}
return result
}
receiveFileMessages() {
local result := []
local messageHandlers, messageHandler, result, pid, fileName, file, line, data, category
pid := ProcessExist()
fileName := (kTempDirectory . "Messages\" . pid . ".msg")
if FileExist(fileName) {
file := false
try {
file := FileOpen(fileName, "rw-rwd")
if !file
return result
}
catch Any as exception {
logError(exception)
if isDevelopment()
logMessage(kLogWarn, "Waiting for file `"" . fileName . "`"...")
return result
}
messageHandlers := MessageManager.MessageHandlers
while !file.AtEOF {
line := Trim(file.ReadLine(), " `t`n`r")
if (StrLen(line) == 0)
break
if InStr(line, ":") {
data := StrSplit(line, ":", , 2)
category := data[1]
messageHandler := (messageHandlers.Has(category) ? messageHandlers[category] : messageHandlers["*"])
logMessage(kLogInfo, translate("Dispatching message `"") . category . (data[2] ? translate("`": ") . data[2] : translate("`"")))
result.Push(Array(messageHandler, category, decode(data[2])))
}
}
file.Length := 0
file.Close()
}
return result
}
sendPipeMessage(category, data) {
local zero := 0
local pipeName, pipe
static ERROR_PIPE_CONNECTED := 535
static ERROR_PIPE_LISTENING := 536
pipeName := "\\.\pipe\SC." . category
pipe := DllCall("CreateNamedPipe", "str", pipeName, "uint", 2, "uint", 0, "uint", 255, "uint", 1024, "uint", 1024, "uint", 0, "ptr", 0)
DllCall("ConnectNamedPipe", "ptr", pipe, "ptr", 0)
if (true || (A_LastError = ERROR_PIPE_CONNECTED)) {
category := (chr(0xfeff) . (category . ":" . encode(data)))
DllCall("WriteFile", "ptr", pipe, "str", category, "uint", (StrLen(category) + 1) * 2, "uint*", &zero, "ptr", 0)
DllCall("CloseHandle", "ptr", pipe)
return true
}
else
return false
}
sendFileMessage(pid, category, data) {
local text := category . ":" . encode(data) . "`n"
try {
FileAppend(text, kTempDirectory . "Messages\" . pid . ".msg")
}
catch Any as exception {
return false
}
return true
}
receiveMessages() {
local fileMessages := this.receiveFileMessages()
return ((fileMessages.Length > 0) ? fileMessages : this.receivePipeMessages())
}
deliverMessages() {
local outgoingMessages := this.OutgoingMessages
local failed := []
local worked := true
local handler
while worked {
worked := false
if (outgoingMessages.Length > 0) {
handler := outgoingMessages[1]
if !inList(failed, handler)
if handler.Call() {
outgoingMessages.RemoveAt(1)
worked := true
}
else
failed.Push(handler)
}
}
}
run() {
local messages
if !this.Paused {
protectionOn()
try {
messages := this.receiveMessages()
if (messages.Length > 0)
MessageManager.MessagesDispatcher(messages).start()
else
this.deliverMessages()
}
finally {
protectionOff()
}
}
this.Sleep := MessageManager.sPriority
}
messageSend(messageType, category, data, target := false, request := "NORM") {
local messageHandlers, messageHandler
switch messageType {
case kLocalMessage:
logMessage(kLogInfo, translate("Sending message `"") . category . (data ? translate("`": ") . data : translate("`"")) . translate(" in current process"))
messageHandlers := MessageManager.MessageHandlers
messageHandler := (messageHandlers.Has(category) ? messageHandlers[category] : messageHandler := messageHandlers["*"])
logMessage(kLogInfo, translate("Dispatching message `"") . category . (data ? translate("`": ") . data : translate("`"")))
Task.startTask(ObjBindMethod(messageHandler, "call", category, data))
case kWindowMessage:
logMessage(kLogInfo, translate("Sending message `"") . category . (data ? translate("`": ") . data : translate("`"")) . translate(" to target ") . target)
if (request = "INTR")
sendWindowMessage(target, category, data, request)
else
this.OutgoingMessages.Push(sendWindowMessage.Bind(target, category, data, request))
case kPipeMessage:
logMessage(kLogInfo, translate("Sending message `"") . category . (data ? translate("`": ") . data : translate("`"")))
this.OutgoingMessages.Push(ObjBindMethod(this, "sendPipeMessage", category, data))
case kFileMessage:
logMessage(kLogInfo, translate("Sending message `"") . category . (data ? translate("`": ") . data : translate("`"")) . translate(" to target ") . target)
this.OutgoingMessages.Push(ObjBindMethod(this, "sendFileMessage", target, category, data))
default:
throw "Unknown message type (" . messageType . ") detected in messageSend..."
}
}
}
;;;-------------------------------------------------------------------------;;;
;;; Private Function Declaration Section ;;;
;;;-------------------------------------------------------------------------;;;
createMessageReceiver() {
local messageReceiverGui := Gui("ToolWindow -Caption -SysMenu", A_ScriptName)
messageReceiverGui.BackColor := "D0D0D0"
messageReceiverGui.Add("Text", "X10 Y10", "Modular Simulator Controller System")
messageReceiverGui.Add("Text", , A_ScriptName)
messageReceiverGui.MarginX := "10"
messageReceiverGui.MarginY := "10"
messageReceiverGui.Show("X-100 Y-100 W1 H1 NA")
WinSetTransparent(0, messageReceiverGui)
}
unknownMessageHandler(category, data) {
logMessage(kLogCritical, translate("Unhandled message `"") . category . translate("`": ") . data)
}
encodeDWORD(string) {
local result := 0
loop StrLen(string) {
result <<= 8
result += Ord(SubStr(string, A_Index, 1))
}
return result
}
decodeDWORD(data) {
local result := ""
local char
loop 4 {
result := (Chr(data & 0xFF) . result)
data >>= 8
}
until !data
return result
}
sendWindowMessage(target, category, data, request) {
local curDetectHiddenWindows := A_DetectHiddenWindows
local curTitleMatchMode := A_TitleMatchMode
local dwData, cbData, lpData, struct, message, wParam, lParam
category := (category . ":" . data)
;---------------------------------------------------------------------------
; construct the message to send
;---------------------------------------------------------------------------
dwData := encodeDWORD(request)
cbData := (StrLen(category) * 2) + 1 ; length of DATA string (incl. ZERO)
lpData := &category ; pointer to DATA string
;---------------------------------------------------------------------------
; put the message in a COPYDATASTRUCT
;---------------------------------------------------------------------------
struct := Buffer(A_PtrSize * 3, 0) ; initialize COPYDATASTRUCT
NumPut("UInt", dwData, struct, A_PtrSize * 0) ; DWORD
NumPut("UInt", cbData, struct, A_PtrSize * 1) ; DWORD
NumPut("UInt", lpData, struct, A_PtrSize * 2) ; 32bit pointer
;---------------------------------------------------------------------------
; parameters for PostMessage command
;---------------------------------------------------------------------------
message := 0x4a ; WM_COPYDATA
wParam := "" ; not used
lParam := &struct ; COPYDATASTRUCT
SetTitleMatchMode(2) ; match part of the title
DetectHiddenWindows(true) ; needed for sending messages
try {
PostMessage(message, wParam, lParam, "", target)
return true
}
catch Any as exception {
logError(exception, true)
return false
}
finally {
DetectHiddenWindows(curDetectHiddenWindows)
SetTitleMatchMode(curTitleMatchMode)
}
}
receiveWindowMessage(wParam, lParam, *) {
local messageHandlers, messageHandler, dwData, cbData, lpData, request, length, category, data
;---------------------------------------------------------------------------
; retrieve info from COPYDATASTRUCT
;---------------------------------------------------------------------------
dwData := NumGet(lParam + A_PtrSize * 0, "UPtr") ; DWORD encoded request
cbData := NumGet(lParam + A_PtrSize * 1, "UPtr") ; length of DATA string (incl ZERO)
lpData := NumGet(lParam + A_PtrSize * 2, "UPtr") ; pointer to DATA string
;---------------------------------------------------------------------------
; interpret available info
;---------------------------------------------------------------------------
request := decodeDWORD(dwData) ; 4-char decoded request
if ((request = "RS") || (request = "SD")) {
length := (cbData - 1) ; length of DATA string (excl ZERO)
data := StrGet(lpData, length, "") ; DATA string from pointer
}
else if ((request = "NORM") || (request = "INTR")) {
length := (cbData - 1) / 2 ; length of DATA string (excl ZERO)
data := StrGet(lpData, length) ; DATA string from pointer
}
else
throw "Unhandled message received: " . request . " in receiveWindowMessage..."
data := StrSplit(data, ":", , 2)
category := data[1]
messageHandlers := MessageManager.MessageHandlers
messageHandler := (messageHandlers.Has(category) ? messageHandlers[category] : messageHandlers["*"])
logMessage(kLogInfo, translate("Dispatching message `"") . category . (data[2] ? translate("`": ") . data[2] : translate("`"")))
if ((request = "RS") || (request = "INTR")) {
try {
withProtection(ObjBindMethod(messageHandler, "call", category, data[2]))
}
catch Any as exception {
logError(exception, true)
}
}
else
Task.startTask(ObjBindMethod(messageHandler, "call", category, data[2]))
}
stopMessageManager(arguments*) {
local pid
if ((arguments.Length > 0) && inList(["Logoff", "Shutdown"], arguments[1]))
return false
Task.removeTask(MessageManager.Instance)
pid := ProcessExist()
if FileExist(kTempDirectory . "Messages\" . pid . ".msg")
deleteFile(kTempDirectory . "Messages\" . pid . ".msg")
return false
}
startMessageManager(*) {
local pid
DirCreate(kTempDirectory . "Messages")
OnMessage(0x4a, receiveWindowMessage)
registerMessageHandler("*", unknownMessageHandler)
MessageManager().start()
pid := ProcessExist()
if FileExist(kTempDirectory . "Messages\" . pid . ".msg")
deleteFile(kTempDirectory . "Messages\" . pid . ".msg")
OnExit(stopMessageManager)
}
;;;-------------------------------------------------------------------------;;;
;;; Public Function Declaration Section ;;;
;;;-------------------------------------------------------------------------;;;
functionMessageHandler(category, data) {
local function
if InStr(data, ":") {
data := StrSplit(data, ":", , 2)
return withProtection(%data[1]%, string2Values(";", data[2])*)
}
else
return withProtection(%data%)
}
methodMessageHandler(category, object, data) {
if InStr(data, ":") {
data := StrSplit(data, ":", , 2)
return withProtection(ObjBindMethod(object, data[1], string2Values(";", data[2])*))
}
else
return withProtection(ObjBindMethod(object, data))
}
registerMessageHandler(category, handler, object := false) {
if isInstance(handler, MessageManager.MessageHandler)
MessageManager.MessageHandlers[category] := handler
else {
if object
MessageManager.MessageHandlers[category] := MessageManager.MethodMessageHandler(object, handler)
else
MessageManager.MessageHandlers[category] := MessageManager.FunctionMessageHandler(handler)
}
}
messageSend(messageType, category, data, target := false, request := "NORM") {
MessageManager.Instance.messageSend(messageType, category, data, target, request)
}
;;;-------------------------------------------------------------------------;;;
;;; Initialization Section ;;;
;;;-------------------------------------------------------------------------;;;
createMessageReceiver()
startMessageManager()