Debian Codegraph @

src/pyj/read_book/prefs/head_foot.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 from elementmaker import E
6 from gettext import gettext as _
7 from gettext import ngettext
8
9 from book_list.globals import get_session_data
10 from dom import clear, unique_id
11 from dom import svgicon
12 from read_book.globals import current_book
13 from read_book.prefs.utils import create_button_box
14 from session import get_interface_data, session_defaults
15 from utils import fmt_sidx
16 from viewer.constants import CHARS_PER_PAGE
17
18 CONTAINER = unique_id('reader-hf-prefs')
19
20
21 def create_item(region, label, style):
22 def sep():
23 return E.option('\xa0', disabled=True)
24
25 def opt(label, name, selected):
26 return E.option(label, id=name, value=name, selected=bool(selected))
27
28 s = E.div(
29 E.select(
30 data_region=region,
31 opt(_('Empty'), 'empty', True),
32 sep(),
33 opt(_('Book title'), 'title'),
34 opt(_('Authors'), 'authors'),
35 opt(_('Series'), 'series'),
36 sep(),
37 opt(_('Top level section'), 'top-section'),
38 opt(_('Current section'), 'section'),
39 opt(_('View mode'), 'view-mode'),
40 opt(_('View mode as icon'), 'view-mode-icon'),
41 sep(),
42 opt(_('Clock'), 'clock'),
43 opt(_('Controls button on hover'), 'menu-icon-on-hover'),
44 sep(),
45 opt(_('Progress'), 'progress'),
46 opt(_('Time to read book'), 'time-book'),
47 opt(_('Time to read chapter'), 'time-chapter'),
48 opt(_('Time to read chapter and book'), 'time-chapter-book'),
49 opt(_('Position in book'), 'pos-book'),
50 opt(_('Position in chapter'), 'pos-chapter'),
51 opt(_('Pages in chapter'), 'pages-progress'),
52 opt(_('Pages from paper edition'), 'page-list'),
53 opt(_('Pages from paper edition with total'), 'page-list-with-total'),
54 ), E.span(svgicon('angle-down')),
55 data_component='select',
56 )
57
58 return E.tr(
59 style=style or '',
60 E.td(label + ':', style='padding: 1ex 1rem'),
61 E.td(s)
62 )
63
64
65 def create_items(which):
66 if which is 'header' or which is 'footer':
67 ans = E.table(
68 data_which=which,
69 create_item('left', _('Left')),
70 create_item('middle', _('Middle')),
71 create_item('right', _('Right'))
72 )
73 elif which is 'controls_footer':
74 ans = E.table(
75 data_which=which,
76 create_item('left', _('Left'), 'display: none'),
77 create_item('middle', _('Middle')),
78 create_item('right', _('Right'))
79 )
80 else:
81 ans = E.table(
82 data_which=which,
83 create_item('left', _('Top')),
84 create_item('middle', _('Middle')),
85 create_item('right', _('Bottom'))
86 )
87 return ans
88
89
90 def apply_setting(table, val):
91 for region in 'left middle right'.split(' '):
92 sel = table.querySelector(f'select[data-region={region}]')
93 for opt in sel.selectedOptions:
94 opt.selected = False
95 x = val[region] or 'empty'
96 opt = sel.namedItem(x)
97 if opt:
98 opt.selected = True
99 else:
100 sel.selectedIndex = 0
101
102
103 def get_setting(table):
104 ans = {}
105 for region in 'left middle right'.split(' '):
106 sel = table.querySelector(f'select[data-region={region}]')
107 if sel.selectedIndex > -1:
108 ans[region] = sel.options[sel.selectedIndex].value
109 return ans
110
111
112 def groups():
113 return {'header': _('Header'), 'footer': _('Footer'),
114 'left-margin': _('Left margin'), 'right-margin': _('Right margin'),
115 'controls_footer': _('Controls footer'),
116 }
117
118
119 def restore_defaults():
120 container = document.getElementById(CONTAINER)
121 for which in Object.keys(groups()):
122 table = container.querySelector(f'table[data-which={which}]')
123 apply_setting(table, session_defaults()[which] or {})
124
125
126 def create_head_foot_panel(container, apply_func, cancel_func):
127 gr = groups()
128 container.appendChild(E.div(id=CONTAINER))
129 container = container.lastChild
130
131 for key in gr:
132 s = 'margin: 1rem;'
133 if container.childNodes.length > 0:
134 s += 'margin-top: 0;'
135 container.appendChild(E.h4(gr[key], style=s))
136 container.appendChild(create_items(key))
137 container.appendChild(E.hr(style='margin-top: 1ex; margin-bottom: 1ex'))
138 container.removeChild(container.lastChild)
139
140 sd = get_session_data()
141 for which in Object.keys(gr):
142 table = container.querySelector(f'table[data-which={which}]')
143 apply_setting(table, sd.get(which) or {})
144 container.appendChild(E.div(style='margin: 1rem', create_button_box(restore_defaults, apply_func, cancel_func)))
145
146
147 def commit_head_foot(onchange, container):
148 sd = get_session_data()
149 changed = False
150 for which in Object.keys(groups()):
151 prev = sd.get(which) or {}
152 table = container.querySelector(f'table[data-which={which}]')
153 current = get_setting(table)
154 for region in 'left middle right'.split(' '):
155 if prev[region] is not current[region]:
156 changed = True
157 sd.set(which, get_setting(table))
158
159 if changed:
160 onchange()
161
162
163 if window?.Intl?.DateTimeFormat:
164 time_formatter = window.Intl.DateTimeFormat(undefined, {'hour': 'numeric', 'minute': 'numeric'})
165 else:
166 time_formatter = {'format': def (date):
167 return '{}:{}'.format(date.getHours(), date.getMinutes())
168 }
169
170
171 def set_time_formatter(func):
172 nonlocal time_formatter
173 time_formatter = {'format': func}
174
175
176 def format_time_left(seconds):
177 hours, minutes = divmod(int(seconds / 60), 60)
178 if hours <= 0:
179 if minutes < 1:
180 return _('almost done')
181 minutes = minutes
182 return ngettext('{} min', '{} mins', minutes).format(minutes)
183 if not minutes:
184 return ngettext('{} hour', '{} hours', hours).format(hours)
185 return _('{} h {} mins').format(hours, minutes)
186
187
188 def format_pos(progress_frac, length):
189 if length < 1:
190 return ''
191 pages = Math.ceil(length / CHARS_PER_PAGE)
192 pos = progress_frac * pages
193 return f'{pos:.1f} / {pages}'
194
195
196 def render_head_foot(div, which, region, metadata, current_toc_node, current_toc_toplevel_node, page_list, book_time, chapter_time, pos, override, view_mode):
197 template = get_session_data().get(which) or {}
198 field = template[region] or 'empty'
199 interface_data = get_interface_data()
200 text = ''
201 has_clock = False
202 div.style.textOverflow = 'ellipsis'
203 div.style.overflow = 'hidden'
204 force_display_even_if_overflowed = False
205 if override:
206 text = override
207 elif field is 'menu-icon-on-hover':
208 clear(div)
209 div.appendChild(E.div(class_='visible-on-hover', E.span(_('Show controls')), title=_('Show viewer controls'), style='cursor: pointer'))
210 return has_clock
211 elif field is 'progress':
212 percent = min(100, max(Math.round(pos.progress_frac * 100), 0))
213 text = percent + '%'
214 force_display_even_if_overflowed = True
215 elif field is 'title':
216 text = metadata.title or _('Untitled')
217 elif field is 'authors':
218 text = ' & '.join(metadata.authors or [])
219 elif field is 'series':
220 if metadata.series:
221 ival = fmt_sidx(metadata.series_index, use_roman=interface_data.use_roman_numerals_for_series_number)
222 text = _('{0} of {1}').format(ival, metadata.series)
223 elif field is 'clock':
224 force_display_even_if_overflowed = True
225 text = time_formatter.format(Date())
226 has_clock = True
227 elif field is 'section':
228 text = current_toc_node.title if current_toc_node else ''
229 elif field is 'top-section':
230 text = current_toc_toplevel_node.title if current_toc_toplevel_node else ''
231 if not text:
232 text = current_toc_node.title if current_toc_node else ''
233 elif field is 'view-mode':
234 text = _('Paged') if view_mode is 'paged' else _('Flow')
235 elif field is 'view-mode-icon':
236 text = '📄' if view_mode is 'paged' else '📜'
237 elif field.startswith('time-'):
238 if book_time is None or chapter_time is None:
239 text = _('Calculating...')
240 else:
241 if field is 'time-book':
242 text = format_time_left(book_time)
243 elif field is 'time-chapter':
244 text = format_time_left(chapter_time)
245 else:
246 text = '{} ({})'.format(format_time_left(chapter_time), format_time_left(book_time))
247 elif field.startswith('pos-'):
248 if field is 'pos-book':
249 text = format_pos(pos.progress_frac, pos.book_length)
250 else:
251 text = format_pos(pos.file_progress_frac, pos.chapter_length)
252 elif field is 'pages-progress':
253 if pos.page_counts:
254 text = f'{pos.page_counts.current + 1} / {pos.page_counts.total}'
255 else:
256 text = _('Unknown')
257 elif field is 'page-list':
258 if page_list and page_list.length > 0:
259 if page_list.length is 1:
260 text = page_list[0].pagenum
261 else:
262 text = f'{page_list[0].pagenum} - {page_list[-1].pagenum}'
263 elif field is 'page-list-with-total':
264 if page_list and page_list.length > 0:
265 if page_list.length is 1:
266 text = page_list[0].pagenum
267 else:
268 text = f'{page_list[0].pagenum} - {page_list[-1].pagenum}'
269 full_page_list = current_book().manifest.page_list
270 if full_page_list:
271 text = f'{text} / {full_page_list[-1].pagenum}'
272 if not text:
273 text = '\xa0'
274 if text is not div.textContent:
275 div.textContent = text
276 if force_display_even_if_overflowed:
277 div.style.textOverflow = 'clip'
278 div.style.overflow = 'visible'
279 return has_clock