fy36
2025-05-14 a37aca60ff9914b0abb710f04118b22420f4f398
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
-- Copyright 2011-16 Paul Kulchenko, ZeroBrane LLC
-- authors: Lomtik Software (J. Winwood & John Labenski)
-- Luxinia Dev (Eike Decker & Christoph Kubisch)
---------------------------------------------------------
 
local ide = ide
local layoutlabel = {
  UIMANAGER = "uimgrlayout",
  NOTEBOOK = "nblayout",
  NOTEBOOKOUTPUT = "nbbtmlayout",
  NOTEBOOKPROJECT = "nbprojlayout",
  DOCKNOTEBOOK = "nbdocklayout",
  DOCKNOTEBOOKOUTPUT = "nbbtmdocklayout",
  DOCKNOTEBOOKPROJECT = "nbprojdocklayout",
  STATUSBAR = "statusbar",
}
 
-- ----------------------------------------------------------------------------
-- Initialize the wxConfig for loading/saving the preferences
 
local ini = ide.config.ini
-- if ini path is relative and includes a directory name, make it relative to the IDE location
ini = ini and (not wx.wxIsAbsolutePath(ini) and wx.wxFileName(ini):GetDirCount() > 0
  and MergeFullPath(GetPathWithSep(ide.editorFilename), ini) or ini)
-- check that the ini file doesn't point to a directory
if ini and (wx.wxFileName(ini):IsDir() or wx.wxIsAbsolutePath(ini) and wx.wxDirExists(ini)) then
  ide:Print(("Can't use 'ini' configuration setting '%s' that points to a directory instead of a file; ignored.")
    :format(ini))
  ini = nil
end
-- check that the directory is writable
if ini and wx.wxIsAbsolutePath(ini) and not wx.wxFileName(ini):IsDirWritable() then
  ide:Print(("Can't use 'ini' configuration setting '%s' that points to a non-writable directory; ignored.")
    :format(ini))
  ini = nil
end
 
local settings = wx.wxFileConfig(
  ide:GetProperty("settingsapp"), ide:GetProperty("settingsvendor"), ini or "")
ide.settings = settings
 
local function settingsReadSafe(settings,what,default)
  local cr,out = settings:Read(what,default)
  return cr and out or default
end
 
-- ----------------------------------------------------------------------------
-- wxConfig load/save preferences functions
 
function SettingsRestoreFramePosition(window, windowName)
  local path = settings:GetPath()
  settings:SetPath("/"..windowName)
 
  local clientX, clientY, clientWidth, clientHeight = wx.wxClientDisplayRect()
  local s = tonumber(select(2,settings:Read("s", -1)))
  local w = tonumber(select(2,settings:Read("w", math.floor(clientWidth*0.8))))
  local h = tonumber(select(2,settings:Read("h", math.floor(clientHeight*0.8))))
  local x = tonumber(select(2,settings:Read("x", clientX+math.floor(clientWidth-w)/2)))
  local y = tonumber(select(2,settings:Read("y", clientY+math.floor(clientHeight-h)/2)))
 
  if (s ~= -1) then
    local clientX, clientY, clientWidth, clientHeight = wx.wxClientDisplayRect()
 
    -- if left-top corner outside of the left-top side, reset it to the screen side
    if x < clientX then x = clientX end
    if y < clientY then y = clientY end
 
    -- if the window is too wide for the screen, reset it to the screen size
    if w > clientWidth then w = clientWidth end
    if h > clientHeight then h = clientHeight end
 
    -- if the right-bottom corner is still outside and there is only one display,
    -- then reposition left-top corner, keeping the window centered
    if wx.wxDisplay():GetCount() == 1 then
      local outx = (x + w) - (clientX + clientWidth)
      local outy = (y + h) - (clientY + clientHeight)
      if outx > 0 then x = math.floor(0.5+(x - outx)/2) end
      if outy > 0 then y = math.floor(0.5+(y - outy)/2) end
    end
 
    window:SetSize(x, y, w, h)
  end
 
  -- maximize after setting window position to make sure it's maximized on the correct monitor
  if s == 1 then window:Maximize(true) end
 
  settings:SetPath(path)
