Repository navigation
Expand file tree
/
Copy pathArjUI.lua
More file actions
5046 lines (4570 loc) · 217 KB
/
Copy pathArjUI.lua
File metadata and controls
5046 lines (4570 loc) · 217 KB
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- ArjUI Core v1.2 (Mudlet 4.19.1)
-- GMCP-based UI for Duris MUD
-- Dark Fantasy Aesthetic
ArjUI = ArjUI or {}
ArjUI.VERSION = "1.3.0"
ArjUI.eventHandlers = ArjUI.eventHandlers or {}
ArjUI.playerName = ArjUI.playerName or nil
ArjUI.captureTriggers = ArjUI.captureTriggers or {}
ArjUI.capturing = nil
ArjUI.captureBuffer = {}
ArjUI.customCommands = ArjUI.customCommands or {
players = {}, -- { {text="Label", cmd="command"}, ... } - target auto-appended
mobs = {},
objects = {},
inventory = {},
equipment = {}
}
-- Private messaging system (session-only, not persisted)
ArjUI.privateChats = {} -- { [playerName] = { window, history, unread } }
ArjUI.tellContacts = {} -- List of players we've had tells with
-- ============================================================
-- CLEANUP
-- ============================================================
function ArjUI:kill()
if self.panelGesture then self:finishPanelGesture(self.panelGesture) end
if self.panels then self:saveLayout() end
for _,panel in pairs(self.panels or {}) do self:disposeWidget(panel.frame) end
self.panels=nil; self.maximizedPanel=nil
self:clearGMCPNegotiation()
for id in pairs(self.timers or {}) do killTimer(id) end
self.timers = {}
for _, id in ipairs(self.runtimeTriggers or {}) do killTrigger(id) end
self.runtimeTriggers = {}
for _, id in ipairs(self.captureTriggerIds or {}) do killTrigger(id) end
self.captureTriggerIds = {}
for _, key in ipairs({"uiOnAlias", "uiOffAlias", "debugAlias"}) do
if self[key] then killAlias(self[key]); self[key] = nil end
end
for _, id in ipairs(self.portAliases or {}) do killAlias(id) end
self.portAliases = {}
for _, handler in ipairs(self.eventHandlers) do
killAnonymousEventHandler(handler)
end
self.eventHandlers = {}
-- Kill capture triggers
for _, tid in pairs(self.captureTriggers or {}) do
pcall(function() killTrigger(tid) end)
end
self.captureTriggers = {}
self.capturing = nil
self.captureBuffer = {}
if self.teardownPorted then self:teardownPorted() end
-- Kill routeall trigger
if self.routeAllTriggerId then
pcall(function() killTrigger(self.routeAllTriggerId) end)
self.routeAllTriggerId = nil
end
-- Also kill by name in case it's a permanent trigger
if exists("ArjUI_RouteAll", "trigger") > 0 then
pcall(function() killTrigger("ArjUI_RouteAll") end)
end
-- Clean up popup if open
if self.addCmdPopup then self:disposeWidget(self.addCmdPopup); self.addCmdPopup = nil end
if self.currentMenu then self:disposeWidget(self.currentMenu); self.currentMenu = nil end
if self.bg then
self:disposeWidget(self.bg)
self.bg = nil
end
self.backdrop, self.frameArt, self.artwork = nil, nil, nil
if self.main then
self:disposeWidget(self.main)
self.main = nil
end
self.uiRoot, self.console = nil, nil
-- Old Geyser retains hidden primitives. Release Lua references as well as
-- callback/registry ownership so a removed frame cannot remain active.
for key,value in pairs(self) do
if type(value)=="table" and type(value.name)=="string" and value.name:match("^ArjUI_") then self[key]=nil end
end
self.tabPanels,self.tabButtons,self.chatPanels,self.chatTabs=nil,nil,nil,nil
self.roomViews,self.roomTabs,self.gearViews,self.gearTabs,self.spellTabs=nil,nil,nil,nil,nil
self.shipWidgets,self.shipControls,self.shipPaintTimer=nil,nil,nil
self.shipActionHeight,self.shipPlotOpen=nil,nil
self.privateChats, self.tellContacts = {}, {}
self.exitButtonsStatic, self.groupWidgets = nil, {}
self.playerName, self.damage = nil, nil
-- Restore default borders so main console is visible again
setBorderTop(0)
setBorderBottom(0)
setBorderLeft(0)
setBorderRight(0)
-- Mudlet's main command line remains available while the UI is hidden.
end
function ArjUI:disposeWidget(widget)
-- Adjustable menus live outside the frame's child tree in older Mudlet.
-- Remove only this instance's menu labels and registry entries.
if widget.expiryTimer then killTimer(widget.expiryTimer); self.timers[widget.expiryTimer]=nil; widget.expiryTimer=nil end
if widget.adjLabel then
local function disposeMenu(menu)
if not menu then return end
for _,label in pairs(menu.MenuLabels or {}) do
disposeMenu(label)
self:disposeWidget(label)
end
menu.MenuLabels={}
end
disposeMenu(widget.rCLabel)
if Adjustable.Container.all[widget.name]==widget then
Adjustable.Container.all[widget.name]=nil
for i=#Adjustable.Container.all_windows,1,-1 do
if Adjustable.Container.all_windows[i]==widget.name then table.remove(Adjustable.Container.all_windows,i) end
end
end
end
-- Geyser delete() is available on newer Mudlet releases. Older releases
-- retain hidden primitives; stable names allow them to be reused on import.
if widget.delete then widget:delete()
else
widget:hide()
for _,child in pairs(widget.windowList or {}) do self:disposeWidget(child) end
for _,method in ipairs({"setClickCallback","setReleaseCallback","setMoveCallback","setOnEnter","setOnLeave"}) do
if widget[method] then widget[method](widget,function() end) end
end
if widget.setAction then widget:setAction(function() end) end
if widget.container then widget.container:remove(widget) end
end
end
function ArjUI:after(delay, callback)
self.timers = self.timers or {}
local id
id = tempTimer(delay, function()
self.timers[id] = nil
callback()
end)
self.timers[id] = true
return id
end
function ArjUI:addRuntimeTrigger(pattern, callback)
local id = tempRegexTrigger(pattern, callback)
self.runtimeTriggers = self.runtimeTriggers or {}
table.insert(self.runtimeTriggers, id)
return id
end
function ArjUI:setVisible(visible)
if not self.main then return end
self.hidden = not visible
if visible then
self.bg:show()
self.main:show()
self:layout()
self:applyPanelLayout()
else
self.main:hide()
self.bg:hide()
if self.currentMenu then self.currentMenu:hide() end
for _, chat in pairs(self.privateChats) do
if chat.window then chat.window:hide() end
chat.visible = false
end
if self.panelGesture then self:finishPanelGesture(self.panelGesture) end
setBorderTop(0)
setBorderBottom(0)
setBorderLeft(0)
setBorderRight(0)
end
end
function ArjUI:findArtwork(name)
local home=getMudletHomeDir()
local roots={home,home.."/profiles/"..getProfileName()}
for _,root in ipairs(roots) do
for _,package in ipairs({"Arjinius Client","Arjinius Client V1.0"}) do
local path=(root.."/"..package.."/"..name):gsub("\\","/")
-- Decode with Mudlet, so a corrupt file takes the same fallback as a missing one.
local w,h=getImageSize(path)
if w and h and w>0 and h>0 then return {path=path,width=w,height=h} end
end
end
end
function ArjUI:applyBackground()
if not self.bg then return end
self.artwork={frame=self:findArtwork("duris-frame-slim.png"),
scene=self:findArtwork("duris-backdrop-stormwatch.png")}
self:layoutBackground(getMainWindowSize())
end
function ArjUI:layoutBackground(w,h)
if not self.bg then return end
self.bg:move(0,0); self.bg:resize(w,h)
-- Equal logical corner dimensions avoid stretching the decorated rectangle.
local rail=math.max(1,math.floor(math.min(w*.025,h*.028)))
self.frameArt:resize(w,h)
local frame=self.artwork and self.artwork.frame
if frame then
self.frameArt:setStyleSheet(string.format('background-color: transparent; border: %dpx solid transparent; border-image: url("%s") 96 96 96 96 stretch stretch;',rail,frame.path))
else
self.frameArt:setStyleSheet("background-color: transparent; border: 2px solid #8c6e46;")
end
local scene=self.artwork and self.artwork.scene
local vw,vh=math.max(1,w-2*rail),math.max(1,h-2*rail)
self.backdrop:move(rail,rail); self.backdrop:resize(vw,vh)
if scene and not self.settings.compactHeader then
-- A zero-width Qt border paints only the center slice: centered cover crop,
-- not browser background-size or a stretched panorama. Round source pixels.
local scale=math.max(vw/scene.width,vh/scene.height)
local cx=math.max(0,math.floor((scene.width-vw/scale)/2+.5))
local cy=math.max(0,math.floor((scene.height-vh/scale)/2+.5))
self.backdrop:setStyleSheet(string.format('background-color: transparent; border: 0px; border-image: url("%s") %d %d %d %d stretch stretch;',scene.path,cy,cx,cy,cx))
if not self.hidden then self.backdrop:show() end
else self.backdrop:hide() end
end
-- ============================================================
-- UTILITIES
-- ============================================================
local function styleSafe(widget, css)
if widget and widget.setStyleSheet then
widget:setStyleSheet(css)
end
end
local function labelSet(labelObj, text)
if not labelObj then return end
if labelObj.clear then labelObj:clear() end
if labelObj.echo then labelObj:echo(text or "") end
end
local function makePanel(parent, name, x, y, w, h, css)
local panel = Geyser.Label:new({
name = name, x = x, y = y, width = w, height = h,
}, parent)
styleSafe(panel, css)
labelSet(panel, "")
return panel
end
local function makeConsole(parent, name, x, y, w, h, fontSize, bgColor)
local console = Geyser.MiniConsole:new({
name = name, x = x, y = y, width = w, height = h, fontSize = fontSize or 10, autoWrap = true
}, parent)
-- Default to the warm panel color; the main MUD feed supplies black.
bgColor = bgColor or {12, 11, 9}
console:setBgColor(unpack(bgColor))
console:setFgColor(200, 200, 200)
setBackgroundColor(console.name, bgColor[1], bgColor[2], bgColor[3], 255)
return console
end
-- ============================================================
-- PLAYER LAYOUT (normal rectangles are fractions of uiRoot)
-- ============================================================
local function makeTabs(parent, prefix, names, selectTab)
local buttons = {}
local width = 96 / #names
for i, name in ipairs(names) do
local button = Geyser.Label:new({name=prefix..name, x=(2+(i-1)*width).."%", y=1,
width=(width-1).."%", height=18}, parent)
button:echo("<center>"..name:upper().."</center>")
button:setClickCallback(function(event)
if event.button=="LeftButton" then selectTab(name) end
end)
button:setOnEnter(function() button:setCursor("PointingHand") end)
button:setOnLeave(function() button:setCursor("Arrow") end)
buttons[name] = button
end
return buttons
end
local function showTab(views, active)
for name, view in pairs(views) do
if name == active then view:show() else view:hide() end
end
end
ArjUI.panelDefinitions = {
{id="map", title="MAP", home={0,0,.165,.45}, minimum={190,170}},
{id="room", title="ROOM", home={0,.46,.165,.33}, minimum={150,95}},
{id="output", title="GAME OUTPUT", home={.167,0,.57,.79}, minimum={340,180}, essential=true},
{id="character", title="CHARACTER", home={.739,0,.26,.45}, minimum={285,160}},
{id="players", title="PLAYERS", home={.739,.46,.26,.33}, minimum={190,95}},
{id="chat", title="CHAT", home={.739,.80,.26,.20}, minimum={285,110}},
{id="vitals", title="VITALS", home={0,.80,.165,.195}, minimum={150,110}},
{id="tank", title="TANK / BUFFS", home={.167,.80,.283,.195}, minimum={220,110}},
{id="target", title="TARGET / DEBUFFS", home={.455,.80,.282,.195}, minimum={220,110}},
}
local function copyRect(rect) return {rect[1],rect[2],rect[3],rect[4]} end
local function panelDefault(def)
return {rect=copyRect(def.home), mode=def.private and "floating" or "docked",
locked=not def.private, hidden=false, minimized=false}
end
local function finite(n) return type(n)=="number" and n==n and math.abs(n)<math.huge end
local function validRect(rect)
if type(rect)~="table" then return false end
for i=1,4 do if not finite(rect[i]) then return false end end
return rect[1]>=0 and rect[2]>=0 and rect[1]<1 and rect[2]<1
and rect[3]>0 and rect[3]<=1 and rect[4]>0 and rect[4]<=1
end
-- Profile JSON files share one replacement and recovery path.
local function readJSONFile(path)
local file=io.open(path,"rb")
if not file then return nil,false end
local text=file:read("*a"); file:close()
local ok,data=pcall(yajl.to_value,text)
if ok and type(data)=="table" then return data,true end
return nil,true
end
function ArjUI:readProfileJSON(path)
local data,exists=readJSONFile(path)
if data then return data,true end
local backup,backupExists=readJSONFile(path..".bak")
return backup,exists or backupExists
end
function ArjUI:writeProfileJSON(path, data, label)
local tmp,backup=path..".tmp",path..".bak"
local ok,err=pcall(function()
local text=yajl.to_string(data)
local file=assert(io.open(tmp,"wb"))
local written,writeError=file:write(text)
local closed,closeError=file:close()
assert(written,writeError); assert(closed,closeError)
local installed,why=os.rename(tmp,path)
if not installed then
-- Windows cannot rename over an existing destination. Preserve the old
-- document before installing the new one, including after recovery.
local prior,exists=readJSONFile(path)
assert(exists,why)
local recovered=not prior and readJSONFile(backup)
if recovered then
assert(os.remove(path))
else
local _,backupExists=readJSONFile(backup)
if backupExists then assert(os.remove(backup)) end
assert(os.rename(path,backup))
end
installed,why=os.rename(tmp,path)
if not installed then
local restored=os.rename(backup,path)
error(tostring(why)..(restored and "" or ". Previous data retained at "..backup))
end
end
os.remove(backup)
end)
if not ok then
os.remove(tmp)
self:note("<indian_red>Cannot save "..label..": "..tostring(err))
end
return ok
end
local layoutFile="arjui_layout_v2.json"
function ArjUI:loadLayout()
for _,def in ipairs(self.panelDefinitions) do self.panels[def.id].state=panelDefault(def) end
self.activeRoomTab="mobs"
local directory=getMudletHomeDir().."/"
local data,exists=self:readProfileJSON(directory..layoutFile)
local version=2
if not exists then
data,exists=self:readProfileJSON(directory.."arjui_layout.json")
version=1
end
if not exists then return end
if not data or data.version~=version or type(data.panels)~="table" then
self:note("<indian_red>Saved panel layout is invalid or unsupported; using defaults.")
return
end
if data.roomTab=="items" then self.activeRoomTab="items" end
local function validState(saved)
return type(saved)=="table" and validRect(saved.rect)
and (saved.mode=="docked" or saved.mode=="floating")
and type(saved.locked)=="boolean" and type(saved.hidden)=="boolean"
and type(saved.minimized)=="boolean"
end
local invalid=false
for _,def in ipairs(self.panelDefinitions) do
local saved=data.panels[def.id]
if saved~=nil then
if validState(saved) then
self.panels[def.id].state={rect=copyRect(saved.mode=="docked" and def.home or saved.rect),mode=saved.mode,
locked=saved.locked,hidden=not def.essential and saved.hidden,
minimized=not def.essential and saved.minimized}
else invalid=true end
end
end
-- Combine old panels without hiding content that used to be visible.
if data.panels.room==nil then
local mobs,items=data.panels.mobs,data.panels.items
local room=self.panels.room.state
local function visible(saved) return validState(saved) and not saved.hidden and not saved.minimized end
local function floating(saved) return validState(saved) and saved.mode=="floating" end
local position=(floating(mobs) and mobs) or (floating(items) and items)
if visible(items) and not visible(mobs) then self.activeRoomTab="items" end
if position then
room.rect,room.mode,room.locked=copyRect(position.rect),position.mode,position.locked
elseif validState(mobs) then
room.locked=mobs.locked
elseif validState(items) then
room.locked=items.locked
end
if validState(mobs) and validState(items) then
room.hidden=mobs.hidden and items.hidden
room.minimized=not room.hidden and not visible(mobs) and not visible(items)
end
end
self:updateTabStyles()
if invalid then self:note("<indian_red>Invalid saved panel entries replaced with defaults.") end
end
function ArjUI:saveLayout()
if not self.panels then return end
local data={version=2,panels={},roomTab=self.activeRoomTab}
for _,def in ipairs(self.panelDefinitions) do data.panels[def.id]=self.panels[def.id].state end
return self:writeProfileJSON(getMudletHomeDir().."/"..layoutFile,data,"panel layout")
end
local dockNeighbor={room="vitals",vitals="room",players="chat",chat="players"}
function ArjUI:panelBounds(panel)
local w,h=math.max(1,self.uiRoot:get_width()),math.max(1,self.uiRoot:get_height())
local docked=panel.state.mode=="docked"
local rect=docked and panel.def.home or panel.state.rect
local id=panel.def.id
if self.maximizedPanel==id then return 0,0,w,h end
local pw=math.min(w,math.max(panel.def.minimum[1],rect[3]*w))
local ph=math.min(h,math.max(panel.def.minimum[2],rect[4]*h))
if panel.state.minimized then ph=math.min(h,22) end
local neighbor=self.panels[dockNeighbor[id]]
if docked and not self.maximizedPanel and not panel.state.hidden
and neighbor and neighbor.state.mode=="docked" and not neighbor.state.hidden then
local neighborTop=neighbor.def.home[2]*h
if rect[2]>neighbor.def.home[2] then
-- Keep some space for the upper title when minimum heights cannot fit.
ph=math.min(ph,h-neighborTop-math.min(22,h*.1))
else
local _,bottomTop=self:panelBounds(neighbor)
ph=math.min(ph,bottomTop-rect[2]*h-h*.01)
end
end
return math.max(0,math.min(rect[1]*w,w-pw)),math.max(0,math.min(rect[2]*h,h-ph)),pw,ph
end
-- Whether the panel body can actually be read, independent of saved normal state.
function ArjUI:panelIsVisible(id)
if self.hidden or (self.maximizedPanel and self.maximizedPanel~=id) then return false end
local panel=self.panels and self.panels[id]
return not panel or self.maximizedPanel==id or (not panel.state.hidden and not panel.state.minimized)
end
function ArjUI:reconcilePanelViews()
showTab(self.tabPanels, self.activeTab)
showTab(self.roomViews, self.activeRoomTab)
if self.activeTab=="gear" then showTab(self.gearViews, self.activeGearTab) end
self:reconcileShipViews()
for name,widget in pairs(self.chatPanels or {}) do
if name==self.activeChatTab then widget:show() else widget:hide() end
end
-- Parent show() recursively exposes inactive views. Hide them again without
-- switching tabs (which can send a server command or clear scrollback).
if self.mapper then self.mapper:hide() end
if ArjMapper and ArjMapper.ui then
local ui=ArjMapper.ui
if ui.hoverLabel then ui.hoverLabel:hide() end
if ArjMapper.state.lastDisplayMode=="wilderness" then
if ui.zoneContainer then ui.zoneContainer:hide() end
elseif ui.wildConsole then ui.wildConsole:hide() end
end
for _,panel in pairs(self.panels or {}) do
if self.hidden or (self.maximizedPanel and self.maximizedPanel~=panel.def.id) or (panel.state.hidden and self.maximizedPanel~=panel.def.id) then panel.frame:hide()
elseif panel.state.minimized and self.maximizedPanel~=panel.def.id then panel.frame.Inside:hide() end
end
if self.creditTooltip then self.creditTooltip:hide() end
end
function ArjUI:applyPanel(panel)
local frame,state=panel.frame,panel.state
if panel.def.private then
local chat=self.privateChats[panel.def.id:sub(6)]
if chat then
local visible=self:panelIsVisible(panel.def.id)
if visible and not chat.visible then
chat.unread=0
self:renderTellContacts()
end
chat.visible=visible
end
end
local x,y,w,h=self:panelBounds(panel)
frame:move(x,y); frame:resize(w,h)
frame.locked=state.locked or self.maximizedPanel==panel.def.id
local maximized=self.maximizedPanel==panel.def.id
frame.minimized=state.minimized and not maximized
frame.Inside:move(5,22)
frame.Inside:resize("100%-10px","100%-27px")
if self.hidden or (self.maximizedPanel and not maximized) or (state.hidden and not maximized) then frame:hide()
else
frame:show()
if state.minimized and not maximized then frame.Inside:hide() else frame.Inside:show() end
end
if panel.def.essential then frame.exitLabel:hide(); frame.minimizeLabel:hide() end
end
function ArjUI:applyPanelLayout()
for _,panel in pairs(self.panels or {}) do self:applyPanel(panel) end
self:reconcilePanelViews()
if self.maximizedPanel and not self.hidden then self.panels[self.maximizedPanel].frame:raiseAll() end
if self.panelsButton then self.panelsButton:raise(); self.resetLayoutButton:raise() end
end
function ArjUI:finishPanelGesture(panel)
if self.panelGesture~=panel then return end
panel.frame:onRelease(panel.frame.adjLabel,{button="LeftButton"})
self.panelGesture=nil
end
function ArjUI:capturePanelGesture(panel)
local frame,state=panel.frame,panel.state
local w,h=math.max(1,self.uiRoot:get_width()),math.max(1,self.uiRoot:get_height())
local x=frame:get_x()-self.uiRoot:get_x()
local y=frame:get_y()-self.uiRoot:get_y()
state.mode="floating"
state.rect={math.max(0,x/w),math.max(0,y/h),math.min(1,frame:get_width()/w),
state.minimized and state.rect[4] or math.min(1,frame:get_height()/h)}
self:applyPanel(panel)
local neighbor=self.panels[dockNeighbor[panel.def.id]]
if neighbor then self:applyPanel(neighbor) end
self:reconcilePanelViews()
end
function ArjUI:createPanel(def)
local frame=Adjustable.Container:new({name="ArjUI_Panel_"..def.id:gsub(":","_"),
x=0,y=0,width=200,height=180,autoSave=false,autoLoad=false,dragOut=false,
padding=5,buttonsize=15,titleText=def.title,titleTxtColor="tan",titleFormat="l8",
adjLabelstyle="background-color: #0f0e0c; border: 2px solid #5a4b37; color: #d4a855;",
buttonstyle="background-color: #1a1610; color: #d4a855; border: none;"},self.uiRoot)
local panel={def=def,frame=frame,state=panelDefault(def)}
self.panels[def.id]=panel
frame.adjLabel:setClickCallback(function(event)
if event.button=="RightButton" then self:showPanelMenu(def.id); return end
frame:raiseAll()
if not frame.locked and event.button=="LeftButton" then
-- Prime hit testing on click too: no dependence on a preceding hover.
frame:onMove(frame.adjLabel,event)
frame:onClick(frame.adjLabel,event)
self.panelGesture=panel
end
end)
frame.adjLabel:setMoveCallback(function(event)
frame:onMove(frame.adjLabel,event)
if self.panelGesture==panel then self:capturePanelGesture(panel) end
end)
frame.adjLabel:setReleaseCallback(function(event)
if event.button=="LeftButton" and self.panelGesture==panel then
self:finishPanelGesture(panel)
self:saveLayout()
self:refreshPanelContent(def.id)
end
end)
frame.exitLabel:setClickCallback(function() self:panelAction(def.id,"hide") end)
frame.minimizeLabel:setClickCallback(function()
self:panelAction(def.id,panel.state.minimized and "restore" or "minimize")
end)
return frame.Inside
end
function ArjUI:refreshPanelContent(id)
if ArjMapper and ArjMapper.state.enabled and self:panelIsVisible("map") then
ArjMapper:refreshViewport()
end
if (not id or id=="character") and self.activeTab=="ship" then self:renderShipIfActive() end
end
function ArjUI:panelAction(id,action)
-- Keep saved aliases for the former frames usable.
if id=="mobs" or id=="items" then id="room" end
local panel=self.panels and self.panels[id]
local contact=type(id)=="string" and id:match("^tell:(.+)$")
if not panel and contact and self.privateChats[contact] then
self:openPrivateChat(contact)
panel=self.panels[id]
end
if not panel then self:note("<indian_red>Unknown panel: "..tostring(id)); return false end
if (action=="hide" or action=="minimize") and panel.def.essential then
self:note("<tan>Game output stays visible. Use maximize, float or dock."); return false
end
if action=="dock" and panel.def.private then self:note("<tan>Private chats float inside the dashboard."); return false end
if self.panelGesture then self:finishPanelGesture(self.panelGesture) end
local state=panel.state
if action=="maximize" then
if self.maximizedPanel==id then self.maximizedPanel=nil else self.maximizedPanel=id end
elseif action=="restore" then
if self.maximizedPanel==id then self.maximizedPanel=nil
else state.hidden=false; state.minimized=false end
elseif action=="show" then state.hidden=false; state.minimized=false
elseif action=="hide" then state.hidden=true
elseif action=="minimize" then state.minimized=true
elseif action=="dock" then
state.mode="docked"; state.rect=copyRect(panel.def.home); state.hidden=false; state.minimized=false
elseif action=="float" then state.mode="floating"
elseif action=="lock" then state.locked=true
elseif action=="unlock" then state.locked=false
else return false end
if action~="maximize" and self.maximizedPanel==id and action~="lock" and action~="unlock" then self.maximizedPanel=nil end
self:applyPanelLayout()
if self:panelIsVisible(id) then panel.frame:raiseAll() end
self:refreshPanelContent(id)
if panel.def.private then self:renderTellContacts() end
self:saveLayout()
return true
end
function ArjUI:showPanelMenu(id)
local panel=self.panels[id]
local items={}
for _,action in ipairs({"show","hide","minimize","restore","maximize","dock","float","lock","unlock"}) do
if not ((panel.def.essential and (action=="hide" or action=="minimize")) or (panel.def.private and action=="dock")) then
table.insert(items,{text=action:sub(1,1):upper()..action:sub(2),callback=function() self:panelAction(id,action) end})
end
end
self:showContextMenu(items)
end
function ArjUI:showPanelsMenu()
local items={}
for _,def in ipairs(self.panelDefinitions) do
table.insert(items,{text=def.title,callback=function()
self:panelAction(def.id,"show"); self:showPanelMenu(def.id)
end})
end
for name,chat in pairs(self.privateChats) do
table.insert(items,{text="Tell: "..name,callback=function() self:openPrivateChat(name); self:showPanelMenu("tell:"..name) end})
end
self:showContextMenu(items)
end
function ArjUI:resetLayout()
if self.panelGesture then self:finishPanelGesture(self.panelGesture) end
self.maximizedPanel=nil
if self.currentMenu then self:disposeWidget(self.currentMenu); self.currentMenu=nil end
if self.addCmdPopup then self:disposeWidget(self.addCmdPopup); self.addCmdPopup=nil end
for _,panel in pairs(self.panels) do
panel.state=panelDefault(panel.def)
if panel.def.private then panel.state.hidden=true end
end
for _,chat in pairs(self.privateChats) do if chat.window then chat.visible=false end end
self.activeTab="group"; self.activeChatTab="all"
self.activeRoomTab="mobs"; self.activeGearTab="inv"
self:updateTabStyles(); self:updateChatTabStyles()
self:applyPanelLayout(); self:renderActiveTab(); self:refreshPanelContent()
self:saveLayout()
end
function ArjUI:setupPanelControls()
self.panelsButton=makePanel(self.main,"ArjUI_PanelsButton",0,0,76,22,self.styles.header)
self.panelsButton:echo("Panels")
self.panelsButton:setClickCallback(function() self:showPanelsMenu() end)
self.resetLayoutButton=makePanel(self.main,"ArjUI_ResetLayoutButton",0,0,92,22,self.styles.header)
self.resetLayoutButton:echo("Reset layout")
self.resetLayoutButton:setClickCallback(function() self:resetLayout() end)
end
function ArjUI:layoutCommand(action)
if action=="reset" then self:resetLayout()
elseif action=="lock" or action=="unlock" then
for _,panel in pairs(self.panels) do panel.state.locked=action=="lock" end
if self.panelGesture then self:finishPanelGesture(self.panelGesture) end
self:applyPanelLayout(); self:saveLayout()
else
self:note("<tan>ui layout reset|lock|unlock; ui panel <id> show|hide|minimize|restore|maximize|dock|float|lock|unlock")
for name in pairs(self.privateChats) do self:note("tell:"..name.." (session conversation)") end
for _,def in ipairs(self.panelDefinitions) do
local s=self.panels[def.id].state
self:note(def.id..": "..s.mode..(s.locked and " locked" or " unlocked")..(s.hidden and " hidden" or "")..(s.minimized and " minimized" or ""))
end
end
end
local function toNum(x) return tonumber(x) end
local function upper3(pos)
if not pos or type(pos) ~= "string" then return "" end
return string.upper(pos:sub(1,3))
end
local function pick(tbl, ...)
if not tbl then return nil end
for i = 1, select("#", ...) do
local k = select(i, ...)
local v = tbl[k]
if v ~= nil then return v end
end
return nil
end
local function stripColors(text)
if not text then return "" end
text = text:gsub("&%+.", "")
text = text:gsub("&=..", "")
text = text:gsub("&[nN%]]", "")
text = text:gsub("\27%][^\7]*\7", "")
text = text:gsub("\27%][^\27]*\27\\", "")
text = text:gsub("\27%[%d*;?%d*m", "")
return text
end
-- Duris color code to decho RGB format (for MiniConsoles)
local durisColors = {
r = "<128,0,0>", R = "<255,0,0>",
g = "<0,128,0>", G = "<0,255,0>",
b = "<0,0,170>", B = "<85,85,255>",
c = "<0,128,128>", C = "<0,255,255>",
m = "<128,0,128>", M = "<255,0,255>",
y = "<128,128,0>", Y = "<255,255,0>",
w = "<192,192,192>", W = "<255,255,255>",
L = "<96,96,96>", l = "<96,96,96>",
}
-- Convert Duris color codes to Mudlet decho format (RGB)
local function durisToDecho(text)
if not text then return "" end
local result = {}
local i, len = 1, #text
local currentColor = nil
local buffer = ""
local function flushBuffer()
if buffer ~= "" then
if currentColor then
table.insert(result, currentColor .. buffer)
else
table.insert(result, buffer)
end
buffer = ""
end
end
while i <= len do
local ch = text:sub(i, i)
if ch == "&" and i < len then
local nxt = text:sub(i+1, i+1)
if nxt == "+" and i + 2 <= len then
flushBuffer()
local colorCode = text:sub(i+2, i+2)
currentColor = durisColors[colorCode]
i = i + 3
elseif nxt == "n" or nxt == "N" or nxt == "]" then
flushBuffer()
currentColor = nil
i = i + 2
elseif nxt == "=" and i + 3 <= len then
flushBuffer()
local fgCode = text:sub(i+2, i+2)
currentColor = durisColors[fgCode]
i = i + 4
else
i = i + 1
end
else
buffer = buffer .. ch
i = i + 1
end
end
flushBuffer()
return table.concat(result)
end
-- ============================================================
-- TARGET NORMALIZATION (FIX: clickable mobs/objs passing tags)
-- ============================================================
local function trim(s)
return (s or ""):gsub("^%s+", ""):gsub("%s+$", "")
end
local function normalizeTargetName(name)
if not name then return "" end
-- 1) remove formats we already handle
local s = stripColors(name)
-- 2) remove Mudlet-style tags like <red>, <reset>, etc.
s = s:gsub("<[^>]+>", "")
-- 2b) sometimes we get partial/broken tag fragments; strip common leftovers
s = s:gsub("</[%w_]+", "")
:gsub("<[%w_]+", "")
:gsub("/[%w_]+>", "")
-- 3) collapse whitespace
s = trim(s):gsub("%s+", " ")
-- 4) optionally strip leading articles (often helps targeting)
s = s:gsub("^[Aa]n%s+", "")
:gsub("^[Aa]%s+", "")
:gsub("^[Tt]he%s+", "")
return trim(s)
end
local function quoteIfNeeded(s)
s = trim(s or "")
if s:find("%s") then
return "'" .. s .. "'"
end
return s
end
local function durisTargetKey(name)
-- Start from the clean display name
local s = normalizeTargetName(name)
s = trim(s)
if s == "" then return "" end
-- If it has an "of ..." tail, drop it (corpse of a raccoon -> corpse)
-- This avoids the classic "that isn't a container" / parse confusion.
if s:find("%s+[Oo][Ff]%s+") then
local head = s:match("^(.-)%s+[Oo][Ff]%s+.+$")
if head and head ~= "" then s = trim(head) end
end
-- If it's still multi-word, prefer the last word as a stable keyword
-- (black wolf -> wolf) which Duris will generally match.
if s:find("%s") then
s = s:match("(%S+)$") or s
end
return trim(s)
end
-- ============================================================
-- UI INITIALIZATION
-- ============================================================
function ArjUI:resetCharacterState()
self.state = {
hp = 1, hpmax = 1, mana = 1, manamax = 1, move = 1, movemax = 1,
tnl = 0, tnlBaseline = nil, position = "standing",
area = "Unknown", room = "Unknown", roomId = nil, zoneId = nil,
exits = {}, exitsRaw = {}, npcs = {}, items = {}, players = {},
target = nil, targetHpPct = 100, targetCond = nil, targetPos = nil,
tank = nil, tankHp = nil, tankMaxHp = nil, tankCond = nil, tankPos = nil, iAmTank = false,
group = {}, groupSize = 0, groupMax = 0, affects = {},
doors = {},
coins = { platinum = 0, gold = 0, silver = 0, copper = 0 },
usesMana = true, fighting = nil,
charLevel = nil, charClass = nil, charRace = nil, charGuild = nil, charTitle = nil,
quest = nil,
timeOfDay = "day", -- day, night, dawn, dusk
}
self.initialDataRequested = false
self.spellCapture, self.prepTimer = nil, nil
self.state.spellView = "list"
self.playerName = nil
self.timeQuerySilent = false
self.timeQueryTimer = nil
self.accountMenuBorder = false
self.capturing, self.captureBuffer = nil, {}
self:resetShip()
end
function ArjUI:endSession()
for id in pairs(self.timers or {}) do
if id~=self.gmcpRetryTimer then killTimer(id); self.timers[id]=nil end
end
if self.scanTimer then killTimer(self.scanTimer); self.scanTimer = nil end
self.scanCounts = {}
self:resetCharacterState()
self.damage = {fight=0, fightHits=0, session=0, sessionHits=0, sessionStart=os.time(), lastHit=0}
if ArjAuto and ArjAuto.resetSession then ArjAuto:resetSession() end
if ArjMapper and ArjMapper.resetSession then ArjMapper:resetSession() end
self:renderAll()
self:renderDamage()
self:renderStats()
self:renderInventory()
self:renderEq()
self:renderSpells()
self:renderSpellPreparation()
self:renderWho()
self:renderShip()
end
local preparationStream = "Char.SpellPreparation"
-- Mudlet sends its own Supports.Set. Follow it with one Add so the Duris
-- control rate limit still allows our versioned streams on a fresh socket.
ArjUI.gmcpModules = {"Char.Vitals", "Char.Status", "Char.Affects", "Room.Info", "Room.Map",
"Group.Status", "Comm.Channel", "Combat.Update", "Quest.Status", "Ship.Info", "Ship.Contacts",
"Duris.Capabilities", preparationStream}
local function contains(list, value)
if type(list)~="table" then return false end
for _, item in ipairs(list) do if item==value then return true end end
return false
end
function ArjUI:cancelGMCPRetry()
if not self.gmcpRetryTimer then return end
killTimer(self.gmcpRetryTimer)
self.timers[self.gmcpRetryTimer]=nil
self.gmcpRetryTimer=nil
end
function ArjUI:clearGMCPNegotiation()
self:cancelGMCPRetry()
self.gmcpNegotiation,self.preparationActive=nil,nil
-- The support and interest sets are shared by the socket. Leave them in
-- place until disconnect. Teardown cannot establish exclusive ownership or
-- safely replace the current interests with a cached capabilities reply.
end
function ArjUI:enableGMCP()
if self.gmcpNegotiation then return end
self.gmcpNegotiation={advertisements=0,subscriptions=0}
sendGMCP('Core.Hello {"client":"Mudlet-ArjUI","version":"' .. ArjUI.VERSION .. '"}')
self:requestGMCPState()
end
function ArjUI:requestGMCPState()
local negotiation=self.gmcpNegotiation
if not negotiation or negotiation.synced then return end
local message,modules,attempts
local caps=negotiation.capabilities
if not caps then
message,modules="Core.Supports.Add ",{}
for _,module in ipairs(self.gmcpModules) do modules[#modules+1]=module.." 1" end
negotiation.advertisements=negotiation.advertisements+1
attempts=negotiation.advertisements
else
message,modules="Duris.Subscribe ",{preparationStream.." 1"}
-- Subscribe replaces all interests. Build the set from the latest reply.
for _,name in ipairs(type(caps.interested)=="table" and caps.interested or {}) do
local version=caps.features[name]
if name~=preparationStream and type(name)=="string" and finite(version) then
modules[#modules+1]=name.." "..version
end
end
negotiation.subscriptions=negotiation.subscriptions+1
attempts=negotiation.subscriptions
end
-- Duris refills each control family by one token per second. Schedule
-- before sending so a capability reply can cancel or advance the retry.
if attempts<3 then
self.gmcpRetryTimer=self:after(1.1,function()
self.gmcpRetryTimer=nil
self:requestGMCPState()
end)
end
if attempts<=3 then sendGMCP(message..yajl.to_string(modules)) end
end
function ArjUI:onDurisCapabilities()
local caps = gmcp and gmcp.Duris and gmcp.Duris.Capabilities
if type(caps)~="table" or caps.version~=1 then return end
self.preparationActive = contains(caps.active, preparationStream)
if not self.preparationActive then self:setSpellPreparation(nil) end
local negotiation=self.gmcpNegotiation
if not negotiation or negotiation.synced
or type(caps.features)~="table" or not contains(caps.supported,preparationStream) then return end
local firstReply=not negotiation.capabilities
negotiation.capabilities=caps
if contains(caps.interested,preparationStream) and not self.preparationActive then
-- An interested stream will send its first snapshot on character entry.
negotiation.synced=true
self:cancelGMCPRetry()
elseif firstReply then
-- An already active stream needs a new snapshot for this UI instance.
self:cancelGMCPRetry()
self:requestGMCPState()
end
end
function ArjUI:onSpellPreparation()
if not self.preparationActive then return end
local data = gmcp and gmcp.Char and gmcp.Char.SpellPreparation
if type(data)~="table" or not finite(data.estimatedSeconds) or data.estimatedSeconds<0 then return end
local mode = data.state
if mode=="active" or mode=="paused" or mode=="complete" then
if self.gmcpNegotiation then self.gmcpNegotiation.synced=true end
self:cancelGMCPRetry()
self:setSpellPreparation(mode, data.estimatedSeconds)