-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsui_patches.lua
More file actions
executable file
·1352 lines (1238 loc) · 62.3 KB
/
Copy pathsui_patches.lua
File metadata and controls
executable file
·1352 lines (1238 loc) · 62.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
-- patches.lua — Simple UI
-- Monkey-patches applied to KOReader on plugin load.
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local logger = require("logger")
local _ = require("gettext")
local Config = require("sui_config")
local UI = require("sui_core")
local Bottombar = require("sui_bottombar")
local Titlebar = require("sui_titlebar")
local M = {}
-- Sentinel table reused for UIManager.show calls with no extra args,
-- avoiding a table allocation on every call.
local _EMPTY = {}
-- Persists across plugin re-instantiation because patches.lua stays in
-- package.loaded for the whole session. Prevents the homescreen auto-open
-- from firing more than once (only on the initial boot FM).
-- Cleared in teardownAll so a disable/re-enable cycle starts fresh.
local _hs_boot_done = false
-- Set to true when ReaderUI closes with "Start with Homescreen" active.
-- Picked up by the next setupLayout call to defer the FM paint until after
-- the homescreen is open, eliminating the flash between reader and homescreen.
local _hs_pending_after_reader = false
-- Cached result of the "start_with == homescreen_simpleui" setting.
-- nil means stale; invalidated in teardownAll and updated in patchStartWithMenu.
local _start_with_hs = nil
-- Navpager rebuild coalescence flag.
local _navpager_rebuild_pending = false
-- Returns true when "Start with Homescreen" is the active start_with value.
-- Caches the result so UIManager.show and UIManager.close (hot paths) avoid
-- repeated settings lookups on every call.
local function isStartWithHS()
if _start_with_hs == nil then
_start_with_hs = G_reader_settings:readSetting("start_with", "filemanager") == "homescreen_simpleui"
end
return _start_with_hs
end
-- Linear search over the tab list (typically 3–6 entries).
-- Used only in single-call contexts (boot, onReturn hook). Hot paths
-- in UIManager.show build a set instead to avoid repeated scans.
local function tabInTabs(id, tabs)
for _, v in ipairs(tabs) do
if v == id then return true end
end
return false
end
-- Builds a set from a tab list for O(1) membership tests.
local function tabsToSet(tabs)
local s = {}
for _, v in ipairs(tabs) do s[v] = true end
return s
end
-- ---------------------------------------------------------------------------
-- FileManager.setupLayout
-- Injects the navbar, patches the title bar, and wires up onShow / onPathChanged.
-- ---------------------------------------------------------------------------
function M.patchFileManagerClass(plugin)
local FileManager = require("apps/filemanager/filemanager")
local orig_setupLayout = FileManager.setupLayout
plugin._orig_fm_setup = orig_setupLayout
FileManager.setupLayout = function(fm_self)
local topbar_on = G_reader_settings:nilOrTrue("navbar_topbar_enabled")
fm_self._navbar_height = Bottombar.TOTAL_H() + (topbar_on and require("sui_topbar").TOTAL_TOP_H() or 0)
-- Patch FileChooser.init once on the class so repeated FM rebuilds
-- don't re-wrap. Reduces height to the content area.
local FileChooser = require("ui/widget/filechooser")
if not FileChooser._navbar_patched then
local orig_fc_init = FileChooser.init
plugin._orig_fc_init = orig_fc_init
FileChooser._navbar_patched = true
FileChooser.init = function(fc_self)
if fc_self.height == nil and fc_self.width == nil then
fc_self.height = UI.getContentHeight()
fc_self.y = UI.getContentTop()
end
orig_fc_init(fc_self)
end
end
orig_setupLayout(fm_self)
-- Delegate all FM title-bar customisation to titlebar.lua.
-- apply() is a no-op when the "Custom Title Bar" setting is off.
Titlebar.apply(fm_self)
-- Keep the original inner widget reference so re-wrapping on subsequent
-- setupLayout calls wraps the same widget instead of the wrapper.
local inner_widget
if fm_self._navbar_inner then
inner_widget = fm_self._navbar_inner
else
inner_widget = fm_self[1]
fm_self._navbar_inner = inner_widget
end
local tabs = Config.loadTabConfig()
local navbar_container, wrapped, bar, topbar, bar_idx, topbar_on2, topbar_idx =
UI.wrapWithNavbar(inner_widget, plugin.active_action, tabs)
UI.applyNavbarState(fm_self, navbar_container, bar, topbar, bar_idx, topbar_on2, topbar_idx, tabs)
fm_self[1] = wrapped
fm_self._simpleui_plugin = plugin
plugin:_updateFMHomeIcon()
-- On boot only: if "Start with Homescreen" is active and the homescreen
-- tab exists, defer opening the HS until onShow fires (FM must be on stack).
if not _hs_boot_done then
_hs_boot_done = true
if isStartWithHS() and tabInTabs("homescreen", tabs) then
plugin.active_action = "homescreen"
fm_self._hs_autoopen_pending = true
end
end
-- onShow fires once the FM is on the UIManager stack.
local orig_onShow = fm_self.onShow
fm_self.onShow = function(this)
if orig_onShow then orig_onShow(this) end
Bottombar.resizePaginationButtons(this.file_chooser or this, Bottombar.getPaginationIconSize())
-- Open the homescreen if this FM was flagged at setupLayout time.
if this._hs_autoopen_pending then
this._hs_autoopen_pending = nil
UIManager:scheduleIn(0, function()
local HS = package.loaded["sui_homescreen"]
if not HS then
local ok, m = pcall(require, "sui_homescreen")
HS = ok and m
end
if HS then
if not plugin._goalTapCallback then plugin:addToMainMenu({}) end
-- plugin.ui and loadTabConfig() resolved at tap time so FM
-- reinits or tab config changes while the HS is open are picked up.
HS.show(function(aid) plugin:_navigate(aid, plugin.ui, Config.loadTabConfig(), false) end, plugin._goalTapCallback)
end
end)
return
end
-- Normal FM show: reset the active tab to "home" and navigate to home_dir.
if this._navbar_container then
local t = Config.loadTabConfig()
plugin.active_action = "home"
local home = G_reader_settings:readSetting("home_dir")
if home and this.file_chooser then
-- Suppress onPathChanged: replaceBar below covers the bar update.
this._navbar_suppress_path_change = true
this.file_chooser:changeToPath(home)
this._navbar_suppress_path_change = nil
end
Bottombar.replaceBar(this, Bottombar.buildBarWidget("home", t), t)
UIManager:setDirty(this, "ui")
end
end
plugin:_registerTouchZones(fm_self)
-- Block non-portrait rotations in the File Manager.
-- onSetRotationMode is the event KOReader dispatches when the user or
-- a gesture triggers a screen rotation. Returning true here consumes
-- the event and prevents the FM from rotating to landscape or inverted
-- portrait. The reader is unaffected — it has its own instance and its
-- own onSetRotationMode handler is never touched here.
-- Screen rotation constants: 0 = portrait, 1 = landscape-left,
-- 2 = portrait-inverted, 3 = landscape-right.
fm_self.onSetRotationMode = function(_self, mode)
if mode ~= 0 then return true end -- block; portrait passes through
end
-- onPathChanged: update the active tab when the user navigates directories.
-- Skipped when _navbar_suppress_path_change is set — that flag is raised by
-- programmatic changeToPath calls (tab tap, onShow boot) that already handle
-- the bar rebuild themselves, making this handler redundant in those cases.
fm_self.onPathChanged = function(this, new_path)
if this._navbar_suppress_path_change then return end
local t = Config.loadTabConfig()
local new_active = M._resolveTabForPath(new_path, t) or "home"
plugin.active_action = new_active
if this._navbar_container then
Bottombar.replaceBar(this, Bottombar.buildBarWidget(new_active, t), t)
UIManager:setDirty(this, "ui")
end
plugin:_updateFMHomeIcon()
end
end
end
-- Returns the tab id whose configured path matches the given filesystem path,
-- or nil if no tab matches. Strips trailing slashes before comparing.
function M._resolveTabForPath(path, tabs)
if not path then return nil end
path = path:gsub("/$", "")
local home_dir = G_reader_settings:readSetting("home_dir")
if home_dir then home_dir = home_dir:gsub("/$", "") end
for _i, tab_id in ipairs(tabs) do
if tab_id == "home" then
if home_dir and path == home_dir then return "home" end
elseif tab_id:match("^custom_qa_%d+$") then
local cfg = Config.getCustomQAConfig(tab_id)
if cfg.path then
local cfg_path = cfg.path:gsub("/$", "")
if path == cfg_path then return tab_id end
end
end
end
return nil
end
-- ---------------------------------------------------------------------------
-- FileManagerMenu.getStartWithMenuTable
-- Injects "Home Screen" into KOReader's Start With submenu.
-- Patched once per session; guarded by a flag on the class itself.
-- ---------------------------------------------------------------------------
function M.patchStartWithMenu()
local FileManagerMenu = package.loaded["apps/filemanager/filemanagermenu"]
if not FileManagerMenu then
local ok, m = pcall(require, "apps/filemanager/filemanagermenu")
FileManagerMenu = ok and m or nil
end
if not FileManagerMenu then return end
if FileManagerMenu._simpleui_startwith_patched then return end
local orig_fn = FileManagerMenu.getStartWithMenuTable
if not orig_fn then return end
FileManagerMenu._simpleui_startwith_patched = true
FileManagerMenu._simpleui_startwith_orig = orig_fn
FileManagerMenu.getStartWithMenuTable = function(fmm_self)
local result = orig_fn(fmm_self)
local sub = result.sub_item_table
if type(sub) ~= "table" then return result end
-- Guard against the entry already being present.
local has_homescreen = false
for _i, item in ipairs(sub) do
if item.text == _("Home Screen") and item.radio then has_homescreen = true end
end
if not has_homescreen then
table.insert(sub, math.max(1, #sub), {
text = _("Home Screen"),
checked_func = function() return isStartWithHS() end,
callback = function()
G_reader_settings:saveSetting("start_with", "homescreen_simpleui")
_start_with_hs = true -- update cache immediately
end,
radio = true,
})
end
-- Update the parent item text when "Home Screen" is the active choice.
local orig_text_func = result.text_func
result.text_func = function()
if isStartWithHS() then
return _("Start with") .. ": " .. _("Home Screen")
end
return orig_text_func and orig_text_func() or _("Start with")
end
return result
end
end
-- ---------------------------------------------------------------------------
-- BookList.new
-- Reduces BookList height to the content area (excludes navbar + topbar).
-- ---------------------------------------------------------------------------
function M.patchBookList(plugin)
local BookList = require("ui/widget/booklist")
local orig_bl_new = BookList.new
plugin._orig_booklist_new = orig_bl_new
BookList.new = function(class, attrs, ...)
attrs = attrs or {}
if not attrs.height and not attrs._navbar_height_reduced then
attrs.height = UI.getContentHeight()
attrs.y = UI.getContentTop()
attrs._navbar_height_reduced = true
end
return orig_bl_new(class, attrs, ...)
end
end
-- ---------------------------------------------------------------------------
-- FMColl.onShowCollList + Menu.new + ReadCollection
-- Reduces the coll_list Menu height to the content area. patch_depth gates
-- Menu.new so only menus created during onShowCollList are affected.
-- Also syncs the SimpleUI collections pool when KOReader renames/deletes.
-- ---------------------------------------------------------------------------
function M.patchCollections(plugin)
local ok, FMColl = pcall(require, "apps/filemanager/filemanagercollection")
if not (ok and FMColl) then return end
local Menu = require("ui/widget/menu")
local orig_menu_new = Menu.new
plugin._orig_menu_new = orig_menu_new
plugin._orig_fmcoll_show = FMColl.onShowCollList
local patch_depth = 0
local orig_onShowCollList = FMColl.onShowCollList
FMColl.onShowCollList = function(fmc_self, ...)
patch_depth = patch_depth + 1
local ok2, result = pcall(orig_onShowCollList, fmc_self, ...)
patch_depth = patch_depth - 1
if not ok2 then error(result) end
return result
end
-- Intercept Menu.new only while onShowCollList is on the call stack.
Menu.new = function(class, attrs, ...)
attrs = attrs or {}
if patch_depth > 0
and attrs.covers_fullscreen and attrs.is_borderless
and attrs.is_popout == false
and not attrs.height and not attrs._navbar_height_reduced then
attrs.height = UI.getContentHeight()
attrs.y = UI.getContentTop()
attrs._navbar_height_reduced = true
attrs.name = attrs.name or "coll_list"
end
return orig_menu_new(class, attrs, ...)
end
local ok_rc, RC = pcall(require, "readcollection")
if not (ok_rc and RC) then return end
-- Removes a collection from the SimpleUI selected list and cover-override table.
local function _removeFromPool(name)
local CW = package.loaded["collectionswidget"]
if not CW then return end
local selected = CW.getSelected()
local changed = false
for i = #selected, 1, -1 do
if selected[i] == name then
table.remove(selected, i)
changed = true
end
end
if changed then CW.saveSelected(selected) end
local overrides = CW.getCoverOverrides()
if overrides[name] then
overrides[name] = nil
CW.saveCoverOverrides(overrides)
end
end
-- Renames a collection in the SimpleUI selected list and cover-override table.
local function _renameInPool(old_name, new_name)
local CW = package.loaded["collectionswidget"]
if not CW then return end
local selected = CW.getSelected()
local changed = false
for i, name in ipairs(selected) do
if name == old_name then
selected[i] = new_name
changed = true
end
end
if changed then CW.saveSelected(selected) end
local overrides = CW.getCoverOverrides()
if overrides[old_name] then
overrides[new_name] = overrides[old_name]
overrides[old_name] = nil
CW.saveCoverOverrides(overrides)
end
end
if type(RC.removeCollection) == "function" then
local orig_remove = RC.removeCollection
plugin._orig_rc_remove = orig_remove
RC.removeCollection = function(rc_self, coll_name, ...)
local result = orig_remove(rc_self, coll_name, ...)
local ok2, err = pcall(function()
_removeFromPool(coll_name)
Config.purgeQACollection(coll_name)
Config.invalidateTabsCache()
plugin:_scheduleRebuild()
end)
if not ok2 then logger.warn("simpleui: removeCollection hook:", tostring(err)) end
return result
end
end
if type(RC.renameCollection) == "function" then
local orig_rename = RC.renameCollection
plugin._orig_rc_rename = orig_rename
RC.renameCollection = function(rc_self, old_name, new_name, ...)
local result = orig_rename(rc_self, old_name, new_name, ...)
local ok2, err = pcall(function()
_renameInPool(old_name, new_name)
Config.renameQACollection(old_name, new_name)
plugin:_scheduleRebuild()
end)
if not ok2 then logger.warn("simpleui: renameCollection hook:", tostring(err)) end
return result
end
end
end
-- ---------------------------------------------------------------------------
-- SortWidget.new + PathChooser.new
-- Reduces height to the content area. SortWidget also gets title padding and
-- a _populateItems hook to force a repaint after each sort operation.
-- ---------------------------------------------------------------------------
function M.patchFullscreenWidgets(plugin)
local ok_sw, SortWidget = pcall(require, "ui/widget/sortwidget")
local ok_pc, PathChooser = pcall(require, "ui/widget/pathchooser")
if ok_sw and SortWidget then
local ok_tb, TitleBar = pcall(require, "ui/widget/titlebar")
local orig_sw_new = SortWidget.new
plugin._orig_sortwidget_new = orig_sw_new
SortWidget.new = function(class, attrs, ...)
attrs = attrs or {}
if attrs.covers_fullscreen and not attrs._navbar_height_reduced then
attrs.height = UI.getContentHeight()
attrs.y = UI.getContentTop()
attrs._navbar_height_reduced = true
end
-- Temporarily wrap TitleBar.new to inject horizontal padding,
-- then restore it immediately after SortWidget is constructed.
local orig_tb_new
if ok_tb and TitleBar and attrs.covers_fullscreen then
orig_tb_new = TitleBar.new
TitleBar.new = function(tb_class, tb_attrs, ...)
tb_attrs = tb_attrs or {}
tb_attrs.title_h_padding = Screen:scaleBySize(24)
return orig_tb_new(tb_class, tb_attrs, ...)
end
end
local ok_sw2, sw_or_err = pcall(orig_sw_new, class, attrs, ...)
if orig_tb_new then TitleBar.new = orig_tb_new end
if not ok_sw2 then error(sw_or_err, 2) end
local sw = sw_or_err
if not attrs.covers_fullscreen then return sw end
-- Zero the footer height to remove the pagination bar space.
local vfooter = sw[1] and sw[1][1] and sw[1][1][2] and sw[1][1][2][1]
if vfooter and vfooter[3] and vfooter[3].dimen then
vfooter[3].dimen.h = 0
end
-- Force a full repaint after each sort list update.
local orig_populate = sw._populateItems
if type(orig_populate) == "function" then
sw._populateItems = function(self_sw, ...)
local result = orig_populate(self_sw, ...)
UIManager:setDirty(nil, "ui")
return result
end
end
return sw
end
end
if ok_pc and PathChooser then
local orig_pc_new = PathChooser.new
plugin._orig_pathchooser_new = orig_pc_new
PathChooser.new = function(class, attrs, ...)
attrs = attrs or {}
if attrs.covers_fullscreen and not attrs._navbar_height_reduced then
attrs.height = UI.getContentHeight()
attrs.y = UI.getContentTop()
attrs._navbar_height_reduced = true
end
return orig_pc_new(class, attrs, ...)
end
end
end
-- ---------------------------------------------------------------------------
-- UIManager.show
-- Injects the navbar into qualifying fullscreen widgets and closes the
-- homescreen when any other fullscreen widget appears on top of it.
-- _show_depth prevents re-entrant injection when orig_show calls show again.
-- ---------------------------------------------------------------------------
function M.patchUIManagerShow(plugin)
local orig_show = UIManager.show
plugin._orig_uimanager_show = orig_show
local _show_depth = 0
local INJECT_NAMES = { collections = true, history = true, coll_list = true, homescreen = true }
-- Resolves the live FileManager menu at call time, never capturing a stale
-- reference. The FM is destroyed and recreated each time the reader closes,
-- so a closure over the old FM's .menu would point at ReaderMenu and crash.
-- Defined once here, shared across all injected widgets.
local function _fmMenu()
local live_fm = plugin.ui
if live_fm and live_fm.menu
and type(live_fm.menu.name) == "string"
and live_fm.menu.name:find("filemanager") then
return live_fm.menu
end
local FM2 = package.loaded["apps/filemanager/filemanager"]
local inst = FM2 and FM2.instance
if inst and inst.menu then return inst.menu end
return nil
end
UIManager.show = function(um_self, widget, ...)
-- Fast path: the vast majority of show() calls are non-fullscreen
-- widgets (dialogs, menus, InfoMessage, toasts, etc.). None of the
-- SimpleUI injection logic applies to them — skip everything.
if not (widget and widget.covers_fullscreen) then
return orig_show(um_self, widget, ...)
end
-- Capture varargs before the pcall closure; reuse _EMPTY when none present.
local n_extra = select("#", ...)
local extra_args = n_extra > 0 and { ... } or _EMPTY
_show_depth = _show_depth + 1
-- Wrap the body in pcall so _show_depth is always decremented on error.
local ok, result = pcall(function()
-- When the FM appears after the reader closes with "Start with Homescreen"
-- active, show it silently first then immediately open the HS on top,
-- eliminating the flash of the FM before the homescreen appears.
if _show_depth == 1 and _hs_pending_after_reader
and widget and widget == plugin.ui
and isStartWithHS() then
_hs_pending_after_reader = false
if n_extra > 0 then
orig_show(um_self, widget, table.unpack(extra_args))
else
orig_show(um_self, widget)
end
local HS = package.loaded["sui_homescreen"]
if not HS then
local ok2, m = pcall(require, "sui_homescreen")
HS = ok2 and m
end
if HS and not HS._instance then
if not plugin._goalTapCallback then plugin:addToMainMenu({}) end
local tabs = Config.loadTabConfig()
-- Capture the FM's active tab *before* setting it to "homescreen".
-- The HS widget is injected by UIManager.show below, which reads
-- plugin.active_action as action_before and stores it as
-- _navbar_prev_action. If we called setActiveAndRefreshFM first,
-- action_before would already be "homescreen", so closing the HS
-- via back-button would restore "homescreen" instead of the real
-- previous tab (typically "home"). By setting _navbar_prev_action
-- explicitly after show, we ensure the correct value is used.
local prev_action = plugin.active_action
Bottombar.setActiveAndRefreshFM(plugin, "homescreen", tabs)
-- plugin.ui and loadTabConfig() resolved at tap time so FM
-- reinits or tab config changes while the HS is open are picked up.
HS.show(
function(aid) plugin:_navigate(aid, plugin.ui, Config.loadTabConfig(), false) end,
plugin._goalTapCallback
)
-- Correct _navbar_prev_action: UIManager.show captured "homescreen"
-- as action_before (because setActiveAndRefreshFM ran first), but the
-- real state to restore on back-button close is the tab that was active
-- before the HS opened.
local hs_inst = HS._instance
if hs_inst then hs_inst._navbar_prev_action = prev_action end
end
return
end
-- Injection criteria: top-level show, fullscreen, not already injected,
-- has a title bar (excludes ReaderUI), and is pre-sized or in INJECT_NAMES.
local should_inject = _show_depth == 1
and widget
and not widget._navbar_injected
and not widget._navbar_skip_inject
and widget ~= plugin.ui
and widget.covers_fullscreen
and widget.title_bar -- truthiness check, not ~= nil
and (widget._navbar_height_reduced or (widget.name and INJECT_NAMES[widget.name]))
if not should_inject then
if n_extra > 0 then
return orig_show(um_self, widget, table.unpack(extra_args))
else
return orig_show(um_self, widget)
end
end
widget._navbar_injected = true
-- Resize widget and its first child to the content area when not pre-sized.
if not widget._navbar_height_reduced then
local content_h = UI.getContentHeight()
local content_top = UI.getContentTop()
if widget.dimen then
widget.dimen.h = content_h
widget.dimen.y = content_top
end
if widget[1] and widget[1].dimen then
widget[1].dimen.h = content_h
widget[1].dimen.y = content_top
end
widget._navbar_height_reduced = true
end
-- Delegate injected-widget title-bar customisation to titlebar.lua.
-- applyToInjected() is a no-op when "Custom Title Bar" is off.
Titlebar.applyToInjected(widget)
local tabs = Config.loadTabConfig()
-- Build a set for O(1) membership tests — avoids repeated linear scans
-- over the same tab list for each widget name check below.
local tabs_set = tabsToSet(tabs)
-- Use the stashed pre-tap action if available (set by onTabTap before
-- mutating active_action). This ensures _navbar_prev_action holds the
-- tab that was active *before* the tap, not the tab being opened.
-- Fall back to active_action for programmatic opens (HS boot, etc.)
-- where _navbar_prev_action_pending is not set.
local action_before = plugin._navbar_prev_action_pending or plugin.active_action
plugin._navbar_prev_action_pending = nil -- consume immediately
local effective_action = nil
-- Activate the tab that corresponds to the widget being shown.
if widget.name == "collections" and Config.isFavoritesWidget(widget) and tabs_set["favorites"] then
effective_action = Bottombar.setActiveAndRefreshFM(plugin, "favorites", tabs)
-- NOTE: no onReturn wrapper here. The native onReturn calls
-- UIManager:close(self), which our patchUIManagerClose already
-- intercepts and handles (tab restore + setDirty). Adding a wrapper
-- that also called _restoreTabInFM caused a double restore and a
-- double close() emission on every Back button press.
elseif widget.name == "history" and tabs_set["history"] then
effective_action = Bottombar.setActiveAndRefreshFM(plugin, "history", tabs)
elseif widget.name == "homescreen" and tabs_set["homescreen"] then
effective_action = Bottombar.setActiveAndRefreshFM(plugin, "homescreen", tabs)
elseif widget.name == "coll_list"
or (widget.name == "collections" and not Config.isFavoritesWidget(widget)) then
if tabs_set["collections"] then
effective_action = Bottombar.setActiveAndRefreshFM(plugin, "collections", tabs)
end
end
-- Hide the native page_return_arrow (Back button) when the widget's
-- corresponding tab is absent from the navbar. The arrow is only
-- meaningful as "go back to the collections list" — without the tab
-- there is no such context to return to, so the button should not show.
-- We nil onReturn rather than just hiding the arrow so that
-- _recalculateDimen (called on every page turn) cannot re-show it.
-- The widget's own _recreate_func restores onReturn on the next open,
-- so this nil is scoped to this single injection lifetime.
if widget.name == "collections" and not widget._navbar_onreturn_checked then
widget._navbar_onreturn_checked = true
-- Both favorites and non-favorites collections use onReturn to open
-- coll_list (the collections list). The back button is only meaningful
-- when the "collections" tab is present — that is the context Back
-- navigates to, regardless of whether "favorites" is also a tab.
if not tabs_set["collections"] and widget.onReturn then
widget.onReturn = nil
if widget.page_return_arrow then
widget.page_return_arrow:hide()
end
end
end
local display_action = effective_action or action_before
if not widget._navbar_inner then widget._navbar_inner = widget[1] end
-- For injected fullscreen widgets that are not pageable (e.g. homescreen,
-- collections), build the bar without navpager arrows immediately rather
-- than waiting for the scheduleIn(0) correction. This prevents the brief
-- flash of arrows that are immediately replaced, and avoids the window
-- where touch zones have no arrow but the visual still shows one.
local widget_is_pageable = (type(widget.page_num) == "number")
or (widget.file_chooser and type(widget.file_chooser.page_num) == "number")
local navbar_container, wrapped, bar, topbar, bar_idx, topbar_on, topbar_idx =
UI.wrapWithNavbar(widget._navbar_inner, display_action, tabs,
not widget_is_pageable)
UI.applyNavbarState(widget, navbar_container, bar, topbar, bar_idx, topbar_on, topbar_idx, tabs)
widget._navbar_prev_action = action_before
widget[1] = wrapped
plugin:_registerTouchZones(widget)
-- Register top-of-screen tap/swipe zones to open the KOReader main menu,
-- mirroring FileManagerMenu:initGesListener for all injected pages.
if widget.registerTouchZones then
local DTAP_ZONE_MENU = G_defaults:readSetting("DTAP_ZONE_MENU")
local DTAP_ZONE_MENU_EXT = G_defaults:readSetting("DTAP_ZONE_MENU_EXT")
if DTAP_ZONE_MENU and DTAP_ZONE_MENU_EXT then
widget:registerTouchZones({
{
id = "simpleui_menu_tap",
ges = "tap",
screen_zone = {
ratio_x = DTAP_ZONE_MENU.x, ratio_y = DTAP_ZONE_MENU.y,
ratio_w = DTAP_ZONE_MENU.w, ratio_h = DTAP_ZONE_MENU.h,
},
handler = function(ges)
local m = _fmMenu(); if m then return m:onTapShowMenu(ges) end
end,
},
{
id = "simpleui_menu_ext_tap",
ges = "tap",
screen_zone = {
ratio_x = DTAP_ZONE_MENU_EXT.x, ratio_y = DTAP_ZONE_MENU_EXT.y,
ratio_w = DTAP_ZONE_MENU_EXT.w, ratio_h = DTAP_ZONE_MENU_EXT.h,
},
overrides = { "simpleui_menu_tap" },
handler = function(ges)
local m = _fmMenu(); if m then return m:onTapShowMenu(ges) end
end,
},
{
id = "simpleui_menu_swipe",
ges = "swipe",
screen_zone = {
ratio_x = DTAP_ZONE_MENU.x, ratio_y = DTAP_ZONE_MENU.y,
ratio_w = DTAP_ZONE_MENU.w, ratio_h = DTAP_ZONE_MENU.h,
},
handler = function(ges)
local m = _fmMenu(); if m then return m:onSwipeShowMenu(ges) end
end,
},
{
id = "simpleui_menu_ext_swipe",
ges = "swipe",
screen_zone = {
ratio_x = DTAP_ZONE_MENU_EXT.x, ratio_y = DTAP_ZONE_MENU_EXT.y,
ratio_w = DTAP_ZONE_MENU_EXT.w, ratio_h = DTAP_ZONE_MENU_EXT.h,
},
overrides = { "simpleui_menu_swipe" },
handler = function(ges)
local m = _fmMenu(); if m then return m:onSwipeShowMenu(ges) end
end,
},
})
end
end
-- Resize the return button width to match the side margin.
local rb = widget.return_button
if rb and rb[1] then rb[1].width = UI.SIDE_M() end
Bottombar.resizePaginationButtons(widget, Bottombar.getPaginationIconSize())
if n_extra > 0 then
orig_show(um_self, widget, table.unpack(extra_args))
else
orig_show(um_self, widget)
end
UIManager:setDirty(widget[1], "ui")
-- Navpager: schedule an arrow update for the next event-loop cycle.
-- Skipped when a coalescence-flagged update is already queued.
if G_reader_settings:isTrue("navbar_navpager_enabled") and not _navpager_rebuild_pending then
logger.dbg("simpleui navpager: post-show update scheduled for widget=", tostring(widget.name))
_navpager_rebuild_pending = true
UIManager:scheduleIn(0, function()
_navpager_rebuild_pending = false
if not G_reader_settings:isTrue("navbar_navpager_enabled") then return end
local fm2 = plugin.ui
if not (fm2 and fm2._navbar_container) then return end
local has_prev, has_next = Config.getNavpagerState()
logger.dbg("simpleui navpager: post-show getNavpagerState =>",
"has_prev=", tostring(has_prev), "has_next=", tostring(has_next))
local target2 = (widget._navbar_container and widget) or fm2
if not Bottombar.updateNavpagerArrows(target2, has_prev, has_next) then
local tabs2 = Config.loadTabConfig()
local mode2 = Config.getNavbarMode()
local new_bar = Bottombar.buildBarWidgetWithArrows(
plugin.active_action, tabs2, mode2, has_prev, has_next)
logger.dbg("simpleui tz: post-show replaceBar target=", tostring(target2.name))
Bottombar.replaceBar(target2, new_bar, tabs2)
end
UIManager:setDirty(target2, "ui")
end)
end
end) -- end pcall
_show_depth = _show_depth - 1
if not ok then
logger.warn("simpleui: UIManager.show patch error:", tostring(result))
end
-- Close the homescreen if a different fullscreen widget just appeared on top.
-- Runs regardless of injection; also covers native KOReader widgets (ReaderUI).
-- Excludes the FM itself: the FM opening the HS in onShow must not close it here.
if _show_depth == 0 and widget and widget.covers_fullscreen
and widget.name ~= "homescreen"
and widget ~= plugin.ui
and not widget._sui_keep_homescreen then
local stack = UI.getWindowStack()
for _i, entry in ipairs(stack) do
local w = entry.widget
if w and w.name == "homescreen" then
UIManager:close(w)
break
end
end
end
return result
end
end
-- ---------------------------------------------------------------------------
-- UIManager.close
-- On close of a SimpleUI-injected widget: restores the active tab and,
-- when "Start with Homescreen" is set, re-opens the homescreen.
-- Non-fullscreen widgets are passed straight through (fast path).
-- ---------------------------------------------------------------------------
function M.patchUIManagerClose(plugin)
local orig_close = UIManager.close
plugin._orig_uimanager_close = orig_close
-- Closes any orphaned non-fullscreen widgets, then shows the homescreen.
-- Defined once at patch-install time, not re-created on every close() call.
local function _doShowHS(fm, plugin_ref)
local HS = package.loaded["sui_homescreen"]
if not HS or HS._instance then return end
-- Re-check the stack at execution time: between the scheduleIn(0) call
-- and this function running, a new fullscreen widget (e.g. coll_list
-- opened by onReturn after collections closed) may have appeared.
-- If any fullscreen widget other than the FM is now on the stack,
-- abort — we are not returning to a bare FM.
local live_fm2 = package.loaded["apps/filemanager/filemanager"]
live_fm2 = live_fm2 and live_fm2.instance
for _i, entry in ipairs(UI.getWindowStack()) do
local w = entry.widget
if w and w ~= (live_fm2 or fm) and w.covers_fullscreen then
return -- another fullscreen widget is open; don't re-open HS
end
end
local stack = UI.getWindowStack()
local to_close = {}
for _i, entry in ipairs(stack) do
local w = entry.widget
if w and w ~= fm and not w.covers_fullscreen then
to_close[#to_close + 1] = w
end
end
for _, w in ipairs(to_close) do UIManager:close(w) end
local tabs = Config.loadTabConfig()
-- Capture the FM's active tab before setting it to "homescreen", so that
-- closing the HS via back-button restores the correct previous tab rather
-- than "homescreen" (see same pattern in _hs_pending_after_reader block).
local prev_action = plugin_ref.active_action
Bottombar.setActiveAndRefreshFM(plugin_ref, "homescreen", tabs)
if not plugin_ref._goalTapCallback then plugin_ref:addToMainMenu({}) end
-- plugin_ref.ui and loadTabConfig() resolved at tap time so FM
-- reinits or tab config changes while the HS is open are picked up.
HS.show(
function(aid) plugin_ref:_navigate(aid, plugin_ref.ui, Config.loadTabConfig(), false) end,
plugin_ref._goalTapCallback
)
-- Correct _navbar_prev_action after injection (same reason as above).
local hs_inst = HS._instance
if hs_inst then hs_inst._navbar_prev_action = prev_action end
end
UIManager.close = function(um_self, widget, ...)
-- Fast path: non-fullscreen widgets (dialogs, menus, InfoMessage, etc.)
-- are the vast majority of close() calls — skip all SimpleUI logic.
if not (widget and widget.covers_fullscreen) then
return orig_close(um_self, widget, ...)
end
-- Detect if this is the FileManager itself closing.
-- FM has no name field at class level (name = "filemanager" belongs to its
-- FileChooser child), so widget.name is nil — we identify it by identity.
local widget_is_fm = (widget == plugin.ui)
-- Restore the active tab when a SimpleUI-injected widget closes normally
-- (not via intentional tab navigation).
-- _navbar_injected is cleared immediately after processing so that a
-- second close() on the same widget (e.g. from the native close_callback
-- running after Menu:onCloseAllMenus already called UIManager:close)
-- is a no-op — preventing double restoreTabInFM + double setDirty.
if widget._navbar_injected and not widget._navbar_closing_intentionally then
widget._navbar_injected = nil -- consume: makes re-entry a no-op
-- coll_list sits on top of collections; restoreTabInFM would skip it
-- because another injected widget is still on the stack. Find the
-- prev_action on the underlying collections widget instead.
if widget.name == "coll_list" then
local FM2 = package.loaded["apps/filemanager/filemanager"]
local fm = FM2 and FM2.instance
if fm and fm._navbar_container then
local t = Config.loadTabConfig()
local restored = nil
for _i, entry in ipairs(UI.getWindowStack()) do
local w = entry.widget
if w and w ~= widget and w._navbar_injected
and (w.name == "collections" or w.name == "coll_list") then
restored = w._navbar_prev_action
break
end
end
if not restored then
restored = (fm.file_chooser
and M._resolveTabForPath(fm.file_chooser.path, t))
or t[1] or "home"
end
plugin.active_action = restored
Bottombar.replaceBar(fm, Bottombar.buildBarWidget(restored, t), t)
UIManager:setDirty(fm, "ui")
end
else
-- Pass nil for tabs: restoreTabInFM always loads fresh config.
plugin:_restoreTabInFM(nil, widget._navbar_prev_action)
end
end
-- When the FM itself is closing, the HomescreenWidget (if open) must be
-- closed too. FM:onClose → UIManager:close(fm) → returns; no quit() is
-- ever called explicitly. The event loop exits only when the stack empties.
-- Without this, the HS remains on the stack and the app never terminates.
if widget_is_fm then
local HS = package.loaded["sui_homescreen"]
local hs_inst = HS and HS._instance
if hs_inst then
-- _navbar_closing_intentionally suppresses tab-restore and
-- re-open logic when our patched close() sees the HS widget.
hs_inst._navbar_closing_intentionally = true
orig_close(um_self, hs_inst) -- bypass our wrapper, no re-entry
if HS._instance == hs_inst then HS._instance = nil end
end
end
local result = orig_close(um_self, widget, ...)
-- Re-open the homescreen after any fullscreen widget closes when
-- "Start with Homescreen" is configured. Applies to both injected and
-- native widgets (ReaderProgress, CalendarView, etc.).
-- Exclusions:
-- • the homescreen itself (would loop)
-- • the FileManager — FM closing means the app is exiting
-- • widgets closed by intentional tab navigation
-- • UIManager already in quit (Restart / explicit quit paths)
if isStartWithHS()
and widget.covers_fullscreen
and widget.name ~= "homescreen"
and not widget_is_fm
and not widget._navbar_closing_intentionally
and UIManager._exit_code == nil then
local FM2 = package.loaded["apps/filemanager/filemanager"]
local fm = FM2 and FM2.instance
local other_open = false
for _i, entry in ipairs(UI.getWindowStack()) do
local w = entry.widget
if w and w ~= fm and w ~= widget then
if w.covers_fullscreen then
other_open = true; break
end
end
end
if not other_open then
if widget.name == "ReaderUI" then
-- Only re-open the HS when the reader is closing to return
-- to the FM (tearing_down is nil). When tearing_down=true the
-- reader is closing to open a *new* book — do NOT open the HS.
if not widget.tearing_down then
_hs_pending_after_reader = true
end
else
UIManager:scheduleIn(0, function()
if UIManager._exit_code ~= nil then return end
-- Do NOT open the HS if ReaderUI is still open
-- (user closed a sub-menu like font settings, TOC, etc.
-- while reading — they are still in the reader).
local RUI = package.loaded["apps/reader/readerui"]
if RUI and RUI.instance then return end
local FM3 = package.loaded["apps/filemanager/filemanager"]
local fm2 = FM3 and FM3.instance
if fm2 then _doShowHS(fm2, plugin) end
end)
end
end
end
return result
end
end
-- ---------------------------------------------------------------------------
-- Menu.init
-- Removes the pagination bar from fullscreen FM-style menus when
-- "navbar_pagination_visible" is off.
-- ---------------------------------------------------------------------------
function M.patchMenuInitForPagination(plugin)
local Menu = require("ui/widget/menu")
local TARGET_NAMES = {
filemanager = true, history = true, collections = true, coll_list = true,
}
local orig_menu_init = Menu.init
plugin._orig_menu_init = orig_menu_init
Menu.init = function(menu_self, ...)