end
 
function SettingsSaveFramePosition(window, windowName)
  local path = settings:GetPath()
  settings:SetPath("/"..windowName)
 
  local s = 0
  local w, h = window:GetSizeWH()
  local x, y = window:GetPositionXY()
 
  if window:IsMaximized() then
    s = 1
  elseif window:IsIconized() then
    s = 2
  end
 
  settings:Write("s", s==2 and 0 or s) -- iconized maybe - but that shouldnt be saved
  settings:Write("x", x)
  settings:Write("y", y)
  settings:Write("w", w)
  settings:Write("h", h)
 
  settings:SetPath(path)
end
 
---
-- (table) SettingsRestoreFileHistory (function)
-- restores a list of recently loaded documents from the settings table
-- a table is returned which contains tables each with a filename key, pointing to
-- the filename
function SettingsRestoreFileHistory(fntab)
  local path = settings:GetPath()
  local listname = "/filehistory"
  settings:SetPath(listname)
 
  local outtab = {}
  local inlist = {}
  for id=1,ide.config.filehistorylength do
    local couldread, name = settings:Read(tostring(id), "")
    if not couldread or name == "" then break end
    if not inlist[name] then
      inlist[name] = true
      table.insert(outtab,{filename = name})
    end
  end
 
  if fntab then fntab(outtab) end
 
  settings:SetPath(path)
 
  return outtab
end
 
function SettingsSaveFileHistory (filehistory)
  local listname = "/filehistory"
  local path = settings:GetPath()
  settings:DeleteGroup(listname)
  settings:SetPath(listname)
 
  for i,doc in ipairs(filehistory) do
    settings:Write(tostring(i), doc.filename)
  end
 
  settings:SetPath(path)
end
 
---
-- () SettingsRestoreFileSession (function [, string section])
-- restores a list of opened files from the file settings
-- calls the given function with the restored table, a list
-- of tables containing tables like
-- {filename = "filename", cursorpos = <cursor position>}
function SettingsRestoreFileSession(fntab, section)
  local listname = section or "/session"
  local path = settings:GetPath()
  settings:SetPath(listname)
  local outtab = {}
  local params = {}
  local ismore, key, index = settings:GetFirstEntry("", 0)
  while (ismore) do
    local couldread, value = settings:Read(key, "")
    if tonumber(key) then
      local fname,cursorpos = value:match("^(.+);(.-)$")
      if (couldread and value ~= "") then
        outtab[tonumber(key)] =
          {filename = fname or value, cursorpos = tonumber(cursorpos) or 0}
      end
    else
      params[key] = tonumber(value) or value
    end
    ismore, key, index = settings:GetNextEntry(index)
  end
 
  if fntab then fntab(outtab, params) end
 
  settings:SetPath(path)
 
  return outtab
end
 
---
-- () SettingsSaveFileSession (table opendocs, table params [, string section])
-- saves the list of currently opened documents (passed in the opendocs table)
-- in the settings.
function SettingsSaveFileSession(opendocs, params, section)
  local listname = section or "/session"
  local path = settings:GetPath()
  settings:DeleteGroup(listname)
  settings:SetPath(listname)
 
  for i,doc in ipairs(opendocs) do
    settings:Write(tostring(i), doc.filename..";"..doc.cursorpos)
  end
 
  -- save all other parameters
  for k,v in pairs(params) do settings:Write(k, v) end
 
  settings:SetPath(path)
end
 
---
-- () SettingsRestoreProjectSession (function)
function SettingsRestoreProjectSession(fntab)
  local listname = "/projectsession"
  local path = settings:GetPath()
  settings:SetPath(listname)
  local outtab = {}
  local couldread = true
  local id = 1
  local name
  while (couldread) do
    couldread, name = settings:Read(tostring(id), "")
    couldread = couldread and name ~= ""
    if (couldread) then
      if (wx.wxDirExists(name)) then
        table.insert(outtab,name)
 
        local function projsession(...) ProjectConfig(name, {...}) end
        SettingsRestoreFileSession(projsession, listname .. "/" .. tostring(id))
      end
      id = id + 1
    end
  end
 
  if fntab then fntab(outtab) end
 
  settings:SetPath(path)
 
  return outtab
