-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-reader-header.lua
More file actions
2649 lines (2492 loc) · 122 KB
/
2-reader-header.lua
File metadata and controls
2649 lines (2492 loc) · 122 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
-- Based on these two patches:
-- https://github.com/oh1apps/koreader_header by @oh1apps
-- https://github.com/sebdelsol/KOReader.patches/blob/main/2-statusbar-thin-chapter.lua by @sebdelsol
-- Updated by @mysiak with Github Copilot and Claude Sonnet 4.5
-- Optimizations and code cleanup by Claude Opus 4.5
local Blitbuffer = require("ffi/blitbuffer")
local TextWidget = require("ui/widget/textwidget")
local CenterContainer = require("ui/widget/container/centercontainer")
local VerticalGroup = require("ui/widget/verticalgroup")
local VerticalSpan = require("ui/widget/verticalspan")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local ProgressWidget = require("ui/widget/progresswidget")
local NetworkMgr = require("ui/network/manager")
local BD = require("ui/bidi")
local Size = require("ui/size")
local Geom = require("ui/geometry")
local Device = require("device")
local Font = require("ui/font")
local UIManager = require("ui/uimanager")
local logger = require("logger")
local util = require("util")
local datetime = require("datetime")
local Screen = Device.screen
local _ = require("gettext")
local T = require("ffi/util").template
local ReaderView = require("apps/reader/modules/readerview")
local ReaderMenu = require("apps/reader/modules/readermenu")
local ReaderFooter = require("apps/reader/modules/readerfooter")
-- Available header items
local HEADER_ITEMS = {
time = { name = T(_("Current time (%1)"), "⌚"), generator = nil, is_spacer = false },
battery = { name = T(_("Battery percentage (%1)"), ""), generator = nil, is_spacer = false },
wifi = { name = T(_("Wi-Fi status (%1)"), ""), generator = nil, is_spacer = false },
percentage = { name = T(_("Progress percentage (%1)"), "%"), generator = nil, is_spacer = false },
page_progress = { name = T(_("Current page (%1)"), "/"), generator = nil, is_spacer = false },
pages_left_book = { name = T(_("Pages left in book (%1)"), "→"), generator = nil, is_spacer = false },
pages_left = { name = T(_("Pages left in chapter (%1)"), "⇒"), generator = nil, is_spacer = false },
chapter_progress = { name = T(_("Current page in chapter (%1)"), "//"), generator = nil, is_spacer = false },
book_time_to_read = { name = T(_("Time left to finish book (%1)"), "⏳"), generator = nil, is_spacer = false },
chapter_time_to_read = { name = T(_("Time left to finish chapter (%1)"), "⤻"), generator = nil, is_spacer = false },
title = { name = _("Book title"), generator = nil, is_spacer = false },
author = { name = _("Book author"), generator = nil, is_spacer = false },
chapter = { name = _("Chapter title"), generator = nil, is_spacer = false },
frontlight = { name = T(_("Brightness level (%1)"), "☼"), generator = nil, is_spacer = false },
frontlight_warmth = { name = T(_("Warmth level (%1)"), "⊛"), generator = nil, is_spacer = false },
mem_usage = { name = T(_("KOReader memory usage (%1)"), ""), generator = nil, is_spacer = false },
bookmark_count = { name = T(_("Bookmark count (%1)"), "\u{F097}"), generator = nil, is_spacer = false },
custom_text = { name = _("Custom text"), generator = nil, is_spacer = false, is_dynamic = true },
spacer = { name = _("Dynamic filler"), generator = nil, is_spacer = true },
}
-- Menu order
local ITEMS_ORDER = {
"time", "battery", "wifi", "percentage", "page_progress", "chapter_progress",
"pages_left_book", "pages_left",
"book_time_to_read", "chapter_time_to_read",
"title", "author", "chapter",
"frontlight", "frontlight_warmth", "mem_usage", "bookmark_count",
"custom_text", "spacer"
}
-- Separator styles
local SEPARATOR_STYLES = {
" ",
" • ",
" - ",
" ○ ",
" : ",
"custom",
}
-- Default header items
local header_defaults = {
enabled = true,
items = {"time", "battery", "spacer", "percentage"},
separator_style = 1,
item_separator = " ",
show_progress_bar = true,
progress_bar_height = 3,
progress_bar_mode = "book", -- "book" or "chapter"
chapter_markers = "none", -- "none", "main", or "all"
font_size = 14,
font_bold = false,
custom_texts = {},
disabled_custom_texts = {},
custom_separator = " - ",
header_top_margin = 2,
header_side_margin = 10,
header_bottom_margin = 2,
follow_book_margins = false,
hide_icons = {},
wifi_on_only = false,
title_max_width = 100,
author_max_count = 2,
header_opacity = 100,
background_opacity = 70,
background_enabled = false,
auto_background_for_pdf = true,
-- Progress bar colors stored as hex (default to nil, will use ProgressWidget defaults)
progress_bar_read_color = nil,
progress_bar_unread_color = nil,
progress_bar_marker_color = nil,
-- Color inversion settings
invert_colors = false,
footer_invert_colors = false,
footer_full_refresh_on_toggle = false,
invert_colors_in_night_mode = false,
-- Status bar separator settings
separator_enabled = false,
separator_color = "#000000",
separator_thickness = 2,
separator_top_margin = 4,
separator_side_margin = 0,
separator_follow_book_margins = false,
}
local function getHeaderSettings()
local settings = G_reader_settings:readSetting("custom_header")
if not settings then
settings = util.tableDeepCopy(header_defaults)
G_reader_settings:saveSetting("custom_header", settings)
end
if not settings.items then settings.items = {"time", "battery", "spacer", "percentage"} end
if not settings.separator_style then settings.separator_style = 1 end
if settings.custom_separator == nil then settings.custom_separator = " - " end
-- Set item_separator based on style (use custom if style is "custom")
if SEPARATOR_STYLES[settings.separator_style] == "custom" then
settings.item_separator = settings.custom_separator
else
settings.item_separator = SEPARATOR_STYLES[settings.separator_style]
end
if settings.enabled == nil then settings.enabled = true end
if settings.show_progress_bar == nil then settings.show_progress_bar = true end
if settings.progress_bar_height == nil then settings.progress_bar_height = 3 end
if settings.progress_bar_mode == nil then settings.progress_bar_mode = "book" end
if settings.font_size == nil then settings.font_size = 14 end
if settings.font_bold == nil then settings.font_bold = false end
if settings.custom_texts == nil then settings.custom_texts = {} end
if settings.disabled_custom_texts == nil then settings.disabled_custom_texts = {} end
if settings.hide_icons == nil then settings.hide_icons = {} end
if settings.wifi_on_only == nil then settings.wifi_on_only = false end
if settings.title_max_width == nil then settings.title_max_width = 100 end
if settings.author_max_count == nil then settings.author_max_count = 2 end
if settings.header_opacity == nil then settings.header_opacity = 100 end
if settings.background_opacity == nil then settings.background_opacity = 70 end
if settings.background_enabled == nil then settings.background_enabled = false end
if settings.auto_background_for_pdf == nil then settings.auto_background_for_pdf = true end
-- Initialize color inversion settings
if settings.invert_colors == nil then settings.invert_colors = false end
if settings.footer_invert_colors == nil then settings.footer_invert_colors = false end
if settings.footer_full_refresh_on_toggle == nil then settings.footer_full_refresh_on_toggle = false end
if settings.invert_colors_in_night_mode == nil then settings.invert_colors_in_night_mode = false end
-- Initialize separator settings
if settings.separator_enabled == nil then settings.separator_enabled = false end
if settings.separator_color == nil then settings.separator_color = "#000000" end
if settings.separator_thickness == nil then settings.separator_thickness = 2 end
if settings.separator_top_margin == nil then settings.separator_top_margin = 4 end
if settings.separator_side_margin == nil then settings.separator_side_margin = 0 end
if settings.separator_follow_book_margins == nil then settings.separator_follow_book_margins = false end
-- Clean up unsupported settings - keep only valid keys
local valid_keys = {
enabled = true,
items = true,
separator_style = true,
item_separator = true,
show_progress_bar = true,
progress_bar_height = true,
progress_bar_mode = true,
chapter_markers = true,
font_size = true,
font_bold = true,
custom_texts = true,
disabled_custom_texts = true,
custom_separator = true,
header_top_margin = true,
header_side_margin = true,
header_bottom_margin = true,
follow_book_margins = true,
hide_icons = true,
wifi_on_only = true,
title_max_width = true,
author_max_count = true,
header_opacity = true,
background_opacity = true,
background_enabled = true,
auto_background_for_pdf = true,
_tap_bg_override = true, -- Internal tracking state for tap cycle
progress_bar_read_color = true,
progress_bar_unread_color = true,
progress_bar_marker_color = true,
invert_colors = true,
footer_invert_colors = true,
footer_full_refresh_on_toggle = true,
invert_colors_in_night_mode = true,
separator_enabled = true,
separator_color = true,
separator_thickness = true,
separator_top_margin = true,
separator_side_margin = true,
separator_follow_book_margins = true,
}
local cleaned = false
for key in pairs(settings) do
if not valid_keys[key] then
settings[key] = nil
cleaned = true
end
end
-- Save settings if we cleaned anything
if cleaned then
G_reader_settings:saveSetting("custom_header", settings)
end
return settings
end
local function saveHeaderSettings(settings)
G_reader_settings:saveSetting("custom_header", settings)
end
local function isHeaderEnabled()
return getHeaderSettings().enabled
end
-- Detect if night mode is active
local function isNightMode()
return G_reader_settings:isTrue("night_mode")
end
-- Helper functions for color management
local function isColorDevice()
-- Check if device supports color display
if Device.hasColorScreen then
if type(Device.hasColorScreen) == "function" then
return Device:hasColorScreen()
else
return Device.hasColorScreen
end
end
return false
end
local function validateHexColor(hex)
-- Validate hex color format (#RGB or #RRGGBB)
if not hex or type(hex) ~= "string" then
return false
end
return hex:match("^#%x%x%x$") or hex:match("^#%x%x%x%x%x%x$")
end
local function convertToGrayscale(hex)
-- Convert hex color to grayscale using luminance formula
if not validateHexColor(hex) then
return hex
end
local hex_clean = hex:gsub("#", "")
local r, g, b
if #hex_clean == 3 then
r = tonumber(hex_clean:sub(1, 1), 16) * 17
g = tonumber(hex_clean:sub(2, 2), 16) * 17
b = tonumber(hex_clean:sub(3, 3), 16) * 17
else
r = tonumber(hex_clean:sub(1, 2), 16)
g = tonumber(hex_clean:sub(3, 4), 16)
b = tonumber(hex_clean:sub(5, 6), 16)
end
-- ITU-R BT.709 luminance formula
local gray = math.floor(0.2126 * r + 0.7152 * g + 0.0722 * b)
return string.format("#%02X%02X%02X", gray, gray, gray)
end
local function hexToGrayscaleValue(hex)
-- Convert hex color to grayscale value (0-255) for display
if not hex or type(hex) ~= "string" then
return 128
end
local hex_clean = hex:gsub("#", "")
if #hex_clean >= 2 then
return tonumber(hex_clean:sub(1, 2), 16) or 128
end
return 128
end
local function grayscaleValueToHex(value)
-- Convert grayscale value (0-255) to hex color for storage
if type(value) ~= "number" then
value = 128
end
value = math.max(0, math.min(255, math.floor(value)))
return string.format("#%02X%02X%02X", value, value, value)
end
local function getDefaultProgressBarColors()
-- Get default colors as hex for ProgressWidget
return {
read = "#555555", -- Dark gray for read portion
unread = "#AAAAAA", -- Light gray for unread portion
marker = "#000000", -- Black for chapter markers
}
end
-- Menu item helper functions to reduce duplication
local function createColorPickerItem(params)
-- Creates a color picker menu item that adapts to device type (color vs B/W)
-- params: {setting_key, default_value, label_text, title_text, info_text, reader_ui}
return {
text_func = function()
local h_settings = getHeaderSettings()
local color = h_settings[params.setting_key] or params.default_value
if isColorDevice() then
return T(_(params.label_text), color)
else
local gray_val = hexToGrayscaleValue(color)
return T(_(params.label_text), gray_val)
end
end,
callback = function(touchmenu_instance)
local h_settings = getHeaderSettings()
local current_color = h_settings[params.setting_key] or params.default_value
if isColorDevice() then
-- Color device: use InputDialog for hex color
local InputDialog = require("ui/widget/inputdialog")
local input_dialog
input_dialog = InputDialog:new{
title = _(params.title_text),
input = current_color,
input_hint = "#RRGGBB",
buttons = {
{
{
text = _("Cancel"),
callback = function()
UIManager:close(input_dialog)
end,
},
{
text = _("Reset to default"),
callback = function()
h_settings[params.setting_key] = params.reset_value or nil
saveHeaderSettings(h_settings)
touchmenu_instance:updateItems()
if params.reader_ui and params.reader_ui.document then
UIManager:setDirty(params.reader_ui.dialog, "ui")
end
UIManager:close(input_dialog)
end,
},
{
text = _("Save"),
is_enter_default = true,
callback = function()
local text = input_dialog:getInputText()
if text and text ~= "" then
if not validateHexColor(text) then
UIManager:show(require("ui/widget/infomessage"):new{
text = _("Invalid color format. Use #RGB or #RRGGBB."),
})
return
end
h_settings[params.setting_key] = text
saveHeaderSettings(h_settings)
touchmenu_instance:updateItems()
if params.reader_ui and params.reader_ui.document then
UIManager:setDirty(params.reader_ui.dialog, "ui")
end
UIManager:close(input_dialog)
end
end,
},
},
},
}
UIManager:show(input_dialog)
input_dialog:onShowKeyboard()
else
-- B/W device: use SpinWidget for grayscale slider
local current_value = hexToGrayscaleValue(current_color)
local SpinWidget = require("ui/widget/spinwidget")
local spin_widget = SpinWidget:new{
value = current_value,
value_min = 0,
value_max = 255,
value_step = 5,
value_hold_step = 15,
title_text = _(params.title_text),
info_text = params.info_text and _(params.info_text) or _("0 = black, 255 = white"),
ok_text = _("Set value"),
extra_text = _("Reset to default"),
extra_callback = function()
h_settings[params.setting_key] = params.reset_value or nil
saveHeaderSettings(h_settings)
touchmenu_instance:updateItems()
if params.reader_ui and params.reader_ui.document then
UIManager:setDirty(params.reader_ui.dialog, "ui")
end
end,
callback = function(spin)
h_settings[params.setting_key] = grayscaleValueToHex(spin.value)
saveHeaderSettings(h_settings)
touchmenu_instance:updateItems()
if params.reader_ui and params.reader_ui.document then
UIManager:setDirty(params.reader_ui.dialog, "ui")
end
end,
}
UIManager:show(spin_widget)
end
end,
keep_menu_open = true,
}
end
local function createToggleItem(params)
-- Creates a toggle menu item for boolean settings
-- params: {text, setting_key, reader_ui}
return {
text = _(params.text),
checked_func = function()
local h_settings = getHeaderSettings()
return h_settings[params.setting_key]
end,
callback = function(touchmenu_instance)
local h_settings = getHeaderSettings()
h_settings[params.setting_key] = not h_settings[params.setting_key]
saveHeaderSettings(h_settings)
touchmenu_instance:updateItems()
if params.reader_ui and params.reader_ui.document then
UIManager:setDirty(params.reader_ui.dialog, "ui")
end
end,
}
end
local function createSpinWidgetItem(params)
-- Creates a SpinWidget menu item for numeric settings
-- params: {setting_key, default_value, label_text, title_text, info_text,
-- ok_text, min, max, step, hold_step, reader_ui}
return {
text_func = function()
local h_settings = getHeaderSettings()
return T(_(params.label_text), h_settings[params.setting_key] or params.default_value)
end,
callback = function(touchmenu_instance)
local h_settings = getHeaderSettings()
local SpinWidget = require("ui/widget/spinwidget")
local spin_widget = SpinWidget:new{
value = h_settings[params.setting_key] or params.default_value,
value_min = params.min,
value_max = params.max,
value_step = params.step or 1,
value_hold_step = params.hold_step or (params.step or 1) * 5,
title_text = _(params.title_text),
info_text = params.info_text and _(params.info_text) or nil,
ok_text = params.ok_text and _(params.ok_text) or _("Set value"),
callback = function(spin)
h_settings[params.setting_key] = spin.value
saveHeaderSettings(h_settings)
touchmenu_instance:updateItems()
if params.reader_ui and params.reader_ui.document then
UIManager:setDirty(params.reader_ui.dialog, "ui")
end
end,
}
UIManager:show(spin_widget)
end,
keep_menu_open = true,
}
end
local function createRadioItem(params)
-- Creates a radio button menu item (for selecting one of multiple values)
-- params: {text, setting_key, value, default_value, reader_ui}
return {
text = _(params.text),
checked_func = function()
local h_settings = getHeaderSettings()
local current = h_settings[params.setting_key]
if current == nil and params.default_value ~= nil then
current = params.default_value
end
return current == params.value
end,
callback = function(touchmenu_instance)
local h_settings = getHeaderSettings()
h_settings[params.setting_key] = params.value
saveHeaderSettings(h_settings)
touchmenu_instance:updateItems()
if params.reader_ui and params.reader_ui.document then
UIManager:setDirty(params.reader_ui.dialog, "ui")
end
end,
}
end
local function hasItem(items_list, item_key)
for _, key in ipairs(items_list) do
if key == item_key then return true end
end
return false
end
local function toggleItem(items_list, item_key)
for i, key in ipairs(items_list) do
if key == item_key then
table.remove(items_list, i)
return
end
end
table.insert(items_list, item_key)
end
local function setSeparatorStyle(style_index)
local h_settings = getHeaderSettings()
h_settings.separator_style = style_index
saveHeaderSettings(h_settings)
end
-- Generator functions (defined at module level to avoid recreation on each render)
local function generate_time(self, h_settings)
local time_string = datetime.secondsToHour(os.time(), G_reader_settings:isTrue("twelve_hour_clock")) or ""
if time_string:match("^%d:") then
time_string = "0" .. time_string
end
if h_settings.hide_icons["time"] then
return time_string
else
return "⌚ " .. time_string
end
end
local function generate_battery(self, h_settings)
local battery = ""
if Device:hasBattery() then
local power_dev = Device:getPowerDevice()
local batt_lvl = power_dev:getCapacity() or 0
local is_charging = power_dev:isCharging() or false
if h_settings.hide_icons["battery"] then
battery = batt_lvl .. "%"
else
local batt_prefix = power_dev:getBatterySymbol(power_dev:isCharged(), is_charging, batt_lvl) or ""
battery = batt_prefix .. batt_lvl .. "%"
end
end
return battery
end
local function generate_wifi(self, h_settings)
if NetworkMgr:isWifiOn() then
return "" -- WiFi on icon
elseif h_settings.wifi_on_only then
return "" -- Don't show anything when wifi is off
else
return "" -- WiFi off icon
end
end
local function generate_percentage(self, h_settings)
local pageno = self.state.page or 1
local pages = (self.ui.doc_settings and self.ui.doc_settings.data and self.ui.doc_settings.data.doc_pages) or 1
local percentage = (pageno / pages) * 100
if h_settings.hide_icons["percentage"] then
return string.format("%.0f", percentage) .. "%"
else
return "(" .. string.format("%.0f", percentage) .. "%)"
end
end
local function generate_page_progress(self, h_settings)
local pageno = self.state.page or 1
local pages = (self.ui.doc_settings and self.ui.doc_settings.data and self.ui.doc_settings.data.doc_pages) or 1
return ("%d / %d"):format(pageno, pages)
end
local function generate_pages_left_book(self, h_settings)
local pageno = self.state.page or 1
local pages = (self.ui.doc_settings and self.ui.doc_settings.data and self.ui.doc_settings.data.doc_pages) or 1
local remaining = pages - pageno
if h_settings.hide_icons["pages_left_book"] then
return ("%d / %d"):format(remaining, pages)
else
return ("→ %d / %d"):format(remaining, pages)
end
end
local function generate_pages_left(self, h_settings)
local pageno = self.state.page or 1
if self.ui.toc then
local left = self.ui.toc:getChapterPagesLeft(pageno) or 0
if h_settings.hide_icons["pages_left"] then
return ("%d"):format(left)
else
return ("⇒ %d"):format(left)
end
end
return ""
end
local function generate_chapter_progress(self, h_settings)
local pageno = self.state.page or 1
if self.ui.toc then
local pages_done = self.ui.toc:getChapterPagesDone(pageno) or 0
pages_done = pages_done + 1
local pages_chapter = self.ui.toc:getChapterPageCount(pageno) or 0
if pages_chapter > 0 then
if h_settings.hide_icons["chapter_progress"] then
return ("%d / %d"):format(pages_done, pages_chapter)
else
return ("%d // %d"):format(pages_done, pages_chapter)
end
end
end
return ""
end
local function generate_book_time_to_read(self, h_settings)
if self.ui.document and self.ui.statistics and type(self.ui.document.getTotalPagesLeft) == "function" and type(self.ui.statistics.getTimeForPages) == "function" then
local pageno = self.state.page or 1
local ok, left = pcall(function() return self.ui.document:getTotalPagesLeft(pageno) end)
if ok and left and type(left) == "number" then
local ok2, time_str = pcall(function() return self.ui.statistics:getTimeForPages(left) end)
if ok2 and time_str then
if h_settings.hide_icons["book_time_to_read"] then
return time_str
else
return "⏳ " .. time_str
end
end
end
end
return ""
end
local function generate_chapter_time_to_read(self, h_settings)
if self.ui.statistics and type(self.ui.statistics.getTimeForPages) == "function" then
local pageno = self.state.page or 1
local left = nil
-- Try to get chapter pages left
if self.ui.toc and type(self.ui.toc.getChapterPagesLeft) == "function" then
local ok, result = pcall(function() return self.ui.toc:getChapterPagesLeft(pageno) end)
if ok and result then
left = result
end
end
-- Fallback to total pages left
if not left and self.ui.document and type(self.ui.document.getTotalPagesLeft) == "function" then
local ok, result = pcall(function() return self.ui.document:getTotalPagesLeft(pageno) end)
if ok and result then
left = result
end
end
if left and type(left) == "number" then
local ok, time_str = pcall(function() return self.ui.statistics:getTimeForPages(left) end)
if ok and time_str then
if h_settings.hide_icons["chapter_time_to_read"] then
return time_str
else
return "⤻ " .. time_str
end
end
end
end
return ""
end
local function generate_title(self, h_settings)
if self.ui.doc_props then
local title = self.ui.doc_props.display_title or ""
return title
end
return ""
end
local function generate_author(self, h_settings)
if self.ui.doc_props then
local author = self.ui.doc_props.authors or ""
if author:find("\n") then
local authors_list = util.splitToArray(author, "\n")
local nb_authors = #authors_list
local max_count = h_settings.author_max_count or 2
if nb_authors <= max_count then
-- Display all authors separated by comma
author = table.concat(authors_list, ", ")
else
-- More authors than limit: show first ones and use "et al."
local displayed_authors = {}
for i = 1, max_count do
table.insert(displayed_authors, authors_list[i])
end
author = table.concat(displayed_authors, ", ") .. " et al."
end
end
return author
end
return ""
end
local function generate_chapter(self, h_settings)
local pageno = self.state.page or 1
if self.ui.toc then
return self.ui.toc:getTocTitleByPage(pageno) or ""
end
return ""
end
local function generate_frontlight(self, h_settings)
if Device:hasFrontlight() then
local powerd = Device:getPowerDevice()
if powerd:isFrontlightOn() then
local level = powerd:frontlightIntensity()
local level_str
if Device:isCervantes() or Device:isKobo() then
level_str = ("%d%%"):format(level)
else
level_str = ("%d"):format(level)
end
if h_settings.hide_icons["frontlight"] then
return level_str
else
return "☼" .. level_str
end
else
if h_settings.hide_icons["frontlight"] then
return _("Off")
else
return "☼" .. _("Off")
end
end
end
return ""
end
local function generate_frontlight_warmth(self, h_settings)
if Device:hasNaturalLight() then
local powerd = Device:getPowerDevice()
if powerd:isFrontlightOn() then
local warmth = powerd:frontlightWarmth()
if warmth then
local warmth_str = ("%d%%"):format(warmth)
if h_settings.hide_icons["frontlight_warmth"] then
return warmth_str
else
return "⊛" .. warmth_str
end
end
else
if h_settings.hide_icons["frontlight_warmth"] then
return _("Off")
else
return "⊛" .. _("Off")
end
end
end
return ""
end
local function generate_mem_usage(self, h_settings)
-- Cache memory usage to avoid file I/O on every render (update every 15 seconds for e-readers)
local current_time = os.time()
self._header_cache = self._header_cache or {}
local mem_cache_time = self._header_cache.mem_time or 0
if current_time - mem_cache_time >= 15 then
local statm = io.open("/proc/self/statm", "r")
if statm then
local dummy, rss = statm:read("*number", "*number")
statm:close()
rss = math.floor(rss * (4096 / 1024 / 1024))
self._header_cache.mem_value = "" .. ("%d MiB"):format(rss)
else
self._header_cache.mem_value = ""
end
self._header_cache.mem_time = current_time
end
return self._header_cache.mem_value or ""
end
local function generate_bookmark_count(self, h_settings)
if self.ui.annotation then
local count = self.ui.annotation:getNumberOfAnnotations()
if h_settings.hide_icons["bookmark_count"] then
return ("%d"):format(count)
else
return "\u{F097}" .. ("%d"):format(count)
end
end
return ""
end
-- Generator lookup table
local GENERATORS = {
time = generate_time,
battery = generate_battery,
wifi = generate_wifi,
percentage = generate_percentage,
page_progress = generate_page_progress,
pages_left_book = generate_pages_left_book,
pages_left = generate_pages_left,
chapter_progress = generate_chapter_progress,
book_time_to_read = generate_book_time_to_read,
chapter_time_to_read = generate_chapter_time_to_read,
title = generate_title,
author = generate_author,
chapter = generate_chapter,
frontlight = generate_frontlight,
frontlight_warmth = generate_frontlight_warmth,
mem_usage = generate_mem_usage,
bookmark_count = generate_bookmark_count,
}
local _ReaderView_paintTo_orig = ReaderView.paintTo
local header_settings = G_reader_settings:readSetting("footer")
-- Runtime flag: disables status bar rendering during page browser thumbnail generation
local _page_browser_active = false
-- Guard: ensures at most one full-refresh timer is queued at a time.
-- Without this, Night Mode on Android fires a repaint burst that calls scheduleIn on every
-- iteration, spawning unlimited timer coroutines (the runaway Thread IDs in the ADB log).
local _full_refresh_pending = false
-- Touch zones
local function setupHeaderTouchZone(reader_ui)
if not Device:isTouchDevice() then return end
local header_height = Size.item.height_default -- touch zone height
local header_zone = {
ratio_x = 0,
ratio_y = 0,
ratio_w = 1,
ratio_h = header_height / Screen:getHeight(),
}
reader_ui:registerTouchZones({
{
id = "reader_header_tap",
ges = "tap",
screen_zone = header_zone,
handler = function(ges)
local h_settings = getHeaderSettings()
-- Check if background would be shown based on settings:
-- 1. Manually enabled in settings (background_enabled = true), OR
-- 2. Auto-enabled for this PDF
local background_configured = h_settings.background_enabled
if not background_configured and h_settings.auto_background_for_pdf and reader_ui.document then
local doc_info = reader_ui.document.info
if doc_info and doc_info.has_pages then
background_configured = true
end
end
-- Tap cycle logic (respects menu settings, only toggles via _tap_bg_override):
-- If background configured: off -> on (with bg) -> on (transparent) -> off
-- If background not configured: off -> on -> off
if not h_settings.enabled then
-- Currently off -> turn on (respect background settings)
h_settings.enabled = true
h_settings._tap_bg_override = false -- Clear any previous override
elseif h_settings.enabled and background_configured then
-- Header is on and background is configured
if not h_settings._tap_bg_override then
-- Currently showing with background -> switch to transparent (override to hide bg)
h_settings._tap_bg_override = true
else
-- Currently transparent -> turn off
h_settings.enabled = false
h_settings._tap_bg_override = false
end
else
-- Header is on but background not configured -> just turn off
h_settings.enabled = false
h_settings._tap_bg_override = false
end
saveHeaderSettings(h_settings)
-- Use full refresh if setting is enabled, otherwise use ui refresh
local refresh_type = h_settings.footer_full_refresh_on_toggle and "full" or "ui"
UIManager:setDirty(reader_ui.dialog, refresh_type)
return true
end,
overrides = {
"readerconfigmenu_ext_tap",
"readerconfigmenu_tap",
},
},
})
end
-- Main function
ReaderView.paintTo = function(self, bb, x, y)
_ReaderView_paintTo_orig(self, bb, x, y)
-- Removed render_mode check to enable header on all document types (PDFs, CBZs, etc.) like footer
if not isHeaderEnabled() then return end -- Exit if disabled
if _page_browser_active then return end -- Skip rendering during page browser thumbnail generation
-- Cache settings - fetch once per render
local h_settings = getHeaderSettings()
-- Get screen width dynamically to handle rotation
local screen_width = Screen:getWidth()
-- ===========================!!!!!!!!!!!!!!!=========================== -
-- Configure formatting options for header here, if desired (defaults to footer options)
local header_font_face = "ffont"
local header_font_size = h_settings.font_size
local header_font_bold = h_settings.font_bold
local header_font_color = Blitbuffer.COLOR_BLACK
local header_top_padding = h_settings.header_top_margin or 2
local header_use_book_margins = h_settings.follow_book_margins or false
local header_margin = h_settings.header_side_margin or 10
local left_max_width_pct = 48
local right_max_width_pct = 48
-- Progress bar settings from header settings
local show_progress_bar = h_settings.show_progress_bar
local progress_bar_height = h_settings.progress_bar_height
local progress_bar_margin = h_settings.header_bottom_margin or 2
local chapter_markers = h_settings.chapter_markers or "none"
local toc_markers_width = header_settings and header_settings.toc_markers_width or 2
-- ===========================!!!!!!!!!!!!!!!=========================== -
-- Build set of generators actually needed (only for enabled items)
local needed_generators = {}
for _, item_key in ipairs(h_settings.items) do
local item_base_key = item_key:match("^([^_]+_[^_]+)") or item_key
if GENERATORS[item_key] then
needed_generators[item_key] = true
elseif GENERATORS[item_base_key] then
needed_generators[item_base_key] = true
end
end
-- Also check custom texts for variable references (only enabled ones)
if h_settings.custom_texts then
for idx, text in ipairs(h_settings.custom_texts) do
-- Skip disabled custom texts
if text and not h_settings.disabled_custom_texts[idx] then
for var_name in text:gmatch("{([^}]+)}") do
if GENERATORS[var_name] then
needed_generators[var_name] = true
end
end
end
end
end
-- Cache only needed generator results (with error isolation)
local generator_cache = {}
for key in pairs(needed_generators) do
local generator = GENERATORS[key]
if generator then
local ok, result = pcall(generator, self, h_settings)
generator_cache[key] = ok and (result or "") or ""
end
end
-- Variable substitution for custom text
local function substituteVariables(text)
if not text or text == "" then return "" end
-- Replace {variable} with actual values from cache
local result = text:gsub("{([^}]+)}", function(var_name)
return generator_cache[var_name] or "{" .. var_name .. "}"
end)
return result
end
-- Spacer and dynamic custom text handling
local custom_text_counter = 0
local function buildHeaderWidgets()
local groups = {}
local current_group = {}
local current_group_has_title = false
for _, item_key in ipairs(h_settings.items) do
local item_base_key = item_key:match("^([^_]+_[^_]+)") or item_key
local item = HEADER_ITEMS[item_base_key] or HEADER_ITEMS[item_key]
if item then
if item.is_spacer then
if #current_group > 0 then
table.insert(groups, {text = current_group, has_title = current_group_has_title})
current_group = {}
current_group_has_title = false
end
table.insert(groups, "spacer")