-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathminiOS.lua
More file actions
1496 lines (1380 loc) · 42.3 KB
/
miniOS.lua
File metadata and controls
1496 lines (1380 loc) · 42.3 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
_G._OSNAME = "miniOS classic"
_G._OSVER = "0.6.5"
_G._OSVERSION = _OSNAME .. " " .. _OSVER
_G._OSCREDIT = "miniOS classic by Skye, based off of OpenOS code from OpenComputers.\nminiOS code is under BSD 2-clause licence, OpenOS code is under the MIT licence."
--component code
function component_code()
local adding = {}
local removing = {}
local primaries = {}
-------------------------------------------------------------------------------
-- This allows writing component.modem.open(123) instead of writing
-- component.getPrimary("modem").open(123), which may be nicer to read.
setmetatable(component, { __index = function(_, key)
return component.getPrimary(key)
end})
function component.get(address, componentType)
checkArg(1, address, "string")
checkArg(2, componentType, "string", "nil")
for c in component.list(componentType, true) do
if c:sub(1, address:len()) == address then
return c
end
end
return nil, "no such component"
end
function component.isAvailable(componentType)
checkArg(1, componentType, "string")
if not primaries[componentType] then
-- This is mostly to avoid out of memory errors preventing proxy
-- creation cause confusion by trying to create the proxy again,
-- causing the oom error to be thrown again.
component.setPrimary(componentType, component.list(componentType, true)())
end
return primaries[componentType] ~= nil
end
function component.isPrimary(address)
local componentType = component.type(address)
if componentType then
if component.isAvailable(componentType) then
return primaries[componentType].address == address
end
end
return false
end
function component.getPrimary(componentType)
checkArg(1, componentType, "string")
assert(component.isAvailable(componentType),
"no primary '" .. componentType .. "' available")
return primaries[componentType]
end
function component.setPrimary(componentType, address)
checkArg(1, componentType, "string")
checkArg(2, address, "string", "nil")
if address ~= nil then
address = component.get(address, componentType)
assert(address, "no such component")
end
local wasAvailable = primaries[componentType]
if wasAvailable and address == wasAvailable.address then
return
end
local wasAdding = adding[componentType]
if wasAdding and address == wasAdding.address then
return
end
if wasAdding then
event.cancel(wasAdding.timer)
end
primaries[componentType] = nil
adding[componentType] = nil
local primary = address and component.proxy(address) or nil
if wasAvailable then
computer.pushSignal("component_unavailable", componentType)
end
if primary then
if wasAvailable or wasAdding then
adding[componentType] = {
address=address,
timer=event.timer(0.1, function()
adding[componentType] = nil
primaries[componentType] = primary
computer.pushSignal("component_available", componentType)
end)
}
else
primaries[componentType] = primary
computer.pushSignal("component_available", componentType)
end
end
end
-------------------------------------------------------------------------------
local function onComponentAdded(_, address, componentType)
if not (primaries[componentType] or adding[componentType]) then
component.setPrimary(componentType, address)
end
end
local function onComponentRemoved(_, address, componentType)
if primaries[componentType] and primaries[componentType].address == address or
adding[componentType] and adding[componentType].address == address
then
component.setPrimary(componentType, component.list(componentType, true)())
end
end
event.listen("component_added", onComponentAdded)
event.listen("component_removed", onComponentRemoved)
end
--text libary
function text_code()
local text = {}
function text.detab(value, tabWidth)
checkArg(1, value, "string")
checkArg(2, tabWidth, "number", "nil")
tabWidth = tabWidth or 8
local function rep(match)
local spaces = tabWidth - match:len() % tabWidth
return match .. string.rep(" ", spaces)
end
local result = value:gsub("([^\n]-)\t", rep) -- truncate results
return result
end
function text.padRight(value, length)
checkArg(1, value, "string", "nil")
checkArg(2, length, "number")
if not value or unicode.len(value) == 0 then
return string.rep(" ", length)
else
return value .. string.rep(" ", length - unicode.len(value))
end
end
function text.padLeft(value, length)
checkArg(1, value, "string", "nil")
checkArg(2, length, "number")
if not value or unicode.len(value) == 0 then
return string.rep(" ", length)
else
return string.rep(" ", length - unicode.len(value)) .. value
end
end
function text.trim(value) -- from http://lua-users.org/wiki/StringTrim
local from = string.match(value, "^%s*()")
return from > #value and "" or string.match(value, ".*%S", from)
end
function text.wrap(value, width, maxWidth)
checkArg(1, value, "string")
checkArg(2, width, "number")
checkArg(3, maxWidth, "number")
local line, nl = value:match("([^\r\n]*)(\r?\n?)") -- read until newline
if unicode.len(line) > width then -- do we even need to wrap?
local partial = unicode.sub(line, 1, width)
local wrapped = partial:match("(.*[^a-zA-Z0-9._()'`=])")
if wrapped or unicode.len(line) > maxWidth then
partial = wrapped or partial
return partial, unicode.sub(value, unicode.len(partial) + 1), true
else
return "", value, true -- write in new line.
end
end
local start = unicode.len(line) + unicode.len(nl) + 1
return line, start <= unicode.len(value) and unicode.sub(value, start) or nil, unicode.len(nl) > 0
end
function text.wrappedLines(value, width, maxWidth)
local line, nl
return function()
if value then
line, value, nl = text.wrap(value, width, maxWidth)
return line
end
end
end
-------------------------------------------------------------------------------
function text.tokenize(value)
checkArg(1, value, "string")
local tokens, token = {}, ""
local escaped, quoted, start = false, false, -1
for i = 1, unicode.len(value) do
local char = unicode.sub(value, i, i)
if escaped then -- escaped character
escaped = false
token = token .. char
elseif char == "\\" and quoted ~= "'" then -- escape character?
escaped = true
token = token .. char
elseif char == quoted then -- end of quoted string
quoted = false
token = token .. char
elseif (char == "'" or char == '"') and not quoted then
quoted = char
start = i
token = token .. char
elseif string.find(char, "%s") and not quoted then -- delimiter
if token ~= "" then
table.insert(tokens, token)
token = ""
end
else -- normal char
token = token .. char
end
end
if quoted then
return nil, "unclosed quote at index " .. start
end
if token ~= "" then
table.insert(tokens, token)
end
return tokens
end
-------------------------------------------------------------------------------
function text.endswith(s, send)
return #s >= #send and s:find(send, #s-#send+1, true) and true or false
end
return text
end
--event code
function event_code()
local event, listeners, timers = {}, {}, {}
local lastInterrupt = -math.huge
local function matches(signal, name, filter)
if name and not (type(signal[1]) == "string" and signal[1]:match(name))
then
return false
end
for i = 1, filter.n do
if filter[i] ~= nil and filter[i] ~= signal[i + 1] then
return false
end
end
return true
end
local function call(callback, ...)
local result, message = pcall(callback, ...)
if not result and type(event.onError) == "function" then
pcall(event.onError, message)
return
end
return message
end
local function dispatch(signal, ...)
if listeners[signal] then
local function callbacks()
local list = {}
for index, listener in ipairs(listeners[signal]) do
list[index] = listener
end
return list
end
for _, callback in ipairs(callbacks()) do
if call(callback, signal, ...) == false then
event.ignore(signal, callback) -- alternative method of removing a listener
end
end
end
end
local function tick()
local function elapsed()
local list = {}
for id, timer in pairs(timers) do
if timer.after <= computer.uptime() then
table.insert(list, timer.callback)
timer.times = timer.times - 1
if timer.times <= 0 then
timers[id] = nil
else
timer.after = computer.uptime() + timer.interval
end
end
end
return list
end
for _, callback in ipairs(elapsed()) do
call(callback)
end
end
-------------------------------------------------------------------------------
function event.cancel(timerId)
checkArg(1, timerId, "number")
if timers[timerId] then
timers[timerId] = nil
return true
end
return false
end
function event.ignore(name, callback)
checkArg(1, name, "string")
checkArg(2, callback, "function")
if listeners[name] then
for i = 1, #listeners[name] do
if listeners[name][i] == callback then
table.remove(listeners[name], i)
if #listeners[name] == 0 then
listeners[name] = nil
end
return true
end
end
end
return false
end
function event.listen(name, callback)
checkArg(1, name, "string")
checkArg(2, callback, "function")
if listeners[name] then
for i = 1, #listeners[name] do
if listeners[name][i] == callback then
return false
end
end
else
listeners[name] = {}
end
table.insert(listeners[name], callback)
return true
end
function event.onError(message)
local log = fs.open("/tmp/event.log", "a")
if log then
fs.write(log, message .. "\n")
fs.close(log)
end
end
function event.pull(...)
local args = table.pack(...)
local seconds, name, filter
if type(args[1]) == "string" then
name = args[1]
filter = table.pack(table.unpack(args, 2, args.n))
else
checkArg(1, args[1], "number", "nil")
checkArg(2, args[2], "string", "nil")
seconds = args[1]
name = args[2]
filter = table.pack(table.unpack(args, 3, args.n))
end
local hasFilter = name ~= nil
if not hasFilter then
for i = 1, filter.n do
hasFilter = hasFilter or filter[i] ~= nil
end
end
local deadline = seconds and
(computer.uptime() + seconds) or
(hasFilter and math.huge or 0)
repeat
local closest = seconds and deadline or math.huge
for _, timer in pairs(timers) do
closest = math.min(closest, timer.after)
end
local signal = table.pack(computer.pullSignal(closest - computer.uptime()))
if signal.n > 0 then
dispatch(table.unpack(signal, 1, signal.n))
end
tick()
if event.shouldInterrupt() then
lastInterrupt = computer.uptime()
error("interrupted", 0)
end
if not (seconds or hasFilter) or matches(signal, name, filter) then
return table.unpack(signal, 1, signal.n)
end
until computer.uptime() >= deadline
end
function event.shouldInterrupt()
return computer.uptime() - lastInterrupt > 1 and
keyboard.isControlDown() and
keyboard.isAltDown() and
keyboard.isKeyDown(keyboard.keys.c)
end
function event.timer(interval, callback, times)
checkArg(1, interval, "number")
checkArg(2, callback, "function")
checkArg(3, times, "number", "nil")
local id
repeat
id = math.floor(math.random(1, 0x7FFFFFFF))
until not timers[id]
timers[id] = {
interval = interval,
after = computer.uptime() + interval,
callback = callback,
times = times or 1
}
return id
end
-------------------------------------------------------------------------------
return event
end
--filesystem code
function fs_code()
local fs = {}
fs.drive = {}
--drive mapping table, initilized later
fs.drive._map = {}
--converts a drive letter into a proxy
function fs.drive.letterToProxy(letter)
return fs.drive._map[letter]
end
--finds the proxy associated with the letter
function fs.drive.proxyToLetter(proxy)
for l,p in pairs(fs.drive._map) do
if p == proxy then return l end
end
return nil
end
--maps a proxy to a letter
function fs.drive.mapProxy(letter, proxy)
fs.drive._map[letter] = proxy
end
--finds the address of a drive letter.
function fs.drive.toAddress(letter)
return fs.drive._map[letter].address
end
--finds the drive letter mapped to an address
function fs.drive.toLetter(address)
for l,p in pairs(fs.drive._map) do
if p.address == address then return l end
end
return nil
end
function fs.drive.mapAddress(letter, address)
--print("mapAddress")
if address == nil then fs.drive._map[letter] = nil
else fs.drive._map[letter] = fs.proxy(address) end
end
function fs.drive.autoMap(address) --returns the letter if mapped OR already mapped, false if not.
--print("autoMap")
--we get the address and see if it already is mapped...
local l = fs.drive.toLetter(address)
if l then return l end
--then we take the address and attempt to map it
--start at A:
l = "A"
while true do
--see if it is mapped and then go to the next letter...
if fs.drive._map[l] then l = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ_'):match(l..'(.)') else fs.drive.mapAddress(l, address) return l end
--if we got to the end, fail
if l == "_" then return false end
end
end
function fs.drive.listProxy()
local t = fs.drive._map
local p = {}
for n in pairs(t) do table.insert(p, n) end
table.sort(p, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if p[i] == nil then return nil
else return p[i], t[p[i]]
end
end
return iter
end
function fs.drive.list()
local i = 0 -- iterator variable
local proxyIter = fs.drive.listProxy()
local iter = function () -- iterator function
l, p = proxyIter()
if not l then return nil end
return l, p.address
end
return iter
end
fs.drive._current = "A" --as the boot drive is A:
function fs.drive.setcurrent(letter)
letter = letter:upper()
if not fs.drive._map[letter] then error("Invalid Drive", 2) end
fs.drive._current = letter
end
function fs.drive.drivepathSplit(mixed)
local drive = fs.drive._current
local path
if string.sub(mixed, 2,2) == ":" then
drive = string.sub(mixed, 1,1):upper()
path = string.sub(mixed, 3)
else
path = mixed
end
return drive, path
end
function fs.drive.getcurrent() return fs.drive._current end
function fs.drive.scan()
local to_remove = {}
for letter,proxy in pairs(fs.drive._map) do
if component.type(proxy.address) == nil then
to_remove[#to_remove + 1] = letter
end
end
for _,l in ipairs(to_remove) do
fs.drive._map[l] = nil
end
for address, componentType in component.list() do
if componentType == "filesystem" then filesystem.drive.autoMap(address) end
end
end
function fs.invoke(method, ...) return fs.drive._map[fs.drive._current][method](...) end
function fs.proxy(filter)
checkArg(1, filter, "string")
local address
for c in component.list("filesystem") do
if component.invoke(c, "getLabel") == filter then
address = c
break
end
if filter:sub(2,2) == ":" then
if fs.drive.toAddress(filter:sub(1,1)) == c then address = c break end
end
if c:sub(1, filter:len()) == filter then
address = c
break
end
end
if not address then
return nil, "no such file system"
end
return component.proxy(address)
end
function fs.open(file, mode)
local drive, handle, proxy
drive, path = fs.drive.drivepathSplit(file)
proxy = fs.drive.letterToProxy(drive)
handle, reason = proxy.open(path, mode or 'r')
if not handle then return nil, reason end
return setmetatable({_handle = handle, _proxy = proxy}, {__index = fs})
end
function fs.write(handle, data) return handle._proxy.write(handle._handle, data) end
function fs.read(handle, length) return handle._proxy.read(handle._handle, length or math.huge) end
function fs.seek(handle, mode, position) return handle._proxy.seek(handle._handle, mode, position) end
function fs.close(handle) return handle._proxy.close(handle._handle) end
function fs.isDirectory(path)
local drive
drive, path = fs.drive.drivepathSplit(path)
return fs.drive.letterToProxy(drive).isDirectory(path)
end
function fs.exists(path)
local drive
drive, path = fs.drive.drivepathSplit(path)
return fs.drive.letterToProxy(drive).exists(path)
end
function fs.remove(path)
local drive
drive, path = fs.drive.drivepathSplit(path)
return fs.drive.letterToProxy(drive).remove(path)
end
function fs.copy(fromPath, toPath)
if fs.isDirectory(fromPath) then
return nil, "cannot copy folders"
end
local input, reason = fs.open(fromPath, "rb")
if not input then
return nil, reason
end
local output, reason = fs.open(toPath, "wb")
if not output then
fs.close(input)
return nil, reason
end
repeat
local buffer, reason = filesystem.read(input)
if not buffer and reason then
return nil, reason
elseif buffer then
local result, reason = filesystem.write(output, buffer)
if not result then
filesystem.close(input)
filesystem.close(output)
return nil, reason
end
end
until not buffer
filesystem.close(input)
filesystem.close(output)
return true
end
function fs.rename(path1, path2)
local drive
drive, path = fs.drive.drivepathSplit(path)
return fs.drive.letterToProxy(drive).rename(path1, path2)
end
function fs.makeDirectory(path)
local drive
drive, path = fs.drive.drivepathSplit(path)
return fs.drive.letterToProxy(drive).makeDirectory(path)
end
function fs.list(path)
local drive
drive, path = fs.drive.drivepathSplit(path)
local i = 0
local t = fs.drive.letterToProxy(drive).list(path)
local n = #t
return function()
i = i + 1
if i <= n then return t[i] end
return nil
end
end
function fs.get(path)
local drive
drive, path = fs.drive.drivepathSplit(path)
drive = fs.drive.letterToProxy(drive)
if not drive then return nil, "no such file system"
else return drive, path end
end
--handle inserted and removed filesystems
local function onComponentAdded(_, address, componentType)
if componentType == "filesystem" then
fs.drive.autoMap(address)
end
end
local function onComponentRemoved(_, address, componentType)
if componentType == "filesystem" then
fs.drive.mapAddress(fs.drive.toLetter(address), nil)
end
end
event.listen("component_added", onComponentAdded)
event.listen("component_removed", onComponentRemoved)
local function driveInit()
local boot = fs.proxy(computer.getBootAddress())
local temp = fs.proxy(computer.tmpAddress())
fs.drive._map = { ["A"]=boot, ["X"]=temp }
end
driveInit()
--return the API
return fs
end
--terminal code
function terminal_code()
local term = {}
local cursorX, cursorY = 1, 1
local cursorBlink = nil
--- quick and dirty hacks that allow newer programs to run while not actually writing new code
term.gpu = function() return component.gpu end
term.getViewport = function()
local w, h = component.gpu.getResolution()
return w, h, 0, 0, cursorX, cursorY
end
term.getGlobalArea = function(ignored)
local w,h,dx,dy,rx,ry = term.getViewport(window)
return dx+1,dy+1,w,h
end
term.pull = event.pull
term.keyboard = function() return component.keyboard.address end
term.screen = function() return term.gpu().getScreen() end
local function toggleBlink()
if term.isAvailable() then
cursorBlink.state = not cursorBlink.state
if cursorBlink.state then
cursorBlink.alt = component.gpu.get(cursorX, cursorY)
component.gpu.set(cursorX, cursorY, "▁")
else
component.gpu.set(cursorX, cursorY, cursorBlink.alt)
end
end
end
-------------------------------------------------------------------------------
function term.clear()
if term.isAvailable() then
local w, h = component.gpu.getResolution()
component.gpu.fill(1, 1, w, h, " ")
end
cursorX, cursorY = 1, 1
end
function term.clearLine()
if term.isAvailable() then
local w = component.gpu.getResolution()
component.gpu.fill(1, cursorY, w, 1, " ")
end
cursorX = 1
end
function term.getCursor()
return cursorX, cursorY
end
function term.setCursor(col, row)
checkArg(1, col, "number")
checkArg(2, row, "number")
if cursorBlink and cursorBlink.state then
toggleBlink()
end
cursorX = math.floor(col)
cursorY = math.floor(row)
end
function term.getCursorBlink()
return cursorBlink ~= nil
end
function term.setCursorBlink(enabled)
checkArg(1, enabled, "boolean")
if enabled then
if not cursorBlink then
cursorBlink = {}
cursorBlink.id = event.timer(0.5, toggleBlink, math.huge)
cursorBlink.state = false
elseif not cursorBlink.state then
toggleBlink()
end
elseif cursorBlink then
event.cancel(cursorBlink.id)
if cursorBlink.state then
toggleBlink()
end
cursorBlink = nil
end
end
function term.isAvailable()
return component.isAvailable("gpu") and component.isAvailable("screen")
end
function term.readKey(echo)
local blink = term.getCursorBlink()
term.setCursorBlink(true)
local ok, name, address, charOrValue, code = pcall(event.pull, "key_down")
if not ok then
term.setCursorBlink(blink)
error("interrupted", 0)
end
if name == "key_down" then
if echo then term.write(charOrValue) end
term.setCursorBlink(blink)
end
end
function term.read(history, dobreak, hint)
checkArg(1, history, "table", "nil")
checkArg(3, hint, "table", "function", "nil")
history = history or {}
table.insert(history, "")
local offset = term.getCursor() - 1
local scrollX, scrollY = 0, #history - 1
local hints = { handler = hint }
local function getCursor()
local cx, cy = term.getCursor()
return cx - offset + scrollX, 1 + scrollY
end
local function line()
local cbx, cby = getCursor()
return history[cby]
end
local function setCursor(nbx, nby)
local w, h = component.gpu.getResolution()
local cx, cy = term.getCursor()
scrollY = nby - 1
nbx = math.max(1, math.min(unicode.len(history[nby]) + 1, nbx))
local ncx = nbx + offset - scrollX
if ncx > w then
local sx = nbx - (w - offset)
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1 + offset + dx, cy, w - offset - dx, 1, -dx, 0)
local str = unicode.sub(history[nby], nbx - (dx - 1), nbx)
str = text.padRight(str, dx)
component.gpu.set(1 + math.max(offset, w - dx), cy, unicode.sub(str, 1 + math.max(0, dx - (w - offset))))
elseif ncx < 1 + offset then
local sx = nbx - 1
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1 + offset, cy, w - offset - dx, 1, dx, 0)
local str = unicode.sub(history[nby], nbx, nbx + dx)
--str = text.padRight(str, dx)
component.gpu.set(1 + offset, cy, str)
end
term.setCursor(nbx - scrollX + offset, cy)
end
local function copyIfNecessary()
local cbx, cby = getCursor()
if cby ~= #history then
history[#history] = line()
setCursor(cbx, #history)
end
end
local function redraw()
local cx, cy = term.getCursor()
local bx, by = 1 + scrollX, 1 + scrollY
local w, h = component.gpu.getResolution()
local l = w - offset
local str = unicode.sub(history[by], bx, bx + l)
str = text.padRight(str, l)
component.gpu.set(1 + offset, cy, str)
end
local function setline(to)
local cbx, cby = getCursor()
history[cby] = to
redraw()
end
local function home()
local cbx, cby = getCursor()
setCursor(1, cby)
end
local function ende()
local cbx, cby = getCursor()
setCursor(unicode.len(line()) + 1, cby)
end
local function left()
local cbx, cby = getCursor()
if cbx > 1 then
setCursor(cbx - 1, cby)
return true -- for backspace
end
end
local function right(n)
n = n or 1
local cbx, cby = getCursor()
local be = unicode.len(line()) + 1
if cbx < be then
setCursor(math.min(be, cbx + n), cby)
end
end
local function up()
local cbx, cby = getCursor()
if cby > 1 then
setCursor(1, cby - 1)
redraw()
ende()
end
end
local function down()
local cbx, cby = getCursor()
if cby < #history then
setCursor(1, cby + 1)
redraw()
ende()
end
end
local function delete()
copyIfNecessary()
local cbx, cby = getCursor()
if cbx <= unicode.len(line()) then
history[cby] = unicode.sub(line(), 1, cbx - 1) ..
unicode.sub(line(), cbx + 1)
local cx, cy = term.getCursor()
local w, h = component.gpu.getResolution()
component.gpu.copy(cx + 1, cy, w - cx, 1, -1, 0)
local br = cbx + (w - cx)
local char = unicode.sub(line(), br, br)
if not char or unicode.len(char) == 0 then
char = " "
end
component.gpu.set(w, cy, char)
end
end
local function insert(value)
copyIfNecessary()
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = component.gpu.getResolution()
history[cby] = unicode.sub(line(), 1, cbx - 1) ..
value ..
unicode.sub(line(), cbx)
local len = unicode.len(value)
local n = w - (cx - 1) - len
if n > 0 then
component.gpu.copy(cx, cy, n, 1, len, 0)
end
component.gpu.set(cx, cy, value)
right(len)
end
local function tab()
if not hints.handler then return end
local main_kb = term.keyboard()
-- term may not have a keyboard
-- in which case, we shouldn't be handling tab events
if not main_kb then
return
end
if not hints.cache then
local data = hints.handler
hints.handler = function(...)
if type(data) == "table" then
local args = {...}
local filtered = {}
for _,option in ipairs(data) do
if string.sub(option, 1, #args[1]) == args[1] then
filtered[#filtered + 1] = option
--print(option)
end
end
return filtered
else
return data(...) or {}
end
end
hints.cache = hints.handler(line(), #line() + 1)
hints.cache.i = -1
end
local cache = hints.cache
local cache_size = #cache
if cache_size == 1 and cache.i == 0 then
-- there was only one solution, and the user is asking for the next
hints.cache = hints.handler(cache[1], #line() + 1)
hints.cache.i = -1
cache = hints.cache
cache_size = #cache
end
local change = keyboard.isShiftDown(main_kb) and -1 or 1
cache.i = (cache.i + change) % math.max(#cache, 1)
local next = cache[cache.i + 1]
if next then
local tail = unicode.len(line()) - #line()
setline(next)
local cbx, cby = getCursor()
setCursor(cbx + #line(), cby)
end
end
local function onKeyDown(char, code)
term.setCursorBlink(false)
if code == keyboard.keys.tab then
tab()
else
hints.cache = nil
end
if code == keyboard.keys.back then
if left() then delete() end
elseif code == keyboard.keys.delete then
delete()
elseif code == keyboard.keys.left then
left()
elseif code == keyboard.keys.right then
right()
elseif code == keyboard.keys.home then
home()
elseif code == keyboard.keys["end"] then
ende()
elseif code == keyboard.keys.up then
up()
elseif code == keyboard.keys.down then
down()
elseif code == keyboard.keys.enter then