-
Notifications
You must be signed in to change notification settings - Fork 2
/
cosu.lua
2630 lines (2521 loc) · 89.8 KB
/
cosu.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
--[[ +++ Configurable +++ ]]
local cosuConf = {}
cosuConf.tKeyboard = {
["up"] = keys.up,
["down"] = keys.down,
["left"] = keys.left,
["right"] = keys.right,
["tab"] = keys.tab,
["delete"] = keys.delete,
["backspace"] = keys.backspace,
["enter"] = keys.enter,
["F_Help"] = keys.f1,
["F_SpChar"] = keys.f7,
["F_Run"] = keys.f5,
["F_NewShell"] = keys.f4,
["CTRL"] = {
{ "NewFile", keys.n },
{ "SaveAs", { keys.s, keys.leftShift } },
{ "Save", keys.s },
}
}
cosuConf.bCursorIsBlock = false
cosuConf.cAccentColor = colors.blue
cosuConf.bDoubleClickButton = false
cosuConf.nTabSpace = 4 --[[ Normaly 4 spaces. ]]
cosuConf.bJumpAtEndToBegin = true
cosuConf.bShadows = true
cosuConf.tPalette = {
true,
["black"] = 0x171421,
["blue"] = 0x2A7BDE,
["brown"] = 0xA2734C,
["cyan"] = 0x2AA1B3,
["gray"] = 0x5E5C64,
["green"] = 0x26A269,
["lightBlue"] = 0x33C7DE,
["lightGray"] = 0xD0CFCC,
["lime"] = 0x33D17A,
["magenta"] = 0xC061CB,
["orange"] = 0xE9AD0C,
["pink"] = 0xF66151,
["purple"] = 0xA347BA,
["red"] = 0xC01C28,
["white"] = 0xFFFFFF,
["yellow"] = 0xF3F03E
}
--[[ Color palette for .lua files ]]
local colorMatch = { }
colorMatch["popupBG"]=colors.lightGray
colorMatch["popupFrame"]=colors.gray
colorMatch["popupFont"]=colors.black
colorMatch["cAccentText"]=colors.lightGray
if term.isColor() then
colorMatch["bg"] = colors.black
colorMatch["bracket"] = colors.lightGray
colorMatch["comment"] = colors.gray
colorMatch["func"] = colors.orange
colorMatch["keyword"] = colors.red
colorMatch["number"] = colors.magenta
colorMatch["operator"] = colors.cyan
colorMatch["string"] = colors.green
colorMatch["special"] = colors.yellow
colorMatch["text"] = colors.white
colorMatch["positive"] = colors.lime
colorMatch["negative"] = colors.red
else
cosuConf.cAccentColor = colors.gray
colorMatch["bg"] = colors.black
colorMatch["bracket"] = colors.gray
colorMatch["comment"] = colors.gray
colorMatch["func"] = colors.white
colorMatch["keyword"] = colors.white
colorMatch["number"] = colors.lightGray
colorMatch["operator"] = colors.lightGray
colorMatch["string"] = colors.lightGray
colorMatch["special"] = colors.white
colorMatch["text"] = colors.white
colorMatch["positive"] = colors.white
colorMatch["negative"] = colors.lightGray
end
--[[ +++ Program variables (no touching!) +++ ]]
local nTerm=term.current()
local term=nTerm
local loadAPIVirtual
local tMultibleStrings = {0,0}
--[[ .lua syntax ]]
local tKeywords = {
["and"] = true,
["break"] = true,
["do"] = true,
["else"] = true,
["elseif"] = true,
["end"] = true,
["for"] = true,
["function"] = true,
["if"] = true,
["in"] = true,
["local"] = true,
["nil"] = true,
["not"] = true,
["or"] = true,
["repeat"] = true,
["require"] = true,
["return"] = true,
["then"] = true,
["until"] = true,
["while"] = true,
}
local tPatterns = {
{ "^%-%-.*", colorMatch["comment"] },
{ "^\"\"", colorMatch["string"] },
{ "^\".-[^\\]\"", colorMatch["string"] },
{ "^\'\'", colorMatch["string"] },
{ "^\'.-[^\\]\'", colorMatch["string"] },
{ "^%[%[%]%]", colorMatch["string"] },
{ "^%[%[.-[^\\]%]%]", colorMatch["string"] },
{ "^[\000\001\002\003\004\005\006\007\008\009\010\011\012\013\014\015\016\017\018\019\020\021\022\023\024\025\026\027\028\029\030\031\127\128\129\130\131\132\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@]+", colorMatch["special"] },
{ "^[%d][xA-Fa-f.%d#]+", colorMatch["number"] },
{ "^[%d]+", colorMatch["number"] },
{ "^[,{}%[%]%(%)]", colorMatch["bracket"] },
{ "^[!%/\\:~<>=%*%+%-%%]+", colorMatch["operator"] },
{ "^true", colorMatch["number"] },
{ "^false", colorMatch["number"] },
{ "^[%w_%.]+", function(match, after, _, nLine)
if tKeywords[match] then
return colorMatch["keyword"]
elseif after:sub(2,2) == "(" then
return colorMatch["func"]
end
return colorMatch["text"]
end },
{ "^[^%w_]", colorMatch["text"] }
}
local sGithub = {
["api"]="https://api.github.com/repos/sammyforreal/consult/releases/latest",
["latest"]="https://github.com/sammyforreal/consult/releases/latest/download/cosu.lua"
}
local sVersion = "1.4.4"
local bPreview = false
local tArgs = { ... }
local init = function() return end
local sPath = ""
local tAutoCompleteList = { }
local tContent = { }
local tCursor = { ['x']=1,['y']=1,["lastX"]=1,["lastY"]=1,["autoListY"]=0, ["selectedItem"]=1, ["selectedSubDropdown"]={} }
local mode = "insert" --[[ "insert";"insertAuto";"toolbar","menu"; ]]
local tScroll = { ['x']=0,['y']=0 }
local tActiveKeys = {}
local w,h = term.getSize()
local virtualEnviroment = _ENV
local tPopup = {}
local bReadOnly = false
local running = true
local bSaved = true
local category = { }
local tWidgets = { }
local draw = { }
local bLvlOS = (lOS and LevelOS and lUtils)
local input = { handle = {}, insertAuto = {}, insert = {}, toolbar = {}, menu = {} }
local blits = {[1]='0',[2]='1',[4]='2',[8]='3',[16]='4',[32]='5',[64]='6',[128]='7',[256]='8',[512]='9',[1024]='a',[2048]='b',[4096]='c',[8192]='d',[16384]='e',[32768]='f' }
local blitInvert = {['0']=1,['1']=2,['2']=4,['3']=8,['4']=16,['5']=32,['7']=128,['8']=256,['9']=512,['a']=1024,['b']=2048,['c']=4096,['d']=8192,['e']=16384,['f']=32768 }
--[[ +++ Other functions +++ ]]
local function autocomplete()
tAutoCompleteList = { }
if type(tContent[tCursor.y]) == "nil" then return end
local sCurrentChar = tContent[tCursor.y]:sub(tCursor.x,tCursor.x)
if not (sCurrentChar == ' ' or sCurrentChar == '') then return end
local nStartPos = string.find((tContent[tCursor.y]):sub(1,tCursor.x-1), "[a-zA-Z0-9_%.:]+$")
if nStartPos then
tAutoCompleteList = textutils.complete(tContent[tCursor.y]:sub(nStartPos, tCursor.x-1), virtualEnviroment)
end
return (#tAutoCompleteList > 0)
end
local string = string
function string.rep(str, num)
local tmp = ""
for i = 1, num do
tmp = tmp .. str
end
return tmp
end
local function checkAutoComplete()
if not bReadOnly and settings.get("edit.autocomplete") and (mode == "insert" or mode == "insertAuto") then
if autocomplete() and tCursor.lastY == tCursor.y then
mode = "insertAuto"
else
mode = "insert"
tCursor.autoListY = 0
end
end
end
local function splitStr(str)
local tStrings = {}
for i=1,#str/(w/1.5) do
tStrings[#tStrings+1] = str:sub(1,w/1.5)
str = str:sub(w/1.5+1)
end
tStrings[#tStrings+1] = str
return table.unpack(tStrings)
end
local function formatText(sText,nLength,nColumns)
--[[ splitting ]]
local tSubText = {}
for i=1,#sText/nLength do
tSubText[#tSubText+1] = sText:sub(1,nLength)
sText = sText:sub(nLength+1)
end
tSubText[#tSubText+1] = sText
--[[ remove column overflow ]]
sText = {}
for i=1,nColumns do
sText[i]=tSubText[i]
end
sText[#sText] = sText[#sText]:sub(1,nLength-3).."..."
return table.unpack(sText)
end
local function cToStr(cFG, cBG)
return "{&"..(blits[cFG] or ' ')..(blits[cBG] or ' ')
end
local function fLen(text)
local len = 0
if text:find('{&') then
for word in string.gmatch(text, '([^{&]+)') do
len = len+#word:sub(3)
end
else
return #text
end
return len
end
local function swapColors()
if not cosuConf.tPalette[1] then return end
for color, code in pairs(cosuConf.tPalette) do
if type(color) == "string" then
local tmp = colors.packRGB(term.getPaletteColor(colors[color]))
term.setPaletteColor(colors[color], code)
cosuConf.tPalette[color] = tmp
end
end
end
local function levelLaunch(path,title)
local gW,gH = lOS.wAll.getSize()
local x,y = LevelOS.self.window.win.getPosition()
local win = lOS.execute(
path,
"windowed",
x+(x+w+1<gW and 2 or 0),
y+(y+h+1<gH and 2 or 0),
51,
19,
true
)
win.icon = {'\138', "9"}
if title then
win.title = title
end
end
--[[ +++ Popup handler +++ ]]
local update,info,help,file,error,options,exit,specialChar,openLink,openShell,openPopup
function openPopup(pop)
if bLvlOS then
-- Get length of longest text line
local nLongestMsg = 7
if pop.text then
for _,tMsgs in pairs(pop.text) do
for _,sMsg in pairs(tMsgs) do
if #sMsg > nLongestMsg then
nLongestMsg = #sMsg
end
end
end
end
-- Convert content
local str = ""
local height = 1
if pop.text then
for _,line in pairs(pop.text) do
for _,msg in pairs(line) do
str = str..msg.."\n"
height=height+1
end
str = str..("-"):rep(nLongestMsg).."\n"
height=height+3
end
end
-- Convert buttons
local buttons = {}
for _,tBtn in pairs(pop.button) do
table.insert(buttons, tBtn.label)
end
if #buttons == 0 then
buttons = {"Ok"}
end
local result = {false}
while not result[1] do
draw.handler()
result = {lUtils.popup(pop.name, str, nLongestMsg+2, height, buttons, pop.label, pop.link)}
if result[1] then
if result[2] then
if pop.button[result[2]].func then
pop.button[result[2]].func(pop)
end
end
end
end
else
table.insert(tPopup, 1, pop)
tCursor.selectedItem = 1
end
end
function update(event, ...)
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name == "Update CONSULT" then
table.remove(tPopup, index)
end
end
elseif event == "check" then
--[[ Check updates ]]
if http then
local gitAPI=http.get(sGithub.api)
if gitAPI and gitAPI.getResponseCode()==200 then
local tGitContent = textutils.unserialiseJSON(gitAPI.readAll())
if tGitContent.tag_name ~= sVersion then
gitAPI.close()
return true,tGitContent.tag_name,tGitContent.body
end
gitAPI.close()
end
end
return false
elseif event == "now" then
--[[ GET UPDATE ]]
local gitAPI=http.get(sGithub.latest)
if gitAPI.getResponseCode()==200 then
local tGitContent = gitAPI.readAll()
local file
if bLvlOS then
file = fs.open( fs.combine(fs.getDir(shell.getRunningProgram()),"cosu.lua"),'w')
else
file = fs.open(shell.getRunningProgram(),'w')
end
file.flush()
file.write(tGitContent)
file.close()
end
gitAPI.close()
--[[ Update popup ]]
if bLvlOS then
lOS.notification("CONSULT", "Updated sucessfully! Restart cosu.", shell.getRunningProgram(), 3)
else
for index,pop in pairs(tPopup) do
if pop.name == "Update CONSULT" then
tPopup[index].size = {
['x'] = nil,
['y'] = nil
}
tPopup[index].button = {
{ ['x']=42, ['y']=9, ["label"]="Thanks", ["status"]=false, ["func"]=function() update("close") end }
}
tPopup[index].text={
{
"UPDATE COMPLETE",
},{
"Congratulations! The program just got updated!",
"Restart Consult to make changes take effect.",
"Check out the changelog on Github.",
"(see 'About' page under the 'Info' category for",
" the link to the developers Github.)"
}
}
end
end
end
elseif event == "create" then
local bAvailable,sNewVersion,sChangelog = update("check")
--[[ Update available ]]
if bAvailable then
local tChangelog = {formatText(sChangelog,47,3)}
openPopup({
["status"] = true,
["name"] = "Update CONSULT",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{
"UPDATE AVAILABLE",
},{
"v"..sVersion.." --> v"..sNewVersion.." | Do you want to proceed?",
"",
table.unpack(tChangelog)
}
},
["button"] = {
{ ['x']=42, ['y']=6+#tChangelog, ["label"]="Update", ["status"]=false, ["func"]=function() update("now") end },
{ ['x']=39, ['y']=6+#tChangelog, ["label"]="No", ["status"]=false, ["func"]=function() update("close") end }
}
})
end
end
end
function openLink(event, ...)
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name == "Link" then
table.remove(tPopup, index)
end
end
elseif event == "create" then
local link = tostring(({...})[1])
link = link:sub(2,#link-1)
if fs.isDir(link) and not bLvlOS then return end
if link == "" or link == "..." or link == "." or not fs.exists(link) or link:find('ö') or link:find('ä') or link:find('ü') then return end
local line = "Open the following "..(fs.isDir(link) and "directory" or "file").."?"
local slink = link
if #slink >= #line then
slink = ".."..slink:sub(-(#line-3))
end
openPopup({
["status"] = true,
["name"] = "Link",
["link"] = link,
["size"] = {
['x'] = nil,['y'] = nil
},
["text"] = {
{
line,
cToStr(' ', colorMatch.bg)..(' '):rep(#line)
}
},
["label"] = {
{
content = cToStr(colorMatch.special,colorMatch.bg)..slink,
x=math.floor((#line-#slink)/2+0.5),y=2,
}
},
["button"] = {
{ ['x']=#line-3, ['y']=4, ["label"]="Open", ["status"]=false, ["func"]=function(pop)
local link = pop.link
openLink("close")
if bLvlOS then
if fs.isDir(link) and fs.exists("Program_Files/LevelOS/Explorer/main.lua") then
levelLaunch("Program_Files/LevelOS/Explorer/main.lua "..link)
else
levelLaunch(shell.getRunningProgram().." "..link)
end
tActiveKeys["CTRL"] = false
elseif multishell then
if fs.isDir(link) then
multishell.launch(_ENV, shell.resolveProgram("shell"))
else
multishell.launch(_ENV, shell.getRunningProgram(), link)
end
tActiveKeys["CTRL"] = false
end
end},
{ ['x']=#line-6, ['y']=4, ["label"]="No", ["status"]=false, ["func"]=function() openLink("close") end }
}
})
end
end
function info(event, ...)
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name == "About CONSULT" then
table.remove(tPopup, index)
end
end
elseif event == "create" then
openPopup({
["status"] = true,
["name"] = "About CONSULT",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{
"CONSULT (short cosu) | a Text editor",
},{
" Available under the MIT License.",
" (c) 2022, Sammy L. Koch",
" Source: github.com/1Turtle/consult",
" Version: "..sVersion
}
},
["button"] = {
{ ['x']=31, ['y']=8, ["label"]="Thanks", ["status"]=false, ["func"]=function() info("close") end }
}
})
end
end
function help(event, ...)
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name:sub(1,9) == "Help Page" then
table.remove(tPopup, index)
end
end
elseif event == "change" then
local nPage = ({...})[1]
local nCurP = ({...})[2]
local nMax = ({...})[3]
if bLvlOS then
if nPage > 0 and nCurP < nMax then
nCurP = nCurP+1
elseif nPage < 0 and nCurP > 1 then
nCurP = nCurP-1
end
help("create", nCurP)
else
if nPage > 0 and tPopup[1].page < #tPopup[1].data then
tPopup[1].page = tPopup[1].page+1
tPopup[1].text = tPopup[1].data[tPopup[1].page]
elseif nPage < 0 and tPopup[1].page > 1 then
tPopup[1].page = tPopup[1].page-1
tPopup[1].text = tPopup[1].data[tPopup[1].page]
end
end
elseif event == "create" then
local nPage = ({...})[1]
if not nPage then nPage = 1 end
local popup = {
["status"] = true,
["name"] = "Help Page",
["size"] = {
['x'] = nil,
['y'] = nil
},
["data"] = {
{
{
"Text editor (for dummies) | (1/4)",
},{
"* Navigate cursor with [ARROW] keys or ",
" by clicking with the mouse.",
"* [MOUSE-WHEEL] scrolls up/down.",
"* To type text, use your keyboard. :)",
"* Remove char from the LEFT of your",
" cursor with [BACKSPACE] & from ..."
}
},{
{
"Text editor (for dummies) | (2/4)",
},{
" the RIGHT of your cursor with [DELETE]. ",
"* To place ("..tostring(cosuConf.nTabSpace)..") spaces, use [TAB].",
"* Autocorrect is on by default,",
" when shown, press [TAB] to apply &",
" navigate with [ARROW] keys.",
" (Can be Toggled via system settings.)"
}
},{
{
"Navigationbar/Popups | (3/4)",
},{
"* Click on category to show dropdown.",
"* LEFT/RIGHT [ARROW] keys change category.",
"* UP/DOWN [ARROW] keys choose",
" item from dropdown.","",""
}
},{
{
"Navigationbar/Popups | (4/4)",
},{
"* Choose widget with [ARROW] keys",
" (UP/DOWN works like LEFT/RIGHT.) ",
"* Button: Press [ENTER] to execute.",
"* Textbox: Type to enter input.", "",""
}
}
},
["page"] = nPage,
["text"] = { },
["button"] = {
{ ['x']=10, ['y']=10, ["label"]="Next", ["status"]=false, ["func"]=function(self) help("change",1, self.page, #self.data) end },
{ ['x']=39, ['y']=10, ["label"]="Done", ["status"]=false, ["func"]=function() help("close") end },
{ ['x']=1, ['y']=10, ["label"]="Previous", ["status"]=false, ["func"]=function(self) help("change",-1, self.page, #self.data) end }
}
}
popup.text = popup.data[nPage]
openPopup(popup)
end
end
function file(event, ...)
local tArgs = { ... }
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name:sub(1,7) == "File - " then
table.remove(tPopup, index)
end
end
elseif event == "replace" then
openPopup({
["status"] = true,
["name"] = "File - Replace",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{ "File already Exists! Replace it?" }
},
["tmp"]=tArgs[1],
["button"] = {
{ ['x']=26, ['y']=3, ["label"]="No", ["status"]=false, ["func"]=function() file("close") file("create", "save as") end },
{ ['x']=29, ['y']=3, ["label"]="Yes", ["status"]=false, ["func"]=function(self) local tmp=self.tmp file("close") file("create", "save", tmp, "force") end }
}
})
elseif event == "saved" then
local nLength = 13
if #sPath+3 > 13 then nLength = #sPath+3 end
local pop = {
["status"] = true,
["name"] = "File - Saved",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{ "File saved as", "\'"..sPath.."\'." }
},
["button"] = {
{ ['x']=nLength-1, ['y']=4, ["label"]="Ok", ["status"]=false, ["func"]=function() file("close") end },
{ ['x']=nLength-6, ['y']=4, ["label"]="Exit", ["status"]=false, ["func"]=function() file("close") exit("create") end }
}
}
if bLvlOS then
lOS.notification("CONSULT", "Saved file as \'"..sPath..'\'', shell.getRunningProgram(), 3)
else
table.insert(tPopup, 1, pop)
end
local sPathName = sPath:reverse()
local nLastSlashPos = sPathName:find('/')
if nLastSlashPos then
sPathName = sPathName:sub(nLastSlashPos):reverse()
else
sPathName = sPathName:reverse()
end
if bLvlOS then
LevelOS.setTitle("CONSULT - "..sPathName)
elseif multishell then
multishell.setTitle(multishell.getCurrent(), "cosu-["..sPathName.."]")
end
elseif event == "create" then
if tArgs[1] == "save" then
local tmpPath = sPath
if type(tArgs[2])=="string" then
tmpPath = tArgs[2]
end
if fs.exists(tmpPath) and tmpPath~=sPath and tArgs[3]~="force" then
file("replace", tmpPath)
return
end
local f = fs.open(tmpPath, 'w')
if f then
for _,sLine in pairs(tContent) do
f.writeLine(sLine)
end
f.close()
bSaved = true
sPath = tmpPath
file("saved")
else
file("create", "save as", "error")
end
elseif tArgs[1] == "save as" then
local tMsg = {}
if tArgs[2]=="error" then
tMsg = {"Invalid path!"}
end
table.insert(tPopup, 1, {
["status"] = true,
["name"] = "File - GetName",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{ table.unpack(tMsg),"Enter new path:","" }
},
["textBox"] = {
{ ['x']=1, ['y']=2+#tMsg, ["input"]=sPath }
},
["button"] = {
{ ['x']=6, ['y']=4+#tMsg, ["label"]="Abort", ["status"]=false, ["func"]=function() file("close") end },
{ ['x']=12, ['y']=4+#tMsg, ["label"]="Done", ["status"]=false, ["func"]=function() local tmp=tPopup[1].textBox[1].input file("close") file("create", "save", tmp) end }
}
})
elseif tArgs[1] == "new" then
if bLvlOS then
levelLaunch(shell.getRunningProgram(), "CONSULT")
category.reset()
elseif multishell then
local tabId = multishell.launch(_ENV, shell.getRunningProgram())
multishell.setTitle(tabId, "cosu")
multishell.setFocus(tabId)
category.reset()
else
if bSaved or tArgs[2] == "force" then
tContent = { "" }
tCursor.x,tCursor.y = 1,1
tScroll = { ['x']=0,['y']=0 }
return
end
openPopup({
["status"] = true,
["name"] = "File - New",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{ "Create new project,", "without saving the current one?" }
},
["button"] = {
{ ['x']=25, ['y']=4, ["label"]="No", ["status"]=false, ["func"]=function() file("close") end },
{ ['x']=28, ['y']=4, ["label"]="Yes", ["status"]=false, ["func"]=function() file("close") file("create", "new", "force") end }
}
})
end
end
elseif event == "execute" then
local sDir = '/'..fs.getDir(shell.getRunningProgram())..'/'
local sCurID = tostring( (not bLvlOS and type(multishell)~="nil") and multishell.getCurrent() or "" )
local f = fs.open(sDir..".tmp"..sCurID, 'w')
f.flush()
f.write("local function c() ")
for _,sLine in pairs(tContent) do
f.writeLine(sLine)
end
f.write("end local path=\""..sDir..".tmp"..sCurID.."\"")
f.write([[ local o,e=pcall(c)
if not o then
term.setBackgroundColor(colors.black)
term.setTextColor(colors.red)
print(e)
term.setTextColor(colors.white)
end print("Press any key to exit") sleep(0.05) os.pullEvent("key") ]])
f.close()
if bLvlOS then
levelLaunch(sDir..".tmp"..sCurID, "CONSULT - [running]")
elseif multishell then
local nID = multishell.launch(_ENV, sDir..".tmp"..sCurID, ...)
multishell.setTitle(nID, "cosu-[run"..nID.."]")
multishell.setFocus(nID)
else
term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1,1)
shell.run(sDir..".tmp"..sCurID)
end
end
end
function error(event, name, ...)
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name:find("Error") then
if pop.name == "Error" then
sPath = pop.textBox[1].input
end
table.remove(tPopup, index)
end
end
elseif event == "create" then
local tArgs = { ... }
--[[ Local get size ]]
local nXCounter = 0
local nLongestMsg = 7
for _,tMsgs in pairs(tArgs) do
for _,sMsg in pairs(tMsgs) do
if #sMsg > nLongestMsg then
nLongestMsg = #sMsg
end
nXCounter = nXCounter+1
end
nXCounter = nXCounter+1
end
openPopup({
["status"] = true,
["name"] = "Error - "..name,
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = tArgs,
["button"] = {
{ ['x']=nLongestMsg-1, ['y']=nXCounter+1, ["label"]="Ok", ["status"]=false, ["func"]=function() error("close") end }
}
})
end
end
function options(event, ...)
local tSubArgs = { ... }
local sDir = fs.getDir(shell.getRunningProgram())..'/'
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name:sub(1,10) == "Options - " then
table.remove(tPopup, index)
end
end
elseif event == "set" then
local sConfigName,newValue = tSubArgs[1],tSubArgs[2]
if type(newValue) == "table" then
for key,value in pairs(newValue) do
cosuConf[sConfigName][key] = value
end
else
cosuConf[sConfigName] = newValue
end
elseif event == "load" then
if fs.exists(sDir..".cosu.conf") then
local configFunc, err = loadfile(sDir..".cosu.conf")
if not configFunc then
error("create", "options", {"Fatal error in config file!"}, {"> "..err})
else
local tWrongValues = {}
local bMissingValues = false
local bSuccess = xpcall(
configFunc,
function(err)
err = {splitStr(err)}
error("create", "options", {"Error in config file!"}, err)
end
)
if bSuccess then
local newConfigs = configFunc()
for sConfigName,value in pairs(cosuConf) do
local newValue = newConfigs[sConfigName]
if type(newValue) == type(value) then
options("set", sConfigName, newValue)
elseif type(newValue) == "function" then
if type(newValue())==type(value) then
options("set", sConfigName, newValue())
else
tWrongValues[#tWrongValues+1] = "\'"..sConfigName.. "\' expected \'"..type(value)..'\''
end
elseif type(newValue) == "nil" then
bMissingValues = true
else
tWrongValues[#tWrongValues+1] = "\'"..sConfigName.. "\' expected \'"..type(value)..'\''
end
end
end
if bMissingValues then
options("add missing")
end
if #tWrongValues > 0 and not sPath:find(".cosu.conf") then
error("create", "options",
{"The following values are wrong in",
'\''..sDir..".cosu.conf\':"},
{table.unpack(tWrongValues)}
)
end
end
end
elseif event == "add missing" then
local f = fs.open(sDir..".cosu.conf", 'w')
f.write( "return "..textutils.serialize(cosuConf) )
f.close()
elseif event == "create" then
if not fs.exists(sDir..".cosu.conf") then
local f = fs.open(sDir..".cosu.conf", 'w')
f.write( "return "..textutils.serialize(cosuConf) )
f.close()
end
if bLvlOS then
levelLaunch(shell.getRunningProgram().." "..sDir..".cosu.conf", "CONSULT - [options]")
elseif multishell then
local tabId = multishell.launch(_ENV,
shell.getRunningProgram(),
sDir..".cosu.conf"
)
multishell.setTitle(tabId, "cosu-[options]")
else
if bSaved or tSubArgs[1] == "force" then
tContent = { }
tArgs = { sDir..".cosu.conf" }
init()
tCursor.x,tCursor.y = 1,1
tScroll = { ['x']=0,['y']=0 }
return
end
openPopup({
["status"] = true,
["name"] = "Options - Ask",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{ "Edit Options,", "WITHOUT SAVING project?" }
},
["button"] = {
{ ['x']=15, ['y']=4, ["label"]="Back", ["status"]=false, ["func"]=function() options("close") end },
{ ['x']=20, ['y']=4, ["label"]="Edit", ["status"]=false, ["func"]=function() options("close") options("create", "force") end }
}
})
end
end
end
function exit(event, ...)
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name == "Warning" then
table.remove(tPopup, index)
end
end
elseif event == "JUST DO IT" then
running = (-1)
return
elseif event == "create" then
if bSaved then
running = false
return
end
openPopup({
["status"] = true,
["name"] = "Warning",
["size"] = {
['x'] = nil,
['y'] = nil
},
["text"] = {
{ "Do you really want to exit,", "without saving?" }
},
["button"] = {
{ ['x']=21, ['y']=4, ["label"]="No", ["status"]=false, ["func"]=function() exit("close") end },
{ ['x']=24, ['y']=4, ["label"]="Exit", ["status"]=false, ["func"]=function() exit("JUST DO IT") end }
}
})
end
end
--[[ Placeholder for new options :) ]]
function specialChar(event, ...)
if event == "close" then
for index,pop in pairs(tPopup) do
if pop.name == "Special Chars" then
table.remove(tPopup, index)
end
end
elseif event == "create" then
local tNewPopup = {
["blockControlls"]=true,
["closeAtNoFokus"] = function(self)
local icon = self.list[1].content[self.list[1].selected]
for type,widget in pairs(tWidgets) do
if widget.name == "specialChar" then
if icon ~= type then
tWidgets[icon] = widget
tWidgets[type] = nil
break
end
end
end
input.insert.char(icon)
end,
["key"]=function(self, id,_)
local worked = false
if self.list[1].type == "sidebyside" then
if id == cosuConf.tKeyboard.up and (self.list[1].selected-self.list[1].size.x-1) > 0 then
self.list[1].selected = self.list[1].selected-self.list[1].size.x-1
worked = true
elseif id == cosuConf.tKeyboard.down and (self.list[1].selected+(self.list[1].size.x+1)) < self.list[1].size.max then
self.list[1].selected = self.list[1].selected+(self.list[1].size.x+1)
worked = true