end
 
---
-- () SettingsSaveProjectSession (table projdirs)
-- saves the list of currently active projects
-- in the settings.
function SettingsSaveProjectSession(projdirs)
  local listname = "/projectsession"
  local path = settings:GetPath()
  settings:DeleteGroup(listname)
  settings:SetPath(listname)
 
  for i,dir in ipairs(projdirs) do
    settings:Write(tostring(i), dir)
 
    local opendocs, params = ProjectConfig(dir)
    if opendocs then
      SettingsSaveFileSession(opendocs, params, listname .. "/" .. tostring(i))
    end
  end
 
  settings:SetPath(path)
end
 
function SettingsRestorePackage(package)
  local packagename = "/package/"..package
  local path = settings:GetPath()
  settings:SetPath(packagename)
  local outtab = {}
  local ismore, key, index = settings:GetFirstEntry("", 0)
  while (ismore) do
    local couldread, value = settings:Read(key, "")
    if couldread then
      local ok, res = LoadSafe("return "..value)
      if ok then outtab[key] = res
      else
        outtab[key] = nil
        ide:Print(("Couldn't load and ignored '%s' settings for package '%s': %s")
          :format(key, package, res))
      end
    end
    ismore, key, index = settings:GetNextEntry(index)
  end
  settings:SetPath(path)
  return outtab
end
 
function SettingsSavePackage(package, values, opts)
  local packagename = "/package/"..package
  local path = settings:GetPath()
 
  settings:DeleteGroup(packagename)
  settings:SetPath(packagename)
  for k,v in pairs(values or {}) do settings:Write(k, DumpPlain(v, opts)) end
  settings:SetPath(path)
end
 
-----------------------------------
 
