/
main.lua
984 lines (883 loc) · 34.2 KB
/
main.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
-- Copyright 2011-15 Paul Kulchenko, ZeroBrane LLC
-- authors: Luxinia Dev (Eike Decker & Christoph Kubisch)
---------------------------------------------------------
-- put bin/ and lualibs/ first to avoid conflicts with included modules
-- that may have other versions present somewhere else in path/cpath.
local function isproc()
local file = io.open("/proc")
if file then file:close() end
return file ~= nil
end
local iswindows = os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows')
local islinux = not iswindows and isproc()
local arch = "x86" -- use 32bit by default
local unpack = table.unpack or unpack
if islinux then
local file = io.popen("uname -m")
if file then
local machine=file:read("*l")
local archtype= {
x86_64 = "x64",
armv7l = "armhf",
aarch64 = "aarch64",
}
arch = archtype[machine] or arch
file:close()
end
end
package.cpath = (
iswindows and 'bin/?.dll;bin/clibs/?.dll;' or
islinux and ('bin/linux/%s/lib?.so;bin/linux/%s/clibs/lib?.so;bin/linux/%s/clibs/?.so;'):format(arch,arch,arch) or
--[[isosx]] 'bin/lib?.dylib;bin/clibs/lib?.dylib;bin/clibs/?.dylib;')
.. package.cpath
package.path = 'lualibs/?.lua;lualibs/?/?.lua;lualibs/?/init.lua;lualibs/?/?/?.lua;lualibs/?/?/init.lua;'
.. package.path
require("wx")
require("bit")
require("mobdebug")
if jit and jit.on then jit.on() end -- turn jit "on" as "mobdebug" may turn it off for LuaJIT
dofile "src/util.lua"
-----------
-- IDE
--
local pendingOutput = {}
ide = {
MODPREF = "* ",
MAXMARGIN = wxstc.wxSTC_MAX_MARGIN or 4,
ANYMARKERMASK = 2^24-1,
config = {
path = {
projectdir = "",
app = nil,
},
editor = {
autoactivate = false,
foldcompact = true,
checkeol = true,
saveallonrun = false,
caretline = true,
commentlinetoggle = false,
showfncall = false,
autotabs = false,
usetabs = false,
tabwidth = 2,
usewrap = true,
wrapmode = wxstc.wxSTC_WRAP_WORD,
calltipdelay = 500,
smartindent = true,
fold = true,
autoreload = true,
indentguide = true,
backspaceunindent = true,
linenumber = true,
},
debugger = {
allowediting = false,
verbose = false,
hostname = nil,
ignorecase = false,
linetobreakpoint = false,
numformat = "%.16g",
port = nil,
runonstart = nil,
redirect = nil,
maxdatalength = 256,
maxdatanum = 128,
maxdatalevel = 3,
refuseonconflict = true,
},
default = {
name = 'untitled',
fullname = 'untitled.lua',
interpreter = 'luadeb',
},
outputshell = {
usewrap = true,
},
filetree = {
mousemove = true,
showchanges = true,
},
outline = {
activateonclick = true,
jumptocurrentfunction = true,
showanonymous = '~',
showcurrentfunction = true,
showcompact = false,
showflat = false,
showmethodindicator = false,
showonefile = false,
sort = false,
},
commandbar = {
prefilter = 250, -- number of records after which to apply filtering
maxitems = 30, -- max number of items to show
maxlines = 8, -- max number of lines to show
width = 0.35, -- <1 -- size in proportion to the app frame width; >=1 -- size in pixels
showallsymbols = true, -- show all symbols in a project
},
staticanalyzer = {
infervalue = false, -- run more detailed static analysis; off by default as it's a slower mode
},
search = {
autocomplete = true,
contextlinesbefore = 2,
contextlinesafter = 2,
showaseditor = false,
zoom = 0,
autohide = false,
},
print = {
magnification = -3,
wrapmode = wxstc.wxSTC_WRAP_WORD,
colourmode = wxstc.wxSTC_PRINT_BLACKONWHITE,
header = "%S\t%D\t%p/%P",
footer = nil,
},
toolbar = {
icons = {},
iconmap = {},
iconsize = nil, -- icon size is set dynamically unless specified in the config
},
keymap = {},
imagemap = {
['VALUE-MCALL'] = 'VALUE-SCALL',
},
messages = {},
language = "en",
styles = nil,
stylesoutshell = nil,
autocomplete = true,
autoanalyzer = true,
acandtip = {
startat = 2,
shorttip = true,
nodynwords = true,
ignorecase = false,
fillups = nil,
symbols = true,
droprest = true,
strategy = 2,
width = 60,
maxlength = 450,
warning = true,
},
arg = {}, -- command line arguments
api = {}, -- additional APIs to load
format = { -- various formatting strings
menurecentprojects = "%f | %i",
apptitle = "%T - %F",
},
activateoutput = true, -- activate output/console on Run/Debug/Compile
unhidewindow = false, -- to unhide a gui window
projectautoopen = true,
autorecoverinactivity = 10, -- seconds
outlineinactivity = 0.250, -- seconds
markersinactivity = 0.500, -- seconds
symbolindexinactivity = 2, -- seconds
filehistorylength = 20,
projecthistorylength = 20,
commandlinehistorylength = 10,
bordersize = 3,
savebak = false,
singleinstance = false,
singleinstanceport = 0xe493,
showmemoryusage = false,
showhiddenfiles = false,
hidpi = false, -- HiDPI/Retina display support
hotexit = false,
imagetint = nil,
markertint = true,
menuicon = true,
-- file exclusion lists
excludelist = {".svn/", ".git/", ".hg/", "CVS/", "*.pyc", "*.pyo", "*.exe", "*.dll", "*.obj","*.o", "*.a", "*.lib", "*.so", "*.dylib", "*.ncb", "*.sdf", "*.suo", "*.pdb", "*.idb", ".DS_Store", "*.class", "*.psd", "*.db"},
binarylist = {"*.jpg", "*.jpeg", "*.png", "*.gif", "*.ttf", "*.tga", "*.dds", "*.ico", "*.eot", "*.pdf", "*.swf", "*.jar", "*.zip", ".gz", ".rar"},
},
specs = {
none = {
sep = "\1",
}
},
tools = {},
iofilters = {},
interpreters = {},
packages = {},
apis = {},
timers = {},
onidle = {},
proto = {}, -- prototypes for various classes
app = nil, -- application engine
interpreter = nil, -- current Lua interpreter
frame = nil, -- gui related
debugger = {}, -- debugger related info
filetree = nil, -- filetree
findReplace = nil, -- find & replace handling
settings = nil, -- user settings (window pos, last files..)
session = {
projects = {}, -- project configuration for the current session
lastupdated = nil, -- timestamp of the last modification in any of the editors
lastsaved = nil, -- timestamp of the last recovery information saved
},
-- misc
exitingProgram = false, -- are we currently exiting, ID_EXIT
infocus = nil, -- last component with a focus
editorApp = wx.wxGetApp(),
editorFilename = nil,
openDocuments = {},-- open notebook editor documents[winId] = {
-- editor = wxStyledTextCtrl,
-- index = wxNotebook page index,
-- filePath = full filepath, nil if not saved,
-- fileName = just the filename,
-- modTime = wxDateTime of disk file or nil,
-- isModified = bool is the document modified? }
ignoredFilesList = {},
font = {
eNormal = nil,
eItalic = nil,
oNormal = nil,
oItalic = nil,
fNormal = nil,
},
osname = wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName(),
osarch = arch,
oshome = os.getenv("HOME") or (iswindows and os.getenv('HOMEDRIVE') and os.getenv('HOMEPATH')
and (os.getenv('HOMEDRIVE')..os.getenv('HOMEPATH'))),
wxver = string.match(wx.wxVERSION_STRING, "[%d%.]+"),
startedat = TimeGet(),
test = {}, -- local functions used for testing
Print = function(self, ...)
if DisplayOutputLn then
-- flush any pending output
while #pendingOutput > 0 do DisplayOutputLn(unpack(table.remove(pendingOutput, 1))) end
-- print without parameters can be used for flushing, so skip the printing
if select('#', ...) > 0 then DisplayOutputLn(...) end
return
end
pendingOutput[#pendingOutput + 1] = {...}
end,
}
-- Scintilla switched to using full byte for style numbers from using only first 5 bits
ide.STYLEMASK = ide.wxver <= "2.9.5" and 31 or 255
-- add wx.wxMOD_RAW_CONTROL as it's missing in wxlua 2.8.12.3;
-- provide default for wx.wxMOD_CONTROL as it's missing in wxlua 2.8 that
-- is available through Linux package managers
if not wx.wxMOD_CONTROL then wx.wxMOD_CONTROL = 0x02 end
if not wx.wxMOD_RAW_CONTROL then
wx.wxMOD_RAW_CONTROL = ide.osname == 'Macintosh' and 0x10 or wx.wxMOD_CONTROL
end
if not wx.WXK_RAW_CONTROL then
wx.WXK_RAW_CONTROL = ide.osname == 'Macintosh' and 396 or wx.WXK_CONTROL
end
-- ArchLinux running 2.8.12.2 doesn't have wx.wxMOD_SHIFT defined
if not wx.wxMOD_SHIFT then wx.wxMOD_SHIFT = 0x04 end
-- wxDIR_NO_FOLLOW is missing in wxlua 2.8.12 as well
if not wx.wxDIR_NO_FOLLOW then wx.wxDIR_NO_FOLLOW = 0x10 end
if not wxaui.wxAUI_TB_PLAIN_BACKGROUND then wxaui.wxAUI_TB_PLAIN_BACKGROUND = 2^8 end
if not wx.wxNOT_FOUND then wx.wxNOT_FOUND = -1 end
if not setfenv then -- Lua 5.2
-- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html
-- this assumes f is a function
local function findenv(f)
local level = 1
repeat
local name, value = debug.getupvalue(f, level)
if name == '_ENV' then return level, value end
level = level + 1
until name == nil
return nil end
getfenv = function (f) return(select(2, findenv(f)) or _G) end
setfenv = function (f, t)
local level = findenv(f)
if level then debug.setupvalue(f, level, t) end
return f end
end
if not package.searchpath then
-- from Scintillua by Mitchell (mitchell.att.foicica.com).
-- Searches for the given *name* in the given *path*.
-- This is an implementation of Lua 5.2's `package.searchpath()` function for Lua 5.1.
function package.searchpath(name, path)
local tried = {}
for part in path:gmatch('[^;]+') do
local filename = part:gsub('%?', name)
local f = io.open(filename, 'r')
if f then f:close() return filename end
tried[#tried + 1] = ("no file '%s'"):format(filename)
end
return nil, table.concat(tried, '\n')
end
end
local function loadToTab(folder, tab, recursive, proto)
local files = (wx.wxFileExists(folder) and {folder}
or wx.wxDirExists(folder) and FileSysGetRecursive(folder, recursive, "*.lua")
or {})
for _, file in ipairs(files) do LoadLuaFileExt(tab, file, proto) end
return tab
end
function ide:LoadSpec(path)
loadToTab(path or "spec", ide.specs, true)
UpdateSpecs()
-- force reload of all APIs as some of them may depend on the specs
if ReloadAPIs then ReloadAPIs("*") end
end
function ide:LoadTool(path)
local tools = {}
for name,tool in pairs(loadToTab(path or "tools", {}, false)) do
if tool.fninit then
local ok, err = pcall(tool.fninit, ide:GetMainFrame(), ide:GetMenuBar())
if not ok then ide:Print(("Error when initializing tool %s: %s"):format(name, err)) end
end
if tool.exec and tool.exec.name then table.insert(tools,tool) end
end
-- sort tools
table.sort(tools,function(a,b) return a.exec.name < b.exec.name end)
for _, tool in ipairs(tools) do
-- add menus for each
local id, menu = ide:AddTool(tool.exec.name, tool.exec.fn)
-- add descriptions
if id and tool.exec.description then menu:SetHelpString(id, tool.exec.description) end
end
return #tools
end
function ide:LoadInterpreter(path)
loadToTab(path or "interpreters", ide.interpreters, false, ide.proto.Interpreter)
end
function ide:LoadAPI(path)
local folder = path or "api"
local files = (wx.wxFileExists(folder) and {folder}
or wx.wxDirExists(folder) and FileSysGetRecursive(folder, true, "*.lua")
or {})
for _, file in ipairs(files) do
if not IsDirectory(file) then
local ftype, fname = file:match("api[/\\]([^/\\]+)[/\\](.*)%.")
if not ftype or not fname then
ide:Print(TR("The API file must be located in a subdirectory of the API directory."))
else
ide.apis[ftype] = ide.apis[ftype] or {}
-- make sure the path is absolute to access it if the current directory changes
ide.apis[ftype][fname] = MergeFullPath("", file)
end
end
end
if ReloadAPIs then ReloadAPIs("*") end
end
dofile "src/version.lua"
for _, file in ipairs({"proto", "ids", "style", "keymap", "toolbar", "package"}) do
dofile("src/editor/"..file..".lua")
end
ide.config.styles = StylesGetDefault()
ide.config.stylesoutshell = StylesGetDefault()
local function setLuaPaths(mainpath, osname)
-- use LUA_DEV to setup paths for Lua for Windows modules if installed
local luadev = osname == "Windows" and os.getenv('LUA_DEV')
if luadev and not wx.wxDirExists(luadev) then luadev = nil end
local luadev_path = (luadev
and ('LUA_DEV/?.lua;LUA_DEV/?/init.lua;LUA_DEV/lua/?.lua;LUA_DEV/lua/?/init.lua')
:gsub('LUA_DEV', (luadev:gsub('[\\/]$','')))
or nil)
local luadev_cpath = (luadev
and ('LUA_DEV/?.dll;LUA_DEV/?51.dll;LUA_DEV/clibs/?.dll;LUA_DEV/clibs/?51.dll')
:gsub('LUA_DEV', (luadev:gsub('[\\/]$','')))
or nil)
if luadev then
local path, clibs = os.getenv('PATH'), luadev:gsub('[\\/]$','')..'\\clibs'
if not path:find(clibs, 1, true) then wx.wxSetEnv('PATH', path..';'..clibs) end
end
-- (luaconf.h) in Windows, any exclamation mark ('!') in the path is replaced
-- by the path of the directory of the executable file of the current process.
-- this effectively prevents any path with an exclamation mark from working.
-- if the path has an excamation mark, allow Lua to expand it as this
-- expansion happens only once.
if osname == "Windows" and mainpath:find('%!') then mainpath = "!/../" end
-- if LUA_PATH or LUA_CPATH is not specified, then add ;;
-- ;; will be replaced with the default (c)path by the Lua interpreter
wx.wxSetEnv("LUA_PATH",
(os.getenv("LUA_PATH") or ';') .. ';'
.. "./?.lua;./?/init.lua;./lua/?.lua;./lua/?/init.lua" .. ';'
.. mainpath.."lualibs/?/?.lua;"..mainpath.."lualibs/?.lua;"
.. mainpath.."lualibs/?/?/init.lua;"..mainpath.."lualibs/?/init.lua"
.. (luadev_path and (';' .. luadev_path) or ''))
ide.osclibs = -- keep the list to use for various Lua versions
osname == "Windows" and table.concat({
mainpath.."bin/?.dll",
mainpath.."bin/clibs/?.dll",
},";") or
osname == "Macintosh" and table.concat({
mainpath.."bin/lib?.dylib",
mainpath.."bin/clibs/?.dylib",
mainpath.."bin/clibs/lib?.dylib",
},";") or
osname == "Unix" and table.concat({
mainpath..("bin/linux/%s/lib?.so"):format(arch),
mainpath..("bin/linux/%s/clibs/?.so"):format(arch),
mainpath..("bin/linux/%s/clibs/lib?.so"):format(arch),
},";") or
assert(false, "Unexpected OS name")
wx.wxSetEnv("LUA_CPATH",
(os.getenv("LUA_CPATH") or ';') .. ';' .. ide.osclibs
.. (luadev_cpath and (';' .. luadev_cpath) or ''))
-- on some OSX versions, PATH is sanitized to not include even /usr/local/bin; add it
if osname == "Macintosh" then
local ok, path = wx.wxGetEnv("PATH")
if ok then wx.wxSetEnv("PATH", (#path > 0 and path..":" or "").."/usr/local/bin") end
end
end
ide.test.setLuaPaths = setLuaPaths
---------------
-- process args
local filenames = {}
local configs = {}
do
local arg = {...}
-- application name is expected as the first argument
local fullPath = arg[1] or "zbstudio"
ide.arg = arg
-- on Windows use GetExecutablePath, which is Unicode friendly,
-- whereas wxGetCwd() is not (at least in wxlua 2.8.12.2).
-- some wxlua version on windows report wx.dll instead of *.exe.
local exepath = wx.wxStandardPaths.Get():GetExecutablePath()
if ide.osname == "Windows" and exepath:find("%.exe$") then
fullPath = exepath
-- path handling only works correctly on UTF8-valid strings, so check for that.
-- This may be caused by the launcher on Windows using ANSI methods for command line
-- processing. Keep the path as is for UTF-8 invalid strings as it's still good enough
elseif not wx.wxIsAbsolutePath(fullPath) and wx.wxString().FromUTF8(fullPath) == fullPath then
fullPath = MergeFullPath(wx.wxGetCwd(), fullPath)
end
ide.editorFilename = fullPath
ide.appname = fullPath:match("([%w_-%.]+)$"):gsub("%.[^%.]*$","")
assert(ide.appname, "no application path defined")
for index = 2, #arg do
if (arg[index] == "-cfg" and index+1 <= #arg) then
table.insert(configs,arg[index+1])
elseif arg[index-1] ~= "-cfg"
-- on OSX command line includes -psn... parameter, don't include these
and (ide.osname ~= 'Macintosh' or not arg[index]:find("^-psn")) then
table.insert(filenames,arg[index])
end
end
setLuaPaths(GetPathWithSep(ide.editorFilename), ide.osname)
end
----------------------
-- process application
ide.app = dofile(ide.appname.."/app.lua")
local app = assert(ide.app)
-- load packages
local function processPackages(packages)
-- check dependencies and assign file names to each package
local skip = {}
for fname, package in pairs(packages) do
if type(package.dependencies) == 'table'
and package.dependencies.osname
and not package.dependencies.osname:find(ide.osname, 1, true) then
ide:Print(("Package '%s' not loaded: requires %s platform, but you are running %s.")
:format(fname, package.dependencies.osname, ide.osname))
skip[fname] = true
end
local needsversion = tonumber(package.dependencies)
or type(package.dependencies) == 'table' and tonumber(package.dependencies[1])
or -1
local isversion = tonumber(ide.VERSION)
if isversion and needsversion > isversion then
ide:Print(("Package '%s' not loaded: requires version %s, but you are running version %s.")
:format(fname, needsversion, ide.VERSION))
skip[fname] = true
end
package.fname = fname
end
for fname, package in pairs(packages) do
if not skip[fname] then ide.packages[fname] = package end
end
end
function UpdateSpecs(spec)
for _, spec in pairs(spec and {spec} or ide.specs) do
spec.sep = spec.sep or "\1" -- default separator doesn't match anything
spec.iscomment = {}
spec.iskeyword = {}
spec.isstring = {}
spec.isnumber = {}
if spec.lexerstyleconvert then
for _, s in pairs(spec.lexerstyleconvert.comment or {}) do spec.iscomment[s] = true end
for _, s in pairs(spec.lexerstyleconvert.keywords0 or {}) do spec.iskeyword[s] = true end
for _, s in pairs(spec.lexerstyleconvert.stringtxt or {}) do spec.isstring[s] = true end
for _, s in pairs(spec.lexerstyleconvert.number or {}) do spec.isnumber[s] = true end
end
end
end
----------------------
-- process config
-- set ide.config environment
do
ide.configs = {
system = MergeFullPath("cfg", "user.lua"),
user = ide.oshome and MergeFullPath(ide.oshome, "."..ide.appname.."/user.lua"),
}
ide.configqueue = {}
local num = 0
local package = setmetatable({}, {
__index = function(_,k) return package[k] end,
__newindex = function(_,k,v) package[k] = v end,
__call = function(_,p)
-- package can be defined inline, like "package {...}"
if type(p) == 'table' then
num = num + 1
return ide:AddPackage('config'..num..'package', p)
-- package can be included as "package 'file.lua'" or "package 'folder/'"
elseif type(p) == 'string' then
local config = ide.configqueue[#ide.configqueue]
local pkg
for _, packagepath in ipairs({
'.', 'packages/', '../packages/',
ide.oshome and MergeFullPath(ide.oshome, "."..ide.appname.."/packages")}) do
local p = MergeFullPath(config and MergeFullPath(config, packagepath) or packagepath, p)
pkg = wx.wxDirExists(p) and loadToTab(p, {}, false, ide.proto.Plugin)
or wx.wxFileExists(p) and LoadLuaFileExt({}, p, ide.proto.Plugin)
or wx.wxFileExists(p..".lua") and LoadLuaFileExt({}, p..".lua", ide.proto.Plugin)
if pkg then
processPackages(pkg)
break
end
end
if not pkg then ide:Print(("Can't find '%s' to load package from."):format(p)) end
else
ide:Print(("Can't load package based on parameter of type '%s'."):format(type(p)))
end
end,
})
local includes = {}
local include = function(c)
if c then
for _, config in ipairs({ide.configqueue[#ide.configqueue], ide.configs.user, ide.configs.system}) do
local p = config and MergeFullPath(config.."/../", c)
includes[p] = (includes[p] or 0) + 1
if includes[p] > 1 or LoadLuaConfig(p) or LoadLuaConfig(p..".lua") then return end
includes[p] = includes[p] - 1
end
ide:Print(("Can't find configuration file '%s' to process."):format(c))
end
end
setmetatable(ide.config, {
__index = setmetatable({
-- these are provided for compatibility only to avoid breaking configs using `load.*`
load = {
interpreters = function() ide:Print("Warning: using `load.interpreters()` in config is deprecated.") end,
specs = function() ide:Print("Warning: using `load.specs()` in config is deprecated.") end,
tools = function() ide:Print("Warning: using `load.tools()` in config is deprecated.") end,
},
package = package,
include = include,
}, {__index = _G or _ENV})
})
end
LoadLuaConfig(ide.appname.."/config.lua")
ide.editorApp:SetAppName(ide:GetProperty("settingsapp"))
-- check if the .ini file needs to be migrated on Windows
if ide.osname == 'Windows' and ide.wxver >= "2.9.5" then
-- Windows used to have local ini file kept in wx.wxGetHomeDir (before 2.9),
-- but since 2.9 it's in GetUserConfigDir(), so migrate it.
local ini = ide.editorApp:GetAppName() .. ".ini"
local old = wx.wxFileName(wx.wxGetHomeDir(), ini)
local new = wx.wxFileName(wx.wxStandardPaths.Get():GetUserConfigDir(), ini)
if old:FileExists() and not new:FileExists() then
FileCopy(old:GetFullPath(), new:GetFullPath())
ide:Print(("Migrated configuration file from '%s' to '%s'.")
:format(old:GetFullPath(), new:GetFullPath()))
end
end
----------------------
-- process plugins
if app.preinit then app.preinit() end
ide:LoadInterpreter()
ide:LoadSpec()
do
-- process configs
LoadLuaConfig(ide.configs.system)
LoadLuaConfig(ide.configs.user)
-- process all other configs (if any)
for _, v in ipairs(configs) do LoadLuaConfig(v, true) end
configs = nil
-- check and apply default styles in case a user resets styles in the config
for _, styles in ipairs({"styles", "stylesoutshell"}) do
if not ide.config[styles] then
ide:Print(("Ignored incorrect value of '%s' setting in the configuration file")
:format(styles))
ide.config[styles] = StylesGetDefault()
end
end
local sep = GetPathSeparator()
if ide.config.language then
LoadLuaFileExt(ide.config.messages, "cfg"..sep.."i18n"..sep..ide.config.language..".lua")
end
-- always load 'en' as it's requires as a fallback for pluralization
if ide.config.language ~= 'en' then
LoadLuaFileExt(ide.config.messages, "cfg"..sep.."i18n"..sep.."en.lua")
end
end
processPackages(loadToTab("packages", {}, false, ide.proto.Plugin))
if ide.oshome then
local userpackages = MergeFullPath(ide.oshome, "."..ide.appname.."/packages")
if wx.wxDirExists(userpackages) then
processPackages(loadToTab(userpackages, {}, false, ide.proto.Plugin))
end
end
---------------
-- Load App
for _, file in ipairs({
"settings", "singleinstance", "iofilters", "markup",
"gui", "filetree", "output", "debugger", "outline", "commandbar",
"editor", "findreplace", "commands", "autocomplete", "shellbox", "markers",
"menu_file", "menu_edit", "menu_search", "menu_view", "menu_project", "menu_help",
"print", "inspect" }) do
dofile("src/editor/"..file..".lua")
end
-- delay loading tools until everything is loaded as it modifies the menus
ide:LoadTool()
-- delay loading APIs until auto-complete is loaded
ide:LoadAPI()
-- register all the plugins
PackageEventHandle("onRegister")
-- initialization that was delayed until configs processed and packages loaded
ProjectUpdateInterpreters()
-- load rest of settings
SettingsRestoreFramePosition(ide.frame, "MainFrame")
SettingsRestoreFileHistory(SetFileHistory)
SettingsRestoreEditorSettings()
SettingsRestoreProjectSession(FileTreeSetProjects)
SettingsRestoreFileSession(function(tabs, params)
if params and params.recovery
then return SetOpenTabs(params)
else return SetOpenFiles(tabs, params) end
end)
SettingsRestoreView()
-- ---------------------------------------------------------------------------
-- Load the filenames
do
for _, filename in ipairs(filenames) do
if filename ~= "--" then ide:ActivateFile(filename) end
end
if ide:GetEditorNotebook():GetPageCount() == 0 then NewFile() end
end
if app.postinit then app.postinit() end
-- this is a workaround for a conflict between global shortcuts and local
-- shortcuts (like F2) used in the file tree or a watch panel.
-- because of several issues on OSX (as described in details in this thread:
-- https://groups.google.com/d/msg/wx-dev/juJj_nxn-_Y/JErF1h24UFsJ),
-- the workaround installs a global event handler that manually re-routes
-- conflicting events when the current focus is on a proper object.
-- non-conflicting shortcuts are handled through key-down events.
local remap = {
[ID_ADDWATCH] = ide:GetWatch(),
[ID_EDITWATCH] = ide:GetWatch(),
[ID_DELETEWATCH] = ide:GetWatch(),
[ID_RENAMEFILE] = ide:GetProjectTree(),
[ID_DELETEFILE] = ide:GetProjectTree(),
}
local function rerouteMenuCommand(obj, id)
-- check if the conflicting shortcut is enabled:
-- (1) SetEnabled wasn't called or (2) Enabled was set to `true`.
local uievent = wx.wxUpdateUIEvent(id)
obj:ProcessEvent(uievent)
if not uievent:GetSetEnabled() or uievent:GetEnabled() then
obj:AddPendingEvent(wx.wxCommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED, id))
end
end
local function remapkey(event)
local keycode = event:GetKeyCode()
local mod = event:GetModifiers()
for id, obj in pairs(remap) do
local focus = obj:FindFocus()
if focus and focus:GetId() == obj:GetId() then
local ae = wx.wxAcceleratorEntry(); ae:FromString(KSC(id))
if ae:GetFlags() == mod and ae:GetKeyCode() == keycode then
rerouteMenuCommand(obj, id)
return
end
end
end
event:Skip()
end
ide:GetWatch():Connect(wx.wxEVT_KEY_DOWN, remapkey)
ide:GetProjectTree():Connect(wx.wxEVT_KEY_DOWN, remapkey)
local function resolveConflict(localid, globalid)
return function(event)
local shortcut = ide.config.keymap[localid]
for id, obj in pairs(remap) do
if ide.config.keymap[id]:lower() == shortcut:lower() then
local focus = obj:FindFocus()
if focus and focus:GetId() == obj:GetId() then
obj:AddPendingEvent(wx.wxCommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED, id))
return
-- also need to check for children of objects
-- to avoid re-triggering events when labels are being edited
elseif focus and focus:GetParent():GetId() == obj:GetId() then
return
end
end
end
rerouteMenuCommand(ide.frame, globalid)
end
end
for lid in pairs(remap) do
local shortcut = ide.config.keymap[lid]
-- find a (potential) conflict for this shortcut (if any)
for gid, ksc in pairs(ide.config.keymap) do
-- if the same shortcut is used elsewhere (not one of IDs being checked)
if shortcut:lower() == ksc:lower() and not remap[gid] then
local fakeid = NewID()
ide.frame:Connect(fakeid, wx.wxEVT_COMMAND_MENU_SELECTED, resolveConflict(lid, gid))
ide:SetAccelerator(fakeid, ksc)
end
end
end
if ide.osname == 'Macintosh' then ide:SetAccelerator(ID_VIEWMINIMIZE, "Ctrl-M") end
-- these shortcuts need accelerators handling as they are not present anywhere in the menu
for _, id in ipairs({ ID_GOTODEFINITION, ID_RENAMEALLINSTANCES,
ID_REPLACEALLSELECTIONS, ID_QUICKADDWATCH, ID_QUICKEVAL, ID_ADDTOSCRATCHPAD}) do
local ksc = ide.config.keymap[id]
if ksc and ksc > "" then
local fakeid = NewID()
ide.frame:Connect(fakeid, wx.wxEVT_COMMAND_MENU_SELECTED, function()
local editor = ide:GetEditorWithFocus(ide:GetEditor())
if editor then rerouteMenuCommand(editor, id) end
end)
ide:SetAccelerator(fakeid, ksc)
end
end
for _, id in ipairs({ ID_NOTEBOOKTABNEXT, ID_NOTEBOOKTABPREV }) do
local ksc = ide.config.keymap[id]
if ksc and ksc > "" then
local nbc = "wxAuiNotebook"
ide.frame:Connect(id, wx.wxEVT_COMMAND_MENU_SELECTED, function(event)
local win = ide.frame:FindFocus()
if not win then return end
local notebook = win:GetClassInfo():GetClassName() == nbc and win:DynamicCast(nbc)
or win:GetParent():GetClassInfo():GetClassName() == nbc and win:GetParent():DynamicCast(nbc)
or nil
if not notebook then return end
local first, last = 0, notebook:GetPageCount()-1
local fwd = event:GetId() == ID_NOTEBOOKTABNEXT
if fwd and notebook:GetSelection() == last then
notebook:SetSelection(first)
elseif not fwd and notebook:GetSelection() == first then
notebook:SetSelection(last)
else
notebook:AdvanceSelection(fwd)
end
end)
ide:SetAccelerator(id, ksc)
end
end
-- only set menu bar *after* postinit handler as it may include adding
-- app-specific menus (Help/About), which are not recognized by MacOS
-- as special items unless SetMenuBar is done after menus are populated.
ide.frame:SetMenuBar(ide.frame.menuBar)
ide:Print() -- flush pending output (if any)
PackageEventHandle("onAppLoad")
-- this provides a workaround for Ctrl-(Shift-)Tab not navigating over tabs on OSX
-- http://trac.wxwidgets.org/ticket/17064
if ide.osname == 'Macintosh' then
local frame = ide.frame
local focus
ide.timers.ctrltab = ide:AddTimer(frame, function(event)
local mouse = wx.wxGetMouseState()
-- if anything other that Ctrl (along with Shift) is pressed, then cancel the timer
if not ide:IsValidCtrl(focus)
or not wx.wxGetKeyState(wx.WXK_RAW_CONTROL)
or wx.wxGetKeyState(wx.WXK_ALT) or wx.wxGetKeyState(wx.WXK_CONTROL)
or mouse:LeftDown() or mouse:RightDown() or mouse:MiddleDown() then
ide.timers.ctrltab:Stop()
return
end
local ctrl = frame:FindFocus()
if not ctrl then return end
local nb = focus:GetParent():DynamicCast("wxAuiNotebook")
-- when moving backward from the very first tab, the focus moves
-- to wxAuiTabCtrl on OSX, so need to take that into account
if nb:GetId() ~= ctrl:GetParent():GetId()
or ctrl:GetClassInfo():GetClassName() == "wxAuiTabCtrl" then
local frwd = not wx.wxGetKeyState(wx.WXK_SHIFT)
if nb:GetId() ~= ctrl:GetParent():GetId()
or not frwd and nb:GetSelection() == 0
or frwd and nb:GetSelection() == nb:GetPageCount()-1 then
nb:AdvanceSelection(frwd)
focus = nb:GetPage(nb:GetSelection())
focus:SetFocus()
end
-- don't cancel the timer as the user may be cycling through tabs
end
end)
frame:Connect(wx.wxEVT_CHAR_HOOK, function(event)
local key = event:GetKeyCode()
if key == wx.WXK_RAW_CONTROL then
local ctrl = frame:FindFocus()
local parent = ctrl and ctrl:GetParent()
if parent and parent:GetClassInfo():GetClassName() == "wxAuiNotebook" then
local nb = parent:DynamicCast("wxAuiNotebook")
focus = nb:GetPage(nb:GetSelection())
focus:SetFocus()
ide.timers.ctrltab:Start(20) -- check periodically
end
elseif key == wx.WXK_SHIFT then -- Shift
-- timer is started when `Ctrl` is pressed; even when `Shift` is pressed first,
-- the Ctrl will still be pressed eventually, which will start the timer
else
ide.timers.ctrltab:Stop()
end
event:Skip()
end)
end
-- add Ctrl-Tab and Ctrl-Shift-Tab processing on Linux as there is a similar issue
-- to the one on OSX: http://trac.wxwidgets.org/ticket/17064,
-- but at least on Linux the handling of Tab from CHAR_HOOK works.
if ide.osname == 'Unix' then
ide.frame:Connect(wx.wxEVT_CHAR_HOOK, function(event)
local key = event:GetKeyCode()
if key == wx.WXK_TAB and wx.wxGetKeyState(wx.WXK_CONTROL)
and not wx.wxGetKeyState(wx.WXK_ALT) then
ide.frame:AddPendingEvent(wx.wxCommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED,
wx.wxGetKeyState(wx.WXK_SHIFT) and ID.NOTEBOOKTABPREV or ID.NOTEBOOKTABNEXT
))
else
event:Skip()
end
end)
end
-- The status bar content is drawn incorrectly if it is shown
-- after being initially hidden.
-- Show the statusbar and hide it after showing the frame, which fixes the issue.
local statusbarfix = ide.osname == 'Windows' and not ide.frame:GetStatusBar():IsShown()
if statusbarfix then ide.frame:GetStatusBar():Show(true) end
ide.frame:Show(true)
if statusbarfix then ide.frame:GetStatusBar():Show(false) end
-- somehow having wxAuiToolbar "steals" the focus from the editor on OSX;
-- have to set the focus implicitly on the current editor (if any)
if ide.osname == 'Macintosh' then
local editor = GetEditor()
if editor then editor:SetFocus() end
end
-- enable full screen view if supported (for example, on OSX)
if ide:IsValidProperty(ide:GetMainFrame(), "EnableFullScreenView") then
ide:GetMainFrame():EnableFullScreenView()
end
do
local args = {}
for _, a in ipairs(arg or {}) do args[a] = true end
wx.wxGetApp().MacOpenFiles = function(files)
for _, filename in ipairs(files) do
-- in some cases, OSX sends the last command line parameter that looks like a filename
-- to OpenFile callback, which gets reported to MacOpenFiles.
-- I've tried to trace why this happens, but the only reference I could find
-- is this one: http://lists.apple.com/archives/cocoa-dev/2009/May/msg00480.html
-- To avoid this issue, the filename is skipped if it's present in `arg`.
-- Also see http://trac.wxwidgets.org/ticket/14558 for related discussion.
if not args[filename] then ide:ActivateFile(filename) end
end
args = {} -- reset the argument cache as it only needs to be checked on the initial launch
end
end
wx.wxGetApp():MainLoop()
-- There are several reasons for this call:
-- (1) to fix a crash on OSX when closing with debugging in progress.
-- (2) to fix a crash on Linux 32/64bit during GC cleanup in wxlua
-- after an external process has been started from the IDE.
-- (3) to fix exit on Windows when started as "bin\lua src\main.lua".
os.exit()