-
Notifications
You must be signed in to change notification settings - Fork 1
/
manager_lib.lua
1721 lines (1599 loc) · 57.5 KB
/
manager_lib.lua
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
local tw, th = term.getSize()
local nodes_win = window.create(term.current(), 1, 1, tw, th)
local gui_win = window.create(term.current(), 1, 1, tw, th)
local d = require "draw"
d.set_default(nodes_win)
local line_func = d.aligned_cubic_line
--- Root coordinate to draw the field in relation to
local root_x = 1
local root_y = 1
local show_packets = true
local tick_delay = 0.1
---@type boolean Whether the user is currently connecting nodes togther
local connecting = false
---@type Connector
local connection_connector
---@type integer Connecting line source
local connection_sx
---@type integer Connecting line source
local connection_sy
---@type integer Connecting line destination
local connection_dx
---@type integer Connecting line destination
local connection_dy
---@type Node|Connector? Last selected Node or Connector for editing
local last_selected
local function uuid()
local template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
return string.gsub(template, '[xy]', function(c)
local v = (c == 'x') and math.random(0, 0xf) or math.random(8, 0xb)
return string.format('%x', v)
end)
end
---@class Node Generic Node
---@field label string?
---@field id string
---@field node_type string
---@field inputs Connector[]
---@field outputs Connector[]
---@field window Window
---@field dragging boolean
---@field drag_x integer
---@field drag_y integer
---@field locked boolean? Whether editing the connectors is allowed
---@field x integer
---@field y integer
---@field w integer
---@field h integer
local node__index = {}
local node_meta = { __index = node__index }
---@param x integer
---@param y integer
---@return integer
---@return integer
function node__index:local_pos_to_screen(x, y)
local wx, wy = nodes_win.getPosition()
return x + self.x - 2 + root_x + wx, y + self.y - 2 + root_y + wy
end
---@param x integer
---@param y integer
---@return integer
---@return integer
function node__index:screen_pos_to_local(x, y)
local wx, wy = nodes_win.getPosition()
return x - self.x + 2 - root_x - wx, y - self.y + 2 - root_y - wy
end
function node__index:update_window()
self.window.reposition(root_x + self.x, root_y + self.y, self.w, self.h)
end
function node__index:on_event(e)
for _, con in ipairs(self.inputs) do
con:on_event(e)
end
for _, con in ipairs(self.outputs) do
con:on_event(e)
end
end
--- Recalculate width/height and resize the window
function node__index:update_size()
local w = #(self.label or "") + 2
local h = 3
local connection_height = math.max(#self.inputs, #self.outputs)
if connection_height > 0 then
h = h + 1
end
for i = 1, connection_height do
local layer_w = 4
local input, output = self.inputs[i], self.outputs[i]
if input then
layer_w = layer_w + #(input.label or "")
input.y = h
end
if output then
layer_w = layer_w + #(output.label or "")
output.y = h
end
h = h + 2
w = math.max(w, layer_w)
end
self.h = h
self.w = w
self:update_window()
end
function node__index:has_con(con)
for i, v in ipairs(self.outputs) do
if v == con then
return true
end
end
for i, v in ipairs(self.outputs) do
if v == con then
return true
end
end
return false
end
---@param connections Connector[]
local function validate_connections(connections)
for i, con in ipairs(connections) do
if con.link and not con.link_parent:has_con(con.link) then
-- this link is not valid
con.link = nil
con.link_parent = nil
end
end
end
--- Remove any invalid connections
function node__index:validate_connections()
validate_connections(self.inputs)
validate_connections(self.outputs)
end
---Get a connector's position in screen space
---@param con Connector
function node__index:get_con_root_pos(con)
return self.x + root_x, self.y + con.y - 1 + root_y
end
---Draw the node lines
function node__index:draw_lines()
for k, v in pairs(self.outputs) do
if v.link then
if v.sent_a_packet and show_packets then
d.set_col(colors.orange, nil, nodes_win)
else
d.set_col(v.color or colors.white, nil, nodes_win)
end
line_func(
self.x + self.w + root_x,
self.y + v.y - 1 + root_y,
v.link_parent.x + root_x - 1,
v.link.parent.y + v.link.y + root_y - 1,
nodes_win
)
end
end
d.set_col(colors.white, nil, nodes_win)
end
---@type table<string,RegisteredNode>
local registered_nodes = {}
---@type table<string,RegisteredConnector>
local registered_connectors = {}
---@param node Node
---@param connectors Connector[]
---@param side "right"|"left"
local function draw_connectors(node, connectors, side)
for k, v in pairs(connectors) do
local def_icon = registered_connectors[v.con_type].char or "\007"
local icon = (last_selected == v and not node.locked and "\127") or def_icon
if last_selected == v and node.locked then
d.set_col(colors.white, colors.black, node.window)
node.window.setCursorPos(1, 1)
node.window.write("\127")
end
if v.sent_a_packet and show_packets then
d.set_col(colors.orange, nil, node.window)
icon = "!"
else
d.set_col(v.color or colors.white, nil, node.window)
end
if side == "left" then
d.invert(node.window)
end
local str, x
if side == "right" then
str = ("%s%s"):format(v.label or "", icon)
x = node.w - #str + 1
else
str = ("%s%s"):format(icon, v.label or "")
x = 1
end
d.text(x, v.y, str, node.window)
if side == "left" then
d.invert(node.window)
end
end
end
--- Draw the node contents from scratch
function node__index:draw()
self.window.setVisible(false)
self.window.clear()
d.square(1, 1, self.w, self.h, self.window)
if last_selected == self then
self.window.setCursorPos(1, 1)
self.window.write("\127")
end
d.text(2, 2, self.label or "", self.window)
draw_connectors(self, self.inputs, "left")
draw_connectors(self, self.outputs, "right")
d.set_col(colors.white, nil, self.window)
self.window.setVisible(true)
end
---Add an input connector
---@param con Connector
function node__index:add_input(con)
con.direction = "input"
con.parent = self
self.inputs[#self.inputs + 1] = con
self:update_size()
end
---Add an output connector
---@param con Connector
function node__index:add_output(con)
con.direction = "output"
con.parent = self
self.outputs[#self.outputs + 1] = con
self:update_size()
end
---@param connections Connector[]
local function unlink(connections)
for i, con in ipairs(connections) do
if con.link then
con.link.link = nil
con.link.link_parent = nil
con.link = nil
con.link_parent = nil
end
end
end
--- Delete all connections to this node
function node__index:unlink()
unlink(self.inputs)
unlink(self.outputs)
end
---Start a connection
---@param node Node
---@param connector Connector
---@param x integer
---@param y integer
local function start_connection(node, connector, x, y)
if connector.link then
connector.link:unlink()
connector:unlink()
end
connecting = true
connection_connector = connector
local wx, wy = nodes_win.getPosition()
connection_sx, connection_sy = x - wx + 1, y - wy + 1
connection_dx = connection_sx
connection_dy = connection_sy
end
---Finish a connection
---@param node Node?
---@param connector Connector?
local function connection_end(node, connector)
connecting = false
if node and connector then
connector:unlink()
connection_connector:set_link(node, connector)
end
end
---Provide x,y in screen space
---@param b integer
---@param x integer
---@param y integer
function node__index:mouse_click(b, x, y)
x, y = self:screen_pos_to_local(x, y)
if x == 1 then
-- on the left side
for k, v in ipairs(self.inputs) do
if v.y > y then break end
if y == v.y then
last_selected = v
return true
end
end
elseif x == self.w then
-- on the right side
for k, v in ipairs(self.outputs) do
if v.y > y then break end
if y == v.y then
last_selected = v
return true
end
end
end
if y > 0 and y <= self.h and x > 0 and x <= self.w then
local wx, wy = nodes_win.getPosition()
self.drag_x = x + wx - 1
self.drag_y = y + wy - 1
self.dragging = true
last_selected = self
return true
end
end
---Provide x,y in screen space
---@param b integer
---@param x integer
---@param y integer
function node__index:mouse_up(b, x, y)
x, y = self:screen_pos_to_local(x, y)
if self.dragging then
self.dragging = false
self:update_window()
end
if connecting and x == 1 then
-- on the left side
for k, v in ipairs(self.inputs) do
if v.y > y then break end
if y == v.y and v.con_type == connection_connector.con_type then
connection_end(self, v)
return true
end
end
end
end
---Provide x,y in screen space
---@param b integer
---@param x integer
---@param y integer
function node__index:mouse_drag(b, x, y)
if self.dragging then
self.x = x - root_x - self.drag_x + 1
self.y = y - root_y - self.drag_y + 1
self:update_window()
return true
end
end
local function merge_into(from, to)
for _, func in ipairs(from) do
to[#to + 1] = func
end
end
---Tick all outgoing connections of this node
---@return function[]?
function node__index:tick()
local funcs = {}
for _, v in ipairs(self.outputs) do
local funcs_l = v:tick()
merge_into(funcs_l or {}, funcs)
end
return funcs
end
---@class Packet
--- Transfer data to a connector on this node
---@param connector Connector
---@param packet Packet
function node__index:transfer(connector, packet)
connector:recieve_packet(packet)
end
---@return Node
local function new_node()
local cx, cy = -root_x + math.floor(tw / 2), -root_y + math.floor(th / 2)
---@type Node
local node = setmetatable(
{ x = cx, y = cy, inputs = {}, outputs = {}, id = uuid(), node_type = "DEFAULT" },
node_meta)
node.window = window.create(nodes_win, node.x, node.y, 1, 1)
node:update_size()
return node
end
---@class Connector
---@field sent_a_packet boolean?
---@field link Connector?
---@field link_parent Node?
---@field parent Node
---@field con_type string
---@field direction "input"|"output"
---@field label string?
---@field color color?
---@field y integer
---@field char string?
---@field id string
---@field recieve_packet fun(self:Connector,packet:Packet)
---@field tick fun(self:Connector):function[]? Run on a frequent basis
local con__index = {}
function con__index:unlink()
if self.link then
self.link.link = nil
self.link.link_parent = nil
end
self.link = nil
self.link_parent = nil
end
---@param node Node
---@param con Connector
function con__index:set_link(node, con)
self.link = con
self.link_parent = node
con.link = self
con.link_parent = self.parent
end
function con__index:on_event(e)
end
---Default no-op
function con__index:tick() end
---Default no-op
function con__index:recieve_packet(packet) end
---Create a new default connector
---@return Connector
local function new_connector()
local connector = {
con_type = "DEFAULT",
id = uuid(),
}
return setmetatable(connector, { __index = con__index })
end
---@param connector Connector
---@param packet Packet
local function send_packet_to_link(connector, packet)
connector.sent_a_packet = true
if connector.link and connector.link_parent then
connector.link.sent_a_packet = true
connector.link_parent:transfer(connector.link, packet)
end
end
---@return Connector|Node?
local function get_thing_selected_for_editing()
if not last_selected then
return
end
if last_selected.con_type and not last_selected.parent.locked then
return last_selected
end
if last_selected.con_type then
return last_selected.parent
end
return last_selected
end
---@return string?
local function get_last_selected_label()
if not last_selected then
return
end
if last_selected.con_type and not last_selected.parent.locked then
return ("Connector %s"):format(last_selected.label or last_selected.id)
end
local label = last_selected.label or last_selected.id
if last_selected.con_type then
label = last_selected.parent.label or last_selected.parent.id
end
return ("Node %s"):format(label)
end
local function clear_packet_recieved(node)
for _, v in ipairs(node.inputs) do
v.sent_a_packet = nil
end
for _, v in ipairs(node.outputs) do
v.sent_a_packet = nil
end
end
local active = false
---@type NodeT
local nodes = {}
local function draw_nodes()
nodes_win.clear()
if connecting then
line_func(connection_sx, connection_sy, connection_dx, connection_dy, nodes_win)
end
for k, v in pairs(nodes) do
v:draw()
v:draw_lines()
clear_packet_recieved(v)
end
d.text(root_x, root_y, "X", nodes_win)
d.invert(nodes_win)
local t = " %s (Tab) "
if last_selected == nil then
t = t:format("MENU")
else
t = t:format(("Edit %s"):format(get_last_selected_label():sub(1, tw - (#t + 5))))
end
nodes_win.setCursorPos(1, th)
nodes_win.clearLine()
d.center_text(th, t, nodes_win)
if active then
t = "(Space) \16"
else
t = "(Space) \143"
end
d.text(tw - 8, 1, t, nodes_win)
d.invert(nodes_win)
nodes_win.setVisible(true)
nodes_win.setVisible(false)
end
---@param node Node
local function add_node(node)
nodes[#nodes + 1] = node
end
---@param node Node
local function remove_node(node)
for i, node_i in ipairs(nodes) do
if node_i == node then
table.remove(nodes, i)
break
end
end
unlink(node.inputs)
unlink(node.outputs)
end
local executeLimit = 128 -- limit of functions to run in parallel
---Execute a table of functions in batches
---@param func function[]
---@param skipPartial? boolean Only do complete batches and skip the remainder.
---@return function[] skipped Functions that were skipped as they didn't fit.
local function batch_execute(func, skipPartial)
-- for _, v in ipairs(func) do
-- v()
-- end
local batches = #func / executeLimit
batches = skipPartial and math.floor(batches) or math.ceil(batches)
for batch = 1, batches do
local start = ((batch - 1) * executeLimit) + 1
local batch_end = math.min(start + executeLimit - 1, #func)
parallel.waitForAll(table.unpack(func, start, batch_end))
end
return table.pack(table.unpack(func, 1 + executeLimit * batches))
end
local function handle_ticks()
while true do
sleep(tick_delay)
if active then
local funcs = {}
for _, v in ipairs(nodes) do
local funcs_l = v:tick()
merge_into(funcs_l or {}, funcs)
end
batch_execute(funcs)
end
end
end
local function distribute_event(e)
for k, v in pairs(nodes) do
if v[e[1]](v, table.unpack(e, 2, 5)) then return true end
end
end
local expect = require "cc.expect".expect
--- PrimeUI stuff https://github.com/MCJack123/PrimeUI
-- Initialization code
local PrimeUI = {}
do
local coros = {}
local restoreCursor
--- Adds a task to run in the main loop.
---@param func function The function to run, usually an `os.pullEvent` loop
function PrimeUI.addTask(func)
expect(1, func, "function")
local t = { coro = coroutine.create(func) }
coros[#coros + 1] = t
_, t.filter = coroutine.resume(t.coro)
end
--- Sends the provided arguments to the run loop, where they will be returned.
---@param ... any The parameters to send
function PrimeUI.resolve(...)
coroutine.yield(coros, ...)
end
--- Clears the screen and resets all components. Do not use any previously
--- created components after calling this function.
function PrimeUI.clear()
-- Reset the screen.
term.setCursorPos(1, 1)
term.setCursorBlink(false)
term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
-- Reset the task list and cursor restore function.
coros = {}
restoreCursor = nil
end
--- Sets or clears the window that holds where the cursor should be.
---@param win Window|nil The window to set as the active window
function PrimeUI.setCursorWindow(win)
expect(1, win, "table", "nil")
restoreCursor = win and win.restoreCursor
end
--- Gets the absolute position of a coordinate relative to a window.
---@param win Window The window to check
---@param x number The relative X position of the point
---@param y number The relative Y position of the point
---@return number x The absolute X position of the window
---@return number y The absolute Y position of the window
function PrimeUI.getWindowPos(win, x, y)
if win == term then return x, y end
while win ~= term.native() and win ~= term.current() do
if not win.getPosition then return x, y end
local wx, wy = win.getPosition()
x, y = x + wx - 1, y + wy - 1
_, win = debug.getupvalue(select(2, debug.getupvalue(win.isColor, 1)), 1) -- gets the parent window through an upvalue
end
return x, y
end
--- Runs the main loop, returning information on an action.
---@return any ... The result of the coroutine that exited
function PrimeUI.run()
while true do
-- Restore the cursor and wait for the next event.
if restoreCursor then restoreCursor() end
local ev = table.pack(os.pullEvent())
-- Run all coroutines.
for _, v in ipairs(coros) do
if v.filter == nil or v.filter == ev[1] then
-- Resume the coroutine, passing the current event.
local res = table.pack(coroutine.resume(v.coro, table.unpack(ev, 1, ev.n)))
-- If the call failed, bail out. Coroutines should never exit.
if not res[1] then error(res[2], 2) end
-- If the coroutine resolved, return its values.
if res[2] == coros then return table.unpack(res, 3, res.n) end
-- Set the next event filter.
v.filter = res[2]
end
end
end
end
--- Draws a line of text at a position.
---@param win Window The window to draw on
---@param x number The X position of the left side of the text
---@param y number The Y position of the text
---@param text string The text to draw
---@param fgColor color|nil The color of the text (defaults to white)
---@param bgColor color|nil The color of the background (defaults to black)
function PrimeUI.label(win, x, y, text, fgColor, bgColor)
expect(1, win, "table")
expect(2, x, "number")
expect(3, y, "number")
expect(4, text, "string")
fgColor = expect(5, fgColor, "number", "nil") or colors.white
bgColor = expect(6, bgColor, "number", "nil") or colors.black
win.setCursorPos(x, y)
win.setTextColor(fgColor)
win.setBackgroundColor(bgColor)
win.write(text)
end
--- Creates a text input box.
---@param win Window The window to draw on
---@param x number The X position of the left side of the box
---@param y number The Y position of the box
---@param width number The width/length of the box
---@param action function|string A function or `run` event to call when the enter key is pressed
---@param fgColor color|nil The color of the text (defaults to white)
---@param bgColor color|nil The color of the background (defaults to black)
---@param replacement string|nil A character to replace typed characters with
---@param history string[]|nil A list of previous entries to provide
---@param completion function|nil A function to call to provide completion
---@param default string|nil A string to return if the box is empty
function PrimeUI.inputBox(win, x, y, width, action, fgColor, bgColor, replacement, history, completion, default)
expect(1, win, "table")
expect(2, x, "number")
expect(3, y, "number")
expect(4, width, "number")
expect(5, action, "function", "string")
fgColor = expect(6, fgColor, "number", "nil") or colors.white
bgColor = expect(7, bgColor, "number", "nil") or colors.black
expect(8, replacement, "string", "nil")
expect(9, history, "table", "nil")
expect(10, completion, "function", "nil")
expect(11, default, "string", "nil")
-- Create a window to draw the input in.
local box = window.create(win, x, y, width, 1)
box.setTextColor(fgColor)
box.setBackgroundColor(bgColor)
box.clear()
-- Call read() in a new coroutine.
PrimeUI.addTask(function()
-- We need a child coroutine to be able to redirect back to the window.
local coro = coroutine.create(read)
-- Run the function for the first time, redirecting to the window.
local old = term.redirect(box)
local ok, res = coroutine.resume(coro, replacement, history, completion, default)
term.redirect(old)
-- Run the coroutine until it finishes.
while coroutine.status(coro) ~= "dead" do
-- Get the next event.
local ev = table.pack(os.pullEvent())
-- Redirect and resume.
old = term.redirect(box)
ok, res = coroutine.resume(coro, table.unpack(ev, 1, ev.n))
term.redirect(old)
-- Pass any errors along.
if not ok then error(res) end
end
-- Send the result to the receiver.
if type(action) == "string" then
PrimeUI.resolve("inputBox", action, res)
else
action(res)
end
-- Spin forever, because tasks cannot exit.
while true do os.pullEvent() end
end)
end
--- Draws a horizontal line at a position with the specified width.
---@param win Window The window to draw on
---@param x number The X position of the left side of the line
---@param y number The Y position of the line
---@param width number The width/length of the line
---@param fgColor color|nil The color of the line (defaults to white)
---@param bgColor color|nil The color of the background (defaults to black)
function PrimeUI.horizontalLine(win, x, y, width, fgColor, bgColor)
expect(1, win, "table")
expect(2, x, "number")
expect(3, y, "number")
expect(4, width, "number")
fgColor = expect(5, fgColor, "number", "nil") or colors.white
bgColor = expect(6, bgColor, "number", "nil") or colors.black
-- Use drawing characters to draw a thin line.
win.setCursorPos(x, y)
win.setTextColor(fgColor)
win.setBackgroundColor(bgColor)
win.write(("\x8C"):rep(width))
end
--- Adds an action to trigger when a key is pressed.
---@param key number The key to trigger on, from `keys.*`
---@param action function|string A function to call when clicked, or a string to use as a key for a `run` return event
function PrimeUI.keyAction(key, action)
expect(1, key, "number")
expect(2, action, "function", "string")
PrimeUI.addTask(function()
while true do
local _, param1 = os.pullEvent("key") -- wait for key
if param1 == key then
if type(action) == "string" then
PrimeUI.resolve("keyAction", action)
else
action()
end
end
end
end)
end
--- Draws a thin border around a screen region.
---@param win Window The window to draw on
---@param x number The X coordinate of the inside of the box
---@param y number The Y coordinate of the inside of the box
---@param width number The width of the inner box
---@param height number The height of the inner box
---@param fgColor color|nil The color of the border (defaults to white)
---@param bgColor color|nil The color of the background (defaults to black)
function PrimeUI.borderBox(win, x, y, width, height, fgColor, bgColor)
expect(1, win, "table")
expect(2, x, "number")
expect(3, y, "number")
expect(4, width, "number")
expect(5, height, "number")
fgColor = expect(6, fgColor, "number", "nil") or colors.white
bgColor = expect(7, bgColor, "number", "nil") or colors.black
-- Draw the top-left corner & top border.
win.setBackgroundColor(bgColor)
win.setTextColor(fgColor)
win.setCursorPos(x - 1, y - 1)
win.write("\x9C" .. ("\x8C"):rep(width))
-- Draw the top-right corner.
win.setBackgroundColor(fgColor)
win.setTextColor(bgColor)
win.write("\x93")
-- Draw the right border.
for i = 1, height do
win.setCursorPos(win.getCursorPos() - 1, y + i - 1)
win.write("\x95")
end
-- Draw the left border.
win.setBackgroundColor(bgColor)
win.setTextColor(fgColor)
for i = 1, height do
win.setCursorPos(x - 1, y + i - 1)
win.write("\x95")
end
-- Draw the bottom border and corners.
win.setCursorPos(x - 1, y + height)
win.write("\x8D" .. ("\x8C"):rep(width) .. "\x8E")
end
--- Creates a list of entries that can each be selected.
---@param win Window The window to draw on
---@param x number The X coordinate of the inside of the box
---@param y number The Y coordinate of the inside of the box
---@param width number The width of the inner box
---@param height number The height of the inner box
---@param entries string[] A list of entries to show, where the value is whether the item is pre-selected (or `"R"` for required/forced selected)
---@param action function|string A function or `run` event that's called when a selection is made
---@param selectChangeAction function|string|nil A function or `run` event that's called when the current selection is changed
---@param fgColor color|nil The color of the text (defaults to white)
---@param bgColor color|nil The color of the background (defaults to black)
function PrimeUI.selectionBox(win, x, y, width, height, entries, action, selectChangeAction, fgColor, bgColor)
expect(1, win, "table")
expect(2, x, "number")
expect(3, y, "number")
expect(4, width, "number")
expect(5, height, "number")
expect(6, entries, "table")
expect(7, action, "function", "string")
expect(8, selectChangeAction, "function", "string", "nil")
fgColor = expect(9, fgColor, "number", "nil") or colors.white
bgColor = expect(10, bgColor, "number", "nil") or colors.black
-- Create container window.
local entrywin = window.create(win, x, y, width - 1, height)
local selection, scroll = 1, 1
-- Create a function to redraw the entries on screen.
local function drawEntries()
-- Clear and set invisible for performance.
entrywin.setVisible(false)
entrywin.setBackgroundColor(bgColor)
entrywin.clear()
-- Draw each entry in the scrolled region.
for i = scroll, scroll + height - 1 do
-- Get the entry; stop if there's no more.
local e = entries[i]
if not e then break end
-- Set the colors: invert if selected.
entrywin.setCursorPos(2, i - scroll + 1)
if i == selection then
entrywin.setBackgroundColor(fgColor)
entrywin.setTextColor(bgColor)
else
entrywin.setBackgroundColor(bgColor)
entrywin.setTextColor(fgColor)
end
-- Draw the selection.
entrywin.clearLine()
entrywin.write(#e > width - 1 and e:sub(1, width - 4) .. "..." or e)
end
-- Draw scroll arrows.
entrywin.setCursorPos(width, 1)
entrywin.write(scroll > 1 and "\30" or " ")
entrywin.setCursorPos(width, height)
entrywin.write(scroll < #entries - height + 1 and "\31" or " ")
-- Send updates to the screen.
entrywin.setVisible(true)
end
-- Draw first screen.
drawEntries()
-- Add a task for selection keys.
PrimeUI.addTask(function()
while true do
local event, key = os.pullEvent()
local move_down = (event == "key" and key == keys.down) or (event == "mouse_scroll" and key == 1)
local move_up = (event == "key" and key == keys.up) or (event == "mouse_scroll" and key == -1)
if move_down and selection < #entries then
-- Move selection down.
selection = selection + 1
if selection > scroll + height - 1 then scroll = scroll + 1 end
-- Send action if necessary.
if type(selectChangeAction) == "string" then
PrimeUI.resolve("selectionBox", selectChangeAction, selection)
elseif selectChangeAction then
selectChangeAction(selection)
end
-- Redraw screen.
drawEntries()
elseif move_up and selection > 1 then
-- Move selection up.
selection = selection - 1
if selection < scroll then scroll = scroll - 1 end
-- Send action if necessary.
if type(selectChangeAction) == "string" then
PrimeUI.resolve("selectionBox", selectChangeAction, selection)
elseif selectChangeAction then
selectChangeAction(selection)
end
-- Redraw screen.
drawEntries()
elseif event == "key" and key == keys.enter then
-- Select the entry: send the action.
if type(action) == "string" then
PrimeUI.resolve("selectionBox", action, entries[selection])
else
action(entries[selection])
end
end
end
end)
end
--- Creates a text box that wraps text and can have its text modified later.
---@param win Window The parent window of the text box
---@param x number The X position of the box
---@param y number The Y position of the box
---@param width number The width of the box
---@param height number The height of the box
---@param text string The initial text to draw
---@param fgColor color|nil The color of the text (defaults to white)
---@param bgColor color|nil The color of the background (defaults to black)
---@return function redraw A function to redraw the window with new contents
function PrimeUI.textBox(win, x, y, width, height, text, fgColor, bgColor)
expect(1, win, "table")
expect(2, x, "number")
expect(3, y, "number")
expect(4, width, "number")
expect(5, height, "number")
expect(6, text, "string")
fgColor = expect(7, fgColor, "number", "nil") or colors.white
bgColor = expect(8, bgColor, "number", "nil") or colors.black
-- Create the box window.
local box = window.create(win, x, y, width, height)
-- Override box.getSize to make print not scroll.
---@diagnostic disable-next-line: duplicate-set-field
function box.getSize()
return width, math.huge
end
-- Define a function to redraw with.
local function redraw(_text)
expect(1, _text, "string")
-- Set window parameters.
box.setBackgroundColor(bgColor)
box.setTextColor(fgColor)
box.clear()
box.setCursorPos(1, 1)
-- Redirect and draw with `print`.
local old = term.redirect(box)
print(_text)
term.redirect(old)
end
redraw(text)
return redraw
end
--- Creates a clickable button on screen with text.
---@param win Window The window to draw on
---@param x number The X position of the button
---@param y number The Y position of the button
---@param text string The text to draw on the button
---@param action function|string A function to call when clicked, or a string to send with a `run` event
---@param fgColor color|nil The color of the button text (defaults to white)
---@param bgColor color|nil The color of the button (defaults to light gray)
---@param clickedColor color|nil The color of the button when clicked (defaults to gray)
function PrimeUI.button(win, x, y, text, action, fgColor, bgColor, clickedColor)
expect(1, win, "table")