local function saveNotebook(nb)
  local cnt = nb:GetPageCount()
  
  local function addTo(tab,key,value)
    local out = tab[key] or {}
    table.insert(out,value)
    tab[key] = out
  end
  
  local pagesX = {}
  local pagesY = {}
  
  local str = "nblayout|"
  
  for i=1,cnt do
    local pg = nb:GetPage(i-1)
    local doc = ide:GetDocument(pg)
    local id = doc and doc:GetTabText() or nb:GetPageText(i-1)
    local x,y = pg:GetPosition():GetXY()
    addTo(pagesX,x,id)
    addTo(pagesY,y,id)
  end
  
  local function sortedPages(tab)
    local t = {}
    for i in pairs(tab) do
      table.insert(t,i)
    end
    table.sort(t)
    return t
  end
  
  local sortedX = sortedPages(pagesX)
  local sortedY = sortedPages(pagesY)
  
  -- for now only support "1D" splits and prefer
  -- dimension which has more, anything else
  -- requires a more complex algorithm, yet to do
  
  local pagesUse
  local sortedUse
  local split
  
  if ( #sortedX >= #sortedY) then
    pagesUse  = pagesX
    sortedUse = sortedX
    split = "<X>"
  else
    pagesUse  = pagesY
    sortedUse = sortedY
    split = "<Y>"
  end
  
  for _, v in ipairs(sortedUse) do
    local pages = pagesUse[v]
    for _, id in ipairs(pages) do
      str = str..id.."|"
    end
    str = str..split.."|"
  end
  
  return str
end
 
local function loadNotebook(nb,str,fnIdConvert)
  str = str:match("nblayout|(.+)")
  if (not str) then return end
  local cnt = nb:GetPageCount()
  local sel = nb:GetSelection()
 
  -- store old pages
  local currentpages, order = {}, {}
  for i=1,cnt do
    local pg = nb:GetPage(i-1)
    local doc = ide:GetDocument(pg)
    local id = doc and doc:GetTabText() or nb:GetPageText(i-1)
    local newid = fnIdConvert and fnIdConvert(id) or id
    currentpages[newid] = currentpages[newid] or {}
    table.insert(currentpages[newid], {page = pg, text = id, index = i-1})
    order[i] = newid
  end
 
  -- remove them
  for i=cnt,1,-1 do nb:RemovePage(i-1) end
 
  -- read them and perform splits
  local t = 0
  local newsel
  local function finishPage(page)
    if (page.index == sel) then
      newsel = t
    end
    t = t + 1
  end
 
  local direction
  local splits = { X = wx.wxRIGHT, Y = wx.wxBOTTOM }
  for cmd in str:gmatch("([^|]+)") do
    local instr = cmd:match("<(%w)>")
    if (not instr) then
      local id = fnIdConvert and fnIdConvert(cmd) or cmd
      local pageind = next(currentpages[id] or {})
      if (pageind) then
        local page = currentpages[id][pageind]
        currentpages[id][pageind] = nil
 
        nb:AddPage(page.page, page.text)
        if (direction) then nb:Split(t, direction) end
        finishPage(page)
      end
    end
    direction = instr and splits[instr]
  end
  
  -- add anything we forgot; make sure page groups are in the order specified
  for i=1,cnt do
    local pagelist = currentpages[order[i]]
    for _,page in pairs(pagelist) do
      nb:AddPage(page.page, page.text)
      finishPage(page)
    end
  end
  
  -- set the active page as it was before
  if (newsel) then nb:SetSelection(newsel) end
end
 
function SettingsRestoreView()
  local listname = "/view"
  local path = settings:GetPath()
  settings:SetPath(listname)
 
  local frame = ide:GetMainFrame()
  local uimgr = ide:GetUIManager()
  
  local layoutcur = uimgr:SavePerspective()
  local layout = settingsReadSafe(settings,layoutlabel.UIMANAGER,"")
  if (layout ~= layoutcur) then
    -- save the current toolbar besth and re-apply after perspective is loaded
    -- bestw and besth have two separate issues:
    -- (1) layout includes bestw that is only as wide as the toolbar size,
    -- this leaves default background on the right side of the toolbar;
    -- fix it by explicitly replacing with the screen width.
    -- (2) besth may be wrong after icon size changes.
    local toolbar = uimgr:GetPane("toolbar")
    local besth = toolbar:IsOk() and tonumber(uimgr:SavePaneInfo(toolbar):match("besth=([^;]+)"))
 
    -- reload the perspective if the saved one is not empty as it's different from the default
    if #layout > 0 then uimgr:LoadPerspective(layout, true) end
 
    local screenw = frame:GetClientSize():GetWidth()
    if toolbar:IsOk() then toolbar:BestSize(screenw, besth or -1) end
 
    -- check if debugging panes are not mentioned and float them
    for _, name in pairs({"stackpanel", "watchpanel"}) do
      local pane = uimgr:GetPane(name)
      if pane:IsOk() and not layout:find(name) then pane:Float() end
    end
 
    -- check if the toolbar is not mentioned in the layout and show it
    for _, name in pairs({"toolbar"}) do
      local pane = uimgr:GetPane(name)
      if pane:IsOk() and not layout:find(name) then pane:Show() end
    end
 
    -- remove captions from all panes
    local panes = uimgr:GetAllPanes()
    for index = 0, panes:GetCount()-1 do
      uimgr:GetPane(panes:Item(index).name):CaptionVisible(false)
    end
  end
 
  frame:GetStatusBar():Show(settingsReadSafe(settings,layoutlabel.STATUSBAR,true))
 
  uimgr:Update()
  
  layoutcur = saveNotebook(ide:GetOutputNotebook())
  layout = settingsReadSafe(settings,layoutlabel.NOTEBOOKOUTPUT,layoutcur)
  if (layout ~= layoutcur) then
    loadNotebook(ide:GetOutputNotebook(),layout,
      -- treat "Output (running)" same as "Output"
      function(name) return name:match(TR("Output")) or name:match("Output") or name end)
  end
 
  layoutcur = saveNotebook(ide:GetProjectNotebook())
  layout = settingsReadSafe(settings,layoutlabel.NOTEBOOKPROJECT,layoutcur)
  if (layout ~= layoutcur) then
    loadNotebook(ide:GetProjectNotebook(),layout)
  end
 
  -- always select Output tab
  local bottomnotebook = ide:GetOutputNotebook()
  local index = bottomnotebook:GetPageIndex(bottomnotebook.errorlog)
  if index >= 0 then bottomnotebook:SetSelection(index) end
 
  layoutcur = saveNotebook(frame.notebook)
  layout = settingsReadSafe(settings,layoutlabel.NOTEBOOK,layoutcur)
  if (layout ~= layoutcur) then
    loadNotebook(ide.frame.notebook,layout)
    local nb = frame.notebook
    local cnt = nb:GetPageCount()
    for i=0,cnt-1 do
      ide:GetDocument(nb:GetPage(i)):SetTabText(nb:GetPageText(i))
    end
  end
 
  -- restore configuration for notebook pages that have been split;
  -- load saved dock_size values and update current values with saved ones
  -- where dock_size configuration matches
  for l, m in pairs({
    [layoutlabel.DOCKNOTEBOOK] = ide:GetEditorNotebook():GetAuiManager(),
    [layoutlabel.DOCKNOTEBOOKOUTPUT] = ide:GetOutputNotebook():GetAuiManager(),
    [layoutlabel.DOCKNOTEBOOKPROJECT] = ide:GetProjectNotebook():GetAuiManager(),
  }) do
    -- ...|dock_size(5,0,0)=20|dock_size(2,1,0)=200|...
    local prevlayout = settingsReadSafe(settings, l, "")
    local curlayout = m:SavePerspective()
    local newlayout = curlayout:gsub('(dock_size[^=]+=)(%d+)', function(t,v)
        local val = prevlayout:match(EscapeMagic(t)..'(%d+)')
        return t..(val or v)
      end)
    if newlayout ~= curlayout then m:LoadPerspective(newlayout) end
  end
 
  local editor = ide:GetEditor()
  if editor then editor:SetFocus() end
 
  settings:SetPath(path)
end
 
function SettingsSaveView()
  local listname = "/view"
  local path = settings:GetPath()
  settings:DeleteGroup(listname)
  settings:SetPath(listname)
 
  local frame = ide.frame
  local uimgr = frame.uimgr
  
  settings:Write(layoutlabel.UIMANAGER, uimgr:SavePerspective())
  settings:Write(layoutlabel.NOTEBOOK, saveNotebook(ide:GetEditorNotebook()))
  settings:Write(layoutlabel.NOTEBOOKOUTPUT, saveNotebook(ide:GetOutputNotebook()))
  settings:Write(layoutlabel.NOTEBOOKPROJECT, saveNotebook(ide:GetProjectNotebook()))
  settings:Write(layoutlabel.DOCKNOTEBOOK, ide:GetEditorNotebook():GetAuiManager():SavePerspective())
  settings:Write(layoutlabel.DOCKNOTEBOOKOUTPUT, ide:GetOutputNotebook():GetAuiManager():SavePerspective())
  settings:Write(layoutlabel.DOCKNOTEBOOKPROJECT, ide:GetProjectNotebook():GetAuiManager():SavePerspective())
  settings:Write(layoutlabel.STATUSBAR, frame:GetStatusBar():IsShown())
 
  settings:SetPath(path)
end
 
function SettingsRestoreEditorSettings()
  local listname = "/editor"
  local path = settings:GetPath()
  settings:SetPath(listname)
 
  local interpreter = settingsReadSafe(settings, "interpreter",
    ide.config.interpreter or ide.config.default.interpreter)
  ProjectSetInterpreter(interpreter)
 
  settings:SetPath(path)
end
 
function SettingsSaveEditorSettings()
  local listname = "/editor"
  local path = settings:GetPath()
  settings:DeleteGroup(listname)
  settings:SetPath(listname)
 
  settings:Write("interpreter", ide.interpreter and ide.interpreter.fname or ide.config.default.interpreter)
 
  settings:SetPath(path)
end
 
function SettingsSaveAll()
  SettingsSaveFileSession(GetOpenFiles())
  SettingsSaveEditorSettings()
  SettingsSaveProjectSession(FileTreeGetProjects())
  SettingsSaveFileHistory(GetFileHistory())
  SettingsSaveView()
  SettingsSaveFramePosition(ide.frame, "MainFrame")
end