id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
26,500
ui.pyj
kovidgoyal_calibre/src/pyj/book_list/ui.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods from dom import ensure_id, clear from elementmaker import E from book_list.constants import book_list_container_id from book_list.globals import get_current_query from book_list.router import push_state from book_list.library_data import current_library_id, current_virtual_library from utils import encode_query_with_path panel_handlers = {} default_panel_handler = None def set_panel_handler(panel, handler): panel_handlers[panel] = handler def set_default_panel_handler(handler): nonlocal default_panel_handler default_panel_handler = handler def develop_panel(container_id): # To use, go to URL: # http://localhost:8080/#panel=develop-widgets&widget_module=<module name> # Implement the develop(container) method in that module. container = document.getElementById(container_id) q = get_current_query() m = q.widget_module if m: m = get_module(m) if m?.develop: m.develop(container) else: container.textContent = 'The module {} either does not exist or has no develop method.'.format(q.widget_module) set_panel_handler('develop-widgets', develop_panel) def currently_showing_panel(): c = document.getElementById(book_list_container_id) return c.dataset.panel def add_library_info(query): if not query.library_id: query.library_id = current_library_id() if not query.vl: if query.vl is None: v'delete query.vl' else: vlid = current_virtual_library() if vlid: query.vl = vlid def prepare_query(query, panel): q = {k:query[k] for k in (query or {}) if k is not 'panel'} if panel is not 'home': q.panel = panel add_library_info(q) return q def query_as_href(query, panel): q = prepare_query(query, panel or 'book_list') return encode_query_with_path(q) def show_panel(panel, query=None, replace=False): push_state(prepare_query(query, panel), replace=replace) def apply_url_state(state): panel = state.panel or 'home' c = document.getElementById(book_list_container_id) clear(c) c.appendChild(E.div()) c.dataset.panel = panel handler = panel_handlers[panel] or default_panel_handler handler(ensure_id(c.firstChild, 'panel')) apply_url_state.back_from_current = def back_from_current(current_query): q = current_query if q.panel: if '^' in q.panel: q = {k:q[k] for k in q} q.panel = q.panel.rpartition('^')[0] elif q.panel is 'book_list': q = {} else: q = {'panel':'book_list'} add_library_info(q) return q
2,822
Python
.py
75
31.746667
123
0.677431
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,501
__init__.pyj
kovidgoyal_calibre/src/pyj/book_list/__init__.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
98
Python
.py
2
48
72
0.770833
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,502
edit_metadata.pyj
kovidgoyal_calibre/src/pyj/book_list/edit_metadata.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E import traceback from ajax import ajax_send from book_list.book_details import ( add_stars_to, basic_table_rules, fetch_metadata, field_sorter, no_book, report_load_failure ) from book_list.comments_editor import ( create_comments_editor, focus_comments_editor, get_comments_html, set_comments_html ) from book_list.globals import get_current_query, book_whose_metadata_is_being_edited from book_list.library_data import ( book_metadata, cover_url, current_library_id, field_names_for, library_data, load_status, loaded_book_ids, set_book_metadata ) from book_list.router import back, push_state, show_note from book_list.theme import get_color from book_list.top_bar import create_top_bar, set_title from book_list.ui import set_panel_handler, show_panel from date import UNDEFINED_DATE_ISO, format_date from dom import add_extra_css, build_rule, clear, svgicon from file_uploads import update_status_widget, upload_files_widget, upload_status_widget from gettext import gettext as _ from modals import error_dialog, question_dialog from session import get_interface_data from utils import conditional_timeout, fmt_sidx, parse_url_params, safe_set_inner_html from widgets import create_button CLASS_NAME = 'edit-metadata-panel' IGNORED_FIELDS = {'sort', 'uuid', 'id', 'urls_from_identifiers', 'lang_names', 'last_modified', 'path', 'marked', 'size', 'ondevice', 'cover', 'au_map', 'isbn', 'in_tag_browser'} def identity(x): return x value_to_json = identity changes = {} has_changes = False add_extra_css(def(): sel = '.' + CLASS_NAME + ' ' style = basic_table_rules(sel) style += build_rule(sel + 'table.metadata', width='100%') style += build_rule(sel + 'table.metadata td', padding_bottom='0.5ex', padding_top='0.5ex', cursor='pointer') style += build_rule(sel + 'table.metadata tr:hover td:first-of-type', color='green') style += build_rule(sel + 'table.metadata tr:active', transform='scale(1.5)') style += build_rule(sel + '.completions', display='flex', flex_wrap='wrap', align_items='center', margin_bottom='0.5ex') style += build_rule(sel + '.completions > div', margin='0.5ex 0.5rem', margin_left='0', padding='0.5ex 0.5rem', border='solid 1px currentColor', border_radius='1ex', cursor='pointer') style += build_rule(sel + '.completions > div:active', transform='scale(1.5)') style += build_rule(sel + '.completions > div:hover', background=get_color('window-foreground'), color=get_color('window-background')) style += build_rule(sel + '.rating-edit-container', display='flex', flex_wrap='wrap', align_items='center', list_style_type='none') style += build_rule(sel + '.rating-edit-container > li', margin='0.5ex 0.5rem', margin_left='0', padding='0.5ex 0.5rem', border='solid 1px currentColor', border_radius='1ex', cursor='pointer') style += build_rule(sel + '.rating-edit-container > li.current-rating', color=get_color('window-background'), background=get_color('window-foreground')) return style ) def resolved_metadata(mi, field): if Object.prototype.hasOwnProperty.call(changes, field): return changes[field] return mi[field] def resolved_formats(val): val = list(val or v'[]') if changes.added_formats: for data in changes.added_formats: ext = data.ext.toUpperCase() if ext and ext not in val: val.push(ext) if changes.removed_formats: for fmt in changes.removed_formats: fmt = fmt.toUpperCase() if fmt in val: val.remove(fmt) val.sort() return val def truncated_html(val): ans = val.replace(/<[^>]+>/g, '') if ans.length > 40: ans = ans[:40] + '…' return ans def onsubmit_field2(container_id, book_id, field, value): nonlocal has_changes c = document.getElementById(container_id) if not c: return d = c.querySelector('div[data-ctype="edit"]') if not d: return is_series = value.series_index is not undefined if is_series: unchanged = value.series_name is book_metadata(book_id)[field] and value.series_index is book_metadata(book_id)[field + '_index'] else: unchanged = value is book_metadata(book_id)[field] if unchanged: on_close(container_id) return clear(d) d.appendChild(E.div(style='margin: 1ex 1rem', _('Contacting server, please wait') + '…')) if is_series: changes[field] = value_to_json(value.series_name) changes[field + '_index'] = float(value.series_index) else: changes[field] = value_to_json(value) has_changes = True show_book(container_id, book_id) on_close(container_id) def onsubmit_field(get_value, container_id, book_id, field): c = document.getElementById(container_id) if not c: return d = c.querySelector('div[data-ctype="edit"]') if not d: return if get_value is html_edit_get_value: html_edit_get_value(d, onsubmit_field2.bind(None, container_id, book_id, field)) else: ok, value = get_value(d) if not ok: return # needed to avoid console error about form submission failing because form is removed from DOM in onsubmit handler window.setTimeout(onsubmit_field2, 0, container_id, book_id, field, value) def create_form(widget, get_value, container_id, book_id, field): submit_action = onsubmit_field.bind(None, get_value, container_id, book_id, field) button = create_button(_('OK'), action=submit_action) widget.classList.add('metadata-editor') form = E.form( action='javascript: void(0)', onsubmit=submit_action, style='margin: 1ex auto', E.div(widget, style='margin-bottom: 1ex'), E.div(class_='edit-form-button-container', button), E.input(type='submit', style='display:none'), ) return form # Simple line edit {{{ def line_edit_get_value(container): return True, container.querySelector('input[type="text"]').value def simple_line_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json name = fm.name or field le = E.input(type='text', name=name.replace('#', '_c_'), autocomplete=True, style='width: 100%') le.value = resolved_metadata(mi, field) or '' form = create_form(le, line_edit_get_value, container_id, book_id, field) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) le.focus(), le.select() value_to_json = identity # }}} # Text edit {{{ def text_edit_get_value(container): return True, container.querySelector('textarea').value def text_edit(container_id, book_id, field, fm, div, mi, get_name): nonlocal value_to_json name = fm.name or field le = E.textarea(name=name.replace('#', '_c_'), spellcheck='true', wrap='soft', style='width: 100%; min-height: 70vh') le.value = resolved_metadata(mi, get_name or field) or '' form = create_form(le, text_edit_get_value, container_id, book_id, field) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) le.focus() def html_edit_get_value(container, proceed): get_comments_html(container, def (html, data): proceed(html) ) def html_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json value_to_json = identity val = resolved_metadata(mi, field) or '' name = fm.name or field c = E.div(style='width: 100%; min-height: 75vh') form = create_form(c, html_edit_get_value, container_id, book_id, field) editor = create_comments_editor(c) set_comments_html(c, val) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) focus_comments_editor(c) value_to_json = identity editor.init() # }}} # Number edit {{{ def number_edit_get_value(container): return True, container.querySelector('input[type="number"]').value def number_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json name = fm.name or field le = E.input(type='number', name=name.replace('#', '_c_'), step='any' if fm.datatype is 'float' else '1') val = resolved_metadata(mi, field) if val?: le.value = val else: le.value = '' form = create_form(le, number_edit_get_value, container_id, book_id, field) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) le.focus(), le.select() def safe_parse(x): f = parseFloat if fm.datatype is 'float' else parseInt ans = f(x) if isNaN(ans): ans = None return ans value_to_json = safe_parse # }}} # Line edit with completions {{{ def remove_item(container_id, name): c = document.getElementById(container_id) if not c: return le = c.querySelector('[data-ctype="edit"] input') val = le.value or '' val = value_to_json(val) val = [x for x in val if x is not name] le.value = val.join(update_completions.list_to_ui) le.focus() line_edit_updated(container_id, le.dataset.field) def add_completion(container_id, name): c = document.getElementById(container_id) if not c: return le = c.querySelector('[data-ctype="edit"] input') val = le.value or '' val = value_to_json(val) if jstype(val) is 'string': le.value = name elif val: if val.length: val[-1] = name else: val.push(name) le.value = val.join(update_completions.list_to_ui) + update_completions.list_to_ui le.focus() line_edit_updated(container_id, le.dataset.field) def show_completions(container_id, div, field, prefix, names): clear(div) completions = E.div(class_='completions') if names.length: div.appendChild(E.div(_('Tap to add:'))) div.appendChild(completions) for i, name in enumerate(names): completions.appendChild(E.div(E.span(style='color: green', svgicon('plus'), '\xa0'), name, onclick=add_completion.bind(None, container_id, name))) if i >= 50: break def query_contains(haystack, needle): return haystack.toLowerCase().indexOf(needle) is not -1 def query_startswitch(haystack, needle): return haystack.toLowerCase().indexOf(needle) is 0 def update_removals(container_id): c = document.getElementById(container_id) if not c: return d = c.querySelector('div[data-ctype="edit"]') if not d or d.style.display is not 'block': return div = d.lastChild.previousSibling clear(div) val = d.querySelector('input')?.value or '' val = value_to_json(val) if jstype(val) is 'string' or not val.length: return div.appendChild(E.div(_('Tap to remove:'))) removals = E.div(class_='completions') div.appendChild(removals) for i, name in enumerate(val): removals.appendChild(E.div(E.span(style='color: ' + get_color('window-error-foreground'), svgicon('eraser'), '\xa0'), name, onclick=remove_item.bind(None, container_id, name))) if i >= 50: break def update_completions(container_id, ok, field, names): c = document.getElementById(container_id) if not c: return d = c.querySelector('div[data-ctype="edit"]') if not d or d.style.display is not 'block': return div = d.lastChild clear(div) if not ok: err = E.div() safe_set_inner_html(err, names) div.appendChild(E.div( _('Failed to download items for completion, with error:'), err )) return val = d.querySelector('input').value or '' val = value_to_json(val) if jstype(val) is 'string': prefix = val else: prefix = val[-1] if val.length else '' if prefix is update_completions.prefix: return needle = prefix.toLowerCase().strip() if needle: interface_data = get_interface_data() universe = update_completions.names if update_completions.prefix and needle.startswith(update_completions.prefix.toLowerCase()) else names q = query_contains if interface_data.completion_mode is 'contains' else query_startswitch matching_names = [x for x in universe if q(x, needle) and x is not prefix] else: matching_names = [] update_completions.prefix = prefix update_completions.names = matching_names show_completions(container_id, div, field, prefix, matching_names) update_completions.list_to_ui = None update_completions.names = v'[]' update_completions.prefix = '' def line_edit_updated(container_id, field): field_names_for(field, update_completions.bind(None, container_id)) update_removals(container_id) def multiple_line_edit(list_to_ui, ui_to_list, container_id, book_id, field, fm, div, mi): nonlocal value_to_json update_completions.list_to_ui = list_to_ui name = fm.name or field le = E.input( type='text', name=name.replace('#', '_c_'), style='width: 100%', autocomplete='off', data_field=field, oninput=line_edit_updated.bind(None, container_id, field) ) val = (resolved_metadata(mi, field) or v'[]') if field is 'languages': ln = mi.lang_names or {} val = [ln[l] or l for l in val] if list_to_ui: val = val.join(list_to_ui) le.value = val form = create_form(le, line_edit_get_value, container_id, book_id, field) if list_to_ui: div.appendChild(E.div(style='margin: 0.5ex 1rem', _( 'Edit the "{0}" below. Multiple items can be separated by "{1}".').format(name, list_to_ui.strip()))) else: div.appendChild(E.div(style='margin: 0.5ex 1rem', _( 'Edit the "{0}" below.').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) div.appendChild(E.div(style='margin: 0.5ex 1rem')) div.appendChild(E.div(E.span(_('Loading all {}...').format(name)), style='margin: 0.5ex 1rem')) le.focus(), le.select() if list_to_ui: value_to_json = def(raw): seen = {} ans = v'[]' for x in [a.strip() for a in raw.split(ui_to_list) if a.strip()]: if not seen[x]: seen[x] = True ans.push(x) return ans else: value_to_json = identity field_names_for(field, update_completions.bind(None, container_id)) update_removals(container_id) # }}} # Series edit {{{ def series_edit_get_value(container): val = { 'series_name': container.querySelector('input[type="text"]').value, 'series_index': parseFloat(parseFloat(container.querySelector('input[type="number"]').value).toFixed(2)), } return True, val def series_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json name = fm.name or field le = E.input(type='text', name=name.replace('#', '_c_'), style='width: 100%', oninput=line_edit_updated.bind(None, container_id, field), data_field=field) le.value = resolved_metadata(mi, field) or '' value_to_json = identity ne = E.input(type='number', step='any', name=name.replace('#', '_c_') + '_index') ne.value = parseFloat(parseFloat(resolved_metadata(mi, field + '_index')).toFixed(2)) table = E.table(style='width: 100%', E.tr(E.td(_('Name:') + '\xa0'), E.td(le, style='width: 99%; padding-bottom: 1ex')), E.tr(E.td(_('Number:') + '\xa0'), E.td(ne)) ) form = create_form(table, series_edit_get_value, container_id, book_id, field) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below.').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) div.appendChild(E.div(style='margin: 0.5ex 1rem')) div.appendChild(E.div(E.span(_('Loading all {}...').format(name)), style='margin: 0.5ex 1rem')) le.focus(), le.select() field_names_for(field, update_completions.bind(None, container_id)) # }}} # Date edit {{{ def date_edit_get_value(container): return True, container.querySelector('input[type="date"]').value def date_to_datetime(raw): if not raw: return UNDEFINED_DATE_ISO return raw + 'T12:00:00+00:00' # we use 12 so that the date is the same in most timezones def date_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json value_to_json = date_to_datetime name = fm.name or field le = E.input(type='date', name=name.replace('#', '_c_'), min=UNDEFINED_DATE_ISO.split('T')[0], pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}") val = resolved_metadata(mi, field) or '' if val: val = format_date(val, 'yyyy-MM-dd') le.value = val or '' form = create_form(le, date_edit_get_value, container_id, book_id, field) def clear(ev): ev.currentTarget.closest('form').querySelector('input').value = '' def today(ev): ev.currentTarget.closest('form').querySelector('input').value = Date().toISOString().substr(0, 10) form.firstChild.appendChild( E.span( '\xa0', create_button(_('Clear'), action=clear), '\xa0', create_button(_('Today'), action=today), )) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below.').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) le.focus(), le.select() # }}} # Identifiers edit {{{ def remove_identifier(evt): li = evt.currentTarget.closest('li') li.parentNode.removeChild(li) def add_identifier(container_id, name, val): c = document.getElementById(container_id)?.querySelector('.identifiers-edit') if not c: return b = create_button(_('Remove'), action=remove_identifier) c.appendChild(E.li(style='padding-bottom: 1ex; margin-bottom: 1ex; border-bottom: solid 1px currentColor', E.table(style='width: 100%', E.tr(E.td(_('Type:') + '\xa0'), E.td(style='padding-bottom: 1ex; width: 99%', E.input(type='text', style='width:100%', autocomplete=True, value=name or '')), E.td(rowspan='2', style='padding: 0.5ex 1rem; vertical-align: middle', b)), E.tr(E.td(_('Value:') + '\xa0'), E.td(E.input(type='text', style='width: 100%', autocomplete=True, value=val or ''))), ))) def identifiers_get_value(container): ans = {} for li in container.querySelectorAll('.identifiers-edit > li'): n, v = li.querySelectorAll('input') n, v = n.value, v.value if n and v: ans[n] = v return True, ans def identifiers_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json name = fm.name or field val = resolved_metadata(mi, 'identifiers') or {} c = E.ul(class_='identifiers-edit', style='list-style-type: none') form = create_form(c, identifiers_get_value, container_id, book_id, field) bc = form.querySelector('.edit-form-button-container') bc.insertBefore(create_button(_('Add identifier'), None, add_identifier.bind(None, container_id, '', '')), bc.firstChild) bc.insertBefore(document.createTextNode('\xa0'), bc.lastChild) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below.').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) for k in Object.keys(val): add_identifier(container_id, k, val[k]) value_to_json = identity # }}} # Rating edit {{{ def rating_get_value(container): return True, parseInt(container.querySelector('.current-rating[data-rating]').getAttribute('data-rating')) def set_rating(evt): li = evt.currentTarget for nli in li.closest('ul').childNodes: nli.classList.remove('current-rating') li.classList.add('current-rating') def rating_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json val = resolved_metadata(mi, field) or 0 numbers = list(range(11)) if fm.display?.allow_half_stars else list(range(0, 11, 2)) name = fm.name or field c = E.ul(class_='rating-edit-container') for n in numbers: s = E.li(data_rating=n + '', onclick=set_rating) c.appendChild(s) if n is val: s.classList.add('current-rating') if n: add_stars_to(s, n, numbers.length > 6) else: s.appendChild(document.createTextNode(_('Unrated'))) form = create_form(c, rating_get_value, container_id, book_id, field) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Choose the "{}" below').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) value_to_json = identity # }}} # Enum edit {{{ def enum_get_value(container): return True, container.querySelector('.current-rating[data-rating]').getAttribute('data-rating') def enum_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json val = resolved_metadata(mi, field) or '' name = fm.name or field c = E.ul(class_='rating-edit-container') for n in v'[""]'.concat(fm.display.enum_values): s = E.li(data_rating=n + '', onclick=set_rating) c.appendChild(s) if n is val: s.classList.add('current-rating') s.appendChild(document.createTextNode(n or _('Blank'))) form = create_form(c, enum_get_value, container_id, book_id, field) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Choose the "{}" below').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) value_to_json = identity # }}} # Bool edit {{{ def bool_edit(container_id, book_id, field, fm, div, mi): nonlocal value_to_json val = resolved_metadata(mi, field) if val: val = 'y' else: if val is False: val = 'n' else: val = '' name = fm.name or field c = E.ul(class_='rating-edit-container') names = {'': _('Blank'), 'y': _('Yes'), 'n': _('No')} for n in v"['', 'y', 'n']": s = E.li(data_rating=n + '', onclick=set_rating) c.appendChild(s) if n is val: s.classList.add('current-rating') s.appendChild(document.createTextNode(names[n])) form = create_form(c, enum_get_value, container_id, book_id, field) div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Choose the "{}" below').format(name))) div.appendChild(E.div(style='margin: 0.5ex 1rem', form)) val_map = {'': None, 'y': True, 'n': False} value_to_json = def(x): return val_map[x] # }}} # Cover edit {{{ def cover_chosen(top_container_id, book_id, container_id, files): nonlocal has_changes container = document.getElementById(container_id) if not container: return if not files[0]: return file = files[0] changes.cover = file has_changes = True on_close(top_container_id) cover_chosen.counter = 0 def remove_cover(top_container_id, book_id): nonlocal has_changes changes.cover = '--remove--' has_changes = True on_close(top_container_id) def cover_edit(container_id, book_id, field, fm, div, mi): upload_files_widget(div, cover_chosen.bind(None, container_id, book_id), _( 'Change the cover by <a>selecting the cover image</a> or drag and drop of the cover image here.'), single_file=True, accept_extensions='png jpeg jpg') div.appendChild(E.div( style='padding: 1rem', create_button(_('Remove existing cover'), action=remove_cover.bind(None, container_id, book_id)))) # }}} # Formats edit {{{ def format_added(top_container_id, book_id, container_id, files): nonlocal has_changes container = document.getElementById(container_id) if not container: return if not files[0]: return added = changes.added_formats or v'[]' for file in files: ext = file.name.rpartition('.')[-1] data = {'name': file.name, 'size': file.size, 'type': file.type, 'data_url': None, 'ext': ext} added.push(data) r = FileReader() r.onload = def(evt): data.data_url = evt.target.result r.readAsDataURL(file) changes.added_formats = added has_changes = True on_close(top_container_id) def remove_format(top_container_id, book_id, fmt): nonlocal has_changes has_changes = True removed_formats = changes.removed_formats or v'[]' removed_formats.push(fmt.toUpperCase()) changes.removed_formats = removed_formats on_close(top_container_id) def formats_edit(container_id, book_id, field, fm, div, mi): upload_files_widget(div, format_added.bind(None, container_id, book_id), _( 'Add a format by <a>selecting the book file</a> or drag and drop of the book file here.'), single_file=True) remove_buttons = E.div(style='padding: 1rem; display: flex; flex-wrap: wrap; align-content: flex-start') formats = resolved_formats(mi.formats) for i, fmt in enumerate(formats): remove_buttons.appendChild(create_button( _('Remove {}').format(fmt.upper()), action=remove_format.bind(None, container_id, book_id, fmt.upper()))) remove_buttons.lastChild.style.marginBottom = '1ex' remove_buttons.lastChild.style.marginRight = '1rem' div.appendChild(remove_buttons) # }}} def switch_to_edit_panel(container): d = container.querySelector('div[data-ctype="edit"]') d.style.display = 'block' d.previousSibling.style.display = 'none' clear(d) return d def edit_field(container_id, book_id, field): nonlocal value_to_json fm = library_data.field_metadata[field] c = document.getElementById(container_id) mi = book_metadata(book_id) if not c or not fm or not mi: return d = switch_to_edit_panel(c) update_completions.ui_to_list = None update_completions.list_to_ui = None update_completions.names = v'[]' update_completions.prefix = '' if field is 'authors': multiple_line_edit(' & ', '&', container_id, book_id, field, fm, d, mi) elif field is 'cover': cover_edit(container_id, book_id, field, fm, d, mi) elif field is 'formats': formats_edit(container_id, book_id, field, fm, d, mi) elif fm.datatype is 'series': series_edit(container_id, book_id, field, fm, d, mi) elif fm.datatype is 'datetime': date_edit(container_id, book_id, field, fm, d, mi) elif fm.datatype is 'rating': rating_edit(container_id, book_id, field, fm, d, mi) elif fm.datatype is 'enumeration': enum_edit(container_id, book_id, field, fm, d, mi) elif fm.datatype is 'bool': bool_edit(container_id, book_id, field, fm, d, mi) elif fm.datatype is 'int' or fm.datatype is 'float': number_edit(container_id, book_id, field, fm, d, mi) elif field is 'identifiers': identifiers_edit(container_id, book_id, field, fm, d, mi) elif fm.datatype is 'comments' or field is 'comments': ias = fm.display?.interpret_as if ias is 'short-text': simple_line_edit(container_id, book_id, field, fm, d, mi) elif ias is 'long-text': text_edit(container_id, book_id, field, fm, d, mi) elif ias is 'markdown': text_edit(container_id, book_id, field, fm, d, mi, field + '#markdown#') else: html_edit(container_id, book_id, field, fm, d, mi) else: if fm.link_column: multiple_line_edit(fm.is_multiple?.list_to_ui, fm.is_multiple?.ui_to_list, container_id, book_id, field, fm, d, mi) else: simple_line_edit(container_id, book_id, field, fm, d, mi) if field is 'title': value_to_json = def(x): return x or _('Untitled') elif field is 'authors': value_to_json = def(x): ans = [a.strip() for a in x.split('&') if a.strip()] if not ans.length: ans = [_('Unknown')] return ans def render_metadata(mi, table, container_id, book_id): # {{{ field_metadata = library_data.field_metadata interface_data = get_interface_data() current_edit_action = None def allowed_fields(field): fm = field_metadata[field] if not fm: return False if field.endswith('_index'): pfm = field_metadata[field[:-len('_index')]] if pfm and pfm.datatype is 'series': return False if fm.datatype is 'composite': return False if field.startswith('#'): return True if field in IGNORED_FIELDS or field.endswith('_sort') or field[0] is '@': return False return True fields = library_data.book_display_fields if not fields or not fields.length: fields = sorted(filter(allowed_fields, mi), key=field_sorter(field_metadata)) else: fields = filter(allowed_fields, fields) fields = list(fields) added_fields = {f:True for f in fields} if not added_fields.title: added_fields.title = True fields.insert(0, 'title') for other_field in Object.keys(library_data.field_metadata): if not added_fields[other_field] and allowed_fields(other_field) and other_field not in IGNORED_FIELDS: fields.push(other_field) def add_row(name, val, is_html=False, join=None): if val is undefined or val is None: val = v'[" "]' if join else '\xa0' def add_val(v): if not v.appendChild: v += '' if v.appendChild: table.lastChild.lastChild.appendChild(v) else: table.lastChild.lastChild.appendChild(document.createTextNode(v)) table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td())) if is_html: table.lastChild.lastChild.appendChild(document.createTextNode(truncated_html(val + ''))) else: if not join: add_val(val) else: for v in val: add_val(v) if v is not val[-1]: table.lastChild.lastChild.appendChild(document.createTextNode(join)) return table.lastChild.lastChild def process_composite(field, fm, name, val): if fm.display and fm.display.contains_html: add_row(name, val, is_html=True) elif fm.is_multiple and fm.is_multiple.list_to_ui: all_vals = filter(None, map(str.strip, val.split(fm.is_multiple.list_to_ui))) add_row(name, all_vals, join=fm.is_multiple.list_to_ui) else: add_row(name, val) def process_authors(field, fm, name, val): add_row(name, val, join=' & ') def process_publisher(field, fm, name, val): add_row(name, val) def process_rating(field, fm, name, val): stars = E.span() val = int(val or 0) if val > 0: for i in range(val // 2): stars.appendChild(svgicon('star')) if fm.display.allow_half_stars and (val % 2): stars.appendChild(svgicon('star-half')) add_row(name, stars) else: add_row(name, None) def process_identifiers(field, fm, name, val): if val: keys = Object.keys(val) if keys.length: table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td())) td = table.lastChild.lastChild for k in keys: if td.childNodes.length: td.appendChild(document.createTextNode(', ')) td.appendChild(document.createTextNode(k)) return add_row(name, None) def process_languages(field, fm, name, val): if val and val.length: table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td())) td = table.lastChild.lastChild for k in val: lang = k if mi.lang_names and mi.lang_names[k]: lang = mi.lang_names[k] td.appendChild(document.createTextNode(lang)) if k is not val[-1]: td.appendChild(document.createTextNode(', ')) return add_row(name, None) def process_datetime(field, fm, name, val): if val: fmt = interface_data['gui_' + field + '_display_format'] or (fm['display'] or {}).date_format add_row(name, format_date(val, fmt)) else: add_row(name, None) def process_series(field, fm, name, val): if val: ifield = field + '_index' try: ival = float(resolved_metadata(mi, ifield)) except Exception: ival = 1.0 ival = fmt_sidx(ival, use_roman=interface_data.use_roman_numerals_for_series_number) table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td())) s = safe_set_inner_html(E.span(), _('{0} of <i>{1}</i>').format(ival, val)) table.lastChild.lastChild.appendChild(s) else: add_row(name, None) def process_formats(field, fm, name, val): val = resolved_formats(val) if val.length: join = fm.is_multiple.list_to_ui if fm.is_multiple else None add_row(name, val, join=join) else: add_row(name, None) def process_field(field, fm): name = fm.name or field datatype = fm.datatype val = resolved_metadata(mi, field) if field is 'comments' or datatype is 'comments': add_row(name, truncated_html(val or '')) return func = None if datatype is 'composite': func = process_composite elif datatype is 'rating': func = process_rating elif field is 'identifiers': func = process_identifiers elif field is 'authors': func = process_authors elif field is 'publisher': func = process_publisher elif field is 'languages': func = process_languages elif field is 'formats': func = process_formats elif datatype is 'datetime': func = process_datetime elif datatype is 'series': func = process_series if func: func(field, fm, name, val) else: if datatype is 'text' or datatype is 'enumeration': if val is not undefined and val is not None: join = fm.is_multiple.list_to_ui if fm.is_multiple else None add_row(name, val, join=join) else: add_row(name, None) elif datatype is 'bool': add_row(name, _('Yes') if val else (_('No') if val? else '')) elif datatype is 'int' or datatype is 'float': if val is not undefined and val is not None: fmt = (fm.display or {}).number_format if fmt: val = fmt.format(val) else: val += '' add_row(name, val) else: add_row(name, None) for field in fields: fm = field_metadata[field] if not fm: continue current_edit_action = edit_field.bind(None, container_id, book_id, field) try: process_field(field, fm) except Exception: print('Failed to render metadata field: ' + field) traceback.print_exc() current_edit_action = edit_field.bind(None, container_id, book_id, 'cover') table.appendChild(E.tr(onclick=current_edit_action, E.td(_('Cover')), E.td())) img = E.img( style='max-width: 100%; max-height: 400px', ) if changes.cover: if changes.cover is '--remove--': img.removeAttribute('src') changes.cover = None else: r = FileReader() r.onload = def(evt): img.src = evt.target.result changes.cover = evt.target.result r.readAsDataURL(changes.cover) v'delete changes.cover' else: img.src = cover_url(book_id) table.lastChild.lastChild.appendChild(img) # }}} def changes_submitted(container_id, book_id, end_type, xhr, ev): nonlocal changes, has_changes changes = {} has_changes = False if end_type is 'abort': on_close(container_id) return if end_type is not 'load': error_dialog(_('Failed to update metadata on server'), _( 'Updating metadata for the book: {} failed.').format(book_id), xhr.error_html) return try: dirtied = JSON.parse(xhr.responseText) except Exception as err: error_dialog(_('Could not update metadata for book'), _('Server returned an invalid response'), err.toString()) return cq = get_current_query() if cq.from_read_book: window.parent.postMessage( {'type': 'update_cached_book_metadata', 'library_id': cq.library_id, 'book_id': cq.book_id, 'metadata': dirtied[book_id], 'from_read_book': cq.from_read_book}, document.location.protocol + '//' + document.location.host ) else: for bid in dirtied: set_book_metadata(bid, dirtied[bid]) on_close(container_id) def on_progress(container_id, book_id, loaded, total, xhr): container = document.getElementById(container_id) if container and total: update_status_widget(container, loaded, total) def edit_note(field, item): show_note(field, 0, item, panel='edit_note') def show_select_panel(): q = parse_url_params() q.panel = 'select_item_for_edit_notes' push_state(q, replace=False) def select_item_for_edit_notes(container, mi): set_title(container, _('Edit notes')) field_metadata = library_data.field_metadata def allowed_fields(field): fm = field_metadata[field] if not fm: return False return library_data.fields_that_support_notes.indexOf(field) > -1 container.appendChild(E.div(style='padding: 0.5rem')) d = container.lastChild d.appendChild(E.div(svgicon('pencil'), ' ' , _('Tap on an item below to edit the notes associated with it.'), style='margin-bottom: 0.5rem')) dl = E.dl() fields = sorted(filter(allowed_fields, mi), key=field_sorter(field_metadata)) for field in fields: val = resolved_metadata(mi, field) fm = field_metadata[field] if val: dl.appendChild(E.dt(fm.name)) if jstype(val) is 'string': val = v'[val]' dd = E.dd(style='text-indent: 1em; margin-bottom: 0.5em') dl.appendChild(dd) for i, x in enumerate(val): a = E.a(x, href='javascript:void(0)', class_='blue-link', onclick=edit_note.bind(None, field, x)) dd.appendChild(a) if i < val.length - 1: dd.appendChild(document.createTextNode(fm.is_multiple.list_to_ui)) if dl.firstChild: d.appendChild(dl) else: d.appendChild(E.div(_('This book has no authors/series/etc. that can have notes added to them'))) def submit_changes(container_id, book_id): c = document.getElementById(container_id) d = c.querySelector('div[data-ctype="show"]') clear(d) d.appendChild(E.div(style='margin: 1ex 1rem', _('Uploading changes to server, please wait...'))) data = {'changes': changes, 'loaded_book_ids': loaded_book_ids()} w = upload_status_widget() d.appendChild(w) ajax_send( f'cdb/set-fields/{book_id}/{current_library_id()}', data, changes_submitted.bind(None, container_id, book_id), on_progress.bind(None, container_id, book_id)) def show_book(container_id, book_id): container = document.getElementById(container_id) mi = book_metadata(book_id) if not container or not mi: return div = container.querySelector('div[data-ctype="show"]') if not div: return clear(div) cq = get_current_query() if has_changes: b = create_button(_('Apply changes'), action=submit_changes.bind(None, container_id, book_id)) div.appendChild(E.div(style='margin: 1ex 1rem', b)) else: div.appendChild(E.div( style='margin: 1ex 1rem', E.div(_('Tap any field below to edit that field.')), E.div(E.a(svgicon('pencil'), '\xa0', _('Add notes for authors, series, etc.'), href='javascript:void(0)', onclick=show_select_panel, class_='blue-link'), style='display:' + ('none' if cq.from_read_book else 'block')), )) div.appendChild(E.table(class_='metadata')) render_metadata(mi, div.lastChild, container_id, book_id) if has_changes: b = create_button(_('Apply changes'), action=submit_changes.bind(None, container_id, book_id)) div.appendChild(E.div(style='margin: 1ex 1rem', b)) def is_edit_panel_showing(container): d = container.querySelector('div[data-ctype="edit"]') return bool(d and d.style.display is 'block') def close_edit_panel(container): d = container.querySelector('div[data-ctype="edit"]') d.style.display = 'none' d.previousSibling.style.display = 'block' clear(d), clear(d.previousSibling) def on_close(container_id): cq = get_current_query() if cq.panel is 'select_item_for_edit_notes': back() return c = document.getElementById(container_id) if c: if is_edit_panel_showing(c): close_edit_panel(c) q = parse_url_params() show_book(container_id, int(q.book_id)) c.querySelector(f'.{CLASS_NAME}').focus() return if cq.from_read_book: window.parent.postMessage( {'type': 'edit_metadata_closed', 'from_read_book': cq.from_read_book}, document.location.protocol + '//' + document.location.host ) else: if has_changes: question_dialog(_('Are you sure?'), _( 'Any changes you have made will be discarded.' ' Do you wish to discard all changes?'), def (yes): if yes: back() ) else: back() def proceed_after_succesful_fetch_metadata(container_id, book_id): nonlocal changes, has_changes changes = {} has_changes = False container = document.getElementById(container_id) mi = book_metadata(book_id) if not mi or not container: if get_current_query().from_read_book: container.textContent = _('Failed to read metadata for book') return show_panel('book_details', query=parse_url_params(), replace=True) return cq = get_current_query() clear(container.lastChild) if cq.panel is 'select_item_for_edit_notes': select_item_for_edit_notes(container, mi) return set_title(container, _('Edit metadata for {}').format(mi.title)) container.lastChild.appendChild(E.div(data_ctype='show', style='display:block')) container.lastChild.appendChild(E.div(data_ctype='edit', style='display:none')) show_book(container_id, book_id) def create_edit_metadata(container): q = parse_url_params() current_book_id = q.book_id if not current_book_id: no_book(container) return current_book_id = int(current_book_id) container_id = container.parentNode.id if not book_metadata(current_book_id): fetch_metadata(container_id, current_book_id, proceed_after_succesful_fetch_metadata) else: proceed_after_succesful_fetch_metadata(container_id, current_book_id) def check_for_books_loaded(): container = this if load_status.loading: conditional_timeout(container.id, 5, check_for_books_loaded) return container = container.lastChild clear(container) if not load_status.ok: report_load_failure(container) return create_edit_metadata(container) def handle_keypress(container_id, ev): if not ev.altKey and not ev.ctrlKey and not ev.metaKey and not ev.shiftKey: if ev.key is 'Escape': ev.preventDefault(), ev.stopPropagation() on_close(container_id) def init(container_id): container = document.getElementById(container_id) create_top_bar(container, title=_('Edit metadata'), action=on_close.bind(None, container_id), icon='close') container.appendChild(E.div(class_=CLASS_NAME, tabindex='0', onkeydown=handle_keypress.bind(None, container_id))) container.lastChild.focus() container.lastChild.appendChild(E.div(_('Loading books from the calibre library, please wait...'), style='margin: 1ex 1em')) conditional_timeout(container_id, 5, check_for_books_loaded) def init_select_item_for_edit_notes(container_id): q = parse_url_params() book_whose_metadata_is_being_edited(int(q.book_id)) container = document.getElementById(container_id) create_top_bar(container, title=_('Edit metadata'), action=on_close.bind(None, container_id), icon='close') container.appendChild(E.div(class_=CLASS_NAME, tabindex='0', onkeydown=handle_keypress.bind(None, container_id))) container.lastChild.focus() container.lastChild.appendChild(E.div(_('Loading books from the calibre library, please wait...'), style='margin: 1ex 1em')) conditional_timeout(container_id, 5, check_for_books_loaded) set_panel_handler('edit_metadata', init) set_panel_handler('select_item_for_edit_notes', init_select_item_for_edit_notes)
46,048
Python
.py
1,048
36.444656
245
0.632478
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,503
top_bar.pyj
kovidgoyal_calibre/src/pyj/book_list/top_bar.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from book_list.theme import get_color, get_font_size from dom import set_css, clear, create_keyframes, build_rule, svgicon, add_extra_css from elementmaker import E from gettext import gettext as _ from session import get_interface_data bar_counter = 0 CLASS_NAME = 'main-top-bar' SPACING = '0.75em' VSPACING = '0.5ex' THROBBER_NAME = 'top-bar-throbber' add_extra_css(def(): sel = '.' + CLASS_NAME + ' ' style = '' style += create_keyframes(THROBBER_NAME, 'from { transform: scale(1); } 50% { transform: scale(0.5); } to { transform: scale(1); }') style += build_rule(sel + 'a', display='inline-block', vertical_align='middle', overflow='hidden', cursor='pointer', color=get_color('bar-foreground'), background='none', padding_top=VSPACING, padding_bottom=VSPACING) style += build_rule(sel + 'a:hover', transform='scale(1.5)') style += build_rule(sel + 'a:active', transform='scale(2)') style += build_rule(sel + 'a:focus', outline='none') style += build_rule(sel + 'a.top-bar-title:hover', transform='scale(1)', color=get_color('bar-highlight'), font_style='italic') style += build_rule(sel + 'a.top-bar-title:active', transform='scale(1)', color=get_color('bar-highlight'), font_style='italic') return style ) def create_markup(container): for i in range(2): bar = E.div( class_=CLASS_NAME, E.div(style="white-space:nowrap; overflow:hidden; text-overflow: ellipsis; padding-left: 0.5em;"), E.div(style="white-space:nowrap; text-align:right; padding-right: 0.5em;") ) if i is 0: set_css(bar, position='fixed', left='0', top='0', z_index='1') set_css(bar, width='100%', display='flex', flex_direction='row', flex_wrap='wrap', justify_content='space-between', font_size=get_font_size('title'), user_select='none', color=get_color('bar-foreground'), background_color=get_color('bar-background') ) container.appendChild(bar) def get_bars(container): return container.getElementsByClassName(CLASS_NAME) def set_left_data(container, title='calibre', icon='heart', action=None, tooltip='', run_animation=False, title_action=None, title_tooltip=None): bars = get_bars(container) if icon is 'heart': if not tooltip: tooltip = _('Donate to support calibre development') interface_data = get_interface_data() for i, bar in enumerate(bars): left = bar.firstChild clear(left) title_elem = 'a' if callable(title_action) else 'span' left.appendChild(E.a(title=tooltip, svgicon(icon))) left.appendChild(E(title_elem, title, title=title_tooltip, class_='top-bar-title', style='margin-left: {0}; font-weight: bold; padding-top: {1}; padding-bottom: {1}; vertical-align: middle'.format(SPACING, VSPACING))) if i is 0: a = left.firstChild if icon is 'heart': set_css(a, animation_name=THROBBER_NAME, animation_duration='1s', animation_timing_function='ease-in-out', animation_iteration_count='5', animation_play_state='running' if run_animation else 'paused' ) set_css(a.firstChild, color=get_color('heart')) a.setAttribute('href', interface_data.donate_link) a.setAttribute('target', 'donate-to-calibre') if action is not None: a.addEventListener('click', def(event): event.preventDefault() action.bind(event)() ) if callable(title_action): a = a.nextSibling a.addEventListener('click', def(event): event.preventDefault() title_action.bind(event)() ) def set_title(container, text): bars = get_bars(container) for bar in bars: bar.firstChild.firstChild.nextSibling.textContent = text def set_title_tooltip(container, text): bars = get_bars(container) for bar in bars: bar.firstChild.firstChild.nextSibling.title = text def create_top_bar(container, **kw): create_markup(container) set_left_data(container, **kw) def add_button(container, icon, action=None, tooltip=''): if not icon: raise ValueError('An icon must be specified') bars = get_bars(container) for i, bar in enumerate(bars): right = bar.firstChild.nextSibling right.appendChild(E.a( style="margin-left: " + SPACING, title=tooltip, svgicon(icon), )) right.lastChild.dataset.buttonIcon = icon if i is 0: if action is not None: right.lastChild.addEventListener('click', def(event): event.preventDefault(), action() ) def clear_buttons(container): bars = get_bars(container) for i, bar in enumerate(bars): right = bar.firstChild.nextSibling clear(right) def set_button_visibility(container, icon, visible): for bar in get_bars(container): right = bar.firstChild.nextSibling elem = right.querySelector(f'[data-button-icon="{icon}"]') if elem: elem.style.display = 'inline-block' if visible else 'none'
5,449
Python
.py
114
39.140351
221
0.632005
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,504
show_note.pyj
kovidgoyal_calibre/src/pyj/book_list/show_note.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from ajax import ajax from book_list.comments_editor import ( create_comments_editor, destroy_editor, focus_comments_editor, get_comments_html, set_comments_html ) from book_list.details_list import sandbox_css from book_list.globals import book_whose_metadata_is_being_edited from book_list.library_data import book_metadata from book_list.router import back, home, show_note from book_list.top_bar import add_button, create_top_bar from book_list.ui import set_panel_handler from gettext import gettext as _ from modals import ajax_send_progress_dialog, error_dialog from utils import parse_url_params, safe_set_inner_html, sandboxed_html def message_from_iframe(ev): c = document.getElementById(current_container_id) if c and c.lastChild: iframe = c.querySelector('iframe') if iframe and ev.source is iframe.contentWindow: if ev.data.key: ev.data.from_iframe = True close_action = get_close_action()[0] onkeydown(current_container_id, close_action, ev.data) def make_iframe(html): html += ''' <script> function onkeydown(ev) { ev.preventDefault() ev.stopPropagation() msg = { key: ev.key, altKey: ev.altKey, ctrlKey: ev.ctrlKey, code: ev.code, isComposing: ev.isComposing, repeat: ev.repeat, shiftKey: ev.shiftKey, metaKey: ev.metaKey, } window.parent.postMessage(msg, '*') } document.onkeydown = onkeydown ''' + '<' + '/script>' iframe = sandboxed_html(html, sandbox_css() + '\n\nhtml { overflow: visible; margin: 0.5rem; }', 'allow-scripts') iframe.tabIndex = -1 # prevent tab from focusing this iframe iframe.style.width = '100%' iframe.style.flexGrow = '10' if not message_from_iframe.added: message_from_iframe.added = True window.addEventListener('message', message_from_iframe, False) return iframe current_note_markup = None current_container_id = '' def on_item_val_based_notes_fetched(load_type, xhr, ev): nonlocal current_note_markup container = document.getElementById(this) if not container: return q = parse_url_params() current_note_markup = None if load_type is 'load': data = JSON.parse(xhr.responseText) q.html = data.html q.item_id = str(data.item_id) current_note_markup = q show_note(q.field, q.item_id, q.item, replace=True, library_id=q.library_id or None, close_action=q.close_action, panel=q.panel) return old = container.querySelector('div.loading') p = old.parentNode p.removeChild(old) container.appendChild(E.div()) safe_set_inner_html(container.lastChild, xhr.error_html) def on_notes_fetched(load_type, xhr, ev): nonlocal current_note_markup q = parse_url_params() if load_type is 'load': html = xhr.responseText q.html = xhr.responseText current_note_markup = q else: current_note_markup = None html = xhr.error_html container = document.getElementById(this) if not container: return old = container.querySelector('div.loading') p = old.parentNode p.removeChild(old) if q.panel is 'show_note': create_note_display(container) elif q.panel is 'edit_note': if current_note_markup: create_editor(container.lastChild, current_note_markup.html) else: container.appendChild(E.div()) safe_set_inner_html(container.lastChild, html) def edit_note(): q = parse_url_params() show_note(q.field, q.item_id, q.item, library_id=q.library_id, panel='edit_note') def onkeydown(container_id, close_action, ev): if ev.key is 'Escape': if not ev.from_iframe: ev.preventDefault(), ev.stopPropagation() close_action() elif ev.key is 'e' or ev.key is 'E': q = parse_url_params() if q.panel is 'show_note': if not ev.from_iframe: ev.preventDefault(), ev.stopPropagation() edit_note() def setup_container(container, close_action): container.style.height = '100vh' container.style.display = 'flex' container.style.flexDirection = 'column' container.appendChild(E.div(tabindex='0', style='flex-grow: 10; display: flex; align-items: stretch')) container.lastChild.addEventListener('keydown', onkeydown.bind(None, container.id, close_action), {'passive': False, 'capture': True}) container.lastChild.focus() def get_close_action(): q = parse_url_params() if q.panel is 'show_note': close_action, close_icon = back, 'close' q = parse_url_params() ca = q.close_action if ca is 'home': close_action, close_icon = def(): home();, 'home' else: close_action, close_icon = back, 'close' return close_action, close_icon def create_note_display(container): add_button(container, 'edit', action=edit_note, tooltip=_('Edit this note [E]')) html = current_note_markup.html container.lastChild.appendChild(make_iframe(html)) def reroute_with_item_id(container, q): container.lastChild.appendChild(E.div(_('Loading') + '…', style='margin: 0.5rem', class_='loading')) url = 'get-note-from-item-val/' + encodeURIComponent(q.field) + '/' + encodeURIComponent(q.item) if q.library_id: url += '/' + encodeURIComponent(q.library_id) ajax(url, on_item_val_based_notes_fetched.bind(container.id), bypass_cache=False).send() return def init_display_note(container_id): nonlocal current_container_id current_container_id = container_id container = document.getElementById(container_id) close_action, close_icon = get_close_action() q = parse_url_params() create_top_bar(container, title=q.item, action=close_action, icon=close_icon) setup_container(container, close_action) if q.item_id is '0' or q.item_id is 0 or not q.item_id: return reroute_with_item_id(container, q) if current_note_markup and current_note_markup.library_id is q.library_id and current_note_markup.field is q.field and current_note_markup.item_id is q.item_id: create_note_display(container) else: container.lastChild.appendChild(E.div(_('Loading') + '…', style='margin: 0.5rem', class_='loading')) url = 'get-note/' + encodeURIComponent(q.field) + '/' + encodeURIComponent(q.item_id) if q.library_id: url += '/' + encodeURIComponent(q.library_id) ajax(url, on_notes_fetched.bind(container_id), bypass_cache=False).send() def save(container_id, book_id): c = document.getElementById(container_id) if not c: return q = parse_url_params() url = 'set-note/' + encodeURIComponent(q.field) + '/' + encodeURIComponent(q.item_id) if q.library_id: url += '/' + encodeURIComponent(q.library_id) close_action = get_close_action()[0] def on_complete(end_type, xhr, evt): nonlocal current_note_markup if end_type is 'abort': close_action() return if end_type is not 'load': error_dialog(_('Failed to send notes to server'), _( 'Updating the notes for: {} failed.').format(q.item), xhr.error_html) return q.html = xhr.responseText current_note_markup = q destroy_editor(c) if book_id: mi = book_metadata(book_id) if mi: mi.items_with_notes = mi.items_with_notes or {} mi.items_with_notes[q.field] = mi.items_with_notes[q.field] or {} if q.html: mi.items_with_notes[q.field][q.item] = int(q.item_id) else: v'delete mi.items_with_notes[q.field][q.item]' close_action() def on_got_html(html, extra_data): ajax_send_progress_dialog(url, {'html': html, 'searchable_text': extra_data.text, 'images': extra_data.images}, on_complete, _('Sending note data to calibre server...')) get_comments_html(c, on_got_html) def init_edit(container_id): nonlocal current_container_id current_container_id = container_id container = document.getElementById(container_id) q = parse_url_params() close_action, close_icon = get_close_action() create_top_bar(container, title=_('Edit {}').format(q.item), action=close_action, icon=close_icon, tooltip=_('Discard any changes')) setup_container(container, close_action) if q.item_id is '0' or q.item_id is 0 or not q.item_id: return reroute_with_item_id(container, q) if current_note_markup and current_note_markup.library_id is q.library_id and current_note_markup.field is q.field and current_note_markup.item_id is q.item_id: create_editor(container.lastChild, current_note_markup.html) else: container.lastChild.appendChild(E.div(_('Loading') + '…', style='margin: 0.5rem', class_='loading')) url = 'get-note/' + encodeURIComponent(q.field) + '/' + encodeURIComponent(q.item_id) if q.library_id: url += '/' + encodeURIComponent(q.library_id) ajax(url, on_notes_fetched.bind(container_id), bypass_cache=False).send() def create_editor(container, html): book_id = book_whose_metadata_is_being_edited() book_whose_metadata_is_being_edited(None) bar_container = document.getElementById(current_container_id) if bar_container: add_button(bar_container, 'check', action=save.bind(None, bar_container.id, book_id), tooltip=_('Save the changes')) c = container.appendChild(E.div(style='flex-grow:10')) editor = create_comments_editor(c, {'insert_image_files': True}) set_comments_html(c, html) focus_comments_editor(c) editor.init() set_panel_handler('show_note', init_display_note) set_panel_handler('edit_note', init_edit)
10,017
Python
.py
220
38.845455
177
0.669982
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,505
globals.pyj
kovidgoyal_calibre/src/pyj/book_list/globals.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals session_data = None def set_session_data(sd): nonlocal session_data session_data = sd return session_data def get_session_data(): return session_data def main_js(newval): if newval is not undefined: main_js.ans = newval return main_js.ans def get_current_query(newval): if newval: get_current_query.ans = newval return get_current_query.ans def get_db(db): if db: get_db.db = db return get_db.db def get_translations(val): if val: get_translations.ans = val return get_translations.ans def book_whose_metadata_is_being_edited(set_book_id=''): if jstype(set_book_id) is 'number': book_whose_metadata_is_being_edited.ans = set_book_id elif set_book_id is None: book_whose_metadata_is_being_edited.ans = None return book_whose_metadata_is_being_edited.ans
1,007
Python
.py
32
26.75
72
0.702282
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,506
book_details.pyj
kovidgoyal_calibre/src/pyj/book_list/book_details.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from elementmaker import E import traceback from ajax import ajax, ajax_send, encode_query_component from book_list.delete_book import refresh_after_delete, start_delete_book from book_list.globals import get_session_data from book_list.item_list import create_item, create_item_list from book_list.library_data import ( all_libraries, book_after, book_metadata, cover_url, current_library_id, current_virtual_library, download_url, library_data, load_status, set_book_metadata ) from book_list.router import back, home, open_book, report_a_load_failure, show_note from book_list.theme import ( color_scheme, get_color, get_color_as_rgba, get_font_size ) from book_list.top_bar import add_button, clear_buttons, create_top_bar, set_title from book_list.ui import query_as_href, set_panel_handler, show_panel from book_list.views import search_query_for from date import format_date from dom import add_extra_css, build_rule, clear, ensure_id, svgicon, unique_id from gettext import gettext as _ from modals import create_custom_dialog, error_dialog, warning_dialog from read_book.touch import ( copy_touch, install_handlers, interpret_single_gesture, touch_id, update_touch ) from session import get_interface_data from utils import ( conditional_timeout, debounce, fmt_sidx, human_readable, parse_url_params, safe_set_inner_html, sandboxed_html ) from widgets import create_button, create_spinner bd_counter = 0 CLASS_NAME = 'book-details-panel' SEARCH_INTERNET_CLASS = 'book-details-search-internet' COPY_TO_LIBRARY_CLASS = 'book-details-copy-to-library' FORMAT_PRIORITIES = [ 'EPUB', 'AZW3', 'DOCX', 'LIT', 'MOBI', 'ODT', 'RTF', 'MD', 'MARKDOWN', 'TXT', 'PDF' ] def sort_formats_key(fmt): ans = FORMAT_PRIORITIES.indexOf(fmt) if ans < 0: ans = FORMAT_PRIORITIES.length return ans def get_preferred_format(metadata, output_format, input_formats, for_download): formats = (metadata and metadata.formats) or v'[]' formats = [f.toUpperCase() for f in formats] fmt = 'EPUB' if output_format is 'PDF' else output_format if formats.length and formats.indexOf(fmt) is -1: found = False formats = sorted(formats, key=sort_formats_key) for q in formats: if input_formats[q]: fmt = q found = True break if for_download and not found and formats.length: fmt = formats[0] return fmt.toUpperCase() IGNORED_FIELDS = {'title', 'sort', 'uuid', 'id', 'urls_from_identifiers', 'lang_names', 'last_modified', 'path'} default_sort = {f:i+1 for i, f in enumerate(('title', 'title_sort', 'authors', 'author_sort', 'series', 'rating', 'pubdate', 'tags', 'timestamp', 'pubdate', 'identifiers', 'languages', 'publisher', 'last_modified'))} default_sort['formats'] = 999 def field_sorter(field_metadata): return def(field): lvl = '{:03d}'.format(default_sort[field] or 998) fm = (field_metadata[field] or {})[field] or {} return lvl + (fm.name or 'zzzzz') def href_for_search(name, val, use_quotes=True): query = ('{}:"={}"' if use_quotes else '{}:{}').format(name, str.replace(val, '"', r'\"')) q = search_query_for(query) return query_as_href(q) def on_fmt_click(ev): fmt = ev.currentTarget.dataset.format book_id = int(ev.currentTarget.dataset.bookId) title, sz = this create_custom_dialog(title, def(parent, close_modal): def action(which): close_modal() which(book_id, fmt) if fmt.lower() is 'pdf': read_button = download_url(book_id, fmt, 'inline') else: read_button = action.bind(None, read_format) parent.appendChild(E.div( E.div(_('What would you like to do with the {} format?').format(fmt)), E.div(class_='button-box', create_button(_('Read'), 'book', read_button), '\xa0', create_button(_('Download'), 'cloud-download', download_url(book_id, fmt), _('File size: {}').format(human_readable(sz)), download_filename=f'{title}.{fmt.toLowerCase()}') ) )) ) def adjust_iframe_height(iframe): de = iframe.contentWindow.document.documentElement # scrollHeight is inaccurate on Firefox iframe.style.height = de.offsetHeight + 5 + 'px' iframe.dataset.last_window_width = window.innerWidth + '' return de def setup_iframe(iframe): de = adjust_iframe_height(iframe) for a in de.querySelectorAll('a[href]'): a.setAttribute('target', '_parent') def forward_touch_events(ev): container = window.parent.document.getElementById(render_book.container_id) if container: dup = v'new ev.constructor(ev.type, ev)' container.dispatchEvent(dup) for key in ('start', 'move', 'end', 'cancel'): iframe.contentWindow.addEventListener(f'touch{key}', forward_touch_events) def adjust_all_iframes(ev): for iframe in document.querySelectorAll(f'.{CLASS_NAME} iframe'): ww = parseInt(iframe.dataset.last_window_width) if ww is not window.innerWidth: adjust_iframe_height(iframe) def add_stars_to(stars, val, allow_half_stars): for i in range(val // 2): stars.appendChild(svgicon('star')) if allow_half_stars and (val % 2): stars.appendChild(svgicon('star-half')) if window?: window.addEventListener('resize', debounce(adjust_all_iframes, 250)) def adjusting_sandboxed_html(html, extra_css): color = get_color_as_rgba('window-foreground') css = f'\n\n:root {{ color-scheme: {color_scheme()} }}\n\nhtml, body {{ overflow: hidden; color: rgba({color[0]}, {color[1]}, {color[2]}, {color[3]}) }}' if extra_css: css += '\n\n' + extra_css # allow-same-origin is needed for resizing and allow-top-navigation is # needed for links with target="_parent" ans = sandboxed_html(html, css, 'allow-same-origin allow-top-navigation-by-user-activation') ans.addEventListener('load', def(ev): setup_iframe(ev.target);) ans.style.height = '50vh' ans.dataset.last_window_width = '0' return ans def render_metadata(mi, table, book_id, iframe_css): # {{{ field_metadata = library_data.field_metadata interface_data = get_interface_data() def allowed_fields(field): if field.endswith('_index'): fm = field_metadata[field[:-len('_index')]] if fm and fm.datatype is 'series': return False if field.startswith('#'): return True if field in IGNORED_FIELDS or field.endswith('_sort'): return False if mi[field] is undefined: return False return True fields = library_data.book_display_fields vertical_categories = {x: True for x in (library_data.book_details_vertical_categories or v'[]')} if not fields or not fields.length or get_session_data().get('show_all_metadata'): fields = sorted(filter(allowed_fields, mi), key=field_sorter(field_metadata)) else: fields = filter(allowed_fields, fields) comments = v'[]' link_maps = mi.link_maps or v'{}' def show_note_action(field, item_id, item_val): show_note(field, item_id, item_val) def add_note_link(field, name, val, parent): if mi.items_with_notes and mi.items_with_notes[field] and mi.items_with_notes[field][val]: parent.appendChild(document.createTextNode(' ')) parent.appendChild(E.a( svgicon('pencil'), title=_('Show notes for: {}').format(val), href='javascript:void(0)', onclick=show_note_action.bind( None, field, mi.items_with_notes[field][val], val), class_='blue-link')) def add_row(field, name, val, is_searchable=False, is_html=False, join=None, search_text=None, use_quotes=True): if val is undefined or val is None: return is_vertical = vertical_categories[field] def add_val(v): if not v.appendChild: v += '' parent = table.lastChild.lastChild if is_searchable: text_rep = search_text or v parent.appendChild(E.a( v, title=_('Click to see books with {0}: {1}').format(name, text_rep), class_='blue-link', href=href_for_search(is_searchable, text_rep, use_quotes=use_quotes) )) if link_maps[field] and link_maps[field][text_rep]: url = link_maps[field][text_rep] if url.startswith('https://') or url.startswith('http://'): parent.appendChild(document.createTextNode(' ')) parent.appendChild(E.a( svgicon('external-link'), title=_('Click to open') + ': ' + url, href=url, target='_new', class_='blue-link')) else: if v.appendChild: parent.appendChild(v) else: parent.appendChild(document.createTextNode(v)) if jstype(v) is 'string' and not is_html: add_note_link(field, name, v, parent) table.appendChild(E.tr(E.td(name), E.td())) if is_html and /[<>]/.test(val + ''): table.lastChild.lastChild.appendChild(adjusting_sandboxed_html(val + '', iframe_css)) else: if not join: add_val(val) else: for v in val: add_val(v) if v is not val[-1]: if is_vertical: table.lastChild.lastChild.appendChild(E.br()) else: table.lastChild.lastChild.appendChild(document.createTextNode(join)) return table.lastChild.lastChild def process_composite(field, fm, name, val): if fm.display and fm.display.contains_html: add_row(field, name, val, is_html=True) return if fm.is_multiple and fm.is_multiple.list_to_ui: all_vals = filter(None, map(str.strip, val.split(fm.is_multiple.list_to_ui))) add_row(field, name, all_vals, is_searchable=field, join=fm.is_multiple.list_to_ui) else: add_row(field, name, val, is_searchable=field) def process_authors(field, fm, name, val): add_row(field, name, val, is_searchable=field, join=' & ') def process_publisher(field, fm, name, val): add_row(field, name, val, is_searchable=field) def process_formats(field, fm, name, val): if val.length and book_id?: table.appendChild(E.tr(E.td(name), E.td())) td = table.lastChild.lastChild for fmt in val: fmt = fmt.toUpperCase() td.appendChild(E.a( fmt, class_='blue-link', href='javascript:void(0)', title=_('Read or download this book in the {} format').format(fmt), onclick=on_fmt_click.bind(v'[mi.title, mi.format_sizes[fmt] || 0]'), data_format=fmt, data_book_id='' + book_id)) if fmt is not val[-1]: td.appendChild(document.createTextNode(', ')) def process_rating(field, fm, name, val): stars = E.span() val = int(val or 0) if val > 0: add_stars_to(stars, val, fm.display?.allow_half_stars) add_row(field, name, stars, is_searchable=field, search_text=val/2 + '') def process_identifiers(field, fm, name, val): def ids_sorter(x): return (x[0] or '').toLowerCase() if val and mi.urls_from_identifiers and mi.urls_from_identifiers.length > 0: td = E.td() for text, k, idval, url in sorted(mi.urls_from_identifiers or v'[]', key=ids_sorter): if td.childNodes.length: td.appendChild(document.createTextNode(', ')) td.appendChild(E.a(class_='blue-link', title='{}:{}'.format(k, idval), target='_new', href=url, text)) if td.childNodes.length: table.appendChild(E.tr(E.td(name), td)) def process_size(field, fm, name, val): if val: try: add_row(field, name, human_readable(int(val))) except: add_row(field, name, val+'') def process_languages(field, fm, name, val): if val and val.length: table.appendChild(E.tr(E.td(name), E.td())) td = table.lastChild.lastChild for k in val: if mi.lang_names: lang = mi.lang_names[k] or k else: lang = k td.appendChild(E.a(lang, class_='blue-link', title=_('Click to see books with language: {}').format(lang), href=href_for_search(field, k) )) if k is not val[-1]: td.appendChild(document.createTextNode(', ')) def process_datetime(field, fm, name, val): if val: fmt = interface_data['gui_' + field + '_display_format'] or (fm['display'] or {}).date_format formatted_val = format_date(val, fmt) if formatted_val: add_row(field, name, formatted_val, is_searchable=field, search_text=val) def process_series(field, fm, name, val): if val: ifield = field + '_index' try: ival = float(mi[ifield]) except Exception: ival = 1.0 ival = fmt_sidx(ival, use_roman=interface_data.use_roman_numerals_for_series_number) table.appendChild(E.tr(E.td(name), E.td())) s = safe_set_inner_html(E.span(), _('{0} of <a>{1}</a>').format(ival, val)) a = s.getElementsByTagName('a') if a and a.length: a = a[0] a.setAttribute('href', href_for_search(field, val)) a.setAttribute('title', _('Click to see books with {0}: {1}').format(name, val)) a.setAttribute('class', 'blue-link') else: print("WARNING: Translation of series template is incorrect as it does not have an <a> tag") table.lastChild.lastChild.appendChild(s) add_note_link(field, name, val, table.lastChild.lastChild) def process_field(field, fm): name = fm.name or field datatype = fm.datatype val = mi[field] if field is 'comments' or datatype is 'comments' or fm.display?.composite_show_in_comments: if not val: return ias = fm.display?.interpret_as or 'html' hp = fm.display?.heading_position or 'hide' if ias is 'long-text': if hp is 'side': add_row(field, name, val).style.whiteSpace = 'pre-wrap' return val = E.pre(val, style='white-space:pre-wrap').outerHTML elif ias is 'short-text': if hp is 'side': add_row(field, name, val) return val = E.span(val).outerHTML else: if field is 'comments' and '<' not in val: val = '\n'.join(['<p class="description">{}</p>'.format(x.replace(/\n/g, '<br>')) for x in val.split('\n\n')]) if hp is 'side': add_row(field, name, val, is_html=True) return comments.push(v'[field, val]') return func = None if datatype is 'composite': func = process_composite elif field is 'formats': func = process_formats elif datatype is 'rating': func = process_rating elif field is 'identifiers': func = process_identifiers elif field is 'authors': func = process_authors elif field is 'publisher': func = process_publisher elif field is 'languages': func = process_languages elif field is 'size': func = process_size elif datatype is 'datetime': func = process_datetime elif datatype is 'series': func = process_series if func: func(field, fm, name, val) else: if datatype is 'text' or datatype is 'enumeration': if val is not undefined and val is not None: join = fm.is_multiple.list_to_ui if fm.is_multiple else None add_row(field, name, val, join=join, is_searchable=field) elif datatype is 'bool': if library_data.bools_are_tristate: v = _('Yes') if val else ('' if val is undefined or val is None else _('No')) else: v = _('Yes') if val else _('No') if v: add_row(field, name, v, is_searchable=field, use_quotes=False) elif datatype is 'int' or datatype is 'float': if val is not undefined and val is not None: fmt = (fm.display or {}).number_format if fmt: formatted_val = fmt.format(val) if formatted_val: val += '' add_row(field, name, formatted_val, is_searchable=field, search_text=val) else: val += '' add_row(field, name, val, is_searchable=field, search_text=val) for field in fields: fm = field_metadata[field] if not fm: continue try: process_field(field, fm) except Exception: print('Failed to render metadata field: ' + field) traceback.print_exc() all_html = '' for field, comment in comments: if comment: fm = field_metadata[field] if fm.display?.heading_position is 'above': name = fm.name or field all_html += f'<h3>{name}</h3>' all_html += comment iframe = adjusting_sandboxed_html(all_html, iframe_css) iframe.style.marginTop = '2ex' table.parentNode.appendChild(iframe) # }}} def basic_table_rules(sel): style = '' style += build_rule(sel + 'table.metadata td', vertical_align='top') style += build_rule(sel + 'table.metadata td:first-of-type', font_style='italic', color='var(--calibre-color-faded-text)', padding_right='0.5em', white_space='nowrap', text_align='right') style += build_rule(sel + 'table.metadata td:last-of-type', overflow_wrap='break-word') return style add_extra_css(def(): sel = '.' + CLASS_NAME + ' ' style = basic_table_rules(sel) style += build_rule(sel + ' .next-book-button:hover', transform='scale(1.5)') sel = '.' + SEARCH_INTERNET_CLASS style += build_rule(sel, margin='1ex 1em') style += build_rule(sel + ' ul > li', list_style_type='none') style += build_rule(sel + ' ul > li > a', padding='2ex 1em', display='block', width='100%') sel = '.' + COPY_TO_LIBRARY_CLASS style += build_rule(sel, margin='1ex 1em') return style ) current_fetch = None def no_book(container): container.appendChild(E.div( style='margin: 1ex 1em', _('No book found') )) def on_img_err(err): img = err.target if img.parentNode: img.parentNode.style.display = 'none' def preferred_format(book_id, for_download): interface_data = get_interface_data() return get_preferred_format(book_metadata(book_id), interface_data.output_format, interface_data.input_formats, for_download) def read_format(book_id, fmt): open_book(book_id, fmt) def read_book(book_id): fmt = preferred_format(book_id) if fmt and fmt.lower() is 'pdf': window.open(download_url(book_id, fmt, 'inline'), '_blank') else: read_format(book_id, fmt) def download_format(book_id, fmt): window.location = download_url(book_id, fmt) def download_book(book_id): fmt = preferred_format(book_id, True) download_format(book_id, fmt) def next_book(book_id, delta): next_book_id = book_after(book_id, delta) if next_book_id: q = parse_url_params() q.book_id = next_book_id + '' show_panel('book_details', query=q, replace=True) def render_book(container_id, book_id): render_book.book_id = book_id render_book.container_id = container_id is_random = parse_url_params().book_id is '0' c = document.getElementById(container_id) if not c: return install_touch_handlers(c, book_id) metadata = book_metadata(book_id) render_book.title = metadata.title set_title(c, metadata.title) authors = metadata.authors.join(' & ') if metadata.authors else _('Unknown') alt = _('{} by {}\n\nClick to read').format(metadata.title, authors) border_radius = 20 button_style = f'cursor: pointer; border-radius: {border_radius//5}px;' button_style += 'color: #ccc; background-color:rgba(0, 0, 0, 0.75);' button_style += 'display: flex; justify-content: center; align-items: center; padding: 2px;' if is_random: button_style += 'display: none;' def prev_next_button(is_prev): delta = -1 if is_prev else 1 nbid = book_after(book_id, delta) s = button_style if not nbid or nbid is book_id: s += '; display: none' return E.div( style=s, title=_('Previous book [Ctrl+Left]') if is_prev else _('Next book [Ctrl+Right]'), class_='next-book-button', svgicon('chevron-left' if is_prev else 'chevron-right'), onclick=next_book.bind(None, book_id, delta) ) imgdiv = E.div(style='position: relative', E.img( alt=alt, title=alt, data_title=metadata.title, data_authors=authors, onclick=read_book.bind(None, book_id), style='cursor: pointer; border-radius: 20px; max-width: calc(100vw - 2em); max-height: calc(100vh - 4ex - {}); display: block; width:auto; height:auto; border-radius: {}px'.format(get_font_size('title'), border_radius )), E.div( style=f'position: absolute; top:0; width: 100%; padding: {border_radius//2}px; box-sizing: border-box; font-size: 2rem; display: flex; justify-content: space-between; color: {get_color("button-text")}', prev_next_button(True), prev_next_button(), ), ) img = imgdiv.getElementsByTagName('img')[0] img.onerror = on_img_err img.src = cover_url(book_id) c = c.lastChild c.appendChild(E.div( style='display:flex; padding: 1ex 1em; align-items: flex-start; justify-content: flex-start; flex-wrap: wrap', E.div(style='margin-right: 1em; flex-grow: 3; max-width: 500px', data_book_id='' + book_id), imgdiv )) container = c.lastChild.firstChild read_button = create_button(_('Read'), 'book', read_book.bind(None, book_id), _('Read this book [V]')) fmt = preferred_format(book_id, True) download_button = create_button(_('Download'), 'cloud-download', download_url(book_id, fmt), _('Download this book in the {0} format ({1})').format(fmt, human_readable(metadata.format_sizes[fmt] or 0)), download_filename=f'{metadata.title}.{fmt.toLowerCase()}') row = E.div(read_button, '\xa0\xa0\xa0', download_button, style='margin-bottom: 1ex') if not metadata.formats or not metadata.formats.length: row.style.display = 'none' container.appendChild(row) md = E.div(style='margin-bottom: 2ex') table = E.table(class_='metadata') container.appendChild(md) md.appendChild(table) render_metadata(metadata, table, book_id) def add_top_bar_buttons(container_id): container = document.getElementById(container_id) if container: clear_buttons(container) add_button(container, 'convert', action=convert_book, tooltip=_('Convert this book to another format [C]')) add_button(container, 'edit', action=edit_metadata, tooltip=_('Edit the metadata for this book [E]')) add_button(container, 'trash', action=delete_book, tooltip=_('Delete this book')) book_id = parse_url_params().book_id if book_id is '0': add_button(container, 'random', tooltip=_('Show a random book'), action=def(): fetch_metadata(container_id, 0, proceed_after_succesful_fetch_metadata) ) add_button(container, 'ellipsis-v', action=show_subsequent_panel.bind(None, 'more_actions'), tooltip=_('More actions')) def proceed_after_succesful_fetch_metadata(container_id, book_id): render_book(container_id, book_id) add_top_bar_buttons(container_id) def metadata_fetched(container_id, book_id, proceed, end_type, xhr, event): nonlocal current_fetch if current_fetch is None or current_fetch is not xhr: return # Fetching was aborted current_fetch = None c = document.getElementById(container_id) if not c: return c = c.lastChild if end_type is 'load': try: data = JSON.parse(xhr.responseText) except Exception as err: error_dialog(_('Could not fetch metadata for book'), _('Server returned an invalid response'), err.toString()) return clear(c) book_id = int(data['id']) set_book_metadata(book_id, data) proceed(container_id, book_id) elif end_type is not 'abort': clear(c) c.appendChild(E.div( style='margin: 1ex 1em', _('Could not fetch metadata for book'), E.div(style='margin: 1ex 1em') )) safe_set_inner_html(c.lastChild.lastChild, xhr.error_html) def fetch_metadata(container_id, book_id, proceed): nonlocal current_fetch container = document.getElementById(container_id) if not container: return if current_fetch: current_fetch.abort() current_fetch = ajax('interface-data/book-metadata/' + book_id, metadata_fetched.bind(None, container_id, book_id, proceed), query={'library_id':current_library_id(), 'vl':current_virtual_library()}) current_fetch.send() container = container.lastChild clear(container) container.appendChild(E.div( style='margin: 1ex 1em', create_spinner(), '\xa0' + _('Fetching metadata for the book, please wait') + '…', )) def install_touch_handlers(container, book_id): ongoing_touches = {} gesture_id = 0 container_id = container.id def has_active_touches(): for tid in ongoing_touches: t = ongoing_touches[tid] if t.active: return True return False def handle_touch(ev): nonlocal gesture_id, ongoing_touches container = document.getElementById(container_id) if not container: return if ev.type is 'touchstart': for touch in ev.changedTouches: ongoing_touches[touch_id(touch)] = copy_touch(touch) gesture_id += 1 elif ev.type is 'touchmove': for touch in ev.changedTouches: t = ongoing_touches[touch_id(touch)] if t: update_touch(t, touch) elif ev.type is 'touchcancel': for touch in ev.changedTouches: v'delete ongoing_touches[touch_id(touch)]' elif ev.type is 'touchend': for touch in ev.changedTouches: t = ongoing_touches[touch_id(touch)] if t: t.active = False update_touch(t, touch) if not has_active_touches(): touches = ongoing_touches ongoing_touches = {} num = len(touches) if num is 1: gesture = interpret_single_gesture(touches[Object.keys(touches)[0]], gesture_id) if gesture.type is 'swipe' and gesture.axis is 'horizontal': delta = -1 if gesture.direction is 'right' else 1 next_book(book_id, delta) install_handlers(container, { 'handle_touchstart': handle_touch, 'handle_touchmove': handle_touch, 'handle_touchend': handle_touch, 'handle_touchcancel': handle_touch, }, True) def create_book_details(container): q = parse_url_params() current_book_id = q.book_id if current_book_id is undefined or current_book_id is None: no_book(container) return current_book_id = int(current_book_id) container_id = container.parentNode.id if current_book_id is not 0 and book_metadata(current_book_id): render_book(container_id, current_book_id) add_top_bar_buttons(container_id) else: fetch_metadata(container_id, current_book_id, proceed_after_succesful_fetch_metadata) def report_load_failure(container): report_a_load_failure( container, _('Failed to load books from calibre library, with error:'), load_status.error_html) def check_for_books_loaded(): container = this if load_status.loading: conditional_timeout(container.id, 5, check_for_books_loaded) return container = container.lastChild clear(container) if not load_status.ok: report_load_failure(container) return create_book_details(container) def onkeydown(container_id, close_action, ev): if render_book.book_id: if ev.ctrlKey: if ev.key is 'ArrowLeft': next_book(render_book.book_id, -1) ev.preventDefault(), ev.stopPropagation() elif ev.key is 'ArrowRight': next_book(render_book.book_id, 1) ev.preventDefault(), ev.stopPropagation() elif not ev.ctrlKey and not ev.metaKey and not ev.shiftKey: if ev.key is 'Escape': ev.preventDefault(), ev.stopPropagation() close_action() elif ev.key is 'Delete': ev.preventDefault(), ev.stopPropagation() delete_book() elif ev.key is 'v' or ev.key is 'V': read_book(render_book.book_id) elif ev.key is 'c' or ev.key is 'C': convert_book() elif ev.key is 'e' or ev.key is 'E': edit_metadata() def init(container_id): container = document.getElementById(container_id) close_action, close_icon = back, 'close' q = parse_url_params() ca = q.close_action if ca is 'home': close_action, close_icon = def(): home();, 'home' elif ca is 'book_list': close_action = def(): show_panel('book_list', {'book_id':q.book_id}) create_top_bar(container, title=_('Book details'), action=close_action, icon=close_icon) window.scrollTo(0, 0) # Ensure we are at the top of the window container.appendChild(E.div(class_=CLASS_NAME, tabindex='0')) container.lastChild.addEventListener('keydown', onkeydown.bind(None, container_id, close_action), {'passive': False, 'capture': True}) container.lastChild.focus() container.lastChild.appendChild(E.div(_('Loading books from the calibre library, please wait...'), style='margin: 1ex 1em')) conditional_timeout(container_id, 5, check_for_books_loaded) def show_subsequent_panel(name, replace=False): q = parse_url_params() q.book_id = (render_book.book_id or q.book_id) + '' show_panel('book_details^' + name, query=q, replace=replace) def edit_metadata(): q = parse_url_params() q.book_id = (render_book.book_id or q.book_id) + '' show_panel('edit_metadata', query=q, replace=False) def convert_book(): q = parse_url_params() q.book_id = (render_book.book_id or q.book_id) + '' show_panel('convert_book', query=q, replace=False) def create_more_actions_panel(container_id): container = document.getElementById(container_id) create_top_bar(container, title=_('More actions…'), action=back, icon='close') if get_session_data().get('show_all_metadata'): title, subtitle = _('Show important metadata'), _('Show only the important metadata fields in the book details') else: title, subtitle = _('Show all metadata'), _('Show all metadata fields in the book details') items = [ create_item(_('Search the internet'), subtitle=_('Search for this author or book on various websites'), action=def(): show_subsequent_panel('search_internet', replace=True) ), create_item(title, subtitle=subtitle, action=toggle_fields), create_item(_('Copy to library'), subtitle=_('Copy or move this book to another calibre library'), action=def(): show_subsequent_panel('copy_to_library', replace=True) ), ] container.appendChild(E.div()) create_item_list(container.lastChild, items) def return_to_book_details(): q = parse_url_params() show_panel('book_details', query=q, replace=True) def toggle_fields(): sd = get_session_data() sd.set('show_all_metadata', False if sd.get('show_all_metadata') else True) return_to_book_details() def url_for(template, data): def eqc(x): return encode_query_component(x).replace(/%20/g, '+') return template.format(title=eqc(data.title), author=eqc(data.author)) def search_internet(container_id): if not render_book.book_id or not book_metadata(render_book.book_id): return return_to_book_details() container = document.getElementById(container_id) create_top_bar(container, title=_('Search the internet'), action=back, icon='close') mi = book_metadata(render_book.book_id) data = {'title':mi.title, 'author':mi.authors[0] if mi.authors else _('Unknown')} interface_data = get_interface_data() def link_for(name, template): return E.a(name, class_='simple-link', href=url_for(template, data), target="_blank") author_links = E.ul() book_links = E.ul() if interface_data.search_the_net_urls: for entry in interface_data.search_the_net_urls: links = book_links if entry.type is 'book' else author_links links.appendChild(E.li(link_for(entry.name, entry.url))) for name, url in [ (_('Goodreads'), 'https://www.goodreads.com/book/author/{author}'), (_('Wikipedia'), 'https://en.wikipedia.org/w/index.php?search={author}'), (_('Google Books'), 'https://www.google.com/search?tbm=bks&q=inauthor:%22{author}%22'), ]: author_links.appendChild(E.li(link_for(name, url))) for name, url in [ (_('Goodreads'), 'https://www.goodreads.com/search?q={author}+{title}&search%5Bsource%5D=goodreads&search_type=books&tab=books'), (_('Google Books'), 'https://www.google.com/search?tbm=bks&q=inauthor:%22{author}%22+intitle:%22{title}%22'), (_('Amazon'), 'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords={author}+{title}'), ]: book_links.appendChild(E.li(link_for(name, url))) container.appendChild(E.div(class_=SEARCH_INTERNET_CLASS, safe_set_inner_html(E.h2(), _('Search for the author <i>{}</i> at:').format(data.author)), author_links, E.hr(), safe_set_inner_html(E.h2(), _('Search for the book <i>{}</i> at:').format(data.title)), book_links, )) # Copy to library {{{ def do_copy_to_library(book_id, target_library_id, target_library_name): def handle_result(move, close_func, end_type, xhr, ev): close_func() title = book_metadata(book_id).title return_to_book_details() if end_type is 'abort': return if end_type is not 'load': error_dialog(_('Failed to copy book'), _( 'Failed to copy the book "{}". Click "Show details" for more information.').format(title), xhr.error_html) return try: response = JSON.parse(xhr.responseText)[book_id] if not response: raise Exception('bad') except: error_dialog(_('Failed to copy book'), _( 'Failed to copy the book "{}" because of an invalid response from calibre').format(title)) return if not response.ok: error_dialog(_('Failed to copy book'), _( 'Failed to copy the book "{}". Click "Show details" for more information.').format(title), response.payload ) return if response.action is 'duplicate': warning_dialog(_('Book already exists'), _( 'Could not copy as a book with the same title and authors already exists in the {} library').format(target_library_name)) elif response.action is 'automerge': warning_dialog(_('Book merged'), _( 'The files from the book were merged into a book with the same title and authors in the {} library').format(target_library_name)) if move: refresh_after_delete(book_id, current_library_id()) def trigger_copy(container_id, move, close_func): try: choice = document.querySelector(f'#{dupes_id} input[name="dupes"]:checked').value except: choice = document.querySelector(f'#{dupes_id} input[name="dupes"]').value sd.set('copy_to_library_dupes', choice) duplicate_action, automerge_action = choice.split(';', 2) data = {'book_ids':v'[book_id]', 'move': move, 'duplicate_action': duplicate_action, 'automerge_action': automerge_action} container = document.getElementById(container_id) clear(container) container.appendChild(E.div( _('Contacting calibre to copy book, please wait...'))) ajax_send(f'cdb/copy-to-library/{target_library_id}/{current_library_id()}', data, handle_result.bind(None, move, close_func)) def radio(value, text): return E.div(style='margin-top: 1rem', E.input(type='radio', name='dupes', value=value, checked=value is saved_value), '\xa0', E.span(text)) title = book_metadata(book_id).title dupes_id = unique_id() sd = get_session_data() saved_value = sd.get('copy_to_library_dupes') create_custom_dialog(_( 'Copy book to "{target_library_name}"').format(target_library_name=target_library_name), def (container, close_func): container_id = ensure_id(container) container.appendChild(E.div( E.div(_('Copying: {}').format(title)), E.div(id=dupes_id, E.p(_('If there are already existing books in "{}" with the same title and authors,' ' how would you like to handle them?').format(target_library_name)), radio('add;overwrite', _('Copy anyway')), radio('ignore;overwrite', _('Do not copy')), radio('add_formats_to_existing;overwrite', _('Merge into existing books, overwriting existing files')), radio('add_formats_to_existing;ignore', _('Merge into existing books, keeping existing files')), radio('add_formats_to_existing;new record', _('Merge into existing books, putting conflicting files into a new book record')), ), E.div( class_='button-box', create_button(_('Copy'), None, trigger_copy.bind(None, container_id, False, close_func), highlight=True), '\xa0', create_button(_('Move'), None, trigger_copy.bind(None, container_id, True, close_func)), '\xa0', create_button(_('Cancel'), None, close_func), ) )) if not container.querySelector(f'#{dupes_id} input[name="dupes"]:checked'): container.querySelector(f'#{dupes_id} input[name="dupes"]').checked = True ) def copy_to_library(container_id): if not render_book.book_id or not book_metadata(render_book.book_id): return return_to_book_details() container = document.getElementById(container_id) create_top_bar(container, title=_('Copy to library'), action=back, icon='close') libraries = all_libraries() container.appendChild(E.div(class_=COPY_TO_LIBRARY_CLASS)) container = container.lastChild if libraries.length < 2: container.appendChild(E.div(_('There are no other calibre libraries available to copy the book to'))) return container.appendChild(E.h2(_('Choose the library to copy to below'))) items = [] for library_id, library_name in libraries: if library_id is current_library_id(): continue items.push(create_item(library_name, action=do_copy_to_library.bind(None, render_book.book_id, library_id, library_name))) container.appendChild(E.div()) create_item_list(container.lastChild, items) # }}} def delete_book(): start_delete_book(current_library_id(), render_book.book_id, render_book.title or _('Unknown')) set_panel_handler('book_details', init) set_panel_handler('book_details^more_actions', create_more_actions_panel) set_panel_handler('book_details^search_internet', search_internet) set_panel_handler('book_details^copy_to_library', copy_to_library)
41,857
Python
.py
874
38.065217
229
0.607522
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,507
constants.pyj
kovidgoyal_calibre/src/pyj/viewer/constants.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals FAKE_PROTOCOL = '__FAKE_PROTOCOL__' FAKE_HOST = '__FAKE_HOST__'
216
Python
.py
5
41.8
72
0.736842
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,508
router.pyj
kovidgoyal_calibre/src/pyj/viewer/router.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from modals import close_all_modals from utils import parse_url_params def get_current_query(newval): if newval: get_current_query.ans = newval return get_current_query.ans or {} def apply_url(): close_all_modals() # needed to close any error dialogs, etc when clicking back or forward in the browser or using push_state() to go to a new page data = parse_url_params() data.mode = data.mode or 'read_book' get_current_query.ans = data
623
Python
.py
14
40.857143
151
0.735099
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,509
hints.pyj
kovidgoyal_calibre/src/pyj/read_book/hints.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from dom import clear from elementmaker import E from book_list.theme import get_color from gettext import gettext as _ from read_book.shortcuts import shortcut_for_key_event class Hints: def __init__(self, view): self.view = view container = self.container container.setAttribute('tabindex', '0') container.style.overflow = 'hidden' container.addEventListener('keydown', self.on_keydown, {'passive': False}) container.addEventListener('click', self.container_clicked, {'passive': False}) self.reset() def reset(self): self.hints_map = {} self.current_prefix = '' @property def container(self): return document.getElementById('book-hints-overlay') @property def is_visible(self): return self.container.style.display is not 'none' def focus(self): self.container.focus() def hide(self): if self.is_visible: self.container.style.display = 'none' self.send_message('hide') self.reset() self.view.focus_iframe() def show(self): if not self.is_visible: self.reset() c = self.container c.style.display = 'block' clear(c) self.focus() self.send_message('show') def on_keydown(self, ev): ev.preventDefault(), ev.stopPropagation() if ev.key is 'Escape': self.hide() return if ev.key is 'Enter': if self.current_prefix: self.apply_prefix(True) return if ev.key is 'Backspace': if self.current_prefix: self.current_prefix = self.current_prefix[:-1] self.apply_prefix() return hint_keys = list('1234567890abcdefghijklmnopqrstuvwxyz') q = ev.key.toLowerCase() if hint_keys.indexOf(q) > -1: self.current_prefix += q self.apply_prefix() sc_name = shortcut_for_key_event(ev, self.view.keyboard_shortcut_map) if not sc_name: return def container_clicked(self, ev): ev.stopPropagation(), ev.preventDefault() self.hide() def apply_prefix(self, accept_full_match): matches = v'[]' if self.current_prefix: for k in Object.keys(self.hints_map): if k is '_length': continue q = encode(int(k)) if accept_full_match: if q is self.current_prefix: matches.push(k) break elif q.startswith(self.current_prefix): matches.push(k) if matches.length is 1: self.send_message('activate', hint=self.hints_map[matches[0]]) self.hide() else: self.send_message('apply_prefix', prefix=self.current_prefix) def send_message(self, type, **kw): self.view.iframe_wrapper.send_message('hints', type=type, **kw) def handle_message(self, msg): if msg.type is 'shown': self.reset() self.hints_map = msg.hints_map if not self.hints_map._length: self.no_hints_found() def no_hints_found(self): c = self.container c.appendChild(E.div( _('No links found. Press Esc to close'), style=f'position: absolute; margin: auto; top: 50%; left: 50%; background: {get_color("window-background")};' + ' padding: 1rem; border: solid 1px currentColor; border-radius: 4px; transform: translate(-50%, -50%);' )) def is_visible(a): if not a.offsetParent: return False rect = a.getBoundingClientRect() return rect.left >= 0 and rect.top >= 0 and rect.left < window.innerWidth and rect.top < window.innerHeight def encode(i): return i.toString(36).toLowerCase() def hint_visible_links(): i = 0 hint_map = {} for a in document.body.querySelectorAll('a[href]'): if is_visible(a): i += 1 h = i + '' a.dataset.calibreHintRender = encode(i) a.dataset.calibreHintValue = h a.classList.add('calibre-hint-visible') hint_map[h] = {'type': 'link', 'value': i} hint_map._length = i return hint_map def unhint_links(): for a in document.body.querySelectorAll('a[href]'): a.classList.remove('calibre-hint-visible', 'calibre-hint-enter') v'delete a.dataset.calibreHintRender' v'delete a.dataset.calibreHintValue' def apply_prefix_to_hints(prefix): for a in document.body.querySelectorAll('[data-calibre-hint-value]'): val = int(a.dataset.calibreHintValue) r = encode(val) a.classList.remove('calibre-hint-enter') if not prefix or r.startsWith(prefix): a.classList.add('calibre-hint-visible') a.dataset.calibreHintRender = leftover = r[prefix.length:] or '\xa0' if leftover is '\xa0': a.classList.add('calibre-hint-enter') else: a.classList.remove('calibre-hint-visible')
5,345
Python
.py
137
29.189781
123
0.592164
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,510
search.pyj
kovidgoyal_calibre/src/pyj/read_book/search.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from book_list.theme import get_color from book_list.top_bar import create_top_bar from complete import create_search_bar from dom import clear, add_extra_css, build_rule from gettext import gettext as _, ngettext from modals import error_dialog from read_book.globals import current_book, ui_operations from read_book.search_worker import ( CONNECT_FAILED, DB_ERROR, GET_SPINE_FAILED, UNHANDLED_ERROR, worker_main ) from read_book.shortcuts import shortcut_for_key_event from widgets import create_button, create_spinner from worker import start_worker def parse_error_msg(msg): details = msg.msg emsg = _('Unknown error') if msg.code is GET_SPINE_FAILED: emsg = _('Loading text from the book failed.') elif msg.code is CONNECT_FAILED: emsg = _('Connecting to database storing the local copy of the book failed in the worker thread.') elif msg.code is UNHANDLED_ERROR: emsg = _('There was an unhandled error while searching.') elif msg.code is DB_ERROR: emsg = msg.error.msg details = msg.error.details return emsg, details def get_toc_data(book): spine = book.manifest.spine spine_toc_map = {name: v'[]' for name in spine} parent_map = {} toc_id_map = {} def process_node(node): toc_id_map[node.id] = node items = spine_toc_map[node.dest] if items: items.push(node) children = node.children if children: for child in children: parent_map[child.id] = node process_node(child) toc = book.manifest.toc if toc: process_node(toc) return { 'spine': spine, 'spine_toc_map': spine_toc_map, 'spine_idx_map': {name: idx for idx, name in enumerate(spine)}, 'parent_map': parent_map, 'toc_id_map': toc_id_map } class SearchOverlay: display_type = 'flex' CONTAINER_ID = 'book-search-overlay' def __init__(self, view): self.view = view self.search_in_flight = {'id': None, 'mode': 'contains', 'case_sensitive': False} self._worker = None self.request_counter = 0 self.result_map = {} c = self.container c.style.backgroundColor = get_color('window-background') c.style.maxHeight = '100vh' c.style.minHeight = '100vh' c.style.flexDirection = 'column' c.style.alignItems = 'stretch' c.style.overflow = 'hidden' c.style.userSelect = 'none' c.addEventListener('keydown', self.onkeydown) c.addEventListener('keyup', self.onkeyup) self.result_handler = None create_top_bar(c, title=_('Search in book'), action=self.hide, icon='close') search_button = create_button(_('Search'), 'search') c.appendChild(E.div( style='display: flex; padding: 1rem; padding-bottom: 0.5rem; overflow: hidden', create_search_bar(self.run_search, 'search-in-book', button=search_button), E.div('\xa0\xa0'), search_button, )) c.lastChild.firstChild.style.flexGrow = '100' sd = get_session_data() mode = sd.get('book_search_mode') c.appendChild(E.div( style='display: flex; padding: 1rem; padding-top: 0.5rem; padding-bottom: 0; align-items: center; overflow: hidden', E.label( _('Search type:') + '\xa0', E.select( name='mode', title=_('''Type of search: Contains: Search for the entered text anywhere Whole words: Search for whole words that equal the entered text Regex: Interpret the entered text as a regular expression '''), E.option(_('Contains'), value='contains', selected=mode=='contains'), E.option(_('Whole words'), value='word', selected=mode=='word'), E.option(_('Regex'), value='regex', selected=mode=='regex'), onchange=def(event): get_session_data().set('book_search_mode', event.target.value) ), ), E.div('\xa0\xa0'), E.label(E.input( type='checkbox', name='case_sensitive', checked=bool(sd.get('book_search_case_sensitive'))), onchange=def(event): get_session_data().set('book_search_case_sensitive', event.target.checked) , _('Case sensitive'), ), E.div('\xa0\xa0'), create_button(_('Return'), 'chevron-left', action=self.return_to_original_position, tooltip=_('Go back to where you were before searching')) )) c.appendChild(E.hr()) c.appendChild(E.div( style='display: none; overflow: auto', tabindex='0', E.div( style='text-align: center', E.div(create_spinner('4em', '4em')), E.div(_('Searching, please wait…'), style='margin-top: 1ex'), ), E.div(), )) for child in c.childNodes: if child is not c.lastChild: child.style.flexShrink = '0' @property def current_query(self): c = self.container return { 'mode': c.querySelector('select[name=mode]').value, 'case_sensitive': c.querySelector('input[name=case_sensitive]').checked, 'text': c.querySelector('input[type=search]').value } @current_query.setter def current_query(self, q): c = self.container c.querySelector('select[name=mode]').value = q.mode or 'contains' c.querySelector('input[name=case_sensitive]').checked = bool(q.case_sensitive) c.querySelector('input[type=search]').value = q.text or '' @property def bottom_container(self): return self.container.lastChild @property def results_container(self): return self.bottom_container.lastChild def show_wait(self): c = self.bottom_container c.style.display = 'block' c.firstChild.style.display = 'block' c.lastChild.style.display = 'none' def show_results(self): c = self.bottom_container c.style.display = 'block' c.firstChild.style.display = 'none' c.lastChild.style.display = 'block' c.focus() def clear_results(self): clear(self.results_container) self.result_map = {} @property def worker(self): if not self._worker: self._worker = start_worker('read_book.search') self._worker.onmessage = self.on_worker_message self.clear_caches() return self._worker def do_initial_search(self, text, query): q = {'mode': 'contains', 'case_sensitive': True, 'text': text, 'only_first_match': True} self.request_counter += 1 self.initial_search_result_counter = 0 self.initial_search_human_readable_query = query self.search_in_flight.id = self.request_counter self.result_handler = self.handle_initial_search_result self.worker.postMessage({ 'type': 'search', 'current_name': '', 'id': self.request_counter, 'query': q }) def handle_initial_search_result(self, msg): if msg.type is 'error': emsg, details = parse_error_msg(msg) error_dialog(_('Could not search'), emsg, details) self.result_handler = None self.initial_search_result_counter = 0 elif msg.id is self.search_in_flight.id: if msg.type is 'search_complete': self.search_in_flight.id = None self.result_handler = None if self.initial_search_result_counter is 0: self.view.hide_loading() window.alert(_('The full text search query {} was not found in the book, try a manual search.').format(self.initial_search_human_readable_query)) self.initial_search_result_counter = 0 elif msg.type is 'search_result': self.initial_search_result_counter += 1 if self.initial_search_result_counter is 1: self.view.discover_search_result(msg.result) self.view.hide_loading() def queue_search(self, query, book, current_name): self.request_counter += 1 self.original_position = self.view.currently_showing.bookpos self.view.get_current_cfi('search-original-pos', self.set_original_pos) self.search_in_flight.id = self.request_counter self.worker.postMessage({ 'type': 'search', 'current_name': current_name, 'id': self.request_counter, 'query': query }) self.clear_results() self.show_wait() def set_original_pos(self, request_id, data): self.original_position = data.cfi def return_to_original_position(self): if self.original_position: self.view.goto_cfi(self.original_position) self.hide() def on_worker_message(self, evt): msg = evt.data if self.result_handler: return self.result_handler(msg) if msg.type is 'error': emsg, details = parse_error_msg(msg) error_dialog(_('Could not search'), emsg, details) elif msg.id is self.search_in_flight.id: if msg.type is 'search_complete': self.search_in_flight.id = None if Object.keys(self.result_map).length is 0: self.no_result_received() elif msg.type is 'search_result': self.result_received(msg.result) def no_result_received(self): self.show_results() self.results_container.appendChild(E.div( style='margin: 1rem', _('No matching results found'))) def result_received(self, result): self.show_results() self.result_map[result.result_num] = result sr = Object.assign({}, result) self.view.discover_search_result(sr) toc_node_id = result.toc_nodes[0] if result.toc_nodes.length else -1 toc_node = self.toc_data.toc_id_map[toc_node_id] c = self.results_container group = c.querySelector(f'[data-toc-node-id="{toc_node_id}"]') if not group: group = E.div( data_toc_node_id=toc_node_id + '', data_spine_index=result.spine_idx + '', E.div( E.span('+\xa0', style='display: none'), E.span(toc_node?.title or _('Unknown')), title=_('Click to show/hide the results in this chapter'), onclick=def(ev): ev.target.closest('[data-toc-node-id]').classList.toggle('collapsed') ), E.ul() ) appended = False for child in c.querySelectorAll('[data-spine-index]'): csi = parseInt(child.dataset.spineIndex) if csi > result.spine_idx: appended = True c.insertBefore(group, child) break if not appended: c.appendChild(group) ul = group.getElementsByTagName('ul')[0] tt = '' if result.toc_nodes.length: lines = v'[]' for i, node_id in enumerate(result.toc_nodes): lines.push('\xa0\xa0' * i + '➤ ' + (self.toc_data.toc_id_map[node_id]?.title or _('Unknown'))) tt = ngettext('Table of Contents section:', 'Table of Contents sections:', lines.length) tt += '\n' + lines.join('\n') rnum = result.result_num entry = E.li(title=tt, data_result_num=rnum + '', onclick=self.result_clicked.bind(None, rnum)) if result.before: entry.appendChild(E.span('…' + result.before)) entry.appendChild(E.strong(result.text)) if result.after: entry.appendChild(E.span(result.after + '…')) ul.appendChild(entry) @property def current_result_container(self): return self.container.querySelector('.current') def make_result_current(self, result_num): q = result_num + '' for li in self.container.querySelectorAll('[data-result-num]'): if li.dataset.resultNum is q: li.classList.add('current') li.scrollIntoView() else: li.classList.remove('current') def search_result_discovered(self, sr): self.make_result_current(sr.result_num) def search_result_not_found(self, sr): if sr.on_discovery: return error_dialog( _('Search result not found'), _( 'This search result matches text that is hidden in the book and cannot be displayed')) self.show() def select_search_result_in_book(self, result_num): sr = Object.assign({}, self.result_map[result_num]) sr.on_discovery = 0 self.view.show_search_result(sr) def result_clicked(self, rnum): self.make_result_current(rnum) self.select_search_result_in_book(rnum) self.hide() def clear_caches(self, book): self.clear_results() self.bottom_container.style.display = 'none' if self._worker: book = book or current_book() self.toc_data = get_toc_data(book) data = { 'book_hash': book.book_hash, 'stored_files': book.stored_files, 'spine': book.manifest.spine, 'toc_data': self.toc_data } self.worker.postMessage({'type': 'clear_caches', 'book': data}) def next_match(self, delta): delta = delta or 1 num_of_results = Object.keys(self.result_map).length c = self.current_result_container if c: rnum = parseInt(c.dataset.resultNum) - 1 rnum = (rnum + delta + num_of_results) % num_of_results rnum += 1 else: rnum = 1 self.make_result_current(rnum) self.results_container.focus() cr = self.current_result_container if cr: self.select_search_result_in_book(cr.dataset.resultNum) def onkeyup(self, event): if event.key is 'Escape' or event.key is 'Esc': self.hide() event.stopPropagation(), event.preventDefault() def onkeydown(self, event): sc_name = shortcut_for_key_event(event, self.view.keyboard_shortcut_map) if sc_name is 'next_match': self.next_match(1) event.stopPropagation(), event.preventDefault() return if sc_name is 'previous_match': self.next_match(-1) event.stopPropagation(), event.preventDefault() return def find_next(self, backwards): self.next_match(-1 if backwards else 1) @property def container(self): return document.getElementById(self.CONTAINER_ID) @property def is_visible(self): return self.container.style.display is not 'none' def set_text(self, text): self.container.querySelector('input[type=search]').value = text or '' def hide(self): self.container.style.display = 'none' ui_operations.focus_iframe() def show(self): c = self.container c.style.display = self.display_type inp = c.querySelector('input') inp.focus(), inp.select() def run_search(self): q = self.current_query if not q.text: self.clear_results() self.show_results() else: self.queue_search(q, current_book(), self.view.currently_showing.name) add_extra_css(def(): css = '' sel = f'#{SearchOverlay.CONTAINER_ID} ' sel += ' div[data-toc-node-id]' css += build_rule(sel, margin='1rem') css += sel + '.collapsed > div > span { display: inline !important; }' css += build_rule(sel + '.collapsed > ul', display='none') css += build_rule(sel + ' > div', font_style='italic', font_weight='bold', cursor='pointer') css += build_rule(sel + ' li', list_style_type='none', margin='1rem', margin_right='0', cursor='pointer') css += build_rule(sel + ' li.current', border_left='solid 2px ' + get_color('link-foreground'), padding_left='2px') css += build_rule(sel + ' li strong', color=get_color('link-foreground'), font_style='italic') return css ) main = worker_main
16,807
Python
.py
384
33.473958
165
0.592737
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,511
test_cfi.pyj
kovidgoyal_calibre/src/pyj/read_book/test_cfi.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from read_book.cfi import encode, decode, escape_for_cfi, unescape_from_cfi, cfi_for_selection from testing import assert_equal, test @test def cfi_escaping(): t = 'a^!,1' assert_equal(t, unescape_from_cfi(escape_for_cfi(t))) @test def cfi_roundtripping(): idc = 0 def nid(): nonlocal idc idc += 1 return idc + '' document.body.appendChild(E.p('abc')) p = document.body.firstChild path_to_p = '/2/4/2' assert_equal(encode(document, p), path_to_p) assert_equal(decode(path_to_p), {'node': p}) assert_equal(encode(document, p.firstChild), f'{path_to_p}/1:0') assert_equal(decode(f'{path_to_p}/1:0'), {'node': p.firstChild, 'offset': 0}) assert_equal(encode(document, p.firstChild, 1), f'{path_to_p}/1:1') assert_equal(decode(f'{path_to_p}/1:1'), {'node': p.firstChild, 'offset': 1}) p.appendChild(document.createTextNode('def')) assert_equal(encode(document, p.firstChild, 5), f'{path_to_p}/1:5') assert_equal(p.childNodes.length, 2) assert_equal(encode(document, p.lastChild, 1), f'{path_to_p}/1:4') assert_equal(decode(f'{path_to_p}/1:5'), {'node': p.lastChild, 'offset': 2}) assert_equal(decode(f'{path_to_p}/1:1'), {'node': p.firstChild, 'offset': 1}) p.appendChild(E.span('123', id=nid())) span = p.lastChild path_to_span = f'{path_to_p}/2[{span.id}]' p.appendChild(document.createTextNode('456')) assert_equal(encode(document, p.lastChild, 1), f'{path_to_p}/1:7') assert_equal(decode(f'{path_to_p}/1:7'), {'node': p.lastChild, 'offset': 1}) assert_equal(encode(document, span), path_to_span) assert_equal(decode(path_to_span), {'node': span}) assert_equal(encode(document, span.firstChild, 1), f'{path_to_span}/1:1') assert_equal(decode(f'{path_to_span}/1:1'), {'node': span.firstChild, 'offset': 1}) @test def cfi_with_range_wrappers(): document.body.appendChild(E.p('abc', E.span('def', data_calibre_range_wrapper='1'), '123')) p = document.body.firstChild path_to_p = encode(document, p) rw1 = p.querySelector('span') assert_equal(encode(document, p.firstChild, 1), f'{path_to_p}/1:1') assert_equal(decode(f'{path_to_p}/1:1'), {'node': p.firstChild, 'offset': 1}) assert_equal(encode(document, rw1), f'{path_to_p}/1:3') assert_equal(decode(f'{path_to_p}/1:3'), {'node': p.firstChild, 'offset': 3}) assert_equal(encode(document, rw1.firstChild, 1), f'{path_to_p}/1:4') assert_equal(decode(f'{path_to_p}/1:4'), {'node': rw1.firstChild, 'offset': 1}) assert_equal(encode(document, p.lastChild, 1), f'{path_to_p}/1:7') assert_equal(decode(f'{path_to_p}/1:7'), {'node': p.lastChild, 'offset': 1}) p.appendChild(E.span('456', E.i('789'), data_calibre_range_wrapper='2')) itag = p.querySelector('i') assert_equal(encode(document, p.lastChild.firstChild, 1), f'{path_to_p}/1:10') assert_equal(decode(f'{path_to_p}/1:10'), {'node': p.lastChild.firstChild, 'offset': 1}) assert_equal(encode(document, itag), f'{path_to_p}/2') assert_equal(decode(f'{path_to_p}/2'), {'node': itag}) assert_equal(encode(document, itag.firstChild, 2), f'{path_to_p}/2/1:2') assert_equal(decode(f'{path_to_p}/2/1:2'), {'node': itag.firstChild, 'offset': 2}) document.body.appendChild(E.p('abc')) p = document.body.lastChild path_to_p = encode(document, p) p.appendChild(document.createTextNode('def')) assert_equal(decode(f'{path_to_p}/1:2'), {'node': p.firstChild, 'offset': 2}) assert_equal(decode(f'{path_to_p}/3:2'), {'node': p.lastChild, 'offset': 2}) document.body.appendChild(E.p('abc')) p = document.body.lastChild path_to_p = encode(document, p) without_wrapper = encode(document, p.firstChild, 0) assert_equal(without_wrapper, f'{path_to_p}/1:0') p.removeChild(p.firstChild) p.appendChild(E.span('abc', data_calibre_range_wrapper='7')) with_wrapper = encode(document, p.firstChild.firstChild, 0) assert_equal(without_wrapper, with_wrapper) p.appendChild(document.createTextNode('def')) after_wrapper = encode(document, p.lastChild, 1) assert_equal(after_wrapper, f'{path_to_p}/1:4') document.body.appendChild( E.p(E.span('abc', data_calibre_range_wrapper='8'), 'def', E.span('123', data_calibre_range_wrapper='9'), '456')) p = document.body.lastChild path_to_p = encode(document, p) rw = p.querySelectorAll('span')[-1] assert_equal(decode(f'{path_to_p}/1:0'), {'node': p.firstChild.firstChild, 'offset': 0}) assert_equal(decode(f'{path_to_p}/1:5'), {'node': p.firstChild.nextSibling, 'offset': 2}) assert_equal(decode(f'{path_to_p}/1:7'), {'node': rw.firstChild, 'offset': 1}) assert_equal(decode(f'{path_to_p}/1:11'), {'node': rw.nextSibling, 'offset': 2}) document.body.appendChild(E.p( E.span('Labor is', data_calibre_range_wrapper='10'), E.em(E.span('not the source', data_calibre_range_wrapper='10')), E.span(' of all wealth.', data_calibre_range_wrapper='10'), ' ', E.em('Nature'), ' is just as much. The above', )) p = document.body.lastChild path_to_p = encode(document, p) r = document.createRange() em = p.querySelectorAll('em')[-1] r.setStart(em.firstChild, 0) r.setEnd(p.lastChild, 3) assert_equal(r.toString(), 'Nature is') bounds = cfi_for_selection(r) s = decode(bounds.start) r.setStart(s.node, s.offset) e = decode(bounds.end) r.setEnd(e.node, e.offset) assert_equal(r.toString(), 'Nature is') assert_equal(decode(bounds.end), {'node': p.lastChild, 'offset': 3})
5,805
Python
.py
113
46.283186
120
0.651745
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,512
iframe.pyj
kovidgoyal_calibre/src/pyj/read_book/iframe.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals import traceback from select import first_visible_word, is_start_closer_to_point, move_end_of_selection, selection_extents, word_at_point from fs_images import fix_fullscreen_svg_images from iframe_comm import IframeClient from range_utils import ( all_annots_in_selection, highlight_associated_with_selection, last_span_for_crw, reset_highlight_counter, select_crw, unwrap_all_crw, unwrap_crw, wrap_text_in_range ) from read_book.anchor_visibility import ensure_page_list_target_is_displayed, invalidate_anchor_position_cache from read_book.cfi import cfi_for_selection, range_from_cfi from read_book.extract import get_elements from read_book.find import reset_find_caches, select_search_result, select_tts_mark, tts_data from read_book.flow_mode import anchor_funcs as flow_anchor_funcs from read_book.flow_mode import auto_scroll_action as flow_auto_scroll_action from read_book.flow_mode import cancel_drag_scroll as cancel_drag_scroll_flow from read_book.flow_mode import ensure_selection_boundary_visible as ensure_selection_boundary_visible_flow from read_book.flow_mode import ensure_selection_visible, flow_onwheel, flow_to_scroll_fraction from read_book.flow_mode import handle_gesture as flow_handle_gesture from read_book.flow_mode import handle_shortcut as flow_handle_shortcut from read_book.flow_mode import jump_to_cfi as flow_jump_to_cfi from read_book.flow_mode import layout as flow_layout from read_book.flow_mode import scroll_by_page as flow_scroll_by_page from read_book.flow_mode import scroll_to_extend_annotation as flow_annotation_scroll from read_book.flow_mode import start_drag_scroll as start_drag_scroll_flow from read_book.footnotes import is_footnote_link from read_book.gestures import action_for_gesture from read_book.globals import ( annot_id_uuid_map, clear_annot_id_uuid_map, current_book, current_layout_mode, current_spine_item, runtime, set_boss, set_current_spine_item, set_layout_mode, set_toc_anchor_map ) from read_book.highlights import highlight_style_as_css from read_book.hints import apply_prefix_to_hints, hint_visible_links, unhint_links from read_book.mathjax import apply_mathjax from read_book.paged_mode import anchor_funcs as paged_anchor_funcs from read_book.paged_mode import auto_scroll_action as paged_auto_scroll_action from read_book.paged_mode import ( calc_columns_per_screen, current_cfi, get_columns_per_screen_data, page_counts, progress_frac, reset_paged_mode_globals, scroll_to_elem, snap_to_selection, will_columns_per_screen_change ) from read_book.paged_mode import cancel_drag_scroll as cancel_drag_scroll_paged from read_book.paged_mode import ensure_selection_boundary_visible as ensure_selection_boundary_visible_paged from read_book.paged_mode import handle_gesture as paged_handle_gesture from read_book.paged_mode import handle_shortcut as paged_handle_shortcut from read_book.paged_mode import jump_to_cfi as paged_jump_to_cfi from read_book.paged_mode import layout as paged_layout from read_book.paged_mode import onwheel as paged_onwheel from read_book.paged_mode import prepare_for_resize as paged_prepare_for_resize from read_book.paged_mode import resize_done as paged_resize_done from read_book.paged_mode import scroll_by_page as paged_scroll_by_page from read_book.paged_mode import scroll_to_extend_annotation as paged_annotation_scroll from read_book.paged_mode import scroll_to_fraction as paged_scroll_to_fraction from read_book.paged_mode import start_drag_scroll as start_drag_scroll_paged from read_book.referencing import elem_for_ref, end_reference_mode, start_reference_mode from read_book.resources import finalize_resources, unserialize_html from read_book.settings import ( apply_colors, apply_font_size, apply_settings, apply_stylesheet, opts, set_color_scheme_class, set_selection_style, update_settings ) from read_book.shortcuts import create_shortcut_map, keyevent_as_shortcut, shortcut_for_key_event from read_book.smil import flatten_smil_map, mark_smil_element, smil_element_at from read_book.toc import find_anchor_before_range, update_visible_toc_anchors from read_book.touch import create_handlers as create_touch_handlers from read_book.touch import reset_handlers as reset_touch_handlers from read_book.viewport import scroll_viewport from utils import debounce, is_ios FORCE_FLOW_MODE = False CALIBRE_VERSION = '__CALIBRE_VERSION__' ONSCROLL_DEBOUNCE_TIME = 1000 ERS_SUPPORTED_FEATURES = {'dom-manipulation', 'layout-changes', 'touch-events', 'mouse-events', 'keyboard-events', 'spine-scripting'} def layout_style(): return 'scrolling' if current_layout_mode() is 'flow' else 'paginated' drag_mouse_position = {'x': None, 'y': None} def cancel_drag_scroll(): cancel_drag_scroll_flow() cancel_drag_scroll_paged() class EPUBReadingSystem: @property def name(self): return 'calibre' @property def version(self): return CALIBRE_VERSION @property def layoutStyle(self): return layout_style() def hasFeature(self, feature, version): return feature in ERS_SUPPORTED_FEATURES def __repr__(self): return f'{{name:{self.name}, version:{self.version}, layoutStyle:{self.layoutStyle}}}' def __str__(self): return self.__repr__() class FullBookSearch: def __init__(self): start_spine_index = current_spine_item()?.index if not start_spine_index?: start_spine_index = -1 self.start_spine_index = start_spine_index self.progress_frac_at_start = progress_frac() self.first_result_shown = False class IframeBoss: def __init__(self): window.navigator.epubReadingSystem = EPUBReadingSystem() self.last_cfi = None self.last_search_at = -1001 self.reference_mode_enabled = False self.replace_history_on_next_cfi_update = True self.blob_url_map = {} self.content_ready = False self.last_window_width = self.last_window_height = -1 self.forward_keypresses = False self.full_book_search_in_progress = None set_boss(self) handlers = { 'change_color_scheme': self.change_color_scheme, 'change_font_size': self.change_font_size, 'viewer_font_size_changed': self.viewer_font_size_changed, 'change_number_of_columns': self.change_number_of_columns, 'number_of_columns_changed': self.number_of_columns_changed, 'change_scroll_speed': self.change_scroll_speed, 'display': self.display, 'gesture_from_margin': self.gesture_from_margin, 'get_current_cfi': self.get_current_cfi, 'initialize':self.initialize, 'modify_selection': self.modify_selection, 'next_screen': self.on_next_screen, 'scroll_to_anchor': self.on_scroll_to_anchor, 'scroll_to_frac': self.on_scroll_to_frac, 'scroll_to_ref': self.on_scroll_to_ref, 'fake_popup_activation': self.on_fake_popup_activation, 'set_reference_mode': self.set_reference_mode, 'toggle_autoscroll': self.toggle_autoscroll, 'fake_wheel_event': self.fake_wheel_event, 'window_size': self.received_window_size, 'overlay_visibility_changed': self.on_overlay_visibility_changed, 'show_search_result': self.show_search_result, 'handle_navigation_shortcut': self.on_handle_navigation_shortcut, 'annotations': self.annotations_msg_received, 'tts': self.tts_msg_received, 'audio-ebook': self.audio_ebook_msg_received, 'hints': self.hints_msg_received, 'copy_selection': self.copy_selection, 'replace_highlights': self.replace_highlights, 'clear_selection': def(): window.getSelection().removeAllRanges();, } self.comm = IframeClient(handlers, 'main-iframe') self.last_window_ypos = 0 self.length_before = None def on_overlay_visibility_changed(self, data): cancel_drag_scroll() if data.visible: self.forward_keypresses = True if self.auto_scroll_action: self.auto_scroll_active_before_overlay = self.auto_scroll_action('is_active') self.auto_scroll_action('stop') else: self.forward_keypresses = False if self.auto_scroll_active_before_overlay: self.auto_scroll_active_before_overlay = undefined self.auto_scroll_action('start') def modify_selection(self, data): sel = window.getSelection() use_end = False if data.granularity is 'all': r = document.createRange() r.selectNode(document.body) sel.removeAllRanges() sel.addRange(r) else: use_end = data.direction is 'forward' or data.direction is 'right' try: sel.modify('extend', data.direction, data.granularity) except: if data.granularity is 'paragraph': sel.modify('extend', data.direction, 'line') self.ensure_selection_boundary_visible(use_end) def initialize(self, data): scroll_viewport.update_window_size(data.width, data.height) window.addEventListener('error', self.onerror) window.addEventListener('scroll', debounce(self.onscroll, ONSCROLL_DEBOUNCE_TIME)) window.addEventListener('scroll', self.no_latency_onscroll) window.addEventListener('resize', debounce(self.onresize, 500)) window.addEventListener('wheel', self.onwheel, {'passive': False}) window.addEventListener('keydown', self.onkeydown, {'passive': False}) window.addEventListener('mousemove', self.onmousemove, {'passive': True}) window.addEventListener('mouseup', self.onmouseup, {'passive': True}) window.addEventListener('dblclick', self.ondoubleclick, {'passive': True}) document.documentElement.addEventListener('contextmenu', self.oncontextmenu, {'passive': False}) document.addEventListener('selectionchange', self.onselectionchange) self.color_scheme = data.color_scheme create_touch_handlers() def onerror(self, evt): msg = evt.message script_url = evt.filename line_number = evt.lineno column_number = evt.colno error_object = evt.error evt.stopPropagation(), evt.preventDefault() if error_object is None: # This happens for cross-domain errors (probably javascript injected # into the browser via extensions/ userscripts and the like). It also # happens all the time when using Chrome on Safari, so ignore this # type of error console.log(f'Unhandled error from external javascript, ignoring: {msg} {script_url} {line_number}') return is_internal_error = script_url in ('about:srcdoc', 'userscript:viewer.js') if is_internal_error: # dont report errors from scripts in the book itself console.log(f'{script_url}: {error_object}') try: fname = script_url.rpartition('/')[-1] or script_url msg = msg + '<br><span style="font-size:smaller">' + 'Error at {}:{}:{}'.format(fname, line_number, column_number or '') + '</span>' details = traceback.format_exception(error_object).join('') if error_object else '' if details: console.log(details) self.send_message('error', errkey='unhandled-error', details=details, msg=msg) except: console.log('There was an error in the iframe unhandled exception handler') else: (console.error or console.log)('There was an error in the JavaScript from within the book') def display(self, data): cancel_drag_scroll() drag_mouse_position.x = drag_mouse_position.y = None self.length_before = None self.content_ready = False clear_annot_id_uuid_map() reset_highlight_counter() set_toc_anchor_map() self.replace_history_on_next_cfi_update = True self.book = current_book.book = data.book self.smil_map = data.smil_map self.smil_anchor_map, self.smil_par_list = flatten_smil_map(self.smil_map) self.link_attr = 'data-' + self.book.manifest.link_uid self.reference_mode_enabled = data.reference_mode_enabled self.is_titlepage = data.is_titlepage spine = self.book.manifest.spine index = spine.indexOf(data.name) reset_paged_mode_globals() set_layout_mode('flow' if FORCE_FLOW_MODE else data.settings.read_mode) if current_layout_mode() is 'flow': self.do_layout = flow_layout self.handle_wheel = flow_onwheel self.handle_navigation_shortcut = flow_handle_shortcut self._handle_gesture = flow_handle_gesture self.to_scroll_fraction = flow_to_scroll_fraction self.jump_to_cfi = flow_jump_to_cfi self.anchor_funcs = flow_anchor_funcs self.auto_scroll_action = flow_auto_scroll_action self.scroll_to_extend_annotation = flow_annotation_scroll self.ensure_selection_visible = ensure_selection_visible self.ensure_selection_boundary_visible = ensure_selection_boundary_visible_flow self.start_drag_scroll = start_drag_scroll_flow paged_auto_scroll_action('stop') else: self.do_layout = paged_layout self.handle_wheel = paged_onwheel self.handle_navigation_shortcut = paged_handle_shortcut self.to_scroll_fraction = paged_scroll_to_fraction self.jump_to_cfi = paged_jump_to_cfi self._handle_gesture = paged_handle_gesture self.anchor_funcs = paged_anchor_funcs self.auto_scroll_action = paged_auto_scroll_action self.scroll_to_extend_annotation = paged_annotation_scroll self.ensure_selection_visible = snap_to_selection self.ensure_selection_boundary_visible = ensure_selection_boundary_visible_paged self.start_drag_scroll = start_drag_scroll_paged flow_auto_scroll_action('stop') update_settings(data.settings) self.keyboard_shortcut_map = create_shortcut_map(data.settings.keyboard_shortcuts) set_current_spine_item({ 'name':data.name, 'is_first':index is 0, 'is_last':index is spine.length - 1, 'index': index, 'initial_position':data.initial_position }) self.last_cfi = None for name in self.blob_url_map: window.URL.revokeObjectURL(self.blob_url_map[name]) document.body.style.removeProperty('font-family') root_data, self.mathjax, self.blob_url_map = finalize_resources(self.book, data.name, data.resource_data) self.highlights_to_apply = data.highlights unserialize_html(root_data, self.content_loaded, None, data.name) def on_scroll_to_frac(self, data): self.to_scroll_fraction(data.frac, False) def toggle_autoscroll(self): self.auto_scroll_action('toggle') def handle_gesture(self, gesture): gesture.resolved_action = action_for_gesture(gesture, current_layout_mode() is 'flow') if gesture.resolved_action is 'show_chrome': self.send_message('show_chrome') elif gesture.resolved_action is 'decrease_font_size': self.send_message('bump_font_size', increase=False) elif gesture.resolved_action is 'increase_font_size': self.send_message('bump_font_size', increase=True) elif gesture.resolved_action is 'highlight_or_inspect': self.handle_long_tap(gesture) else: self._handle_gesture(gesture) def handle_long_tap(self, gesture): elements = get_elements(gesture.viewport_x, gesture.viewport_y) if elements.img: self.send_message('view_image', calibre_src=elements.img) return if elements.highlight: select_crw(elements.crw) return r = word_at_point(gesture.viewport_x, gesture.viewport_y) if r: s = document.getSelection() s.removeAllRanges() s.addRange(r) def gesture_from_margin(self, data): self.handle_gesture(data.gesture) def fake_wheel_event(self, data): # these are wheel events from margin or selection mode self.onwheel(data.evt) def report_human_scroll(self, scrolled_by_frac): self.send_message('human_scroll', scrolled_by_frac=scrolled_by_frac or None) def on_scroll_to_anchor(self, data): frag = data.frag if frag: self.replace_history_on_next_cfi_update = False self.scroll_to_anchor(frag) else: self.to_scroll_fraction(0.0, False) def on_next_screen(self, data): backwards = data.backwards if current_layout_mode() is 'flow': flow_scroll_by_page(-1 if backwards else 1, data.flip_if_rtl_page_progression) else: paged_scroll_by_page(backwards, data.all_pages_on_screen, data.flip_if_rtl_page_progression) def change_font_size(self, data): if data.base_font_size? and data.base_font_size != opts.base_font_size: opts.base_font_size = data.base_font_size apply_font_size() if not runtime.is_standalone_viewer: # in the standalone viewer this is a separate event as # apply_font_size() is a no-op self.relayout_on_font_size_change() def viewer_font_size_changed(self, data): self.relayout_on_font_size_change() def change_number_of_columns(self, data): if current_layout_mode() is 'flow': self.send_message('error', errkey='changing-columns-in-flow-mode') return cdata = get_columns_per_screen_data() delta = int(data.delta) if delta is 0: new_val = 0 else: new_val = max(1, cdata.cps + delta) opts.columns_per_screen[cdata.which] = new_val self.relayout_on_font_size_change() self.send_message('columns_per_screen_changed', which=cdata.which, cps=new_val) def relayout_on_font_size_change(self): if current_layout_mode() is not 'flow' and will_columns_per_screen_change(): self.do_layout(self.is_titlepage) if self.last_cfi: cfi = self.last_cfi[len('epubcfi(/'):-1].partition('/')[2] if cfi: self.jump_to_cfi('/' + cfi) self.update_cfi() invalidate_anchor_position_cache() self.update_toc_position(True) def number_of_columns_changed(self, data): opts.columns_per_screen = data.columns_per_screen self.relayout_on_font_size_change() def change_scroll_speed(self, data): if data.lines_per_sec_auto?: opts.lines_per_sec_auto = data.lines_per_sec_auto def change_stylesheet(self, data): opts.user_stylesheet = data.sheet or '' apply_stylesheet() def change_color_scheme(self, data): if data.color_scheme and data.color_scheme.foreground and data.color_scheme.background: opts.color_scheme = data.color_scheme apply_colors() set_color_scheme_class() def content_loaded(self): document.documentElement.style.overflow = 'hidden' if self.is_titlepage and not opts.cover_preserve_aspect_ratio: document.body.classList.add('cover-fill') document.body.classList.add(f'calibre-viewer-{layout_style()}') set_color_scheme_class() if self.reference_mode_enabled: start_reference_mode() self.last_window_width, self.last_window_height = scroll_viewport.width(), scroll_viewport.height() if self.highlights_to_apply: self.apply_highlights_on_load(self.highlights_to_apply) self.highlights_to_apply = None apply_settings() invalidate_anchor_position_cache() fix_fullscreen_svg_images() self.do_layout(self.is_titlepage) if self.mathjax: return apply_mathjax(self.mathjax, self.book.manifest.link_uid, self.content_loaded_stage2) # window.setTimeout(self.content_loaded_stage2, 1000) self.content_loaded_stage2() def content_loaded_stage2(self): reset_find_caches() self.connect_links() if runtime.is_standalone_viewer: self.listen_for_image_double_clicks() self.content_ready = True if document.head?.firstChild: # this is the loading styles used to suppress scrollbars during load # added in unserialize_html document.head.removeChild(document.head.firstChild) csi = current_spine_item() if csi.initial_position: ipos = csi.initial_position self.replace_history_on_next_cfi_update = ipos.replace_history or False if ipos.type is 'frac': self.to_scroll_fraction(ipos.frac, True) elif ipos.type is 'anchor': self.scroll_to_anchor(ipos.anchor) elif ipos.type is 'ref': self.scroll_to_ref(ipos.refnum) elif ipos.type is 'cfi': self.jump_to_cfi(ipos.cfi) elif ipos.type is 'search_result': self.show_search_result(ipos, True) elif ipos.type is 'edit_annotation': window.setTimeout(def(): self.annotations_msg_received({'type': 'edit-highlight', 'uuid': ipos.uuid}) , 5) elif ipos.type is 'smil_id': self.audio_ebook_msg_received({'type': 'play', 'anchor': ipos.anchor}) elif ipos.type is 'pagelist_ref': self.scroll_to_pagelist_ref(ipos.anchor) spine = self.book.manifest.spine files = self.book.manifest.files spine_index = csi.index self.length_before = 0 if spine_index > -1: for i in range(spine_index): si = spine[i] if si: self.length_before += files[si]?.length or 0 self.send_message( 'content_loaded', progress_frac=self.calculate_progress_frac(), file_progress_frac=progress_frac(), page_counts=page_counts() ) self.last_cfi = None self.auto_scroll_action('resume') reset_touch_handlers() # Needed to mitigate issue https://bugs.chromium.org/p/chromium/issues/detail?id=464579 window.setTimeout(self.update_cfi, ONSCROLL_DEBOUNCE_TIME) window.setTimeout(self.update_toc_position, 0) load_event = document.createEvent('Event') load_event.initEvent('load', False, False) window.dispatchEvent(load_event) def calculate_progress_frac(self): current_name = current_spine_item().name files = self.book.manifest.files file_length = files[current_name]?.length or 0 if self.length_before is None: return 0 frac = progress_frac() ans = (self.length_before + (file_length * frac)) / self.book.manifest.spine_length return ans def get_current_cfi(self, data): cfi = current_cfi() csi = current_spine_item() def epubcfi(cfi): return 'epubcfi(/{}{})'.format(2*(index+1), cfi) if cfi else None if cfi and csi: index = csi.index if index > -1: selection = window.getSelection() selcfi = seltext = None if selection and not selection.isCollapsed: seltext = selection.toString() selcfi = cfi_for_selection() selcfi.start = epubcfi(selcfi.start) selcfi.end = epubcfi(selcfi.end) cfi = epubcfi(cfi) self.send_message( 'report_cfi', cfi=cfi, progress_frac=self.calculate_progress_frac(), file_progress_frac=progress_frac(), request_id=data.request_id, selected_text=seltext, selection_bounds=selcfi, page_counts=page_counts()) return self.send_message( 'report_cfi', cfi=None, progress_frac=0, file_progress_frac=0, page_counts=page_counts(), request_id=data.request_id) def update_cfi(self, force_update): cfi = current_cfi() if cfi: index = current_spine_item().index if index > -1: cfi = 'epubcfi(/{}{})'.format(2*(index+1), cfi) pf = self.calculate_progress_frac() fpf = progress_frac() if cfi is not self.last_cfi or force_update: self.last_cfi = cfi self.send_message( 'update_cfi', cfi=cfi, replace_history=self.replace_history_on_next_cfi_update, progress_frac=pf, file_progress_frac=fpf, page_counts=page_counts()) self.replace_history_on_next_cfi_update = True else: self.send_message( 'update_progress_frac', progress_frac=pf, file_progress_frac=fpf, page_counts=page_counts()) def update_toc_position(self, recalculate_toc_anchor_positions): visible_anchors = update_visible_toc_anchors(self.book.manifest.toc_anchor_map, self.book.manifest.page_list_anchor_map, bool(recalculate_toc_anchor_positions)) self.send_message('update_toc_position', visible_anchors=visible_anchors) def onscroll(self): if self.content_ready: self.update_cfi() self.update_toc_position() def no_latency_onscroll(self): pf = self.calculate_progress_frac() fpf = progress_frac() self.send_message( 'update_progress_frac', progress_frac=pf, file_progress_frac=fpf, page_counts=page_counts()) sel = window.getSelection() if sel and not sel.isCollapsed: self.send_message('update_selection_position', selection_extents=selection_extents(current_layout_mode() is 'flow', True)) def onresize(self): self.send_message('request_size') if self.content_ready: if is_ios: # On iOS window.innerWidth/Height are wrong inside the iframe, # so we wait for the reply from request_size return self.onresize_stage2() def onselectionchange(self): if not self.content_ready: return sel = window.getSelection() text = '' annot_id = None collapsed = not sel or sel.isCollapsed start_is_anchor = True if not collapsed: text = sel.toString() annot_id = highlight_associated_with_selection(sel, annot_id_uuid_map) r = sel.getRangeAt(0) start_is_anchor = r.startContainer is sel.anchorNode and r.startOffset is sel.anchorOffset now = window.performance.now() by_search = now - self.last_search_at < 1000 self.send_message( 'selectionchange', text=text, empty=v'!!collapsed', annot_id=annot_id, drag_mouse_position=drag_mouse_position, selection_change_caused_by_search=by_search, selection_extents=selection_extents(current_layout_mode() is 'flow'), rtl=scroll_viewport.rtl, vertical=scroll_viewport.vertical_writing_mode, start_is_anchor=start_is_anchor ) def onresize_stage2(self): if scroll_viewport.width() is self.last_window_width and scroll_viewport.height() is self.last_window_height: # Safari at least, generates lots of spurious resize events return if current_layout_mode() is not 'flow': paged_prepare_for_resize(self.last_window_width, self.last_window_height) self.do_layout(self.is_titlepage) self.last_window_width, self.last_window_height = scroll_viewport.width(), scroll_viewport.height() if self.last_cfi: cfi = self.last_cfi[len('epubcfi(/'):-1].partition('/')[2] if cfi: self.jump_to_cfi('/' + cfi) if current_layout_mode() is not 'flow': paged_resize_done() self.update_cfi() self.update_toc_position() sel = window.getSelection() if sel and not sel.isCollapsed: # update_selection_position has probably already been called by # no_latency_onscroll but make sure self.send_message('update_selection_position', selection_extents=selection_extents(current_layout_mode() is 'flow')) def received_window_size(self, data): scroll_viewport.update_window_size(data.width, data.height) if self.content_ready: self.onresize_stage2() def onwheel(self, evt): if self.content_ready: if evt.preventDefault: evt.preventDefault() if evt.deltaY and evt.ctrlKey and not evt.shiftKey and not evt.altKey and not evt.metaKey: self.send_message('handle_shortcut', name='increase_font_size' if evt.deltaY < 0 else 'decrease_font_size') else: self.handle_wheel(evt) def onmousemove(self, evt): if evt.buttons is not 1: return drag_mouse_position.x = evt.clientX drag_mouse_position.y = evt.clientY if 0 <= evt.clientY <= window.innerHeight: cancel_drag_scroll() return sel = window.getSelection() if not sel: cancel_drag_scroll() return delta = evt.clientY if evt.clientY < 0 else (evt.clientY - window.innerHeight) self.start_drag_scroll(delta) def onmouseup(self, evt): cancel_drag_scroll() drag_mouse_position.x = drag_mouse_position.y = None # ensure selection bar is updated self.onselectionchange() if evt.button is 3 or evt.button is 4: self.send_message('handle_shortcut', name='back' if evt.button is 3 else 'forward') def ondoubleclick(self, evt): self.send_message('annotations', type='double-click') def onkeydown(self, evt): if current_layout_mode() is not 'flow' and evt.key is 'Tab': # Prevent the TAB key from shifting focus as it causes partial scrolling evt.preventDefault() if self.forward_keypresses: self.send_message('handle_keypress', evt=keyevent_as_shortcut(evt)) evt.preventDefault(), evt.stopPropagation() return if self.content_ready: sc_name = shortcut_for_key_event(evt, self.keyboard_shortcut_map) if sc_name: evt.preventDefault() if not self.handle_navigation_shortcut(sc_name, evt): self.send_message('handle_shortcut', name=sc_name) def on_handle_navigation_shortcut(self, data): self.handle_navigation_shortcut(data.name, data.key or { 'key': '', 'altKey': False, 'ctrlKey': False, 'shiftKey': False, 'metaKey': False}) def oncontextmenu(self, evt): if self.content_ready: evt.preventDefault() self.send_message('show_chrome', elements=get_elements(evt.clientX, evt.clientY)) def send_message(self, action, **data): self.comm.send_message(action, data) def connect_links(self): for a in document.body.querySelectorAll(f'a[{self.link_attr}],area[{self.link_attr}]'): a.addEventListener('click', self.link_activated) if runtime.is_standalone_viewer: # links with a target get turned into requests to open a new window by Qt for a in document.body.querySelectorAll('a[target]'): a.removeAttribute('target') def listen_for_image_double_clicks(self): for img in document.querySelectorAll('img, image'): img.addEventListener('dblclick', self.image_double_clicked, {'passive': True}) def image_double_clicked(self, ev): img = ev.currentTarget if img.dataset.calibreSrc: self.send_message('view_image', calibre_src=img.dataset.calibreSrc) def link_activated(self, evt): try: data = JSON.parse(evt.currentTarget.getAttribute(self.link_attr)) except: print('WARNING: Failed to parse link data {}, ignoring'.format(evt.currentTarget?.getAttribute?(self.link_attr))) return self.activate_link(data.name, data.frag, evt.currentTarget) def activate_link(self, name, frag, target_elem): if not name: name = current_spine_item().name try: is_popup = is_footnote_link(target_elem, name, frag, current_spine_item().name, self.book.manifest.link_to_map or {}) except: import traceback traceback.print_exc() is_popup = False if is_popup: self.on_fake_popup_activation({'name': name, 'frag': frag, 'title': target_elem.textContent}) return if name is current_spine_item().name: self.replace_history_on_next_cfi_update = False self.scroll_to_anchor(frag) else: self.send_message('scroll_to_anchor', name=name, frag=frag) def on_fake_popup_activation(self, data): self.send_message( 'show_footnote', name=data.name, frag=data.frag, title=data.title, cols_per_screen=calc_columns_per_screen(), rtl=scroll_viewport.rtl, vertical_writing_mode=scroll_viewport.vertical_writing_mode ) def scroll_to_anchor(self, frag): if frag: elem = document.getElementById(frag) if not elem: c = document.getElementsByName(frag) if c and c.length: elem = c[0] if elem: scroll_to_elem(elem) else: scroll_viewport.scroll_to(0, 0) def scroll_to_pagelist_ref(self, frag): elem = document.getElementById(frag) if not elem: c = document.getElementsByName(frag) if c and c.length: elem = c[0] if elem: ensure_page_list_target_is_displayed(elem) scroll_to_elem(elem) def scroll_to_ref(self, refnum): refnum = int(refnum) elem = elem_for_ref(refnum) if elem: scroll_to_elem(elem) def on_scroll_to_ref(self, data): refnum = data.refnum if refnum?: self.scroll_to_ref(refnum) def show_search_result(self, data, from_load): if self.load_search_result_timer: window.clearTimeout(self.load_search_result_timer) self.load_search_result_timer = None sr = data.search_result if sr.on_discovery: if sr.result_num is 1: self.full_book_search_in_progress = FullBookSearch() elif self.full_book_search_in_progress?.first_result_shown: return self.last_search_at = window.performance.now() before_select_pos = {'x': scroll_viewport.x(), 'y': scroll_viewport.y()} if select_search_result(sr): self.ensure_selection_boundary_visible() need_workaround = from_load and current_layout_mode() is 'paged' if need_workaround: # workaround bug in chrome where sizes are incorrect in paged # mode on initial load for some books self.load_search_result_timer = window.setTimeout(self.ensure_search_result_visible.bind(None, before_select_pos), int(3 * ONSCROLL_DEBOUNCE_TIME / 4)) if self.full_book_search_in_progress and not self.full_book_search_in_progress.first_result_shown and sr.on_discovery: discovered = False if sr.force_jump_to or progress_frac() >= self.full_book_search_in_progress.progress_frac_at_start or current_spine_item().index is not self.full_book_search_in_progress.start_spine_index: self.full_book_search_in_progress.first_result_shown = True discovered = True else: scroll_viewport.scroll_to(before_select_pos.x, before_select_pos.y) self.send_message('search_result_discovered', search_result=data.search_result, discovered=discovered) if not need_workaround: self.add_search_result_to_history_stack(before_select_pos) else: self.send_message('search_result_not_found', search_result=data.search_result) def add_search_result_to_history_stack(self, before_select_pos): self.replace_history_on_next_cfi_update = False self.update_cfi(True) def ensure_search_result_visible(self, before_select_pos): self.load_search_result_timer = None sel = window.getSelection() if sel.isCollapsed or sel.rangeCount is 0: return self.ensure_selection_boundary_visible() self.add_search_result_to_history_stack(before_select_pos) def set_reference_mode(self, data): self.reference_mode_enabled = data.enabled if data.enabled: start_reference_mode() else: end_reference_mode() def apply_highlight(self, uuid, existing, has_notes, style): sel = window.getSelection() if not sel.rangeCount: return anchor_before = find_anchor_before_range(sel.getRangeAt(0), self.book.manifest.toc_anchor_map, self.book.manifest.page_list_anchor_map) text = sel.toString() bounds = cfi_for_selection() style = highlight_style_as_css(style, opts.is_dark_theme, opts.color_scheme.foreground) cls = 'crw-has-dot' if has_notes else None annot_id, intersecting_wrappers = wrap_text_in_range(style, None, cls, self.add_highlight_listeners) removed_highlights = v'[]' if annot_id is not None: intersecting_uuids = {annot_id_uuid_map[x]:True for x in intersecting_wrappers} if existing and intersecting_uuids[existing]: uuid = existing elif intersecting_wrappers.length is 1 and annot_id_uuid_map[intersecting_wrappers[0]]: uuid = annot_id_uuid_map[intersecting_wrappers[0]] intersecting_wrappers = v'[]' removed_highlights = {} for crw in intersecting_wrappers: unwrap_crw(crw) if annot_id_uuid_map[crw]: if annot_id_uuid_map[crw] is not uuid: removed_highlights[annot_id_uuid_map[crw]] = True v'delete annot_id_uuid_map[crw]' removed_highlights = Object.keys(removed_highlights) sel.removeAllRanges() annot_id_uuid_map[annot_id] = uuid self.send_message( 'annotations', type='highlight-applied', uuid=uuid, ok=annot_id is not None, bounds=bounds, removed_highlights=removed_highlights, highlighted_text=text, anchor_before=anchor_before ) reset_find_caches() def annotations_msg_received(self, data): dtype = data?.type if dtype is 'move-end-of-selection': move_end_of_selection(data.pos, data.start) elif dtype is 'set-highlight-style': set_selection_style(data.style) elif dtype is 'trigger-shortcut': self.on_handle_navigation_shortcut(data) elif dtype is 'extend-to-paragraph': sel = window.getSelection() try: try: sel.modify('extend', 'forward', 'paragraphboundary') except: sel.modify('extend', 'forward', 'lineboundary') end_node, end_offset = sel.focusNode, sel.focusOffset try: sel.modify('extend', 'backward', 'paragraphboundary') except: sel.modify('extend', 'backward', 'lineboundary') sel.setBaseAndExtent(sel.focusNode, sel.focusOffset, end_node, end_offset) except: (console.error or console.log)('Failed to extend selection to paragraph') elif dtype is 'extend-to-point': move_end_of_selection(data.pos, is_start_closer_to_point(data.pos)) elif dtype is 'drag-scroll': self.scroll_to_extend_annotation(data.backwards) elif dtype is 'edit-highlight': found_highlight_to_edit = False for qcrw, quuid in Object.entries(annot_id_uuid_map): if quuid is data.uuid and select_crw(qcrw): found_highlight_to_edit = True break if found_highlight_to_edit: self.ensure_selection_visible() window.setTimeout(def(): self.send_message('annotations', type='edit-highlight') , 50) else: self.send_message('annotations', type='edit-highlight-failed', uuid=data.uuid) elif dtype is 'notes-edited': cls = 'crw-has-dot' for qcrw, quuid in Object.entries(annot_id_uuid_map): if quuid is data.uuid: node = last_span_for_crw(qcrw) if node: if data.has_notes: node.classList.add(cls) else: node.classList.remove(cls) elif dtype is 'remove-highlight': found_highlight_to_remove = False for qcrw, quuid in Object.entries(annot_id_uuid_map): if quuid is data.uuid: found_highlight_to_remove = True unwrap_crw(qcrw) v'delete annot_id_uuid_map[qcrw]' if found_highlight_to_remove: # have to remove selection otherwise selection bar does # not hide itself on multiline selections window.getSelection().removeAllRanges() elif dtype is 'apply-highlight': existing = all_annots_in_selection(window.getSelection(), annot_id_uuid_map) if existing.length is 0 or (existing.length is 1 and existing[0] is data.existing): self.apply_highlight(data.uuid, data.existing, data.has_notes, data.style) else: self.send_message( 'annotations', type='highlight-overlapped', uuid=data.uuid, existing=data.existing, has_notes=data.has_notes, style=data.style) elif dtype is 'apply-highlight-overwrite': self.apply_highlight(data.uuid, data.existing, data.has_notes, data.style) elif dtype is 'cite-current-selection': sel = window.getSelection() if not sel.rangeCount: return bounds = cfi_for_selection() text = sel.toString() self.send_message('annotations', type='cite-data', bounds=bounds, highlighted_text=text) else: console.log('Ignoring annotations message to iframe with unknown type: ' + dtype) def apply_highlights_on_load(self, highlights): clear_annot_id_uuid_map() reset_highlight_counter() strcmp = v'new Intl.Collator().compare' highlights.sort(def (a, b): return strcmp(a.timestamp, b.timestamp);) for h in highlights: r = range_from_cfi(h.start_cfi, h.end_cfi) if not r: continue style = highlight_style_as_css(h.style, opts.is_dark_theme, opts.color_scheme.foreground) cls = 'crw-has-dot' if h.notes else None annot_id, intersecting_wrappers = wrap_text_in_range(style, r, cls, self.add_highlight_listeners) if annot_id is not None: annot_id_uuid_map[annot_id] = h.uuid for crw in intersecting_wrappers: unwrap_crw(crw) v'delete annot_id_uuid_map[crw]' def replace_highlights(self, data): highlights = data.highlights unwrap_all_crw() self.apply_highlights_on_load(highlights or v'[]') def add_highlight_listeners(self, wrapper): wrapper.addEventListener('dblclick', self.highlight_wrapper_dblclicked) def highlight_wrapper_dblclicked(self, ev): crw = ev.currentTarget.dataset.calibreRangeWrapper if crw: ev.preventDefault(), ev.stopPropagation() select_crw(crw) def copy_selection(self): try: if document.execCommand('copy'): return except: pass s = window.getSelection() text = s.toString() if text: container = document.createElement('div') for i in range(s.rangeCount): container.appendChild(s.getRangeAt(i).cloneContents()) self.send_message('copy_text_to_clipboard', text=text, html=container.innerHTML) def tts_msg_received(self, data): if data.type is 'mark': self.mark_word_being_spoken(data.num) elif data.type is 'play': text_node, offset = None, 0 if data.pos: r = word_at_point(data.pos.x, data.pos.y) if not r: return else: r = first_visible_word() if r and r.startContainer?.nodeType is Node.TEXT_NODE: text_node, offset = r.startContainer, r.startOffset marked_text = tts_data(text_node, offset) sel = window.getSelection() sel.removeAllRanges() self.send_message('tts', type='text-extracted', marked_text=marked_text, pos=data.pos) def mark_word_being_spoken(self, x): if jstype(x) is 'number': x = {'first': x, 'last': x} self.last_search_at = window.performance.now() if select_tts_mark(x.first, x.last): self.ensure_selection_boundary_visible() def audio_ebook_msg_received(self, data): if data.type is 'mark': if data.anchor: self.last_search_at = window.performance.now() if mark_smil_element(data.anchor): self.ensure_selection_boundary_visible() self.send_message('audio_ebook_message', type='marked', anchor=data.anchor, idx=data.idx) else: self.send_message('audio_ebook_message', type='marked') else: window.getSelection().removeAllRanges() self.send_message('audio_ebook_message', type='marked') elif data.type is 'play': if data.anchor: pos = self.smil_anchor_map[data.anchor] if pos?: par = self.smil_par_list[pos] else: par = None else: par = smil_element_at(data.pos, self.smil_anchor_map, self.smil_par_list) self.send_message('audio_ebook_message', type='start_play_at', par=par or None, anchor=data.anchor or None, pos=data.pos or None) else: console.error(f'Unknown audio ebook message type from main: {data.type}') def hints_msg_received(self, data): if data.type is 'show': # clear selection so that it does not confuse with the hints which use the same colors window.getSelection().removeAllRanges() hints_map = hint_visible_links() self.send_message('hints', type='shown', hints_map=hints_map) elif data.type is 'hide': unhint_links() elif data.type is 'activate': hint = data.hint if hint.type is 'link': a = document.body.querySelector(f'[data-calibre-hint-value="{hint.value}"]') a.removeEventListener('animationend', self.hint_animation_ended) a.addEventListener('animationend', self.hint_animation_ended, False) a.classList.add('calibre-animated-hint') elif data.type is 'apply_prefix': apply_prefix_to_hints(data.prefix) def hint_animation_ended(self, ev): a = ev.currentTarget a.classList.remove('calibre-animated-hint') a.click() def main(): if not main.boss: main.boss = IframeBoss()
49,135
Python
.py
1,003
38.118644
204
0.629505
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,513
view.pyj
kovidgoyal_calibre/src/pyj/read_book/view.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E import read_book.iframe # noqa from ajax import ajax_send from book_list.globals import get_session_data from book_list.home import update_book_in_recently_read_by_user_on_home_page from book_list.theme import cached_color_to_rgba, get_color, set_ui_colors from book_list.ui import show_panel from dom import add_extra_css, build_rule, clear, set_css, svgicon, unique_id from gettext import gettext as _ from iframe_comm import create_wrapped_iframe from modals import error_dialog, warning_dialog from read_book.annotations import AnnotationsManager from read_book.bookmarks import create_new_bookmark from read_book.content_popup import ContentPopupOverlay from read_book.globals import ( current_book, current_spine_item, is_dark_theme, rtl_page_progression, runtime, set_current_spine_item, ui_operations ) from read_book.goto import get_next_section from read_book.highlights import get_current_link_prefix, link_to_epubcfi from read_book.hints import Hints from read_book.open_book import add_book_to_recently_viewed from read_book.overlay import Overlay from read_book.prefs.colors import resolve_color_scheme from read_book.prefs.font_size import change_font_size_by, restore_default_font_size from read_book.prefs.fonts import current_zoom_step_size from read_book.prefs.head_foot import render_head_foot from read_book.prefs.scrolling import ( MIN_SCROLL_SPEED_AUTO as SCROLL_SPEED_STEP, change_scroll_speed ) from read_book.prefs.user_stylesheet import modify_background_image_url_for_fetch from read_book.read_aloud import ReadAloud from read_book.read_audio_ebook import ReadAudioEbook from read_book.resources import load_resources from read_book.scrollbar import BookScrollbar from read_book.search import SearchOverlay from read_book.selection_bar import SelectionBar from read_book.shortcuts import create_shortcut_map from read_book.smil import get_smil_audio_map from read_book.timers import Timers from read_book.toc import get_current_toc_nodes, update_visible_toc_nodes, get_current_pagelist_items from read_book.touch import set_left_margin_handler, set_right_margin_handler from session import get_device_uuid, get_interface_data from utils import ( default_context_menu_should_be_allowed, html_escape, parse_url_params, safe_set_inner_html, username_key ) add_extra_css(def(): sel = '.book-side-margin' ans = build_rule(sel, cursor='pointer', text_align='center', height='100dvh', user_select='none', display='flex', align_items='center', justify_content='space-between', flex_direction='column') ans += build_rule(sel + ' > .arrow', display='none') ans += build_rule(sel + ' > *', max_width='100%', overflow='hidden') ans += build_rule(sel + ':hover > .not-arrow', display='none') ans += build_rule(sel + ':active > .not-arrow', display='none') ans += build_rule(sel + ':hover > .arrow', display='block') ans += build_rule(sel + ':active > .arrow', display='block', transform='scale(2)') ans += build_rule('.book-h-margin .visible-on-hover', visibility='hidden') ans += build_rule('.book-h-margin:hover .visible-on-hover', visibility='visible') ans += build_rule('.book-h-margin .visible-on-hover:hover', color=get_color('window-hover-foreground')) return ans ) # Simple Overlays {{{ def show_controls_help(): container = document.getElementById('controls-help-overlay') container.style.display = 'block' container.style.backgroundColor = get_color('window-background') if not show_controls_help.listener_added: show_controls_help.listener_added = True container.addEventListener('click', def(): document.getElementById('controls-help-overlay').style.display = 'none' ui_operations.focus_iframe() ) container.addEventListener('contextmenu', def(evt): evt.preventDefault(), evt.stopPropagation() document.getElementById('controls-help-overlay').style.display = 'none' ui_operations.focus_iframe() , {'passive': False}) container.addEventListener('keydown', def(event): event.preventDefault(), event.stopPropagation() document.getElementById('controls-help-overlay').style.display = 'none' ui_operations.focus_iframe() , {'passive': False}) def focus(): if container.style.display is 'block': container.querySelector('input').focus() window.setTimeout(focus, 10) if runtime.is_standalone_viewer: clear(container) container.appendChild(E.div( style='margin: 1rem', E.div(style='margin-top: 1rem'), E.div(style='margin-top: 1rem'), E.div(style='margin-top: 1rem'), E.div(style='margin-top: 1rem'), E.input(style='background: transparent; border-width: 0; outline: none', readonly='readonly'), )) div = container.lastChild.firstChild safe_set_inner_html(div, _('Welcome to the <b>calibre E-book viewer</b>!')) div = div.nextSibling safe_set_inner_html(div, _('Use the <b>PageUp/PageDn</b> or <b>Arrow keys</b> to turn pages')) div = div.nextSibling safe_set_inner_html(div, _('Press the <b>Esc</b> key or <b>{}</b> or <b>tap on the top third</b> of the text area to show the viewer controls').format( _('control+click') if 'macos' in window.navigator.userAgent else _('right click') )) div = div.nextSibling safe_set_inner_html(div, _('Press any key to continue…')) focus() return def msg(txt): return set_css(E.div(txt), padding='1ex 1em', text_align='center', margin='auto') left_msg = msg(_('Tap to turn back')) left_width = 'min(25vw, 1in)' right_msg = msg(_('Tap to turn page')) right_width = 'auto' left_grow = 0 right_grow = 1 if rtl_page_progression(): left_msg, right_msg = right_msg, left_msg left_width, right_width = right_width, left_width left_grow, right_grow = right_grow, left_grow # Clear it out if this is not the first time it's created. # Needed to correctly show it again in a different page progression direction. if container.firstChild: container.removeChild(container.firstChild) container.appendChild(E.div( style=f'overflow: hidden; width: 100vw; height: 100dvh; text-align: center; font-size: 1.3rem; font-weight: bold; background: {get_color("window-background")};' + 'display:flex; flex-direction: column; align-items: stretch', E.div( msg(_('Tap (or right click) for controls')), style='height: 25dvh; display:flex; align-items: center; border-bottom: solid 2px currentColor', ), E.div( style="display: flex; align-items: stretch; flex-grow: 10", E.div( left_msg, style=f'width: {left_width}; flex-grow: {left_grow}; display:flex; align-items: center; border-right: solid 2px currentColor', ), E.div( right_msg, style=f'width: {right_width}; display:flex; flex-grow: {right_grow}; align-items: center', ) ) )) # }}} def body_font_size(): ans = body_font_size.ans if not ans: q = window.getComputedStyle(document.body).fontSize if q and q.endsWith('px'): q = parseInt(q) if q and not isNaN(q): ans = body_font_size.ans = q return ans ans = body_font_size.ans = 12 return ans def header_footer_font_size(sz): return min(max(0, sz - 6), body_font_size()) def margin_elem(sd, which, id, onclick, oncontextmenu): sz = sd.get(which, 20) fsz = header_footer_font_size(sz) s = '; text-overflow: ellipsis; white-space: nowrap; overflow: hidden' ans = E.div( style=f'height:{sz}px; overflow: hidden; font-size:{fsz}px; width:100%; padding: 0; display: flex; justify-content: space-between; align-items: center; user-select: none; cursor: pointer', class_='book-h-margin', id=id, E.div(style='margin-right: 1.5em' + s), E.div(style=s), E.div(style='margin-left: 1.5em' + s) ) if onclick: ans.addEventListener('click', onclick) if oncontextmenu: ans.addEventListener('contextmenu', oncontextmenu) return ans def side_margin_elem(self, sd, which, icon): ans = E.div( E.div(class_='arrow', style='order: 3', svgicon(f'caret-{icon}', '100%', '100%')), E.div(style='order:1'), E.div(style='order:2', class_='not-arrow'), E.div(style='order:4'), style='width:{}px; user-select: none'.format(sd.get(f'margin_{which}', 20)), class_='book-side-margin', id=f'book-{which}-margin', onclick=self.side_margin_clicked.bind(None, which), oncontextmenu=self.margin_context_menu.bind(None, which), onwheel=self.on_margin_wheel.bind(None, which) ) return ans class View: def __init__(self, container): self.timers = Timers() self.reference_mode_enabled = False self.loaded_resources = {} self.current_progress_frac = self.current_file_progress_frac = 0 self.current_page_counts = {'current': 0, 'total': 0, 'pages_per_screen': 1} self.current_status_message = '' self.current_toc_node = self.current_toc_toplevel_node = None self.current_toc_families = v'[]' self.report_cfi_callbacks = {} self.get_cfi_counter = 0 self.show_loading_callback_timer = None self.timer_ids = {'clock': 0} self.book_scrollbar = BookScrollbar(self) sd = get_session_data() self.keyboard_shortcut_map = create_shortcut_map(sd.get('keyboard_shortcuts')) if ui_operations.export_shortcut_map: ui_operations.export_shortcut_map(self.keyboard_shortcut_map) left_margin = side_margin_elem(self, sd, 'left', 'right' if sd.get('reverse_page_turn_zones') else 'left') set_left_margin_handler(left_margin) right_margin = side_margin_elem(self, sd, 'right', 'left' if sd.get('reverse_page_turn_zones') else 'right') set_right_margin_handler(right_margin) handlers = { 'autoscroll_state_changed': def(data): self.autoscroll_active = v'!!data.running' if ui_operations.autoscroll_state_changed: ui_operations.autoscroll_state_changed(self.autoscroll_active) , 'bump_font_size': self.bump_font_size, 'content_loaded': self.on_content_loaded, 'error': self.on_iframe_error, 'invisible_text': self.on_invisible_text, 'goto_doc_boundary': def(data): self.goto_doc_boundary(data.start);, 'handle_keypress': self.on_handle_keypress, 'handle_shortcut': self.on_handle_shortcut, 'human_scroll': self.on_human_scroll, 'next_section': self.on_next_section, 'next_spine_item': self.on_next_spine_item, 'print': self.on_print, 'ready': self.on_iframe_ready, 'report_cfi': self.on_report_cfi, 'request_size': self.on_request_size, 'scroll_to_anchor': self.on_scroll_to_anchor, 'selectionchange': self.on_selection_change, 'update_selection_position': self.update_selection_position, 'columns_per_screen_changed': self.on_columns_per_screen_changed, 'show_chrome': self.show_chrome, 'show_footnote': self.on_show_footnote, 'update_cfi': self.on_update_cfi, 'update_progress_frac': self.on_update_progress_frac, 'update_toc_position': self.on_update_toc_position, 'search_result_not_found': self.search_result_not_found, 'search_result_discovered': self.search_result_discovered, 'annotations': self.on_annotations_message, 'tts': self.on_tts_message, 'audio_ebook_message': self.on_audio_ebook_message, 'hints': self.on_hints_message, 'copy_text_to_clipboard': def(data): ui_operations.copy_selection(data.text, data.html) , 'view_image': def(data): if ui_operations.view_image: ui_operations.view_image(data.calibre_src) , } iframe_id = unique_id('read-book-iframe') if runtime.is_standalone_viewer: entry_point = f'{runtime.FAKE_PROTOCOL}://{runtime.SANDBOX_HOST}/book/__index__' else: entry_point = 'read_book.iframe' iframe_kw = { 'id': iframe_id, 'seamless': True, 'sandbox': 'allow-popups allow-scripts allow-popups-to-escape-sandbox', 'style': 'flex-grow: 2', 'allowfullscreen': 'true', } iframe, self.iframe_wrapper = create_wrapped_iframe(handlers, _('Bootstrapping book reader...'), entry_point, iframe_kw) container.appendChild( E.div(style='max-height: 100dvh; width: 100dvw; height: 100dvh; overflow: hidden; display: flex; align-items: stretch', # container for horizontally aligned panels oncontextmenu=def (ev): if not default_context_menu_should_be_allowed(ev): ev.preventDefault() , E.div(style='max-height: 100dvh; display: flex; flex-direction: column; align-items: stretch; flex-grow:2', # container for iframe and any other panels in the same column E.div(style='max-height: 100dvh; flex-grow: 2; display:flex; align-items: stretch', # container for iframe and its overlay left_margin, E.div(style='flex-grow:2; display:flex; align-items:stretch; flex-direction: column', # container for top and bottom margins margin_elem(sd, 'margin_top', 'book-top-margin', self.top_margin_clicked, self.margin_context_menu.bind(None, 'top')), iframe, margin_elem(sd, 'margin_bottom', 'book-bottom-margin', self.bottom_margin_clicked, self.margin_context_menu.bind(None, 'bottom')), ), right_margin, self.book_scrollbar.create(), E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none;', id='book-selection-bar-overlay'), # selection bar overlay E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none;', id='book-read-aloud-overlay'), # read aloud overlay E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none;', id='book-hints-overlay'), # hints overlay E.div(style='position: absolute; top:0; left:0; width: 100%; height:100%; display:none', id=SearchOverlay.CONTAINER_ID), # search overlay E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none', id='book-content-popup-overlay'), # content popup overlay E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; overflow: auto; display:none', id='book-overlay'), # main overlay E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none', id='controls-help-overlay'), # controls help overlay E.div(style='position: absolute; bottom:0em; width: 100%; height: 100%; display:none', id='audio-ebooks-overlay'), # read audio ebook overlay ) ), ), ) self.current_color_scheme = resolve_color_scheme() if runtime.is_standalone_viewer: document.documentElement.addEventListener('keydown', self.handle_keypress, {'passive': False}) set_ui_colors(self.current_color_scheme.is_dark_theme) is_dark_theme(self.current_color_scheme.is_dark_theme) self.search_overlay = SearchOverlay(self) self.content_popup_overlay = ContentPopupOverlay(self) self.overlay = Overlay(self) self.selection_bar = SelectionBar(self) self.read_aloud = ReadAloud(self) self.read_audio_ebook = ReadAudioEbook(self) self.hints = Hints(self) self.modal_overlays = v'[self.selection_bar, self.read_aloud, self.hints, self.read_audio_ebook]' self.processing_spine_item_display = False self.pending_load = None self.currently_showing = {'selection': {'empty': True}, 'on_load':v'[]'} self.book_scrollbar.apply_visibility() self.annotations_manager = AnnotationsManager(self) @property def iframe(self): return self.iframe_wrapper.iframe def copy_to_clipboard(self): self.iframe_wrapper.send_message('copy_selection') def show_not_a_library_book_error(self): error_dialog(_('Not a calibre library book'), _( 'This book is not a part of a calibre library, so no calibre:// URL for it exists.')) def copy_current_location_to_clipboard(self, as_url): link_prefix = get_current_link_prefix() if not link_prefix and as_url: return self.show_not_a_library_book_error() self.get_current_cfi('copy-location-url', def (req_id, data): if as_url: text = link_to_epubcfi(data.cfi, link_prefix) else: text = data.cfi ui_operations.copy_selection(text) ) def set_scrollbar_visibility(self, visible): sd = get_session_data() sd.set('book_scrollbar', bool(visible)) self.book_scrollbar.apply_visibility() def toggle_scrollbar(self): sd = get_session_data() self.set_scrollbar_visibility(not sd.get('book_scrollbar')) def on_annotations_message(self, data): self.selection_bar.handle_message(data) def on_tts_message(self, data): self.read_aloud.handle_message(data) def on_audio_ebook_message(self, data): self.read_audio_ebook.handle_message(data) def on_hints_message(self, data): self.hints.handle_message(data) def side_margin_clicked(self, which, event): backwards = which is 'left' if get_session_data().get('reverse_page_turn_zones'): backwards = not backwards if event.button is 0: event.preventDefault(), event.stopPropagation() sd = get_session_data() self.iframe_wrapper.send_message( 'next_screen', backwards=backwards, flip_if_rtl_page_progression=True, all_pages_on_screen=sd.get('paged_margin_clicks_scroll_by_screen')) elif event.button is 2: event.preventDefault(), event.stopPropagation() window.setTimeout(self.show_chrome, 0) self.focus_iframe() def top_margin_clicked(self, event): if event.button is 0 or event.button is 2: event.preventDefault(), event.stopPropagation() self.show_chrome() else: self.focus_iframe() def bottom_margin_clicked(self, event): if event.button is 0 or event.button is 2: event.preventDefault(), event.stopPropagation() window.setTimeout(self.show_chrome, 0) self.focus_iframe() def margin_context_menu(self, which, event): event.preventDefault(), event.stopPropagation() self.show_chrome() def on_margin_wheel(self, which, event): event.preventDefault() self.send_wheel_event_to_iframe(event, f'margin-{which}') def send_wheel_event_to_iframe(self, event, location): evt = {'location': location} for attr in ('deltaX', 'deltaY', 'deltaMode', 'altKey', 'ctrlKey', 'shiftKey', 'metaKey'): evt[attr] = event[attr] self.iframe_wrapper.send_message('fake_wheel_event', evt=evt) def forward_gesture(self, gesture): self.iframe_wrapper.send_message('gesture_from_margin', gesture=gesture) def iframe_size(self): iframe = self.iframe l, r = document.getElementById('book-left-margin'), document.getElementById('book-right-margin') w = r.offsetLeft - l.offsetLeft - iframe.offsetLeft t, b = document.getElementById('book-top-margin'), document.getElementById('book-bottom-margin') h = b.offsetTop - t.offsetTop - iframe.offsetTop return w, h def on_request_size(self, data): # On iOS/Safari window.innerWidth/Height are incorrect inside an iframe window.scrollTo(0, 0) # ensure the window is at 0 because otherwise it sometimes moves down a bit on mobile thanks to the disappearing nav bar w, h = self.iframe_size() self.iframe_wrapper.send_message('window_size', width=w, height=h) def on_print(self, data): print(data.string) def on_human_scroll(self, data): if data.scrolled_by_frac is None: self.timers.reset_read_timer() else: name = self.currently_showing.name length = self.book.manifest.files[name]?.length if length: amt_scrolled = data.scrolled_by_frac * length self.timers.on_human_scroll(amt_scrolled) def on_handle_keypress(self, data): self.handle_keypress(data.evt) def handle_keypress(self, evt): if self.overlay.is_visible and evt.key is 'Escape': if self.overlay.handle_escape(): if evt.preventDefault: evt.preventDefault(), evt.stopPropagation() def overlay_visibility_changed(self, visible): if self.iframe_wrapper.send_message: self.iframe_wrapper.send_message('overlay_visibility_changed', visible=visible) if ui_operations.overlay_visibility_changed: ui_operations.overlay_visibility_changed(visible) if visible: for x in self.modal_overlays: x.hide() else: self.selection_bar.update_position() def on_handle_shortcut(self, data): if not data.name: return if data.name is 'back': window.history.back() elif data.name is 'forward': window.history.forward() elif data.name is 'show_chrome': self.show_chrome() elif data.name is 'show_chrome_force': self.show_chrome_force() elif data.name is 'toggle_toc': ui_operations.toggle_toc() elif data.name is 'toggle_bookmarks': if ui_operations.toggle_bookmarks: ui_operations.toggle_bookmarks() else: self.overlay.show_bookmarks() elif data.name is 'show_profiles': self.overlay.show_profiles() elif data.name is 'toggle_highlights': ui_operations.toggle_highlights() elif data.name is 'new_bookmark': self.new_bookmark() elif data.name is 'copy_to_clipboard': self.copy_to_clipboard() elif data.name is 'copy_location_to_clipboard' or data.name is 'copy_location_as_url_to_clipboard': self.copy_current_location_to_clipboard('url' in data.name) elif data.name is 'toggle_inspector': ui_operations.toggle_inspector() elif data.name is 'toggle_lookup': ui_operations.toggle_lookup() elif data.name is 'toggle_full_screen': ui_operations.toggle_full_screen() elif data.name is 'toggle_paged_mode': self.toggle_paged_mode() elif data.name is 'toggle_toolbar': self.toggle_toolbar() elif data.name is 'toggle_scrollbar': self.toggle_scrollbar() elif data.name is 'quit': ui_operations.quit() elif data.name is 'start_search': self.show_search() elif data.name is 'next_match': ui_operations.find_next() elif data.name is 'previous_match': ui_operations.find_next(True) elif data.name is 'increase_font_size': self.bump_font_size({'increase': True}) elif data.name is 'decrease_font_size': self.bump_font_size({'increase': False}) elif data.name is 'default_font_size': restore_default_font_size() elif data.name is 'toggle_full_screen': ui_operations.toggle_full_screen() elif data.name is 'toggle_reference_mode': self.toggle_reference_mode() elif data.name is 'read_aloud': self.start_read_aloud() elif data.name is 'toggle_hints': self.toggle_hints() elif data.name is 'toggle_read_aloud': self.toggle_read_aloud() elif data.name is 'reload_book': self.reload_book() elif data.name is 'sync_book': self.overlay.sync_book() elif data.name is 'next_section': self.on_next_section({'forward': True}) elif data.name is 'previous_section': self.on_next_section({'forward': False}) elif data.name is 'open_book': self.overlay.open_book() elif data.name is 'next': self.iframe_wrapper.send_message( 'next_screen', backwards=False, flip_if_rtl_page_progression=False, all_pages_on_screen=get_session_data().get('paged_margin_clicks_scroll_by_screen')) elif data.name is 'previous': self.iframe_wrapper.send_message( 'next_screen', backwards=True, flip_if_rtl_page_progression=False, all_pages_on_screen=get_session_data().get('paged_margin_clicks_scroll_by_screen')) elif data.name is 'clear_selection': self.iframe_wrapper.send_message('clear_selection') elif data.name is 'print': ui_operations.print_book() elif data.name is 'preferences': self.show_chrome({'initial_panel': 'show_prefs'}) elif data.name is 'metadata': self.overlay.show_metadata() elif data.name is 'edit_book': ui_operations.edit_book(current_spine_item(), self.current_file_progress_frac, self.currently_showing?.selection?.text) elif data.name is 'goto_location': self.overlay.show_ask_for_location() elif data.name is 'select_all': self.iframe_wrapper.send_message('modify_selection', granularity='all') elif data.name.startsWith('shrink_selection_by_'): self.iframe_wrapper.send_message('modify_selection', direction='backward', granularity=data.name.rpartition('_')[-1]) elif data.name.startsWith('extend_selection_by_'): self.iframe_wrapper.send_message('modify_selection', direction='forward', granularity=data.name.rpartition('_')[-1]) elif data.name is 'extend_selection_to_start_of_line': self.iframe_wrapper.send_message('modify_selection', direction='backward', granularity='lineboundary') elif data.name is 'extend_selection_to_end_of_line': self.iframe_wrapper.send_message('modify_selection', direction='forward', granularity='lineboundary') elif data.name is 'scrollspeed_increase': self.update_scroll_speed(SCROLL_SPEED_STEP) elif data.name is 'scrollspeed_decrease': self.update_scroll_speed(-SCROLL_SPEED_STEP) elif data.name is 'toggle_autoscroll': self.toggle_autoscroll() elif data.name.startsWith('switch_color_scheme:'): self.switch_color_scheme(data.name.partition(':')[-1]) elif data.name is 'increase_number_of_columns': self.iframe_wrapper.send_message('change_number_of_columns', delta=1) elif data.name is 'decrease_number_of_columns': self.iframe_wrapper.send_message('change_number_of_columns', delta=-1) elif data.name is 'reset_number_of_columns': self.iframe_wrapper.send_message('change_number_of_columns', delta=0) else: self.iframe_wrapper.send_message('handle_navigation_shortcut', name=data.name) def on_selection_change(self, data): self.currently_showing.selection = { 'text': data.text, 'empty': data.empty, 'start': data.selection_extents.start, 'end': data.selection_extents.end, 'annot_id': data.annot_id, 'drag_mouse_position': data.drag_mouse_position, 'selection_change_caused_by_search': data.selection_change_caused_by_search, 'rtl': data.rtl, 'vertical': data.vertical, 'start_is_anchor': data.start_is_anchor } if ui_operations.selection_changed: ui_operations.selection_changed(self.currently_showing.selection.text, self.currently_showing.selection.annot_id) self.selection_bar.update_position() def new_bookmark(self): if ui_operations.new_bookmark: self.get_current_cfi('new-bookmark', ui_operations.new_bookmark) else: self.get_current_cfi('new-bookmark', def (req_id, data): create_new_bookmark(self.annotations_manager, data) ) def update_selection_position(self, data): sel = self.currently_showing.selection sel.start = data.selection_extents.start sel.end = data.selection_extents.end self.selection_bar.update_position() def on_columns_per_screen_changed(self, data): sd = get_session_data() cps = sd.get('columns_per_screen') or {} cps[data.which] = int(data.cps) sd.set('columns_per_screen', cps) def switch_color_scheme(self, name): get_session_data().set('current_color_scheme', name) ui_operations.redisplay_book() def toggle_paged_mode(self): sd = get_session_data() mode = sd.get('read_mode') new_mode = 'flow' if mode is 'paged' else 'paged' sd.set('read_mode', new_mode) ui_operations.redisplay_book() def toggle_autoscroll(self): self.iframe_wrapper.send_message('toggle_autoscroll') def toggle_toolbar(self): sd = get_session_data() misc = sd.get('standalone_misc_settings') misc.show_actions_toolbar = v'!misc.show_actions_toolbar' sd.set('standalone_misc_settings', misc) def on_invisible_text(self, data): warning_dialog( _('Not found'), _('The text: <i>{}</i> is present on this page but not visible').format(html_escape(data.text)), on_close=def(): self.search_overlay.show() ) def bump_font_size(self, data): mult = 1 if data.increase else -1 frac = 0.2 if runtime.is_standalone_viewer: frac = current_zoom_step_size() / 100 change_font_size_by(mult * frac) def on_show_footnote(self, data): self.show_content_popup() self.content_popup_overlay.show_footnote(data) def hide_overlays(self): self.overlay.hide() self.search_overlay.hide() self.content_popup_overlay.hide() self.focus_iframe() @property def overlay_prevents_navigation(self): for x in self.modal_overlays: if x.is_visible and x.prevent_navigation: return True return False def focus_iframe(self): for x in self.modal_overlays: if x.is_visible: x.focus() return self.iframe.contentWindow.focus() def start_read_aloud(self, dont_start_talking): if self.book.manifest.has_smil: for x in self.modal_overlays: if x is not self.read_audio_ebook: x.hide() self.read_audio_ebook.show() else: for x in self.modal_overlays: if x is not self.read_aloud: x.hide() self.read_aloud.show() if not dont_start_talking: self.read_aloud.play() def toggle_read_aloud(self): if self.read_audio_ebook.is_visible: self.read_audio_ebook.hide() elif self.read_aloud.is_visible: self.read_aloud.hide() else: self.start_read_aloud() def toggle_hints(self): if self.hints.is_visible: self.hints.hide() else: for x in self.modal_overlays: if x is not self.hints: x.hide() self.hints.show() def show_chrome(self, data): if self.content_popup_overlay.is_visible: self.content_popup_overlay.hide() return self.content_popup_overlay elements = {} if data and data.elements: elements = data.elements initial_panel = data?.initial_panel or None self.get_current_cfi('show-chrome', self.do_show_chrome.bind(None, elements, initial_panel)) def show_chrome_force(self): self.hide_overlays() self.show_chrome() def do_show_chrome(self, elements, initial_panel, request_id, cfi_data): self.hide_overlays() self.update_cfi_data(cfi_data) if initial_panel: getattr(self.overlay, initial_panel)() else: self.overlay.show(elements) def prepare_for_close(self): def close_prepared(request_id, cfi_data): ui_operations.close_prep_finished(cfi_data.cfi) self.get_current_cfi('prepare-close', close_prepared) def show_search(self, trigger): self.hide_overlays() text = self.currently_showing.selection.text if runtime.is_standalone_viewer: ui_operations.show_search(text or '', trigger) else: if text: self.search_overlay.set_text(text) self.search_overlay.show(text) if trigger and text: self.search_overlay.find_next() def show_content_popup(self): self.hide_overlays() self.content_popup_overlay.show() def set_margins(self): no_margins = self.currently_showing.name is self.book.manifest.title_page_name sd = get_session_data() margin_left = 0 if no_margins else sd.get('margin_left') margin_right = 0 if no_margins else sd.get('margin_right') margin_top = 0 if no_margins else sd.get('margin_top') margin_bottom = 0 if no_margins else sd.get('margin_bottom') max_text_height = sd.get('max_text_height') th = window.innerHeight - margin_top - margin_bottom if not no_margins and max_text_height > 100 and th > max_text_height: extra = (th - max_text_height) // 2 margin_top += extra margin_bottom += extra max_text_width = sd.get('max_text_width') tw = window.innerWidth - margin_left - margin_right if not no_margins and max_text_width > 100 and tw > max_text_width: extra = (tw - max_text_width) // 2 margin_left += extra margin_right += extra set_css(document.getElementById('book-top-margin'), height=margin_top + 'px', font_size=header_footer_font_size(margin_top) + 'px') set_css(document.getElementById('book-bottom-margin'), height=margin_bottom + 'px', font_size=header_footer_font_size(margin_bottom) + 'px') def side_margin(which, val): m = document.getElementById('book-{}-margin'.format(which)) if which is 'left': # Explicitly set the width of the central panel. This is needed # on small screens with chrome, without it sometimes the right # margin/scrollbar goes off the screen. m.nextSibling.style.maxWidth = 'calc(100vw - {}px)'.format( margin_left + margin_right + self.book_scrollbar.effective_width) set_css(m, width=val + 'px') val = min(val, 25) s = m.querySelector('.arrow').style s.width = val + 'px' s.height = val + 'px' side_margin('left', margin_left), side_margin('right', margin_right) def on_iframe_ready(self, data): data.width, data.height = self.iframe_size() if ui_operations.on_iframe_ready: ui_operations.on_iframe_ready() return self.do_pending_load def do_pending_load(self): if self.pending_load: data = self.pending_load self.pending_load = None self.show_spine_item_stage2(data) def on_iframe_error(self, data): title = data.title or _('There was an error processing the book') msg = _('Unknown error') if data.errkey: if data.errkey is 'no-auto-scroll-in-paged-mode': title = _('No auto scroll in paged mode') msg = _('Switch to flow mode (Viewer preferences->Page layout) to enable auto scrolling') elif data.errkey is 'changing-columns-in-flow-mode': title=_('In flow mode') msg=_('Cannot change number of pages per screen in flow mode, switch to paged mode first.') elif data.errkey = 'unhandled-error': title = _('Unhandled error') if data.is_non_critical: warning_dialog(title, msg, data.details, on_close=ui_operations.focus_iframe) return ui_operations.show_error(title, msg, data.details) def apply_color_scheme(self): self.current_color_scheme = ans = resolve_color_scheme() iframe = self.iframe if runtime.is_standalone_viewer: set_ui_colors(self.current_color_scheme.is_dark_theme) else: iframe.style.colorScheme = 'dark' if self.current_color_scheme.is_dark_theme else 'light' is_dark_theme(self.current_color_scheme.is_dark_theme) for which in 'left top right bottom'.split(' '): m = document.getElementById('book-{}-margin'.format(which)) s = m.style mc = ans[f'margin_{which}'] if mc: s.backgroundColor, s.color = mc.split(':') else: s.color = ans.foreground s.backgroundColor = ans.background sd = get_session_data() iframe.style.backgroundColor = ans.background or 'white' bg_image = sd.get('background_image') if bg_image: iframe.style.backgroundImage = f'url({modify_background_image_url_for_fetch(bg_image)})' else: iframe.style.backgroundImage = 'none' if sd.get('background_image_style') is 'scaled': iframe.style.backgroundSize = '100% 100%' iframe.style.backgroundRepeat = 'no-repeat' iframe.style.backgroundAttachment = 'scroll' iframe.style.backgroundPosition = 'center' else: iframe.style.backgroundSize = 'auto' iframe.style.backgroundRepeat = 'repeat' iframe.style.backgroundAttachment = 'scroll' iframe.style.backgroundPosition = '0 0' self.content_popup_overlay.apply_color_scheme(ans.background, ans.foreground) self.book_scrollbar.apply_color_scheme(ans) # this is needed on iOS where the bottom margin has its own margin, # so we dont want the body background color to bleed through iframe.parentNode.style.backgroundColor = ans.background iframe.parentNode.parentNode.style.backgroundColor = ans.background return ans def on_resize(self): if self.book and self.currently_showing.name: sd = get_session_data() if sd.get('max_text_width') or sd.get('max_text_height'): self.set_margins() def show_loading_message(self, msg): self.overlay.show_loading_message(msg) def show_loading(self): msg = _('Loading next section from <i>{title}</i>, please wait…').format(title=self.book.metadata.title or _('Unknown')) if self.show_loading_callback_timer is not None: clearTimeout(self.show_loading_callback_timer) self.show_loading_callback_timer = setTimeout(self.show_loading_message.bind(None, msg), 200) def hide_loading(self): if window.read_book_initial_open_search_text: q = window.read_book_initial_open_search_text v'delete window.read_book_initial_open_search_text' self.search_overlay.do_initial_search(q.text, q.query) self.show_loading_message(_('Searching for: {}').format(q.query)) return if self.show_loading_callback_timer is not None: clearTimeout(self.show_loading_callback_timer) self.show_loading_callback_timer = None self.iframe.style.visibility = 'visible' self.overlay.hide_loading_message() self.focus_iframe() def parse_cfi(self, encoded_cfi, book): name = cfi = None if encoded_cfi and encoded_cfi.startswith('epubcfi(/'): cfi = encoded_cfi[len('epubcfi(/'):-1] snum, rest = cfi.partition('/')[::2] try: snum = int(snum) except Exception: print('Invalid spine number in CFI:', snum) if jstype(snum) is 'number': name = book.manifest.spine[(int(snum) // 2) - 1] or name cfi = '/' + rest return name, cfi def open_book_page(self): # Open the page for the current book in a new tab if self.book and self.book.key: show_panel('book_details', {'library_id': self.book.key[0], 'book_id': self.book.key[1] + ''}, replace=False) def clear_book_resource_caches(self): self.loaded_resources = {} self.content_popup_overlay.loaded_resources = {} def reload_book(self): self.clear_book_resource_caches() ui_operations.reload_book() def display_book(self, book, initial_position, is_redisplay): self.hide_overlays() self.iframe.focus() is_current_book = self.book and self.book.key == book.key self.book_load_started = True if is_current_book: if not is_redisplay: self.search_overlay.clear_caches(book) # could be a reload else: if self.book: self.iframe_wrapper.reset() self.content_popup_overlay.reset() self.clear_book_resource_caches() self.timers.start_book(book) self.search_overlay.clear_caches(book) unkey = username_key(get_interface_data().username) self.book = current_book.book = book hl = None if not is_redisplay: if self.read_audio_ebook: self.read_audio_ebook.hide() clear(self.read_audio_ebook.container) if runtime.is_standalone_viewer: hl = book.highlights v'delete book.highlights' else: if unkey and book.annotations_map[unkey]: hl = book.annotations_map[unkey].highlight self.annotations_manager.set_bookmarks(book.annotations_map[unkey].bookmark or v'[]') self.annotations_manager.set_highlights(hl or v'[]') if runtime.is_standalone_viewer: add_book_to_recently_viewed(book) if ui_operations.update_last_read_time: ui_operations.update_last_read_time(book) pos = {'replace_history':True} if not book.manifest.spine.length: ui_operations.show_error(_('Invalid book'), _('This book is empty, with no items in the spine')) return name = book.manifest.spine[0] cfi = None if initial_position and initial_position.type is 'cfi' and initial_position.data.startswith('epubcfi(/'): cfi = initial_position.data else: q = parse_url_params() if q.bookpos and q.bookpos.startswith('epubcfi(/'): cfi = q.bookpos elif book.last_read_position and book.last_read_position[unkey]: cfi = book.last_read_position[unkey] cfiname, internal_cfi = self.parse_cfi(cfi, book) if cfiname and internal_cfi: name = cfiname pos.type, pos.cfi = 'cfi', internal_cfi navigated = False if initial_position: if initial_position.type is 'toc': navigated = self.goto_toc_node(initial_position.data) elif initial_position.type is 'bookpos': navigated = True self.goto_book_position(initial_position.data) elif initial_position.type is 'ref': navigated = self.goto_reference(initial_position.data) if navigated: self.hide_loading() else: self.show_name(name, initial_position=pos) sd = get_session_data() help_key = 'controls_help_shown_count' + ('_rtl_page_progression' if rtl_page_progression() else '') if not self[help_key]: self[help_key] = True c = sd.get(help_key, 0) if c < 2: show_controls_help() sd.set('controls_help_shown_count' + ('_rtl_page_progression' if rtl_page_progression() else ''), c + 1) def preferences_changed(self): self.set_margins() ui_operations.update_url_state(True) ui_operations.redisplay_book() def redisplay_book(self): # redisplay_book() is called when settings are changed if not self.book: if runtime.is_standalone_viewer: self.overlay.open_book() return sd = get_session_data() self.keyboard_shortcut_map = create_shortcut_map(sd.get('keyboard_shortcuts')) if ui_operations.export_shortcut_map: ui_operations.export_shortcut_map(self.keyboard_shortcut_map) self.book_scrollbar.apply_visibility() self.display_book(self.book, None, True) def iframe_settings(self, name): sd = get_session_data() bg_image_fade = 'transparent' cs = self.apply_color_scheme() fade = int(sd.get('background_image_fade')) rgba = cached_color_to_rgba(cs.background) if self.iframe.style.backgroundImage is not 'none' and fade > 0: bg_image_fade = f'rgba({rgba[0]}, {rgba[1]}, {rgba[2]}, {fade/100})' return { 'margin_left': 0 if name is self.book.manifest.title_page_name else sd.get('margin_left'), 'margin_right': 0 if name is self.book.manifest.title_page_name else sd.get('margin_right'), 'margin_top': 0 if name is self.book.manifest.title_page_name else sd.get('margin_top'), 'margin_bottom': 0 if name is self.book.manifest.title_page_name else sd.get('margin_bottom'), 'read_mode': sd.get('read_mode'), 'columns_per_screen': sd.get('columns_per_screen'), 'color_scheme': cs, 'override_book_colors': sd.get('override_book_colors'), 'is_dark_theme': cs.is_dark_theme, 'bg_image_fade': bg_image_fade, 'base_font_size': sd.get('base_font_size'), 'user_stylesheet': sd.get('user_stylesheet'), 'keyboard_shortcuts': sd.get('keyboard_shortcuts'), 'hide_tooltips': sd.get('hide_tooltips'), 'cover_preserve_aspect_ratio': sd.get('cover_preserve_aspect_ratio'), 'paged_wheel_scrolls_by_screen': sd.get('paged_wheel_scrolls_by_screen'), 'paged_wheel_section_jumps': sd.get('paged_wheel_section_jumps'), 'paged_pixel_scroll_threshold': sd.get('paged_pixel_scroll_threshold'), 'lines_per_sec_auto': sd.get('lines_per_sec_auto'), 'lines_per_sec_smooth': sd.get('lines_per_sec_smooth'), 'scroll_auto_boundary_delay': sd.get('scroll_auto_boundary_delay'), 'scroll_stop_boundaries': sd.get('scroll_stop_boundaries'), 'reverse_page_turn_zones': sd.get('reverse_page_turn_zones'), 'gesture_overrides': sd.get('gesture_overrides'), } def show_name(self, name, initial_position=None): if self.currently_showing.loading: return self.processing_spine_item_display = False initial_position = initial_position or {'replace_history':False} spine = self.book.manifest.spine idx = spine.indexOf(name) self.currently_showing = { 'name':name, 'settings':self.iframe_settings(name), 'initial_position':initial_position, 'loading':True, 'spine_index': idx, 'selection': {'empty': True}, 'on_load': v'[]', } self.show_loading() set_current_spine_item(name) if idx > -1: self.currently_showing.bookpos = 'epubcfi(/{})'.format(2 * (idx +1)) self.set_margins() self.load_doc(name, self.show_spine_item) def load_doc(self, name, done_callback): def cb(resource_data): self.loaded_resources = resource_data done_callback(resource_data) load_resources(self.book, name, self.loaded_resources, cb) def goto_doc_boundary(self, start): name = self.book.manifest.spine[0 if start else self.book.manifest.spine.length - 1] self.show_name(name, initial_position={'type':'frac', 'frac':0 if start else 1, 'replace_history':False}) def goto_frac(self, frac): if not self.book or not self.book.manifest: return chapter_start_page = 0 total_length = self.book.manifest.spine_length page = total_length * frac chapter_frac = 0 chapter_name = None for name in self.book.manifest.spine: chapter_length = self.book.manifest.files[name]?.length or 0 chapter_end_page = chapter_start_page + chapter_length if chapter_start_page <= page <= chapter_end_page: num_pages = chapter_end_page - chapter_start_page - 1 if num_pages > 0: chapter_frac = (page - chapter_start_page) / num_pages else: chapter_frac = 0 chapter_name = name break chapter_start_page = chapter_end_page if not chapter_name: chapter_name = self.book.manifest.spine[-1] chapter_frac = max(0, min(chapter_frac, 1)) if self.currently_showing.name is chapter_name: self.iframe_wrapper.send_message('scroll_to_frac', frac=chapter_frac) else: self.show_name(chapter_name, initial_position={'type':'frac', 'frac':chapter_frac, 'replace_history':True}) def goto_book_position(self, bpos): val = max(0, min(1000 * float(bpos) / self.current_position_data.book_length, 1)) return self.goto_frac(val) def goto_pagelist_item(self, item): name = item.dest frag = item.frag or '' self.show_name(name, initial_position={'type':'pagelist_ref', 'anchor':frag, 'replace_history':False}) def on_scroll_to_anchor(self, data): self.show_name(data.name, initial_position={'type':'anchor', 'anchor':data.frag, 'replace_history':False}) def link_in_content_popup_activated(self, name, frag, is_popup, title): self.content_popup_overlay.hide() if is_popup: self.iframe_wrapper.send_message('fake_popup_activation', name=name, frag=frag, title=title) else: self.goto_named_destination(name, frag) def goto_cfi(self, bookpos, add_to_history): cfiname, internal_cfi = self.parse_cfi(bookpos, self.book) if cfiname and internal_cfi: # Note that goto_cfi is used by back() so it must not add to # history by default, otherwise forward() will not work pos = {'replace_history': not add_to_history} name = cfiname pos.type, pos.cfi = 'cfi', internal_cfi self.show_name(name, initial_position=pos) return True return False def goto_reference(self, reference): if not self.book or not self.book.manifest: return index, refnum = reference.split('.') index, refnum = int(index), (int(refnum) if refnum else 1) chapter_name = self.book.manifest.spine[index] if not chapter_name: return False if self.currently_showing.name is chapter_name: self.iframe_wrapper.send_message('scroll_to_ref', refnum=refnum) else: self.show_name(chapter_name, initial_position={'type':'ref', 'refnum':refnum, 'replace_history':True}) return True def goto_named_destination(self, name, frag): if self.currently_showing.name is name: self.iframe_wrapper.send_message('scroll_to_anchor', frag=frag) else: spine = self.book.manifest.spine idx = spine.indexOf(name) if idx is -1: error_dialog(_('Destination does not exist'), _( 'The file {} does not exist in this book').format(name), on_close=def(): ui_operations.focus_iframe() ) return False self.show_name(name, initial_position={'type':'anchor', 'anchor':frag, 'replace_history':False}) return True def goto_toc_node(self, node_id): if self.overlay_prevents_navigation: return toc = self.book.manifest.toc found = False def process_node(x): nonlocal found if x.id is node_id: self.goto_named_destination(x.dest or '', x.frag or '') found = True return for c in x.children: process_node(c) if toc: process_node(toc) return found def sync_data_received(self, reading_pos_cfi, annotations_map): if annotations_map: ui_operations.annotations_synced(annotations_map) if annotations_map.highlight: if self.annotations_manager.merge_highlights(annotations_map.highlight): hl = self.annotations_manager.highlights_for_currently_showing() self.iframe_wrapper.send_message('replace_highlights', highlights=hl) if reading_pos_cfi: self.goto_cfi(reading_pos_cfi) def set_notes_for_highlight(self, uuid, notes): if self.annotations_manager.set_notes_for_highlight(uuid, notes): self.selection_bar.notes_edited(uuid) self.selection_bar.update_position() def show_next_spine_item(self, previous): spine = self.book.manifest.spine idx = spine.indexOf(self.currently_showing.name) if previous: if idx is 0: return False idx = min(spine.length - 1, max(idx - 1, 0)) self.show_name(spine[idx], initial_position={'type':'frac', 'frac':1, 'replace_history':True}) else: if idx is spine.length - 1: return False idx = max(0, min(spine.length - 1, idx + 1)) self.show_name(spine[idx], initial_position={'type':'frac', 'frac':0, 'replace_history':True}) return True def on_next_spine_item(self, data): self.show_next_spine_item(data.previous) def on_next_section(self, data): toc_node = get_next_section(data.forward) if toc_node: self.goto_named_destination(toc_node.dest, toc_node.frag) def get_current_cfi(self, request_id, callback): self.get_cfi_counter += 1 request_id += ':' + self.get_cfi_counter self.report_cfi_callbacks[request_id] = callback self.iframe_wrapper.send_message('get_current_cfi', request_id=request_id) def update_cfi_data(self, data): username = get_interface_data().username if self.book: self.currently_showing.bookpos = data.cfi unkey = username_key(username) if not self.book.last_read_position: self.book.last_read_position = {} self.book.last_read_position[unkey] = data.cfi self.set_progress_frac(data.progress_frac, data.file_progress_frac, data.page_counts) self.update_header_footer() if ui_operations.update_last_read_time: ui_operations.update_last_read_time(self.book) return username def on_report_cfi(self, data): cb = self.report_cfi_callbacks[data.request_id] if cb: cb(data.request_id.rpartition(':')[0], { 'cfi': data.cfi, 'progress_frac': data.progress_frac, 'file_progress_frac': data.file_progress_frac, 'selected_text': data.selected_text, 'selection_bounds': data.selection_bounds, 'page_counts': data.page_counts }) v'delete self.report_cfi_callbacks[data.request_id]' def on_update_progress_frac(self, data): self.set_progress_frac(data.progress_frac, data.file_progress_frac, data.page_counts) self.update_header_footer() def on_update_cfi(self, data): overlay_shown = not self.processing_spine_item_display and self.overlay.is_visible if overlay_shown or self.search_overlay.is_visible or self.content_popup_overlay.is_visible: # Chrome on Android stupidly resizes the viewport when the on # screen keyboard is displayed. This means that the push_state() # below causes the overlay to be closed, making it impossible to # type anything into text boxes. # See https://bugs.chromium.org/p/chromium/issues/detail?id=404315 return username = self.update_cfi_data(data) ui_operations.update_url_state(data.replace_history) if username: key = self.book.key lrd = {'device':get_device_uuid(), 'cfi':data.cfi, 'pos_frac':data.progress_frac} ajax_send('book-set-last-read-position/{library_id}/{book_id}/{fmt}'.format( library_id=key[0], book_id=key[1], fmt=key[2]), lrd, def(end_type, xhr, ev): if end_type is not 'load': print('Failed to update last read position, AJAX call did not succeed') ) update_book_in_recently_read_by_user_on_home_page(key[0], key[1], key[2], data.cfi) @property def current_position_data(self): if self.book?.manifest: book_length = self.book.manifest.spine_length or 0 name = self.currently_showing.name chapter_length = self.book.manifest.files[name]?.length or 0 else: book_length = chapter_length = 0 pos = { 'progress_frac': self.current_progress_frac, 'book_length': book_length, 'chapter_length': chapter_length, 'file_progress_frac': self.current_file_progress_frac, 'cfi': self.currently_showing?.bookpos, 'page_counts': self.current_page_counts, } return pos def show_status_message(self, msg, timeout): self.current_status_message = msg or '' self.update_header_footer() if self.current_status_message: if not timeout?: timeout = 10000 window.setTimeout(def(): self.show_status_message();, timeout) def create_template_renderer(self): if not self.book: return pos = self.current_position_data book_length = pos.book_length * max(0, 1 - pos.progress_frac) chapter_length = pos.chapter_length * max(0, 1 - pos.file_progress_frac) book_time = self.timers.time_for(book_length) chapter_time = self.timers.time_for(chapter_length) mi = self.book.metadata sd = get_session_data() view_mode = sd.get('read_mode') def render(div, name, which, override): return render_head_foot(div, name, which, mi, self.current_toc_node, self.current_toc_toplevel_node, self.current_pagelist_items, book_time, chapter_time, pos, override, view_mode) return render def update_header_footer(self): renderer = self.create_template_renderer() if not renderer: return sd = get_session_data() has_clock = False def render_template(div, edge, name): nonlocal has_clock c = div.lastChild b = c.previousSibling a = b.previousSibling if sd.get(f'margin_{edge}', 20) > 5: override = self.current_status_message if edge is 'bottom' else '' hca = renderer(a, name, 'left', override) hcb = renderer(b, name, 'middle', '') hcc = renderer(c, name, 'right', '') if hca or hcb or hcc: has_clock = True else: clear(a), clear(b), clear(c) for edge in ('left', 'right', 'top', 'bottom'): div = document.getElementById(f'book-{edge}-margin') if div: tname = {'left':'left-margin', 'right': 'right-margin', 'top': 'header', 'bottom': 'footer'}[edge] render_template(div, edge, tname) if has_clock: if not self.timer_ids.clock: self.timer_ids.clock = window.setInterval(self.update_header_footer, 60000) else: if self.timer_ids.clock: window.clearInterval(self.timer_ids.clock) self.timer_ids.clock = 0 def on_update_toc_position(self, data): update_visible_toc_nodes(data.visible_anchors) self.current_toc_families = get_current_toc_nodes() self.current_pagelist_items = get_current_pagelist_items() if self.current_toc_families.length: first = self.current_toc_families[0] self.current_toc_node = first[-1] self.current_toc_toplevel_node = first[0] else: self.current_toc_node = self.current_toc_toplevel_node = None if runtime.is_standalone_viewer: r = v'[]' for fam in self.current_toc_families: if fam.length: r.push(fam[-1].id) ui_operations.update_current_toc_nodes(r) self.update_header_footer() def show_spine_item(self, resource_data): self.pending_load = resource_data if self.iframe_wrapper.ready: self.do_pending_load() else: self.iframe_wrapper.init() def show_spine_item_stage2(self, resource_data): # We cannot encrypt this message because the resource data contains # Blob objects which do not survive encryption self.processing_spine_item_display = True self.current_status_message = '' self.iframe.style.visibility = 'hidden' fdata = self.book.manifest.files[self.currently_showing.name] smil_map = None if self.book.manifest.has_smil and fdata: smil_map = fdata.smil_map self.currently_showing.smil_audio_map = get_smil_audio_map(smil_map) self.iframe_wrapper.send_unencrypted_message('display', resource_data=resource_data, book=self.book, name=self.currently_showing.name, initial_position=self.currently_showing.initial_position, smil_map=smil_map or None, settings=self.currently_showing.settings, reference_mode_enabled=self.reference_mode_enabled, is_titlepage=self.currently_showing.name is self.book.manifest.title_page_name, highlights=self.annotations_manager.highlights_for_currently_showing(), ) def on_content_loaded(self, data): for x in self.modal_overlays: if not x.dont_hide_on_content_loaded: x.hide() self.processing_spine_item_display = False self.currently_showing.loading = False self.hide_loading() self.set_progress_frac(data.progress_frac, data.file_progress_frac, data.page_counts) self.update_header_footer() window.scrollTo(0, 0) # ensure window is at 0 on mobile where the navbar causes issues if self.book_load_started: self.book_load_started = False if ui_operations.clear_history: ui_operations.clear_history() if ui_operations.content_file_changed: ui_operations.content_file_changed(self.currently_showing.name) if self.read_aloud.is_visible: self.read_aloud.play() for x in self.currently_showing.on_load: x() self.currently_showing.on_load = v'[]' def set_progress_frac(self, progress_frac, file_progress_frac, page_counts): self.current_progress_frac = progress_frac or 0 self.current_file_progress_frac = file_progress_frac or 0 self.current_page_counts = page_counts self.book_scrollbar.sync_to_contents(self.current_progress_frac) def update_font_size(self): self.iframe_wrapper.send_message('change_font_size', base_font_size=get_session_data().get('base_font_size')) def viewer_font_size_changed(self): self.iframe_wrapper.send_message('viewer_font_size_changed', base_font_size=get_session_data().get('base_font_size')) def update_scroll_speed(self, amt): self.iframe_wrapper.send_message('change_scroll_speed', lines_per_sec_auto=change_scroll_speed(amt)) def update_color_scheme(self): cs = self.apply_color_scheme() self.iframe_wrapper.send_message('change_color_scheme', color_scheme=cs) def toggle_reference_mode(self): self.reference_mode_enabled = not self.reference_mode_enabled self.iframe_wrapper.send_message('set_reference_mode', enabled=self.reference_mode_enabled) if ui_operations.reference_mode_changed: ui_operations.reference_mode_changed(self.reference_mode_enabled) def discover_search_result(self, sr): if sr.search_finished: if self.search_result_discovery: self.search_result_discovery.finished = True if not self.search_result_discovery.discovered and self.search_result_discovery.first_search_result and self.search_result_discovery.queue.length is 0: sr = self.search_result_discovery.first_search_result sr.force_jump_to = True self.search_result_discovery.jump_forced = True self.show_search_result(sr) return if sr.result_num is 1: self.search_result_discovery = { 'queue': v'[]', 'on_discovery': sr.on_discovery, 'in_flight': None, 'discovered': False, 'first_search_result': sr, 'finished': False, 'jump_forced': False, } if not self.search_result_discovery or self.search_result_discovery.discovered or self.search_result_discovery.on_discovery is not sr.on_discovery: return self.search_result_discovery.queue.push(sr) if not self.search_result_discovery.in_flight: self.show_search_result(self.search_result_discovery.queue.shift()) def handle_search_result_discovery(self, sr, discovered): if self.search_result_discovery?.on_discovery is sr.on_discovery: self.search_result_discovery.in_flight = None if discovered: if not self.search_result_discovery.discovered: self.search_result_discovery.discovered = True ui_operations.search_result_discovered(sr) elif not self.search_result_discovery.discovered and self.search_result_discovery.queue.length: self.show_search_result(self.search_result_discovery.queue.shift()) elif not self.search_result_discovery.discovered and self.search_result_discovery.finished and not self.search_result_discovery.jump_forced: sr = self.search_result_discovery.first_search_result sr.force_jump_to = True self.search_result_discovery.jump_forced = True self.show_search_result(sr) def search_result_discovered(self, data): self.handle_search_result_discovery(data.search_result, data.discovered) def search_result_not_found(self, data): if ui_operations.search_result_not_found: ui_operations.search_result_not_found(data.search_result) self.handle_search_result_discovery(data.search_result, False) def show_search_result(self, sr): if self.currently_showing.name is sr.file_name: if self.currently_showing.loading: self.currently_showing.on_load.push(self.show_search_result.bind(None, sr)) else: self.iframe_wrapper.send_message('show_search_result', search_result=sr) else: self.show_name(sr.file_name, initial_position={'type':'search_result', 'search_result':sr, 'replace_history':True}) if self.search_result_discovery?.on_discovery is sr.on_discovery: self.search_result_discovery.in_flight = sr.result_num def highlight_action(self, uuid, which): spine = self.book.manifest.spine spine_index = self.annotations_manager.spine_index_for_highlight(uuid, spine) if spine_index < 0 or spine_index >= spine.length: if which is 'edit': self.selection_bar.report_failed_edit_highlight(uuid) return if which is 'edit': if self.currently_showing.spine_index is spine_index: self.selection_bar.edit_highlight(uuid) else: self.show_name(spine[spine_index], initial_position={'type':'edit_annotation', 'uuid': uuid, 'replace_history':True}) elif which is 'delete': self.selection_bar.remove_highlight_with_id(uuid) elif which is 'goto': cfi = self.annotations_manager.cfi_for_highlight(uuid, spine_index) if cfi: self.goto_cfi(cfi, True)
70,596
Python
.py
1,384
40.184971
220
0.622785
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,514
bookmarks.pyj
kovidgoyal_calibre/src/pyj/read_book/bookmarks.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.item_list import build_list, create_item, create_side_action from dom import ensure_id, set_css from modals import question_dialog from widgets import create_button from read_book.toc import get_book_mark_title def goto_cfi(cfi, view): view.goto_cfi(cfi, True) def remove_bookmark(annotations_manager, title, list_dom_node): question_dialog(_('Are you sure?'), _('Do you want to permanently delete this bookmark?'), def (yes): if yes: annotations_manager.remove_bookmark(title) list_dom_node.style.display = 'none' ) def edit_bookmark(annotations_manager, title, list_dom_node): new_title = window.prompt(_('Enter new title for bookmark:'), title) if new_title: if annotations_manager.edit_bookmark(title, new_title): console.log(list_dom_node) list_dom_node.querySelector('.item-title').textContent = new_title def create_bookmarks_list(annotations_manager, onclick): bookmarks = sorted(annotations_manager.all_bookmarks(), key=def(x): return x.title.toLowerCase();) items = [] for bookmark in bookmarks: if not bookmark.removed: sa = create_side_action('trash', remove_bookmark.bind(None, annotations_manager, bookmark.title), _('Remove this bookmark')) ea = create_side_action('edit', edit_bookmark.bind(None, annotations_manager, bookmark.title), _('Edit this bookmark')) items.push(create_item( bookmark.title, data=bookmark.pos, action=onclick.bind(None, goto_cfi.bind(None, bookmark.pos)), side_actions=[sa, ea] )) c = E.div(style='margin-top: 1ex') build_list(c, items) return c def create_new_bookmark(annotations_manager, data): base_default_title = get_book_mark_title() or _('Bookmark') title = window.prompt(_('Enter title for bookmark:'), data.selected_text or annotations_manager.default_bookmark_title(base_default_title)) if not title: return False cfi = data.cfi if data.selection_bounds?.start: cfi = data.selection_bounds.start annotations_manager.add_bookmark(title, cfi) return True def new_bookmark(container_id, annotations_manager, data, onclick, ev): if create_new_bookmark(annotations_manager, data): onclick(def(): pass;) def create_bookmarks_panel(annotations_manager, data, book, container, onclick): set_css(container, display='flex', flex_direction='column') container.appendChild(E.div(style='padding: 1rem')) container = container.lastChild container_id = ensure_id(container) button = create_button(_('New bookmark'), 'plus', new_bookmark.bind(None, container_id, annotations_manager, data, onclick)) container.appendChild(E.div(button)) container.appendChild(E.div(create_bookmarks_list(annotations_manager, onclick)))
3,092
Python
.py
60
45.333333
143
0.70756
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,515
smil.pyj
kovidgoyal_calibre/src/pyj/read_book/smil.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from read_book.anchor_visibility import is_anchor_on_screen from read_book.globals import get_boss def flatten_seq(seq, par_list): if seq.par: for par in seq.par: if par.anchor: par_list.push(par) if seq.seq: for child in seq.seq: flatten_seq(child, par_list) def flatten_smil_map(smil_map): anchor_map = {} par_list = v'[]' if smil_map: flatten_seq(smil_map, par_list) par_list.sort(def (a, b): return a.num - b.num;) for i in range(par_list.length): anchor_map[par_list[i].anchor] = i return anchor_map, par_list def get_smil_audio_map(smil_map): audio_map = {} def flatten(seq): if seq.par: for par in seq.par: if par.audio: a = audio_map[par.audio] if not a: a = audio_map[par.audio] = v'[]' a.push(par) if seq.seq: for child in seq.seq: flatten(child) if smil_map: flatten(smil_map) for v in Object.values(audio_map): v.sort(def(a, b): return a.start - b.start;) return {'audio_files': audio_map} def get_smil_id_for_timestamp(audio_file_name, timestamp, smil_audio_map, prev_idx): pars = smil_audio_map.audio_files[audio_file_name] if not pars: return None, None prev_idx = prev_idx or 0 if prev_idx >= pars.length or prev_idx < 0: prev_idx = 0 for i in range(prev_idx, pars.length): if pars[i].start <= timestamp <= pars[i].end: return pars[i].anchor, i for i in range(0, prev_idx): if pars[i].start <= timestamp <= pars[i].end: return pars[i].anchor, i return None, None def next_audio_file_for_spine_item(audio_file_name, smil_audio_map): if audio_file_name: keys = Object.keys(smil_audio_map) idx = keys.indexOf(audio_file_name) if 0 <= idx < keys.length - 1: return keys[idx+1], smil_audio_map[keys[idx+1]] return None, None def first_par(smil_map): par_list = flatten_smil_map(smil_map)[1] for par in par_list: if par.anchor: return par return None def find_next_audio_in_spine(spine_idx, book_manifest): spine = book_manifest.spine file_map = book_manifest.files for i in range(spine_idx + 1, spine.length): q = spine[i] f = file_map[q] if f and f.smil_map: par = first_par(f.smil_map) if par: return q, par return None, None def smil_element_at(pos, anchor_map, par_list): if pos: # first see if we get lucky elem = document.elementFromPoint(pos.x, pos.y) if elem and elem.id and anchor_map[elem.id]?: return par_list[anchor_map[elem.id]] # now try to find a par that intersects pos af = get_boss().anchor_funcs for par in par_list: if par.anchor and par.audio: elem = document.getElementById(par.anchor) if elem: br = af.get_bounding_client_rect(elem) if br.x <= pos.x <= (br.x + br.width) and br.y <= pos.y <= (br.y + br.height): return par return None else: # use first visible anchor for par in par_list: if par.anchor and par.audio and is_anchor_on_screen(par.anchor): return par # just use first par for par in par_list: if par.audio: return par return None def mark_smil_element(anchor): elem = document.getElementById(anchor) if elem: sel = window.getSelection() sel.selectAllChildren(elem) return bool(sel.rangeCount and sel.toString()) return False
3,996
Python
.py
110
27.390909
98
0.582406
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,516
goto.pyj
kovidgoyal_calibre/src/pyj/read_book/goto.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals import traceback from elementmaker import E from gettext import gettext as _ from ajax import encode_query_component from book_list.item_list import build_list, create_item from dom import ensure_id, set_css from modals import error_dialog from read_book.globals import current_book, runtime, ui_operations from read_book.prefs.head_foot import format_pos from read_book.toc import get_border_nodes, get_toc_maps from widgets import create_button def create_goto_list(onclick, current_position_data, page_list): ans = E.div() items = v'[]' location_text = format_pos(current_position_data.progress_frac, current_position_data.book_length) + ' :: ' if current_position_data.cfi: location_text += current_position_data.cfi landmarks = current_book().manifest.landmarks toc = current_book().manifest.toc id_map = get_toc_maps(toc)[1] before, after = get_border_nodes(toc, id_map) if after: items.push(create_item(_('Next section'), icon='caret-right', subtitle=after.title, action=onclick.bind(None, after.dest, after.frag))) if before: items.push(create_item(_('Previous section'), icon='caret-left', subtitle=before.title, action=onclick.bind(None, before.dest, before.frag))) items.push(create_item(_('Book start'), action=onclick.bind(None, def(view): view.goto_doc_boundary(True);))) items.push(create_item(_('Book end'), action=onclick.bind(None, def(view): view.goto_doc_boundary(False);))) items.push(create_item(_('Metadata'), subtitle=_('Details about this book'), action=onclick.bind(None, def(view): view.overlay.show_metadata() ))) if not runtime.is_standalone_viewer: items.push(create_item(_('Book page in library'), subtitle=_('The page for this book in the calibre library'), action=onclick.bind(None, def(view): view.open_book_page() ))) items.push(create_item(_('Location'), subtitle=location_text, action=onclick.bind(None, def(view): view.overlay.show_ask_for_location();))) if page_list and page_list.length > 0: items.push(create_item(_('Page number'), subtitle=_('Typically the page number from a paper edition of this book'), action=onclick.bind(None, def(view): view.overlay.show_page_list(page_list);))) for l in landmarks: items.push(create_item(l.title, action=onclick.bind(None, l.dest, l.frag))) build_list(ans, items) return ans def get_next_section(forward): toc = current_book().manifest.toc id_map = get_toc_maps(toc)[1] before, after = get_border_nodes(toc, id_map) return after if forward else before def create_goto_panel(current_position_data, book, container, onclick): panel = create_goto_list(onclick, current_position_data, book.manifest.page_list) set_css(container, display='flex', flex_direction='column') set_css(panel, flex_grow='10') container.appendChild(panel) def create_page_list_overlay(book, overlay, container): list_container = E.div() pl = overlay.view.current_pagelist_items if pl and pl.length > 0: if pl.length is 1: text = _('Currently on page: {}').format(pl[0].pagenum) else: text = _('Currently on pages: {}').format(pl[0].pagenum + ' - ' + pl[1].pagenum) container.appendChild(E.div(style='margin: 1em', text)) container.appendChild(list_container) page_list = book.manifest.page_list or v'[]' items = v'[]' def goto(x): overlay.view.goto_pagelist_item(x) overlay.hide() for x in page_list: items.push(create_item(x.pagenum, action=goto.bind(None, x), )) build_list(list_container, items) def create_location_overlay(current_position_data, book, overlay, container): container_id = ensure_id(container) container.appendChild(E.div(style='margin: 0 1rem')) container = container.lastChild current_cfi = current_position_data.cfi calibre_book_url = book?.calibre_book_url def copy_button(text_to_copy): return create_button(_('Copy'), action=def(): src = document.querySelector(f'#{container_id} input') orig = src.value src.value = text_to_copy src.focus() src.select() try: document.execCommand('copy') finally: src.value = orig ) def display_and_copy(label, text): container.appendChild(E.div( style='margin: 1rem; margin-bottom: calc(1rem - 1ex); display: flex; align-items: baseline; flex-wrap: wrap', E.div(style='flex-grow: 10; text-overflow: ellipsis; margin-bottom: 1ex', label, ' ', E.span(text, style='font-size: smaller; font-family: monospace')), copy_button(text) )) if current_cfi: display_and_copy(_('Current location:'), current_cfi) def goto_cfi(cfi): if ui_operations.goto_cfi(cfi): overlay.hide() else: error_dialog(_('No such location'), _( 'No location {} found').format(cfi)) def goto_ref(ref): ref = ref.replace(/,/g, '.') if ui_operations.goto_reference(ref): overlay.hide() else: error_dialog(_('No such reference'), _( 'No reference {} found').format(ref)) if current_position_data.book_length > 0: container.appendChild( E.div(style='margin: 1rem', _('Current position: {}').format( format_pos(current_position_data.progress_frac, current_position_data.book_length)))) container.appendChild( E.div(style='margin: 1rem', _( 'Type the position, location or reference below. For a reference type ref: followed by the reference:'))) def goto_pos(): src = document.querySelector(f'#{container_id} [name=newpos]').value if not src: return if src.indexOf('epubcfi(') is 0: return goto_cfi(src) if src.indexOf('ref:') is 0: return goto_ref(src[len('ref:'):]) try: ui_operations.goto_book_position(float(src)) except: error_dialog(_('Not a valid book position'), _( '{} is not a valid book position').format(src), traceback.format_exc()) else: overlay.hide() container.appendChild(E.div( style='margin: 1rem;', E.div( style='display: flex; align-items: baseline; flex-wrap: wrap', E.label(_('Go to:'), style='margin-right: 1rem'), E.input(name='newpos', type='text', min='0', max=str(current_position_data.book_length), step='0.1', style='flex-grow: 10; margin-right: 1rem', onkeydown=def(ev): if ev.key is 'Enter': goto_pos() ), E.span(' '), create_button(_('Go'), action=goto_pos) ) )) if calibre_book_url: if current_cfi: calibre_book_url += '?open_at=' + encode_query_component(current_cfi) display_and_copy(_('URL for this position:'), calibre_book_url) elif not runtime.is_standalone_viewer: display_and_copy(_('URL for this position:'), window.top.location.toString()) window.setTimeout(def(): container = document.getElementById(container_id) if container: container.querySelector('[name=newpos]').focus() , 10)
7,612
Python
.py
158
39.822785
203
0.636474
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,517
mathjax.pyj
kovidgoyal_calibre/src/pyj/read_book/mathjax.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from elementmaker import E from read_book.globals import runtime def get_url(mathjax_files, name): ans = mathjax_files[name] if not ans: return name if jstype(ans) is not 'string': ans = mathjax_files[name] = window.URL.createObjectURL(ans) return ans def postprocess(link_uid): for a in document.getElementsByTagName('a'): href = a.getAttribute('href') if href and href.startswith('#'): a.setAttribute('href', 'javascript: void(0)') a.setAttribute('data-' + link_uid, JSON.stringify({'frag':href[1:]})) def load_mathjax(src): script = E.script(type='text/javascript') script.async = True script.src = src document.head.appendChild(script) standalone_proceed_data = { 'link_uid': None, 'proceed': None, 'event_listender_added': False, } def standalone_proceed(): if standalone_proceed_data.proceed: postprocess(standalone_proceed_data.link_uid) standalone_proceed_data.proceed() standalone_proceed_data.proceed = None def apply_mathjax(mathjax_files, link_uid, proceed): if runtime.is_standalone_viewer: if not standalone_proceed_data.event_listender_added: standalone_proceed_data.event_listender_added = True document.documentElement.addEventListener("calibre-mathjax-typeset-done", standalone_proceed) if standalone_proceed_data.proceed: print('MathJax apply called while a previous apply is still running') standalone_proceed_data.link_uid = link_uid standalone_proceed_data.proceed = proceed load_mathjax(f'{runtime.FAKE_PROTOCOL}://{runtime.SANDBOX_HOST}/mathjax/startup.js') return window.MathJax = v'{}' window.MathJax.startup = { 'ready': def (): window.MathJax.startup.defaultReady() # monkeypatch the method responsible for mapping font URLs # to use our blob URLs, see https://github.com/mathjax/MathJax/issues/2458 window.MathJax.startup.output.font.addFontURLs = def (styles, fonts, url): base = url.partition('/')[2] for name in fonts: clone = v'{}' font = fonts[name] for key in Object.keys(font): clone[key] = font[key] font_name = clone.src.partition('/')[2].partition('"')[0] full_name = base + '/' + font_name src = get_url(mathjax_files, full_name) clone.src = clone.src.replace(/".+?"/, f'"{src}"') styles[name] = clone window.MathJax.startup.promise.then(def(): postprocess(link_uid) proceed() ) , } # also do any changes in pdf-mathjax-loader.js for the standalone # viewer/editor/pdf output window.MathJax.loader = { 'load': v"['input/tex-full', 'input/asciimath', 'input/mml', 'output/chtml']", 'require': def (url): return new Promise(def (resolve, reject): name = url.partition('/')[2] script = document.createElement('script') script.charset = 'UTF-8' script.onload = def (): resolve(url) script.onerror = def (): reject(url) script.src = get_url(mathjax_files, name) document.head.appendChild(script) ) , } for s in document.scripts: if s.type is 'text/x-mathjax-config': es = document.createElement('script') es.text = s.text document.head.appendChild(es) document.head.removeChild(es) load_mathjax(get_url(mathjax_files, 'startup.js'))
3,967
Python
.py
93
32.365591
105
0.598756
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,518
cfi.pyj
kovidgoyal_calibre/src/pyj/read_book/cfi.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals # Based on code originally written by Peter Sorotkin # http://code.google.com/p/epub-revision/source/browse/trunk/src/samples/cfi/epubcfi.js # # Improvements with respect to that code: # 1. Works on all browsers (WebKit, Firefox and IE >= 9) # 2. Works for content in elements that are scrollable (i.e. have their own scrollbars) # 3. Much more comprehensive testing/error handling # 4. Properly encodes/decodes assertions # 5. Handles points in the padding of elements consistently # 6. Has a utility method to calculate the CFI for the current viewport position robustly # # Tested on: Firefox 9, IE 9, Chromium 16, Qt WebKit 2.1 # The main entry points are: # at(x, y): Maps a point to a CFI, if possible # at_current(): Returns the CFI corresponding to the current viewport scroll location # # scroll_to(cfi): which scrolls the browser to a point corresponding to the # given cfi, and returns the x and y co-ordinates of the point. from read_book.viewport import scroll_viewport, rem_size # CFI escaping {{{ escape_pat = /[\[\],^();~@!]/g unescape_pat = /[\^](.)/g def escape_for_cfi(raw): return (raw or '').replace(escape_pat, '^$&') def unescape_from_cfi(raw): return (raw or '').replace(unescape_pat, '$1') # }}} def fstr(d): # {{{ # Convert a timestamp floating point number to a string ans = '' if d < 0: ans = '-' d = -d n = Math.floor(d) ans += n n = Math.round((d-n)*100) if n is not 0: ans += "." + (n/10 if (n % 10 is 0) else n) return ans # }}} def get_current_time(target): # {{{ return fstr(target.currentTime or 0) # }}} def id_is_unique(idval): # {{{ try: multiples = document.querySelectorAll('[id=' + window.CSS.escape(idval) + ']') except: return False if multiples and multiples.length < 2: return True return False # }}} # Convert point to character offset {{{ def range_has_point(range_, x, y): rects = range_.getClientRects() for v'var i = 0; i < rects.length; i++': rect = rects[i] if (rect.left <= x <= rect.right) and (rect.top <= y <= rect.bottom): return True return False def offset_in_text_node(node, range_, x, y): limits = v'[0, node.nodeValue.length]' while limits[0] is not limits[1]: pivot = Math.floor( (limits[0] + limits[1]) / 2 ) lr = v'[limits[0], pivot]' rr = v'[pivot+1, limits[1]]' range_.setStart(node, pivot) range_.setEnd(node, pivot+1) if range_has_point(range_, x, y): return pivot range_.setStart(node, rr[0]) range_.setEnd(node, rr[1]) if range_has_point(range_, x, y): limits = rr continue range_.setStart(node, lr[0]) range_.setEnd(node, lr[1]) if range_has_point(range_, x, y): limits = lr continue break return limits[0] def find_offset_for_point(x, y, node, cdoc): range_ = cdoc.createRange() child = node.firstChild while child: if Node.TEXT_NODE <= child.nodeType <= Node.ENTITY_NODE and child.nodeValue and child.nodeValue.length: range_.setStart(child, 0) range_.setEnd(child, child.nodeValue.length) if range_has_point(range_, x, y): return v'[child, offset_in_text_node(child, range_, x, y)]' child = child.nextSibling # The point must be after the last bit of text/in the padding/border, we dont know # how to get a good point in this case return None, None # }}} def set_current_time(target, val): # {{{ if target.currentTime is undefined: return if target.readyState is 4 or target.readyState is "complete": target.currentTime = val + 0 else: target.addEventListener("canplay", def(): target.currentTime = val;, False) # }}} # def encode(doc, node, offset, tail): {{{ def is_text_node(node): return node.nodeType is Node.TEXT_NODE or node.nodeType is Node.CDATA_SECTION_NODE def text_length_in_range_wrapper(node): p = node.firstChild ans = 0 while p: if is_text_node(p): ans += p.nodeValue.length elif p.nodeType is Node.ELEMENT_NODE and p.dataset?.calibreRangeWrapper: ans += text_length_in_range_wrapper(p) p = p.nextSibling return ans def adjust_node_for_text_offset(node): if node.parentNode and node.parentNode.dataset?.calibreRangeWrapper: node = node.parentNode offset = 0 adjusted = False while True: p = node.previousSibling if not p or p.nodeType > Node.COMMENT_NODE: break if is_text_node(p): offset += p.nodeValue.length elif p.nodeType is Node.ELEMENT_NODE and p.dataset?.calibreRangeWrapper: offset += text_length_in_range_wrapper(p) node = p adjusted = True if adjusted and node.nodeType is Node.ELEMENT_NODE and node.dataset?.calibreRangeWrapper: if not node.firstChild or node.firstChild.nodeType is not Node.TEXT_NODE: node.insertBefore(document.createTextNode(''), node.firstChild or None) node = node.firstChild return node, offset, adjusted def unwrapped_nodes(range_wrapper): ans = v'[]' for child in range_wrapper.childNodes: if child.nodeType is Node.ELEMENT_NODE and child.dataset?.calibreRangeWrapper: ans = ans.concat(unwrapped_nodes(child)) else: ans.push(child) return ans def increment_index_for_child(child, index, sentinel): is_element = child.nodeType is Node.ELEMENT_NODE if is_element and child.dataset?.calibreRangeWrapper: nodes = unwrapped_nodes(child) index = increment_index_for_children(nodes, index, sentinel) else: index |= 1 # increment if even if is_element: index += 1 return index def increment_index_for_children(children, index, sentinel): for i in range(children.length): child = children[i] index = increment_index_for_child(child, index, sentinel) if child is sentinel: break return index def non_range_wrapper_parent(node): p = node.parentNode child = node while p.dataset?.calibreRangeWrapper: child = p p = p.parentNode return p, child def encode(doc, node, offset, tail): cfi = tail or "" # Handle the offset, if any if node.nodeType is Node.ELEMENT_NODE: if jstype(offset) is 'number': q = node.childNodes.item(offset) if q: if q.nodeType is Node.ELEMENT_NODE: node = q if node.dataset?.calibreRangeWrapper: if not node.firstChild: node.appendChild(document.createTextNode('')) node = node.firstChild elif node.dataset?.calibreRangeWrapper: if not node.firstChild: node.appendChild(document.createTextNode('')) node = node.firstChild if is_text_node(node): offset = offset or 0 adjusted_node, additional_offset, adjusted = adjust_node_for_text_offset(node) if adjusted: node = adjusted_node offset += additional_offset cfi = ":" + offset + cfi elif node.nodeType is not Node.ELEMENT_NODE: # Not handled print(f"Offsets for nodes of type {node.nodeType} are not handled") # Construct the path to node from root is_first = True while node is not doc: p, sentinel = non_range_wrapper_parent(node) if not p: if node.nodeType == Node.DOCUMENT_NODE: # Document node (iframe) win = node.defaultView if win.frameElement: node = win.frameElement cfi = "!" + cfi continue break # Find position of node in parent index = increment_index_for_children(p.childNodes, 0, sentinel) if is_first: is_first = False if node.nodeType is Node.ELEMENT_NODE and node.dataset?.calibreRangeWrapper: index -= 1 # Add id assertions for robustness where possible id = node.id idspec = '' if id and id_is_unique(id): idspec = ('[' + escape_for_cfi(id) + ']') cfi = '/' + index + idspec + cfi node = p return cfi # }}} # def decode(cfi, doc): {{{ def node_at_index(nodes, target, index, iter_text_nodes): for i in range(nodes.length): node = nodes[i] is_element = node.nodeType is Node.ELEMENT_NODE if is_element and node.dataset?.calibreRangeWrapper: q, index = node_at_index(unwrapped_nodes(node), target, index, iter_text_nodes) if q: return q, index continue if (iter_text_nodes and not is_text_node(node)) or (not iter_text_nodes and not is_element): continue if index is target: return node, index index += 1 return None, index def node_for_path_step(parent, target, assertion): if assertion: q = document.getElementById(assertion) if q and id_is_unique(assertion): return q is_element = target % 2 == 0 target //= 2 if is_element and target > 0: target -= 1 return node_at_index(parent.childNodes, target, 0, not is_element)[0] def node_for_text_offset(nodes, offset, first_node): last_text_node = None seen_first = False for i in range(nodes.length): node = nodes[i] if not seen_first: if not first_node or node.isSameNode(first_node): seen_first = True else: continue if is_text_node(node): l = node.nodeValue.length if offset <= l: return node, offset, True last_text_node = node offset -= l # mathml nodes dont have dataset elif node.nodeType is Node.ELEMENT_NODE and node.dataset?.calibreRangeWrapper: qn, offset, ok = node_for_text_offset(unwrapped_nodes(node), offset) if ok: return qn, offset, True return last_text_node, offset, False # Based on a CFI string, returns a decoded CFI, with members: # # node: The node to which the CFI refers. # time: If the CFI refers to a video or sound, this is the time within such to which it refers. # x, y: If the CFI defines a spatial offset (technically only valid for images and videos), # these are the X and Y percentages from the top-left of the image or video. # Note that Calibre has a fallback to set CFIs with spatial offset on the HTML document, # and interprets them as a position within the Calibre-rendered document. # forward: This is set to True if the CFI had a side bias of 'a' (meaning 'after'). # offset: When the CFI refers to a text node, this is the offset (zero-based index) of the character # the CFI refers to. The position is defined as being before the specified character, # i.e. an offset of 0 is before the first character and an offset equal to number of characters # in the text is after the last character. # error: If there was a problem decoding the CFI, this is set to a string describing the error. def decode(cfi, doc): doc = doc or window.document simple_node_regex = /// ^/(\d+) # The node count (\[[^\]]*\])? # The optional id assertion /// error = None node = doc orig_cfi = cfi while cfi.length > 0 and not error: r = cfi.match(simple_node_regex) if r: # Path step target = parseInt(r[1]) assertion = r[2] if assertion: assertion = unescape_from_cfi(assertion.slice(1, assertion.length-1)) q = node_for_path_step(node, target, assertion) if q: node = q cfi = cfi.substr(r[0].length) else: if target: error = f"No matching child found for CFI: {orig_cfi} leftover: {cfi}" break else: cfi = cfi.substr(r[0].length) else if cfi[0] is '!': # Indirection if node.contentDocument: node = node.contentDocument cfi = cfi.substr(1) else: error = "Cannot reference " + node.nodeName + "'s content: " + cfi else: break if error: print(error) return None decoded = {} error = None offset = None r = cfi.match(/^:(\d+)/) if r: # Character offset offset = parseInt(r[1]) cfi = cfi.substr(r[0].length) r = cfi.match(/^~(-?\d+(\.\d+)?)/) if r: # Temporal offset decoded.time = r[1] - 0 # Coerce to number cfi = cfi.substr(r[0].length) r = cfi.match(/^@(-?\d+(\.\d+)?):(-?\d+(\.\d+)?)/) if r: # Spatial offset decoded.x = r[1] - 0 # Coerce to number decoded.y = r[3] - 0 # Coerce to number cfi = cfi.substr(r[0].length) r = cfi.match(/^\[([^\]]+)\]/) if r: assertion = r[1] cfi = cfi.substr(r[0].length) r = assertion.match(/;s=([ab])$/) if r: if r.index > 0 and assertion[r.index - 1] is not '^': assertion = assertion.substr(0, r.index) decoded.forward = (r[1] is 'a') assertion = unescape_from_cfi(assertion) # TODO: Handle text assertion # Find the text node that contains the offset if offset is not None: orig_offset = offset if node.parentNode?.nodeType is Node.ELEMENT_NODE and node.parentNode.dataset?.calibreRangeWrapper: node = node.parentNode qnode, offset, ok = node_for_text_offset(node.parentNode.childNodes, offset, node) if not ok: error = "Offset out of range: " + orig_offset if qnode: node = qnode decoded.offset = offset decoded.node = node if error: decoded.error = error else if cfi.length > 0: decoded.error = "Undecoded CFI: " + cfi if decoded.error: print(decoded.error) return decoded # }}} def cfi_sort_key(cfi): # {{{ simple_node_regex = /// ^/(\d+) # The node count (\[[^\]]*\])? # The optional id assertion /// steps = v'[]' while cfi.length > 0: r = cfi.match(simple_node_regex) if r: # Path step target = parseInt(r[1]) cfi = cfi.substr(r[0].length) steps.push(target) else if cfi[0] is '!': # Indirection cfi = cfi.substr(1) else: break ans = {'steps': steps, 'text_offset': 0, 'temporal_offset': 0, 'spatial_offset': v'[0, 0]'} r = cfi.match(/^:(\d+)/) if r: # Character offset offset = parseInt(r[1]) ans['text_offset'] = offset cfi = cfi.substr(r[0].length) r = cfi.match(/^~(-?\d+(\.\d+)?)/) if r: # Temporal offset ans['temporal_offset'] = r[1] - 0 # Coerce to number cfi = cfi.substr(r[0].length) r = cfi.match(/^@(-?\d+(\.\d+)?):(-?\d+(\.\d+)?)/) if r: # Spatial offset ans['spatial_offset'] = v'[r[1] - 0, r[3] - 0]' cfi = cfi.substr(r[0].length) return ans def create_cfi_cmp(key_map): if not key_map: key_map = {} def cfi_cmp(a_cfi, b_cfi): a = key_map[a_cfi] if not a: a = key_map[a_cfi] = cfi_sort_key(a_cfi) b = key_map[b_cfi] if not b: b = key_map[b_cfi] = cfi_sort_key(b_cfi) for i in range(min(a.steps.length, b.steps.length)): diff = a.steps[i] - b.steps[i] if diff is not 0: return diff diff = a.steps.length - b.steps.length if diff is not 0: return diff if a.temporal_offset is not b.temporal_offset: return a.temporal_offset - b.temporal_offset if a.spatial_offset[0] is not b.spatial_offset[0]: return a.spatial_offset[0] - b.spatial_offset[0] if a.spatial_offset[1] is not b.spatial_offset[1]: return a.spatial_offset[1] - b.spatial_offset[1] if a.text_offset is not b.text_offset: return a.text_offset - b.text_offset return 0 return cfi_cmp def sort_cfis(array_of_cfis): key_map = {cfi: cfi_sort_key(cfi) for cfi in array_of_cfis} Array.prototype.sort.call(array_of_cfis, create_cfi_cmp(key_map)) # }}} def at(x, y, doc): # {{{ # x, y are in viewport co-ordinates doc = doc or window.document cdoc = doc target = None tail = '' offset = None name = None # Drill down into iframes, etc. while True: target = cdoc.elementFromPoint(x, y) if not target or target is cdoc.documentElement or target is cdoc.body: # We ignore both html and body even though body could # have text nodes under it as performance is very poor if body # has large margins/padding (e.g. in fullscreen mode) # A possible solution for this is to wrap all text node # children of body in <span> but that is seriously ugly and # might have side effects. Lets do this only if there are lots of # books in the wild that actually have text children of body, # and even in this case it might be better to change the input # plugin to prevent this from happening. # log("No element at (#{ x }, #{ y })") return None name = target.localName if name not in {'iframe', 'embed', 'object'}: break cd = target.contentDocument if not cd: break # We have an embedded document, transforms x, y into the co-prd # system of the embedded document's viewport rect = target.getBoundingClientRect() x -= rect.left y -= rect.top cdoc = cd (target.parentNode or target).normalize() if name in {'audio', 'video'}: tail = "~" + get_current_time(target) if name in {'img', 'video'}: rect = target.getBoundingClientRect() px = ((x - rect.left)*100)/target.offsetWidth py = ((y - rect.top)*100)/target.offsetHeight tail = str.format('{}@{}:{}', tail, fstr(px), fstr(py)) else if name is not 'audio': # Get the text offset # We use a custom function instead of caretRangeFromPoint as # caretRangeFromPoint does weird things when the point falls in the # padding of the element target, offset = find_offset_for_point(x, y, target, cdoc) if target is None: return None return encode(doc, target, offset, tail) # }}} # Wrapper for decode(), tries to construct a range from the CFI's # character offset and include it in the return value. # # If the CFI defines a character offset, there are three cases: # Case 1. If the offset is 0 and the text node's length is zero, # the range is set to None. This is a failure case, but # later code will try to use the node's bounding box. # Case 2. Otherwise, if the offset is >= the length of the range, # then a range from the previous to the last character is created, # and use_range_end_pos is set. This is the special case. # Case 3. Otherwise, the range is set start at the offset and end at one character past the offset. # # In cases 2 and 3, the range is then checked to verify that bounding information can be obtained. # If not, no range is returned. # # If the CFI does not define a character offset, then the spatial offset is set in the return value. # # Includes everything that the decode() function does, in addition to: # range: A text range, as described above. # use_range_end_pos: If this is True, a position calculated from the range should # use the position after the last character in the range. # (This is set if the offset is equal to the length of the text in the node.) def decode_with_range(cfi, doc): # {{{ doc = doc or window.document decoded = decode(cfi, doc) if not decoded or not decoded.node: return None node = decoded.node ndoc = node.ownerDocument if not ndoc: print(str.format("CFI node has no owner document: {} {}", cfi, node)) return None range_ = None position_at_end_of_range = None if jstype(decoded.offset) is "number": # We can only create a meaningful range if the node length is # positive and nonzero. node_len = node.nodeValue.length if node.nodeValue else 0 if not node_len and node.nextSibling?.dataset?.calibreRangeWrapper and node.nextSibling.firstChild?.nodeType is Node.TEXT_NODE: node = node.nextSibling.firstChild node_len = node.nodeValue.length if node.nodeValue else 0 if node_len: range_ = ndoc.createRange() # Check for special case: End of range offset, after the last character offset = decoded.offset position_at_end_of_range = False if offset >= node_len: offset = node_len - 1 position_at_end_of_range = True range_.setStart(node, offset) range_.setEnd(node, offset + 1) rect = range_.getBoundingClientRect() if not rect: print(str.format("Could not find caret position for {} (offset: {})", cfi, decoded.offset)) range_ = None else: print(f'Caret offset pointed to an empty text node or a non-text node for {cfi}, (offset: {decoded.offset})') range_ = None # Augment decoded with range, if found decoded.range = range_ decoded.use_range_end_pos = position_at_end_of_range return decoded # }}} # It's only valid to call this if you have a decoded CFI with a range included. # Call decoded_to_document_position if you're not sure. def decoded_range_to_document_position(decoded): # Character offset # Get the bounding rect of the range, in (real) viewport space rect = decoded.range.getBoundingClientRect() inserted_node = None if not rect.width and not rect.height and not rect.left and not rect.right: # this happens is range is a text node containing a newline after a # <br> https://bugs.launchpad.net/bugs/1944433 inserted_node = document.createTextNode('\xa0') decoded.range.insertNode(inserted_node) rect = decoded.range.getBoundingClientRect() # Now, get the viewport-space position (vs_pos) we want to scroll to # This is a little complicated. # The box we are using is a character's bounding box. # First, the inline direction. # We want to use the beginning of the box per the ePub CFI spec, # which states character offset CFIs refer to the beginning of the # character, which would be in the inline direction. # Unless the flag is set to use the end of the range: # (because ranges indices may not exceed the range, # but CFI offsets are allowed to be one past the end.) if decoded.use_range_end_pos: inline_vs_pos = scroll_viewport.rect_inline_end(rect) else: inline_vs_pos = scroll_viewport.rect_inline_start(rect) # Next, the block direction. # If the CFI specifies a side bias, we should respect that. # Otherwise, we want to use the block start. if decoded.forward: block_vs_pos = scroll_viewport.rect_block_end(rect) else: block_vs_pos = scroll_viewport.rect_block_start(rect) if inserted_node: inserted_node.parentNode.removeChild(inserted_node) # Now, we need to convert these to document X and Y coordinates. return scroll_viewport.viewport_to_document_inline_block(inline_vs_pos, block_vs_pos, decoded.node.ownerDocument) # This will work on a decoded CFI that refers to a node or node with spatial offset. # It will ignore any ranges, so call decoded_to_document_position unless you're sure the decoded CFI has no range. def decoded_node_or_spatial_offset_to_document_position(decoded): node = decoded.node rect = node.getBoundingClientRect() percentx, percenty = decoded.x, decoded.y # If we have a spatial offset, base the CFI position on the offset into the object if jstype(percentx) is 'number' and node.offsetWidth and jstype(percenty) is 'number' and node.offsetHeight: viewx = rect.left + (percentx*node.offsetWidth)/100 viewy = rect.top + (percenty*node.offsetHeight)/100 doc_left, doc_top = scroll_viewport.viewport_to_document(viewx, viewy, node.ownerDocument) return doc_left, doc_top # Otherwise, base it on the inline and block start and end, along with side bias: else: if decoded.forward: block_vs_pos = scroll_viewport.rect_block_end(rect) else: block_vs_pos = scroll_viewport.rect_block_start(rect) inline_vs_pos = scroll_viewport.rect_inline_start(rect) return scroll_viewport.viewport_to_document_inline_block(inline_vs_pos, block_vs_pos, node.ownerDocument) # This will take a decoded CFI and return a document position. # def decoded_to_document_position(decoded): node = decoded.node if decoded.range is not None: return decoded_range_to_document_position(decoded) else if node is not None and node.getBoundingClientRect: return decoded_node_or_spatial_offset_to_document_position(decoded) # No range, so we can't use that, and no node, so any spatial offset is meaningless return None, None def scroll_to(cfi, callback, doc): # {{{ decoded = decode_with_range(cfi, doc) if not decoded: print("No location information found for cfi: " + cfi) return if jstype(decoded.time) is 'number': set_current_time(decoded.node, decoded.time) def handle_text_node(): # Character offset r = decoded.range so, eo = r.startOffset, r.endOffset original_node = r.startContainer # Save the node index and its parent so we can get the node back # after removing the span and normalizing the parent. node_parent = original_node.parentNode original_node_index = 0 for v'var i = 0; i < node_parent.childNodes.length; i++': if node_parent.childNodes[i].isSameNode(original_node): original_node_index = i break ndoc = original_node.ownerDocument or document span = ndoc.createElement('span') span.setAttribute('style', 'border-width: 0; padding: 0; margin: 0') r.surroundContents(span) scroll_viewport.scroll_into_view(span) return def(): nonlocal original_node, r # Remove the span and get the new position now that scrolling # has (hopefully) completed p = span.parentNode for node in span.childNodes: span.removeChild(node) p.insertBefore(node, span) p.removeChild(span) p.normalize() original_node = node_parent.childNodes[original_node_index] if not original_node: # something bad happened, give up return # Reset the range to what it was before the span was added offset = so while offset > -1: try: r.setStart(original_node, offset) break except: offset -= 1 offset = eo while offset > -1: try: r.setEnd(original_node, offset) break except: offset -= 1 doc_x, doc_y = decoded_range_to_document_position(decoded) # Abort if CFI position is invalid if doc_x is None or doc_y is None: return # Since this position will be used for the upper-left of the viewport, # in RTL mode, we need to offset it by the viewport width so the # position will be on the right side of the viewport, # from where we start reading. # (Note that adding moves left in RTL mode because of the viewport X # coordinate reversal in RTL mode.) if scroll_viewport.rtl: doc_x += scroll_viewport.width() if callback: callback(doc_x, doc_y) def handle_element_node(): node = decoded.node if node.nodeType is Node.TEXT_NODE: node = decoded.node = node.parentNode if not node.scrollIntoView: return scroll_viewport.scroll_into_view(node) return def(): doc_x, doc_y = decoded_node_or_spatial_offset_to_document_position(decoded) # Abort if CFI position is invalid if doc_x is None or doc_y is None: return # Since this position will be used for the upper-left of the viewport, # in RTL mode, we need to offset it by the viewport width so the # position will be on the right side of the viewport, # from where we start reading. # (Note that adding moves left in RTL mode because of the viewport X # coordinate reversal in RTL mode.) if scroll_viewport.rtl: doc_x += scroll_viewport.width() if callback: callback(doc_x, doc_y) if decoded.range is not None: fn = handle_text_node() else: fn = handle_element_node() setTimeout(fn, 10) # }}} def at_point(x, y): # {{{ # The CFI at the specified point. Different to at() in that this method # returns null if there is an error, and also calculates a point from # the CFI and returns null if the calculated point is far from the # original point. def dist(p1, p2): Math.sqrt(Math.pow(p1[0]-p2[0], 2), Math.pow(p1[1]-p2[1], 2)) try: cfi = at(x, y) except: cfi = None if cfi is None: return None try: decoded = decode_with_range(cfi) except: decoded = None if not decoded: return None if cfi: try: cfix, cfiy = decoded_to_document_position(decoded) except: cfix = cfiy = None if cfix is None or cfiy is None or dist(scroll_viewport.viewport_to_document(x, y), v'[cfix, cfiy]') > 50: cfi = None return cfi # }}} def at_current(): # {{{ # We subtract one because the actual position query for CFI elements is relative to the # viewport, and the viewport coordinates actually go from 0 to the size - 1. # If we don't do this, the first line of queries will always fail in those cases where we # start at the right of the viewport because they'll be outside the viewport wini, winb = scroll_viewport.inline_size() - 1, scroll_viewport.block_size() - 1 # Don't let the deltas go too small or too large, to prevent perverse cases where # we don't loop at all, loop too many times, or skip elements because we're # looping too fast. deltai = deltab = max(8, min(Math.ceil(rem_size() / 2), 32)) # i.e. English, Hebrew: if scroll_viewport.horizontal_writing_mode: # Horizontal languages always start at the top startb = 0 endb = winb if scroll_viewport.ltr: # i.e. English: we scan from the left margin to the right margin starti = 0 endi = wini else: # i.e. Hebrew: we scan from the right margin to the left margin starti = wini endi = 0 deltai = -deltai # i.e. Japanese, Mongolian script, traditional Chinese else: # These languages are only top-to-bottom starti = 0 endi = winb # i.e. Japanese: To the next line is from the right margin to the left margin if scroll_viewport.rtl: startb = winb endb = 0 deltab = -deltab # i.e. Mongolian: To the next line is from the left margin to the right margin else: startb = 0 endb = winb # print(f'{starti} {deltai} {endi} {startb} {deltab} {endb}') # Find the bounds up_boundb = max(startb, endb) up_boundi = max(starti, endi) low_boundb = min(startb, endb) low_boundi = min(starti, endi) # In horizontal mode, X is the inline and Y is the block, # but it's reversed for vertical modes, so reverse the lookup. def at_point_vertical_mode(i, b): return at_point(b, i) at_point_conditional = at_point_vertical_mode if scroll_viewport.vertical_writing_mode else at_point def i_loop(curb): curi = starti # The value will be either heading toward the lower or the upper bound, # so just check for exceeding either bound while low_boundi <= curi <= up_boundi: cfi = at_point_conditional(curi, curb) if cfi: # print(f'found CFI at {curi}, {curb} {cfi}\n\t{starti} {deltai} {endi} {startb} {deltab} {endb}') return cfi curi += deltai curb = startb cfi = None while low_boundb <= curb <= up_boundb and not cfi: cfi = i_loop(curb) curb += deltab if cfi: return cfi # Use a spatial offset on the html element, since we could not find a # normal CFI x, y = scroll_viewport.x() + (0 if scroll_viewport.ltr else scroll_viewport.width()), scroll_viewport.y() de = document.documentElement rect = de.getBoundingClientRect() px = (x*100)/rect.width py = (y*100)/rect.height cfi = str.format("/2@{}:{}", fstr(px), fstr(py)) return cfi # }}} def cfi_for_selection(r): # {{{ if not r: r = window.getSelection().getRangeAt(0) def pos(container, offset): nt = container.nodeType if nt is Node.TEXT_NODE or nt is Node.CDATA_SECTION_NODE or nt is Node.COMMENT_NODE: return container, offset if nt is Node.ELEMENT_NODE and offset and container.childNodes.length > offset: return container.childNodes[offset], 0 return container, offset return { 'start': encode(r.startContainer.ownerDocument, *pos(r.startContainer, r.startOffset)), 'end': encode(r.endContainer.ownerDocument, *pos(r.endContainer, r.endOffset)), } # }}} def range_from_cfi(start, end): # {{{ start = decode(start) end = decode(end) if not start or start.error or not end or end.error: return r = document.createRange() r.setStart(start.node, start.offset) r.setEnd(end.node, end.offset) return r # }}}
35,311
Python
.py
848
33.353774
135
0.614571
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,519
word_actions.pyj
kovidgoyal_calibre/src/pyj/read_book/word_actions.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.globals import get_session_data from book_list.item_list import create_item, create_item_list from dom import clear, ensure_id from modals import error_dialog from read_book.globals import ui_operations from widgets import create_button def lookup(close_panel_func, url): close_panel_func() ui_operations.open_url(url) def toggle_custom_container(container_id, visible): container = document.getElementById(container_id) if container: c = container.lastChild list_container = c.previousSibling list_container.style.display = 'none' if visible else 'block' c.style.display = 'block' if visible else 'none' return c def add(container_id): container = document.getElementById(container_id) if not container: return c = container.lastChild name = c.querySelector('input[name="name"]').value url = c.querySelector('input[name="url"]').value if not name or not url: error_dialog(_('Required fields missing'), _( 'You must specify both a name and a URL.')) return sd = get_session_data() actions = sd.get('word_actions', v'[]') actions.push({'title': name, 'url': url}) sd.set('word_actions', actions) toggle_custom_container(container_id, False) populate_list(container) def add_custom(container_id): container = toggle_custom_container(container_id, True) if not container: return clear(container) container.appendChild(E.div(style="margin: 1rem", _('Enter the name and URL for a custom lookup source. The URL must contain ' ' {0} in it, which will be replaced by the word being looked up. For example: ' ' {1}').format('{word}', 'https://google.com/search?q={word}') )) do_add = add.bind(None, container_id) container.appendChild(E.form(E.button(style='display:none', onclick=do_add), E.table(style='margin: 1rem', E.tr(E.td(_('Name:') + '\xa0'), E.td(E.input(type='text', name='name'))), E.tr(E.td('\xa0'), E.td('\xa0')), E.tr(E.td(_('URL:') + '\xa0'), E.td(E.input(type='url', name='url'))), ))) container.append(E.div(style='margin: 1rem; display: flex', create_button(_('Add'), 'plus', add.bind(None, container_id), highlight=True), '\xa0', create_button(_('Cancel'), action=toggle_custom_container.bind(None, container_id, False)), )) container.querySelector('input').focus() def remove(container_id, num): container = document.getElementById(container_id) if not container: return sd = get_session_data() actions = sd.get('word_actions', v'[]') actions.splice(num, 1) sd.set('word_actions', actions) toggle_custom_container(container_id, False) populate_list(container) def remove_custom(container_id): container = toggle_custom_container(container_id, True) if not container: return clear(container) container.appendChild(E.div(style="margin: 1rem", _('Choose a custom lookup to remove'))) items = [create_item(_('Cancel (no removals)'), toggle_custom_container.bind(None, container_id, False))] sd = get_session_data() actions = sd.get('word_actions', v'[]') for i, item in enumerate(actions): items.push(create_item(item.title, remove.bind(None, container_id, i))) container.appendChild(E.div()) create_item_list(container.lastChild, items) def lookup_items(word, close_panel_func, container_id): eword = encodeURIComponent(word) items = [] def a(title, url): items.push(create_item(title, lookup.bind(word, close_panel_func, url.format(word=eword)))) custom_actions = get_session_data().get('word_actions', v'[]') has_custom = custom_actions and custom_actions.length if has_custom: for entry in custom_actions: if entry.title and entry.url: a(entry.title, entry.url) a(_('Google dictionary'), 'https://google.com/search?q=define:{word}') a(_('Wordnik'), 'https://www.wordnik.com/words/{word}') a(_('Search the internet'), 'https://google.com/search?q={word}') items.push(create_item(_('Add a custom lookup'), add_custom.bind(None, container_id))) if has_custom: items.push(create_item(_('Remove a custom lookup'), remove_custom.bind(None, container_id))) return items current_data = None def populate_list(container): word, close_panel_func = current_data list_container = container.lastChild.previousSibling clear(list_container) create_item_list(list_container, lookup_items(word, close_panel_func, ensure_id(container))) def create_word_actions_panel(container, word, close_panel_func): nonlocal current_data word = str.replace(word, '\u00ad', '') current_data = word, close_panel_func container.appendChild(E.div()) container.appendChild(E.div(style='display:none')) populate_list(container) def develop(container): container.appendChild(E.div()) create_word_actions_panel(container, 'develop', def():pass;)
5,283
Python
.py
118
39.20339
110
0.682172
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,520
read_aloud.pyj
kovidgoyal_calibre/src/pyj/read_book/read_aloud.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from book_list.theme import get_color from dom import clear, svgicon, unique_id from gettext import gettext as _ from read_book.globals import ui_operations from read_book.highlights import ICON_SIZE from read_book.selection_bar import BUTTON_MARGIN, get_margins, map_to_iframe_coords from read_book.shortcuts import shortcut_for_key_event HIDDEN = 0 WAITING_FOR_PLAY_TO_START = 1 PAUSED = 2 PLAYING = 3 STOPPED = 4 def is_flow_mode(): sd = get_session_data() mode = sd.get('read_mode') return mode is 'flow' class ReadAloud: dont_hide_on_content_loaded = True prevent_navigation = True def __init__(self, view): self.view = view self._state = HIDDEN self.bar_id = unique_id('bar') container = self.container container.setAttribute('tabindex', '0') container.style.overflow = 'hidden' container.style.justifyContent = 'flex-end' container.style.alignItems = 'flex-end' if is_flow_mode() else 'flex-start' container.appendChild(E.div( id=self.bar_id, style='border: solid 1px currentColor; border-radius: 5px;' 'display: flex; flex-direction: column; margin: 1rem;' )) container.appendChild(E.style( f'#{self.bar_id}.speaking '+'{ opacity: 0.5 }\n\n', f'#{self.bar_id}.speaking:hover '+'{ opacity: 1.0 }\n\n', )) container.addEventListener('keydown', self.on_keydown, {'passive': False}) container.addEventListener('click', self.container_clicked, {'passive': False}) container.addEventListener('contextmenu', self.toggle, {'passive': False}) @property def container(self): return document.getElementById('book-read-aloud-overlay') @property def supports_css_min_max(self): return True @property def bar(self): return document.getElementById(self.bar_id) @property def is_visible(self): return self.container.style.display is not 'none' @property def state(self): return self._state @state.setter def state(self, val): if val is not self._state: self._state = val self.build_bar() def hide(self): if self.state is not HIDDEN: ui_operations.tts('stop') self.state = HIDDEN self.container.style.display = 'none' self.view.focus_iframe() if ui_operations.read_aloud_state_changed: ui_operations.read_aloud_state_changed(False) def show(self): if self.state is HIDDEN: self.container.style.display = 'flex' self.state = STOPPED self.focus() if ui_operations.read_aloud_state_changed: ui_operations.read_aloud_state_changed(True) def focus(self): self.container.focus() def build_bar(self, annot_id): if self.state is HIDDEN: return self.container.style.alignItems = 'flex-end' if is_flow_mode() else 'flex-start' bar_container = self.bar if self.state is PLAYING: bar_container.classList.add('speaking') else: bar_container.classList.remove('speaking') clear(bar_container) bar_container.style.maxWidth = 'min(40rem, 80vw)' if self.supports_css_min_max else '40rem' bar_container.style.backgroundColor = get_color("window-background") for x in [ E.div(style='height: 4ex; display: flex; align-items: center; padding: 5px; justify-content: center'), E.hr(style='border-top: solid 1px; margin: 0; padding: 0; display: none'), E.div( style='display: none; padding: 5px; font-size: smaller', E.div() ) ]: bar_container.appendChild(x) bar = bar_container.firstChild def cb(name, icon, text): ans = svgicon(icon, ICON_SIZE, ICON_SIZE, text) if name: ans.addEventListener('click', def(ev): ev.stopPropagation(), ev.preventDefault() self[name](ev) self.view.focus_iframe() ) ans.classList.add('simple-link') ans.style.marginLeft = ans.style.marginRight = BUTTON_MARGIN return ans if self.state is PLAYING: bar.appendChild(cb('pause', 'pause', _('Pause reading'))) elif self.state is WAITING_FOR_PLAY_TO_START: bar.appendChild(cb(None, 'hourglass', _('Pause reading'))) else: bar.appendChild(cb('play', 'play', _('Start reading') if self.state is STOPPED else _('Resume reading'))) bar.appendChild(cb('slower', 'slower', _('Slow down speech'))) bar.appendChild(cb('faster', 'faster', _('Speed up speech'))) bar.appendChild(cb('configure', 'cogs', _('Configure Read aloud'))) bar.appendChild(cb('hide', 'off', _('Close Read aloud'))) if self.state is not WAITING_FOR_PLAY_TO_START: notes_container = bar_container.lastChild notes_container.style.display = notes_container.previousSibling.style.display = 'block' notes_container = notes_container.lastChild if self.state is STOPPED: notes_container.textContent = _('Tap/click on a word to start from there') elif self.state is PLAYING: notes_container.textContent = _('Tap/click on a word to skip to it') else: notes_container.textContent = _('Tap/click on a word to continue from there') def configure(self): self.pause() self.waiting_for_configure = True ui_operations.tts('configure') def slower(self): ui_operations.tts('slower') def faster(self): ui_operations.tts('faster') def play(self): if self.state is PAUSED: ui_operations.tts('resume_after_configure' if self.waiting_for_configure else 'resume') self.waiting_for_configure = False self.state = PLAYING elif self.state is STOPPED: self.send_message('play') self.state = WAITING_FOR_PLAY_TO_START def pause(self): if self.state is PLAYING: ui_operations.tts('pause') self.state = PAUSED def stop(self): if self.state is PLAYING or self.state is PAUSED: ui_operations.tts('stop') self.state = STOPPED def toggle(self): if self.state is PLAYING: self.pause() elif self.state is PAUSED or self.state is STOPPED: self.play() def container_clicked(self, ev): if ev.button is not 0: return ev.stopPropagation(), ev.preventDefault() margins = get_margins() pos = {'x': ev.clientX, 'y': ev.clientY} pos = map_to_iframe_coords(pos, margins) self.send_message('play', pos=pos) def on_keydown(self, ev): ev.stopPropagation(), ev.preventDefault() if ev.key is 'Escape': self.hide() return if ev.key is ' ' or ev.key is 'MediaPlayPause' or ev.key is 'PlayPause': self.toggle() return if ev.key is 'Play' or ev.key is 'MediaPlay': self.play() return if ev.key is 'Pause' or ev.key is 'MediaPause': self.pause() return if ev.key is 'MediaStop': self.stop() return sc_name = shortcut_for_key_event(ev, self.view.keyboard_shortcut_map) if not sc_name: return if sc_name is 'show_chrome': self.hide() elif sc_name is 'quit': self.hide() ui_operations.quit() def handle_tts_event(self, which, data): if which is 'mark': self.send_message('mark', num=data) elif which is 'begin': self.state = PLAYING elif which is 'pause': self.state = PAUSED elif which is 'resume': self.state = PLAYING elif which is 'end': self.state = STOPPED self.view.show_next_spine_item() elif which is 'configured': self.focus() if self.waiting_for_configure: self.play() if data is not None: pass def send_message(self, type, **kw): self.view.iframe_wrapper.send_message('tts', type=type, **kw) def handle_message(self, msg): if msg.type is 'text-extracted': if msg.pos: self.stop() ui_operations.tts('play', {'marked_text': msg.marked_text})
8,974
Python
.py
222
30.617117
117
0.598256
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,521
profiles.pyj
kovidgoyal_calibre/src/pyj/read_book/profiles.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from book_list.item_list import create_item, create_item_list, create_side_action from book_list.top_bar import create_top_bar from dom import clear, unique_id from gettext import gettext as _ from modals import question_dialog from read_book.globals import ui_operations from session import apply_reader_profile, settings_for_reader_profile from widgets import create_button def save_profile(container_id, hide_panel): container = document.getElementById(container_id) if not container: return name = container.querySelector('[name=profile_name]').value sd = get_session_data() settings = settings_for_reader_profile(sd) ui_operations.save_profile(name, settings, def(): container = document.getElementById(container_id) if container: r = container.querySelector('.saved_msg') if r: clear(r) r.appendChild(E.div(E.i(_('Saved: ') + name), style='margin-top: 1rem; margin-bottom: 1rem')) load_profiles(container_id) ) def use_profile(container_id, profile_name, profile_data): container = document.getElementById(container_id) if not container: return sd = get_session_data() apply_reader_profile(sd, profile_data) if ui_operations.apply_profile: ui_operations.apply_profile(profile_data) container.dispatchEvent(new Event('settings_changed')) container.dispatchEvent(new Event('close_panel')) def delete_profile(container_id, profile_name): question_dialog(_('Are you sure?'), _('Are you sure you want to delete the saved profile named: {}?').format(profile_name), def (ok): if ok: ui_operations.save_profile(profile_name, None, def(): load_profiles(container_id) ) ) def got_all_profiles(container_id, all_profiles): container = document.getElementById(container_id) if not container: return all_profiles['__default__'] = {} names = list_wrap(Object.keys(all_profiles)) names.pysort(def(x): return '' if x is '__default__' else x.toLowerCase();) pl = container.querySelector('.profiles_list_container') clear(pl) pl.appendChild(E.div( _('Load settings from one of the previously saved profiles below…') )) pl.appendChild(E.div()) items = [] for name in names: display_name = name if name is '__default__': display_name = _('Restore settings to default values') side_actions = [] else: side_actions = [create_side_action('trash', delete_profile.bind(None, container_id, name), _('Delete this profile'))] items.push(create_item(display_name, action=use_profile.bind(None, container_id, name, all_profiles[name]), side_actions=side_actions)) create_item_list(pl.lastChild, items) def load_profiles(container_id): container = document.getElementById(container_id) if not container: return pl = container.querySelector('.profiles_list_container') clear(pl) pl.appendChild(E.div(_('Loading saved profiles, please wait…'), style='padding-bottom: 1rem')) ui_operations.get_all_profiles(got_all_profiles.bind(None, container_id)) def create_profiles_panel(container, hide_panel, on_change): create_top_bar(container, title=_('Profiles'), icon='close', action=hide_panel) c = E.div(style='margin: 1rem', id=unique_id('placeholder-prefs')) c.addEventListener('close_panel', def(): hide_panel();, False) c.addEventListener('settings_changed', def(): on_change();, False) container_id = c.id a = E.div( style='display:flex', E.div( E.label(_('Save current settings as profile:') + ' '), E.input( name='profile_name', placeholder=_('Name of profile'), onkeydown=def(e): if e.key is 'Enter': save_profile(container_id, hide_panel) ), ), E.div('\xa0'), E.div( create_button(_('Save'), 'bookmark', save_profile.bind(None, container_id, hide_panel)) ) ) container.appendChild(c) c.appendChild(a) c.appendChild(E.div(class_='saved_msg')) c.appendChild(E.hr()) c.appendChild(E.div(class_='profiles_list_container')) load_profiles(container_id)
4,575
Python
.py
104
36.971154
143
0.66472
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,522
flow_mode.pyj
kovidgoyal_calibre/src/pyj/read_book/flow_mode.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals # Notes about flow mode scrolling: # All the math in flow mode is based on the block and inline directions. # Inline is "the direction lines of text go." # In horizontal scripts such as English and Hebrew, the inline is horizontal # and the block is vertical. # In vertical languages such as Japanese and Mongolian, the inline is vertical # and block is horizontal. # Regardless of language, flow mode scrolls in the block direction. # # In vertical RTL books, the block position scrolls from right to left. |<------| # This means that the viewport positions become negative as you scroll. # This is hidden from flow mode by the viewport, which transparently # negates any inline coordinates sent in to the viewport_to_document* functions # and the various scroll_to/scroll_by functions, as well as the reported X position. # # The result of all this is that flow mode's math can safely pretend that # things scroll in the positive block direction. from dom import set_css from range_utils import wrap_range, unwrap from read_book.cfi import scroll_to as cfi_scroll_to from read_book.globals import current_spine_item, get_boss, rtl_page_progression, ltr_page_progression from read_book.settings import opts from read_book.viewport import line_height, rem_size, scroll_viewport def flow_to_scroll_fraction(frac, on_initial_load): scroll_viewport.scroll_to_in_block_direction(scroll_viewport.document_block_size() * frac) small_scroll_events = v'[]' def clear_small_scrolls(): nonlocal small_scroll_events small_scroll_events = v'[]' def dispatch_small_scrolls(): if small_scroll_events.length: now = window.performance.now() if now - small_scroll_events[-1].time <= 2000: window.setTimeout(dispatch_small_scrolls, 100) return amt = 0 for x in small_scroll_events: amt += x.amt clear_small_scrolls() get_boss().report_human_scroll(amt / scroll_viewport.document_block_size()) def add_small_scroll(amt): small_scroll_events.push({'amt': amt, 'time': window.performance.now()}) window.setTimeout(dispatch_small_scrolls, 100) def report_human_scroll(amt): h = scroll_viewport.height() is_large_scroll = (abs(amt) / h) >= 0.5 if amt > 0: if is_large_scroll: clear_small_scrolls() get_boss().report_human_scroll(amt / scroll_viewport.document_block_size()) else: add_small_scroll(amt) elif amt is 0 or is_large_scroll: clear_small_scrolls() last_change_spine_item_request = {} def _check_for_scroll_end(func, obj, args, report): before = scroll_viewport.block_pos() should_flip_progression_direction = func.apply(obj, args) now = window.performance.now() scroll_animator.sync(now) if scroll_viewport.block_pos() is before: csi = current_spine_item() if last_change_spine_item_request.name is csi.name and now - last_change_spine_item_request.at < 2000: return False last_change_spine_item_request.name = csi.name last_change_spine_item_request.at = now go_to_previous_page = args[0] < 0 if (should_flip_progression_direction): go_to_previous_page = not go_to_previous_page get_boss().send_message('next_spine_item', previous=go_to_previous_page) return False if report: report_human_scroll(scroll_viewport.block_pos() - before) return True def check_for_scroll_end(func): return def (): return _check_for_scroll_end(func, this, arguments, False) def check_for_scroll_end_and_report(func): return def (): return _check_for_scroll_end(func, this, arguments, True) @check_for_scroll_end_and_report def scroll_by_and_check_next_page(y): scroll_viewport.scroll_by_in_block_direction(y) # This indicates to check_for_scroll_end_and_report that it should not # flip the page progression direction. return False def flow_onwheel(evt): di = db = 0 WheelEvent = window.WheelEvent # Y deltas always scroll in the previous and next page direction, # regardless of writing direction, since doing otherwise would # make mouse wheels mostly useless for scrolling in books written # vertically. if evt.deltaY: if evt.deltaMode is WheelEvent.DOM_DELTA_PIXEL: db = evt.deltaY elif evt.deltaMode is WheelEvent.DOM_DELTA_LINE: db = line_height() * evt.deltaY if evt.deltaMode is WheelEvent.DOM_DELTA_PAGE: db = (scroll_viewport.block_size() - 30) * evt.deltaY # X deltas scroll horizontally in both horizontal and vertical books. # It's more natural in both cases. if evt.deltaX: if evt.deltaMode is WheelEvent.DOM_DELTA_PIXEL: dx = evt.deltaX elif evt.deltaMode is WheelEvent.DOM_DELTA_LINE: dx = line_height() * evt.deltaX else: dx = (scroll_viewport.block_size() - 30) * evt.deltaX if scroll_viewport.horizontal_writing_mode: di = dx else: # Left goes forward, so make sure left is positive and right is negative, # which is the opposite of what the wheel sends. if scroll_viewport.rtl: db = -dx # Right goes forward, so the sign is correct. else: db = dx if Math.abs(di) >= 1: scroll_viewport.scroll_by_in_inline_direction(di) if Math.abs(db) >= 1: scroll_by_and_check_next_page(db) @check_for_scroll_end def goto_boundary(dir): position = 0 if dir is DIRECTION.Up else scroll_viewport.document_block_size() scroll_viewport.scroll_to_in_block_direction(position) get_boss().report_human_scroll() return False @check_for_scroll_end_and_report def scroll_by_page(direction, flip_if_rtl_page_progression): b = scroll_viewport.block_size() - 10 scroll_viewport.scroll_by_in_block_direction(b * direction) # Let check_for_scroll_end_and_report know whether or not it should flip # the progression direction. return flip_if_rtl_page_progression and rtl_page_progression() def scroll_to_extend_annotation(backward, horizontal, by_page): direction = -1 if backward else 1 h = line_height() if by_page: h = (window.innerWidth if horizontal else window.innerHeight) - h if horizontal: before = window.pageXOffset window.scrollBy(h * direction, 0) return window.pageXOffset is not before before = window.pageYOffset window.scrollBy(0, h * direction) return window.pageYOffset is not before def is_auto_scroll_active(): return scroll_animator.is_active() def start_autoscroll(): scroll_animator.start(DIRECTION.Down, True) def toggle_autoscroll(): if is_auto_scroll_active(): cancel_scroll() running = False else: start_autoscroll() running = True get_boss().send_message('autoscroll_state_changed', running=running) def handle_shortcut(sc_name, evt): if sc_name is 'down': scroll_animator.start(DIRECTION.Down, False) return True if sc_name is 'up': scroll_animator.start(DIRECTION.Up, False) return True if sc_name is 'start_of_file': goto_boundary(DIRECTION.Up) return True if sc_name is 'end_of_file': goto_boundary(DIRECTION.Down) return True if sc_name is 'left': scroll_by_and_check_next_page(-15 if ltr_page_progression() else 15, 0) return True if sc_name is 'right': scroll_by_and_check_next_page(15 if ltr_page_progression() else -15, 0) return True if sc_name is 'start_of_book': get_boss().send_message('goto_doc_boundary', start=True) return True if sc_name is 'end_of_book': get_boss().send_message('goto_doc_boundary', start=False) return True if sc_name is 'pageup': scroll_by_page(-1, False) return True if sc_name is 'pagedown': scroll_by_page(1, False) return True if sc_name is 'toggle_autoscroll': toggle_autoscroll() return True if sc_name.startsWith('scrollspeed_'): scroll_animator.sync() return False def layout(is_single_page): add_visibility_listener() line_height(True) rem_size(True) set_css(document.body, margin='0', border_width='0', padding='0') body_style = window.getComputedStyle(document.body) # scroll viewport needs to know if we're in vertical mode, # since that will cause scrolling to happen left and right scroll_viewport.initialize_on_layout(body_style) document.documentElement.style.overflow = 'visible' if scroll_viewport.vertical_writing_mode else 'hidden' def auto_scroll_resume(): scroll_animator.wait = False scroll_animator.sync() def add_visibility_listener(): if add_visibility_listener.done: return add_visibility_listener.done = True # Pause auto-scroll while minimized document.addEventListener("visibilitychange", def(): if (document.visibilityState is 'visible'): scroll_animator.sync() else: scroll_animator.pause() ) def cancel_scroll(): scroll_animator.stop() def is_scroll_end(pos): return not (0 <= pos <= scroll_viewport.document_block_size() - scroll_viewport.block_size()) DIRECTION = {'Up': -1, 'up': -1, 'Down': 1, 'down': 1, 'UP': -1, 'DOWN': 1} class ScrollAnimator: DURATION = 100 # milliseconds def __init__(self): self.animation_id = None self.auto = False self.auto_timer = None self.paused = False def is_running(self): return self.animation_id is not None or self.auto_timer is not None def is_active(self): return self.is_running() and (self.auto or self.auto_timer is not None) def start(self, direction, auto): cancel_drag_scroll() if self.wait: return now = window.performance.now() self.end_time = now + self.DURATION self.stop_auto_spine_transition() if not self.is_running() or direction is not self.direction or auto is not self.auto: if self.auto and not auto: self.pause() self.stop() self.auto = auto self.direction = direction self.start_time = now self.start_offset = scroll_viewport.block_pos() self.csi_idx = current_spine_item().index self.animation_id = window.requestAnimationFrame(self.auto_scroll if auto else self.smooth_scroll) def smooth_scroll(self, ts): duration = self.end_time - self.start_time if duration <= 0: self.animation_id = None return progress = max(0, min(1, (ts - self.start_time) / duration)) # max/min to account for jitter scroll_target = self.start_offset scroll_target += Math.trunc(self.direction * progress * duration * line_height() * opts.lines_per_sec_smooth) / 1000 scroll_viewport.scroll_to_in_block_direction(scroll_target) amt = scroll_viewport.block_pos() - self.start_offset if is_scroll_end(scroll_target) and (not opts.scroll_stop_boundaries or (abs(amt) < 3 and duration is self.DURATION)): # "Turn the page" if stop at boundaries option is false or # this is a new scroll action and we were already at the end self.animation_id = None self.wait = True report_human_scroll(amt) get_boss().send_message('next_spine_item', previous=self.direction is DIRECTION.Up) elif progress < 1: self.animation_id = window.requestAnimationFrame(self.smooth_scroll) elif self.paused: self.resume() else: self.animation_id = None report_human_scroll(amt) def auto_scroll(self, ts): elapsed = max(0, ts - self.start_time) # max to account for jitter scroll_target = self.start_offset scroll_target += Math.trunc(self.direction * elapsed * line_height() * opts.lines_per_sec_auto) / 1000 scroll_viewport.scroll_to_in_block_direction(scroll_target) scroll_finished = is_scroll_end(scroll_target) # report every second if elapsed >= 1000: self.sync(ts) if scroll_finished: self.pause() if opts.scroll_auto_boundary_delay >= 0: self.auto_timer = setTimeout(self.request_next_spine_item, opts.scroll_auto_boundary_delay * 1000) else: self.animation_id = window.requestAnimationFrame(self.auto_scroll) def request_next_spine_item(self): self.auto_timer = None get_boss().send_message('next_spine_item', previous=self.direction is DIRECTION.Up) def report(self): amt = scroll_viewport.block_pos() - self.start_offset if abs(amt) > 0 and self.csi_idx is current_spine_item().index: report_human_scroll(amt) def sync(self, ts): if self.auto: self.report() self.csi_idx = current_spine_item().index self.start_time = ts or window.performance.now() self.start_offset = scroll_viewport.block_pos() else: self.resume() def stop(self): self.auto = False if self.animation_id is not None: window.cancelAnimationFrame(self.animation_id) self.animation_id = None self.report() self.stop_auto_spine_transition() def stop_auto_spine_transition(self): if self.auto_timer is not None: clearTimeout(self.auto_timer) self.auto_timer = None self.paused = False def pause(self): if self.auto: self.paused = self.direction self.stop() else: self.paused = False # Resume auto-scroll def resume(self): if self.paused: self.start(self.paused, True) self.paused = False scroll_animator = ScrollAnimator() class FlickAnimator: SPEED_FACTOR = 0.04 DECEL_TIME_CONSTANT = 325 # milliseconds VELOCITY_HISTORY = 300 # milliseconds MIMUMUM_VELOCITY = 100 # pixels/sec def __init__(self): self.animation_id = None def cancel_current_drag_scroll(self): cancel_drag_scroll() def start(self, gesture): self.cancel_current_drag_scroll() self.vertical = gesture.axis is 'vertical' now = window.performance.now() points = times = None for i, t in enumerate(gesture.times): if now - t < self.VELOCITY_HISTORY: points, times = gesture.points[i:], gesture.times[i:] break if times and times.length > 1: elapsed = (times[-1] - times[0]) / 1000 if elapsed > 0 and points.length > 1: delta = points[0] - points[-1] velocity = delta / elapsed if abs(velocity) > self.MIMUMUM_VELOCITY: self.amplitude = self.SPEED_FACTOR * velocity self.start_time = now self.animation_id = window.requestAnimationFrame(self.auto_scroll) def auto_scroll(self, ts): if self.animation_id is None: return elapsed = window.performance.now() - self.start_time delta = self.amplitude * Math.exp(-elapsed / self.DECEL_TIME_CONSTANT) if abs(delta) >= 1: delta = Math.round(delta) if self.vertical: self.scroll_y(delta) else: self.scroll_x(delta) self.animation_id = window.requestAnimationFrame(self.auto_scroll) def scroll_y(self, delta): window.scrollBy(0, delta) def scroll_x(self, delta): window.scrollBy(delta, 0) def stop(self): if self.animation_id is not None: window.cancelAnimationFrame(self.animation_id) self.animation_id = None flick_animator = FlickAnimator() class DragScroller: DURATION = 100 # milliseconds def __init__(self): self.animation_id = None self.direction = 1 self.speed_factor = 1 self.start_time = self.end_time = 0 self.start_offset = 0 def is_running(self): return self.animation_id is not None def smooth_scroll(self, ts): duration = self.end_time - self.start_time if duration <= 0: self.animation_id = None self.start(self.direction, self.speed_factor) return progress = max(0, min(1, (ts - self.start_time) / duration)) # max/min to account for jitter scroll_target = self.start_offset scroll_target += Math.trunc(self.direction * progress * duration * line_height() * opts.lines_per_sec_smooth * self.speed_factor) / 1000 scroll_viewport.scroll_to_in_block_direction(scroll_target) if progress < 1: self.animation_id = window.requestAnimationFrame(self.smooth_scroll) else: self.animation_id = None self.start(self.direction, self.speed_factor) def start(self, direction, speed_factor): now = window.performance.now() self.end_time = now + self.DURATION if not self.is_running() or direction is not self.direction or speed_factor is not self.speed_factor: self.stop() self.direction = direction self.speed_factor = speed_factor self.start_time = now self.start_offset = scroll_viewport.block_pos() self.animation_id = window.requestAnimationFrame(self.smooth_scroll) def stop(self): if self.animation_id is not None: window.cancelAnimationFrame(self.animation_id) self.animation_id = None drag_scroller = DragScroller() def cancel_drag_scroll(): drag_scroller.stop() def start_drag_scroll(delta): limit = opts.margin_top if delta < 0 else opts.margin_bottom direction = 1 if delta >= 0 else -1 speed_factor = min(abs(delta), limit) / limit speed_factor *= (2 - speed_factor) # QuadOut Easing curve drag_scroller.start(direction, 2 * speed_factor) def handle_gesture(gesture): flick_animator.stop() if gesture.resolved_action is 'animated_scroll': flick_animator.start(gesture) elif gesture.resolved_action is 'pan': if gesture.points.length > 1 and not gesture.is_held: delta = gesture.points[-2] - gesture.points[-1] if Math.abs(delta) >= 1: if gesture.axis is 'vertical': # Vertical writing scrolls left and right, # so doing a vertical flick shouldn't change pages. if scroll_viewport.vertical_writing_mode: scroll_viewport.scroll_by(delta, 0) # However, it might change pages in horizontal writing else: scroll_by_and_check_next_page(delta) else: # A horizontal flick should check for new pages in # vertical modes, since they flow left and right. if scroll_viewport.vertical_writing_mode: scroll_by_and_check_next_page(delta) # In horizontal modes, just move by the delta. else: scroll_viewport.scroll_by(delta, 0) elif gesture.resolved_action is 'prev_page' or gesture.resolved_action is 'prev_screen': # should flip = False - previous is previous whether RTL or LTR. # flipping of this command is handled higher up scroll_by_page(-1, False) elif gesture.resolved_action is 'next_page' or gesture.resolved_action is 'next_screen': # should flip = False - next is next whether RTL or LTR. # flipping of this command is handled higher up scroll_by_page(1, False) anchor_funcs = { 'pos_for_elem': def pos_for_elem(elem): if not elem: return {'block': 0, 'inline': 0} br = elem.getBoundingClientRect() # Start of object in the scrolling direction return { 'block': scroll_viewport.viewport_to_document_block(scroll_viewport.rect_block_start(br), elem.ownerDocument), 'inline': scroll_viewport.viewport_to_document_inline(scroll_viewport.rect_inline_start(br), elem.ownerDocument) } , 'visibility': def visibility(pos): q = pos.block # Have to negate X if in RTL for the math to be correct, # as the value that the scroll viewport returns is negated if scroll_viewport.vertical_writing_mode and scroll_viewport.rtl: q = -q if q + 1 < scroll_viewport.block_pos(): # the + 1 is needed for visibility when top aligned, see: https://bugs.launchpad.net/calibre/+bug/1924890 return -1 if q <= scroll_viewport.block_pos() + scroll_viewport.block_size(): return 0 return 1 , 'cmp': def cmp(a, b): return (a.block - b.block) or (a.inline - b.inline) , 'get_bounding_client_rect': def(elem): return elem.getBoundingClientRect() , } def auto_scroll_action(action): if action is 'toggle': toggle_autoscroll() elif action is 'start': if not is_auto_scroll_active(): toggle_autoscroll() elif action is 'stop': if is_auto_scroll_active(): toggle_autoscroll() elif action is 'resume': auto_scroll_resume() return is_auto_scroll_active() def closest_preceding_element(p): while p and not p.scrollIntoView: p = p.previousSibling or p.parentNode return p def ensure_selection_visible(): s = window.getSelection() p = s.anchorNode if not p: return p = closest_preceding_element(p) if p?.scrollIntoView: p.scrollIntoView() r = s.getRangeAt(0) if not r: return rect = r.getBoundingClientRect() if not rect: return if rect.top < 0 or rect.top >= window.innerHeight or rect.left < 0 or rect.left >= window.innerWidth: wrapper = document.createElement('span') wrap_range(r, wrapper) wrapper.scrollIntoView() unwrap(wrapper) def ensure_selection_boundary_visible(use_end): sel = window.getSelection() try: rr = sel.getRangeAt(0) except: rr = None if rr: r = rr.getBoundingClientRect() if r: node = sel.focusNode if use_end else sel.anchorNode x = scroll_viewport.rect_inline_end(r) if use_end else scroll_viewport.rect_inline_start(r) if x < 0 or x >= window.innerWidth: x = scroll_viewport.viewport_to_document_inline(x, doc=node.ownerDocument) if use_end: x -= line_height() scroll_viewport.scroll_to_in_inline_direction(x, True) y = scroll_viewport.rect_block_end(r) if use_end else scroll_viewport.rect_block_start(r) if y < 0 or y >= window.innerHeight: y = scroll_viewport.viewport_to_document_block(y, doc=node.ownerDocument) if use_end: y -= line_height() scroll_viewport.scroll_to_in_block_direction(y, True) def jump_to_cfi(cfi): # Jump to the position indicated by the specified conformal fragment # indicator. cfi_scroll_to(cfi, def(x, y): # block is vertical if text is horizontal if scroll_viewport.horizontal_writing_mode: scroll_viewport.scroll_to_in_block_direction(y) # block is horizontal if text is vertical else: scroll_viewport.scroll_to_in_block_direction(x) )
24,094
Python
.py
562
34.357651
144
0.641951
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,523
annotations.pyj
kovidgoyal_calibre/src/pyj/read_book/annotations.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from gettext import gettext as _ from read_book.cfi import create_cfi_cmp, cfi_sort_key from read_book.globals import ui_operations no_cfi = '/99999999' def bookmark_get_cfi(b): if b.pos_type is 'epubcfi': return b.pos[8:-1] return no_cfi def highlight_get_cfi(hl): cfi = hl.start_cfi if cfi: si = f'/{hl.spine_index}' if hl.spine_index? else no_cfi return si + cfi return no_cfi def sort_annot_list(annots, get_cfi_func): key_map = {no_cfi: cfi_sort_key(no_cfi)} for annot in annots: cfi = get_cfi_func(annot) if cfi and not key_map[cfi]: key_map[cfi] = cfi_sort_key(cfi) cfi_cmp = create_cfi_cmp(key_map) annots.sort(def (a, b): acfi = get_cfi_func(a) bcfi = get_cfi_func(b) return cfi_cmp(acfi, bcfi) ) def annots_descending_cmp(a, b): return -1 if a.timestamp > b.timestamp else (1 if a.timestamp < b.timestamp else 0) def merge_annots_with_identical_field(annots_a, annots_b, field, cfi_getter_func): title_groups = {} changed = False all_annots = annots_a.concat(annots_b) for a in all_annots: q = title_groups[a[field]] if not q: q = title_groups[a[field]] = v'[]' q.push(a) for tg in Object.values(title_groups): tg.sort(annots_descending_cmp) seen = {} ans = v'[]' for a in all_annots: title = a[field] if not seen[title]: seen[title] = True candidates = title_groups[title] if not changed and candidates.length > 1 and candidates[0].timestamp is not candidates[1].timestamp: changed = True ans.push(title_groups[title][0]) if ans.length is not annots_a.length or ans.length is not annots_b.length: changed = True if changed: sort_annot_list(ans, cfi_getter_func) return changed, ans field_map = {'bookmark': 'title', 'highlight': 'uuid'} getter_map = {'bookmark': bookmark_get_cfi, 'highlight': highlight_get_cfi} def merge_annot_lists(a, b, field): key_field = field_map[field] return merge_annots_with_identical_field(a, b, key_field, getter_map[field]) def merge_annotation_maps(a, b): # If you make changes to this algorithm also update the # implementation in calibre.db.annotations updated = False ans = {} for field in field_map: a_items = a[field] or v'[]' b_items = b[field] or v'[]' if not a_items.length: ans[field] = b_items updated = True continue if not b_items.length: ans[field] = a_items continue changed, ans[field] = merge_annot_lists(a_items, b_items, field) if changed: updated = True return updated, ans class AnnotationsManager: # {{{ def __init__(self, view): self.view = view self.set_highlights() self.set_bookmarks() def sync_annots_to_server(self, which): if ui_operations.annots_changed: amap = {} if not which or which is 'bookmarks': amap.bookmark = self.bookmarks.as_array() if not which or which is 'highlights': amap.highlight = Object.values(self.highlights) ui_operations.annots_changed(amap) def set_bookmarks(self, bookmarks): bookmarks = bookmarks or v'[]' self.bookmarks = list(bookmarks) def all_bookmarks(self): return self.bookmarks def add_bookmark(self, title, cfi): if not title or not cfi: return self.bookmarks = [b for b in self.bookmarks if b.title is not title] self.bookmarks.push({ 'type': 'bookmark', 'timestamp': Date().toISOString(), 'pos_type': 'epubcfi', 'pos': cfi, 'title': title, }) sort_annot_list(self.bookmarks, bookmark_get_cfi) self.sync_annots_to_server('bookmarks') def remove_bookmark(self, title): changed = False for b in self.bookmarks: if b.title is title: b.removed = True b.timestamp = Date().toISOString() changed = True if changed: self.sync_annots_to_server('bookmarks') return changed def edit_bookmark(self, title, new_title): changed = False for b in self.bookmarks: if b.title is title: b.title = new_title b.timestamp = Date().toISOString() changed = True if changed: self.sync_annots_to_server('bookmarks') return changed def default_bookmark_title(self, base_default_title): all_titles = {bm.title:True for bm in self.bookmarks if not bm.removed} base_default_title = base_default_title or _('Bookmark') c = 0 while True: c += 1 default_title = f'{base_default_title} #{c}' if not all_titles[default_title]: return default_title def set_highlights(self, highlights): highlights = highlights or v'[]' self.highlights = {h.uuid: h for h in highlights} def all_highlights(self): ans = [h for h in Object.values(self.highlights) if not h.removed].as_array() sort_annot_list(ans, highlight_get_cfi) return ans def merge_highlights(self, highlights): highlights = highlights or v'[]' updated = False if highlights.length: base = {'highlight': Object.values(self.highlights)} newvals = {'highlight': highlights} updated, ans = merge_annotation_maps(base, newvals) if updated: self.set_highlights(ans.highlight) return updated def remove_highlight(self, uuid): h = self.highlights[uuid] if h: h.timestamp = Date().toISOString() h.removed = True v'delete h.style' v'delete h.highlighted_text' v'delete h.start_cfi' v'delete h.end_cfi' v'delete h.notes' v'delete h.spine_name' v'delete h.spine_index' v'delete h.toc_family_titles' return True def delete_highlight(self, uuid): if self.remove_highlight(uuid): self.sync_annots_to_server('highlights') def notes_for_highlight(self, uuid): h = self.highlights[uuid] if uuid else None if h: return h.notes def text_for_highlight(self, uuid): h = self.highlights[uuid] if uuid else None if h: return h.highlighted_text def set_notes_for_highlight(self, uuid, notes): h = self.highlights[uuid] if h: if notes: h.notes = notes else: v'delete h.notes' self.sync_annots_to_server('highlights') return True return False def style_for_highlight(self, uuid): h = self.highlights[uuid] if h: return h.style def data_for_highlight(self, uuid): return self.highlights[uuid] def spine_index_for_highlight(self, uuid, spine): h = self.highlights[uuid] if not h: return -1 ans = h.spine_index name = h.spine_name if name: idx = spine.indexOf(name) if idx > -1: ans = idx return ans def cfi_for_highlight(self, uuid, spine_index): h = self.highlights[uuid] if h: x = 2 * (spine_index + 1) return f'epubcfi(/{x}{h.start_cfi})' def add_highlight(self, msg, style, notes, toc_family): now = Date().toISOString() for uuid in msg.removed_highlights: self.remove_highlight(uuid) annot = self.highlights[msg.uuid] = { 'type': 'highlight', 'timestamp': now, 'uuid': msg.uuid, 'highlighted_text': msg.highlighted_text, 'start_cfi': msg.bounds.start, 'end_cfi': msg.bounds.end, 'style': style, # dict with color and background-color 'spine_name': self.view.currently_showing.name, 'spine_index': self.view.currently_showing.spine_index, } if notes: annot.notes = notes if toc_family?.length: toc_family_titles = v'[]' for x in toc_family: if x.title: toc_family_titles.push(x.title) annot.toc_family_titles = toc_family_titles self.sync_annots_to_server('highlights') def highlights_for_currently_showing(self): name = self.view.currently_showing.name ans = v'[]' for h in Object.values(self.highlights): if h.spine_name is name and not h.removed and h.start_cfi: ans.push(h) return ans # }}}
9,149
Python
.py
247
27.546559
112
0.583107
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,524
search_worker.pyj
kovidgoyal_calibre/src/pyj/read_book/search_worker.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from read_book.db import DB from read_book.resources import text_from_serialized_html from traceback import format_exception GET_SPINE_FAILED = 1 CONNECT_FAILED = 2 UNHANDLED_ERROR = 3 DB_ERROR = 4 _RE_ESCAPE = /[-\/\\^$*+?.()|[\]{}]/g quote_map = {'"': '"“”', "'": "'‘’"} qpat = /(['"])/g spat = /(\s+)/g invisible_chars = '(?:[\u00ad\u200c\u200d]{0,1})' def escape(string): return string.replace(_RE_ESCAPE, '\\$&') def split_string(pat, string): pat.lastIndex = 0 return string.split(pat) def text_to_regex(text): if text and not text.strip(): return r'\s+' has_leading = text.lstrip() is not text has_trailing = text.rstrip() is not text ans = v'["\s+"]' if has_leading else v'[]' for wpart in split_string(spat, text.strip()): if not wpart.strip(): ans.push(r'\s+') else: for part in split_string(qpat, wpart): r = quote_map[part] if r: ans.push('[' + r + ']') else: chars = v'[]' for ch in part: chars.push(escape(ch)) chars.join(invisible_chars) ans.push(part) if has_trailing: ans.push(r'\s+') return ans.join('') class ToCOffsetMap: def __init__(self, toc_nodes, offset_map, previous_toc_node, parent_map): self.toc_nodes = toc_nodes or v'[]' self.offset_map = offset_map or {} self.previous_toc_node = previous_toc_node or None self.parent_map = parent_map or {} def toc_nodes_for_offset(self, offset): matches = v'[]' for node in self.toc_nodes: q = self.offset_map[node.id] if q?: if q > offset: break matches.push(node) if not matches and self.previous_toc_node: matches.push(self.previous_toc_node) ans = v'[]' if matches.length: ancestors = v'[]' node = matches[-1] parent = self.parent_map[node.id] while parent?: ancestors.push(parent) parent = self.parent_map[parent.id] if ancestors.length > 1: # last item in ancestors is the root node for v'var i = ancestors.length - 1; i-- > 0;': ans.push(ancestors[i].id) ans.push(node.id) return ans def toc_offset_map_for_name(name): if wc.toc_offset_map_cache[name]: return wc.toc_offset_map_cache[name] anchor_map = wc.text_cache[name][1] toc_data = wc.current_book.toc_data idx = toc_data.spine_idx_map[name] toc_nodes = toc_data.spine_toc_map[name] if not idx? or idx < 0: wc.toc_offset_map_cache[name] = ToCOffsetMap() return wc.toc_offset_map_cache[name] offset_map = {} for node in toc_nodes: node_id = node.id if node_id?: aid = node.frag offset = anchor_map[aid] or 0 offset_map[node_id] = offset prev_toc_node = None for v'var i = idx; i-- > 0;': spine_name = wc.current_book.spine[i] ptn = toc_data.spine_toc_map[spine_name] if ptn?: prev_toc_node = ptn[-1] break wc.toc_offset_map_cache[name] = ToCOffsetMap(toc_nodes, offset_map, prev_toc_node, toc_data.parent_map) return wc.toc_offset_map_cache[name] def toc_nodes_for_search_result(sr): sidx = sr.spine_idx name = wc.current_book.spine[sidx] if not name: return v'[]' tmap = toc_offset_map_for_name(name) return tmap.toc_nodes_for_offset(sr.offset) class Worker: def __init__(self): self.db = None self.connected_to_db = False self.pending_search = None self.searching = False self.current_query = None self.current_query_id = None self.current_book = None self.regex = None self.result_num = 0 self.clear_caches() @property def initialize_error_msg(self): return self.db?.initialize_error_msg def clear_caches(self): self.text_cache = {} self.toc_offset_map_cache = {} wc = Worker() def send_search_complete(): self.postMessage({'type': 'search_complete', 'id': wc.current_query_id}) wc.current_query = wc.current_query_id = None def search_in_text_of(name): ctx_size = 75 r = wc.regex r.lastIndex = 0 haystack = wc.text_cache[name][0] or '' match_counts = {} spine_idx = wc.current_book.spine.indexOf(name) while True: m = r.exec(haystack) if not m: break text = m[0] start, end = m.index, r.lastIndex before = haystack[Math.max(0, start - ctx_size):start] after = haystack[end:end+ctx_size] q = (before or '')[-15:] + text + (after or '')[:15] match_counts[q] = match_counts[q] or 0 wc.result_num += 1 result = { 'file_name': name, 'spine_idx': spine_idx, 'index': match_counts[q], 'offset': start, 'text': text, 'before': before, 'after': after, 'mode': wc.current_query.query.mode, 'q': q, 'result_num': wc.result_num, 'on_discovery': wc.current_query_id, } result.toc_nodes = toc_nodes_for_search_result(result) self.postMessage({'type': 'search_result', 'id': wc.current_query_id, 'result': result}) if wc.current_query.query.only_first_match: break match_counts[q] += 1 def queue_next_spine_item(spine_idx, allow_current_name): spine_idx = spine_idx % wc.current_book.spine.length name = wc.current_book.spine[spine_idx] if wc.current_query.query.only_first_match and wc.result_num > 0: send_search_complete() return if not name or (not allow_current_name and name is wc.current_query.current_name): send_search_complete() return if wc.text_cache[name]: search_in_text_of(name) setTimeout(queue_next_spine_item.bind(None, spine_idx + 1), 0) return query = wc.current_query wc.db.get_book_file(wc.current_book.book_hash, wc.current_book.stored_files, name, got_spine_item.bind(None, query.id, spine_idx)) def got_spine_item(query_id, spine_idx, result): if query_id is not wc.current_query_id: return if result.ok: name = wc.current_book.spine[spine_idx] wc.text_cache[name] = text_from_serialized_html(result.result, True) search_in_text_of(name) setTimeout(queue_next_spine_item.bind(None, spine_idx + 1), 0) else: if result.details is 'ENOENT': queue_next_spine_item(spine_idx + 1) else: send_error(GET_SPINE_FAILED, result.details) wc.current_query = wc.current_query_id = None def regex_for_query(query): expr = query.text flags = 'umg' if not query.case_sensitive: flags += 'i' if query.mode is not 'regex': if query.mode is 'word': words = v'[]' for part in expr.split(' '): words.push(r'\b' + text_to_regex(part) + r'\b') expr = words.join(r'\s+') else: expr = text_to_regex(expr) return new RegExp(expr, flags) def perform_search(query): wc.current_query = query wc.current_query_id = query.id wc.result_num = 0 if not wc.current_book or not wc.current_book.spine?.length or not query.query.text: send_search_complete() return wc.regex = regex_for_query(query.query) idx = wc.current_book.spine.indexOf(query.current_name) if idx < 0: idx = 0 queue_next_spine_item(idx, True) def worker_connection_done(): wc.connected_to_db = True if not wc.initialize_error_msg: if wc.pending_search: s = wc.pending_search wc.pending_search = None perform_search(s) def send_error(code, msg, error): self.postMessage({'type': 'error', 'code': code, 'msg': msg, 'id': wc.current_query_id, 'error': error}) def on_worker_db_error(title, msg, details): send_error(DB_ERROR, msg, {'title': title, 'msg': msg, 'details': details}) def worker_main(): wc.db = DB(worker_connection_done, on_worker_db_error) self.onmessage = def(e): if e.data.type is 'search': wc.current_query_id = e.data.id if wc.connected_to_db: if wc.initialize_error_msg: send_error(CONNECT_FAILED, wc.initialize_error_msg) else: perform_search(e.data) else: wc.pending_search = e.data elif e.data.type is 'clear_caches': wc.clear_caches() wc.current_book = e.data.book self.addEventListener('error', def (e): send_error(UNHANDLED_ERROR, f'{e.lineno}:{e.message}' + '\n\n' + format_exception(e.error).join('')) )
9,143
Python
.py
240
29.6375
134
0.588089
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,525
footnotes.pyj
kovidgoyal_calibre/src/pyj/read_book/footnotes.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from dom import clear from iframe_comm import IframeClient from read_book.globals import runtime, current_spine_item, set_current_spine_item from read_book.resources import finalize_resources, unserialize_html from read_book.settings import ( apply_settings, set_color_scheme_class, update_settings ) block_names = dict.fromkeys(v"['p', 'div', 'li', 'td', 'h1', 'h2', 'h2', 'h3', 'h4', 'h5', 'h6', 'body']", True).as_object() block_display_styles = dict.fromkeys(v"['block', 'list-item', 'table-cell', 'table']", True).as_object() def elem_roles(elem): return {k.toLowerCase(): True for k in (elem.getAttribute('role') or '').split(' ')} def epub_type(elem): for a in elem.attributes: if a.nodeName.toLowerCase() == 'epub:type' and a.nodeValue: return a.nodeValue def get_containing_block(node): while node and node.tagName and block_names[node.tagName.toLowerCase()] is not True: node = node.parentNode return node def is_footnote_link(a, dest_name, dest_frag, src_name, link_to_map): roles = elem_roles(a) if roles['doc-noteref'] or roles['doc-biblioref'] or roles['doc-glossref']: return True if roles['doc-link']: return False if epub_type(a) is 'noteref': return True # Check if node or any of its first few parents have vertical-align set x, num = a, 3 while x and num > 0: style = window.getComputedStyle(x) if not is_footnote_link.inline_displays[style.display]: break if is_footnote_link.vert_aligns[style.verticalAlign]: return True x = x.parentNode num -= 1 # Check if node has a single child with the appropriate css children = [x for x in a.childNodes if x.nodeType is Node.ELEMENT_NODE] if children.length == 1: style = window.getComputedStyle(children[0]) if is_footnote_link.inline_displays[style.display] and is_footnote_link.vert_aligns[style.verticalAlign]: text_children = [x for x in a.childNodes if x.nodeType is Node.TEXT_NODE and x.nodeValue and /\S+/.test(x.nodeValue)] if not text_children.length: return True eid = a.getAttribute('id') or a.getAttribute('name') files_linking_to_self = link_to_map[src_name] if eid and files_linking_to_self: files_linking_to_anchor = files_linking_to_self[eid] or v'[]' if files_linking_to_anchor.length > 1 or (files_linking_to_anchor.length == 1 and files_linking_to_anchor[0] is not src_name): # An <a href="..." id="..."> link that is linked back from some other # file in the spine, most likely an endnote. We exclude links that are # the only content of their parent block tag, as these are not likely # to be endnotes. cb = get_containing_block(a) if not cb or cb.tagName.toLowerCase() == 'body': return False ltext = a.textContent if not ltext: return False ctext = cb.textContent if not ctext: return False if ctext.strip() is ltext.strip(): return False return True return False is_footnote_link.inline_displays = {'inline': True, 'inline-block': True} is_footnote_link.vert_aligns = {'sub': True, 'super': True, 'top': True, 'bottom': True} def is_epub_footnote(node): et = epub_type(node) if et: et = et.toLowerCase() if et is 'note' or et is 'footnote' or et is 'rearnote': return True roles = elem_roles(node) if roles['doc-note'] or roles['doc-footnote'] or roles['doc-rearnote']: return True return False def get_note_container(node): while node and block_names[node.tagName.toLowerCase()] is not True and block_display_styles[window.getComputedStyle(node).display] is not True: node = node.parentNode return node def get_parents_and_self(node): ans = v'[]' while node and node is not document.body: ans.push(node) node = node.parentNode return ans def get_page_break(node): style = window.getComputedStyle(node) return { 'before': get_page_break.on[style.getPropertyValue('page-break-before')] is True, 'after': get_page_break.on[style.getPropertyValue('page-break-after')] is True, } get_page_break.on = {'always': True, 'left': True, 'right': True} def hide_children(node): for child in node.childNodes: if child.nodeType is Node.ELEMENT_NODE: if child.do_not_hide: hide_children(child) v'delete child.do_not_hide' else: child.style.display = 'none' def unhide_tree(elem): elem.do_not_hide = True for c in elem.getElementsByTagName('*'): c.do_not_hide = True ok_list_types = {'disc': True, 'circle': True, 'square': True} def is_new_footnote_start(elem, start_elem): c = get_note_container(elem) return c is not start_elem and c is not start_elem.firstElementChild def show_footnote(target, known_anchors): if not target: return start_elem = document.getElementById(target) if not start_elem: return start_elem = get_note_container(start_elem) for elem in get_parents_and_self(start_elem): elem.do_not_hide = True style = window.getComputedStyle(elem) if style.display is 'list-item' and ok_list_types[style.listStyleType] is not True: # We cannot display list numbers since they will be # incorrect as we are removing siblings of this element. elem.style.listStyleType = 'none' if is_epub_footnote(start_elem): unhide_tree(start_elem) else: # Try to detect natural boundaries based on markup for this note found_note_start = False for elem in document.documentElement.getElementsByTagName('*'): if found_note_start: eid = elem.getAttribute('id') if eid is not target and known_anchors[eid] and is_new_footnote_start(elem, start_elem): # console.log('Breaking footnote on anchor: ' + elem.getAttribute('id')) v'delete get_note_container(elem).do_not_hide' break pb = get_page_break(elem) if pb.before: # console.log('Breaking footnote on page break before') break if pb.after: unhide_tree(elem) # console.log('Breaking footnote on page break after') break elem.do_not_hide = True else if elem is start_elem: found_note_start = True hide_children(document.body) window.location.hash = '#' + target class PopupIframeBoss: def __init__(self): handlers = { 'initialize': self.initialize, 'clear': self.on_clear, 'display': self.display, } self.comm = IframeClient(handlers, 'popup-iframe') self.blob_url_map = {} self.name = None self.frag = None self.link_attr = None def initialize(self, data): window.addEventListener('error', self.on_error) def on_error(self, evt): msg = evt.message script_url = evt.filename line_number = evt.lineno column_number = evt.colno error_object = evt.error evt.stopPropagation(), evt.preventDefault() if error_object is None: # This happens for cross-domain errors (probably javascript injected # into the browser via extensions/ userscripts and the like). It also # happens all the time when using Chrome on Safari console.log(f'Unhandled error from external javascript, ignoring: {msg} {script_url} {line_number}:{column_number}') else: console.log(error_object) def display(self, data): self.book = data.book self.name = data.name self.frag = data.frag self.link_attr = 'data-' + self.book.manifest.link_uid spine = self.book.manifest.spine index = spine.indexOf(data.name) set_current_spine_item({ 'name':data.name, 'is_first':index is 0, 'is_last':index is spine.length - 1, 'index': index, 'initial_position':data.initial_position }) update_settings(data.settings) for name in self.blob_url_map: window.URL.revokeObjectURL(self.blob_url_map[name]) document.body.style.removeProperty('font-family') root_data, self.mathjax, self.blob_url_map = finalize_resources(self.book, data.name, data.resource_data) self.resource_urls = unserialize_html(root_data, self.content_loaded, self.show_only_footnote, data.name) def connect_links(self): for a in document.body.querySelectorAll(f'a[{self.link_attr}]'): a.addEventListener('click', self.link_activated) if runtime.is_standalone_viewer: # links with a target get turned into requests to open a new window by Qt for a in document.body.querySelectorAll('a[target]'): a.removeAttribute('target') def link_activated(self, evt): try: data = JSON.parse(evt.currentTarget.getAttribute(self.link_attr)) except: print('WARNING: Failed to parse link data {}, ignoring'.format(evt.currentTarget?.getAttribute?(self.link_attr))) return self.activate_link(data.name, data.frag, evt.currentTarget) def activate_link(self, name, frag, target_elem): if not name: name = current_spine_item().name try: is_popup = is_footnote_link(target_elem, name, frag, current_spine_item().name, self.book.manifest.link_to_map or {}) title = target_elem.textContent except: import traceback traceback.print_exc() is_popup = False title = '' self.comm.send_message('link_activated', is_popup=is_popup, name=name, frag=frag, title=title) def on_clear(self, data): clear(document.head) clear(document.body) document.body.textContent = data.text self.name = None self.frag = None def show_only_footnote(self): known_anchors = {} ltm = self.book.manifest.link_to_map?[self.name] if ltm: known_anchors = {k:True for k in Object.keys(ltm)} show_footnote(self.frag, known_anchors) def content_loaded(self): if not self.comm.encrypted_communications: window.setTimeout(self.content_loaded, 2) return self.connect_links() # this is the loading styles used to suppress scrollbars during load # added in unserialize_html document.head.removeChild(document.head.firstChild) document.body.classList.add('calibre-footnote-container') set_color_scheme_class() apply_settings(True) self.comm.send_message('content_loaded', height=document.documentElement.scrollHeight + 25) def main(): main.boss = PopupIframeBoss()
11,442
Python
.py
254
35.92126
147
0.631867
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,526
content_popup.pyj
kovidgoyal_calibre/src/pyj/read_book/content_popup.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from dom import add_extra_css, build_rule, clear, svgicon from iframe_comm import create_wrapped_iframe from read_book.globals import runtime, ui_operations, is_dark_theme from read_book.resources import load_resources CLASS_NAME = 'book-content-popup-container' TOP_LEVEL_DISPLAY = 'flex' add_extra_css(def(): sel = '.' + CLASS_NAME style = '' style += build_rule(sel, justify_content='center', align_items='center', height='100%') sel += ' > div' style += build_rule(sel, border_radius='8px', border='solid currentColor 2px', margin='1rem', padding='0.5rem', box_shadow='2px 2px 4px currentColor') sel += ' > div' style += build_rule(sel, display='flex', justify_content='space-between', align_items='center') sel += ' > div' # button container style += build_rule(sel, display='flex', justify_content='space-between', align_items='center') sel += ' > a' # buttons style += build_rule(sel, margin_left='1ex', cursor='pointer', display='inline-block') style += build_rule(sel + ':hover', transform='scale(1.5)') style += build_rule(sel + ':active', transform='scale(2)') return style ) class ContentPopupOverlay: def __init__(self, view): self.view = view self.loaded_resources = {} c = self.container c.classList.add(CLASS_NAME) c.appendChild(E.div(E.div())) c.addEventListener('click', self.hide) c.firstChild.addEventListener('click', def(ev): ev.stopPropagation(), ev.preventDefault() ) self.pending_load = None def reset(self): if self.iframe_wrapper: self.iframe_wrapper.reset() def create_iframe(self): handlers = { 'ready': self.on_iframe_ready, 'error': self.view.on_iframe_error, 'content_loaded': self.on_content_loaded, 'print': self.on_print, 'link_activated': self.on_link_activated, } iframe_kw = { 'seamless': True, 'sandbox': 'allow-scripts', 'style': 'width: 100%; max-height: 70vh' } if runtime.is_standalone_viewer: entry_point = f'{runtime.FAKE_PROTOCOL}://{runtime.SANDBOX_HOST}/book/__popup__' else: entry_point = 'read_book.footnotes' iframe, self.iframe_wrapper = create_wrapped_iframe( handlers, _('Loading data, please wait...'), entry_point, iframe_kw ) iframe.style.colorScheme = 'dark' if is_dark_theme() else 'light' c = self.container c.firstChild.appendChild(iframe) def on_print(self, data): print(data.string) def on_link_activated(self, data): self.view.link_in_content_popup_activated(data.name, data.frag, data.is_popup, data.title) @property def container(self): return document.getElementById('book-content-popup-overlay') @property def iframe(self): return self.iframe_wrapper.iframe @property def is_visible(self): return self.container.style.display is not 'none' def hide(self): self.container.style.display = 'none' ui_operations.focus_iframe() def show(self): c = self.container c.style.display = TOP_LEVEL_DISPLAY def on_iframe_ready(self, msg): return self.do_pending_load() def apply_color_scheme(self, bg, fg): c = self.container.firstChild c.style.backgroundColor = bg c.style.color = fg try: self.iframe.style.colorScheme = 'dark' if is_dark_theme() else 'light' except: pass def create_footnote_header(self, header): clear(header) header.appendChild( E.h3(self.current_footnote_data.title or _('Footnote')), ) bc = E.div( E.a(svgicon('arrow-right'), title=_('Go to this footnote in the main view'), href='javascript:void(0)'), E.a(svgicon('close'), title=_('Close the footnotes window'), href='javascript:void(0)') ) bc.firstChild.addEventListener('click', def(): self.hide() self.view.goto_named_destination(self.current_footnote_data.name, self.current_footnote_data.frag) ) bc.lastChild.addEventListener('click', self.hide) header.appendChild(bc) def load_doc(self, name, done_callback): def cb(resource_data): self.loaded_resources = resource_data done_callback(resource_data) load_resources(self.view.book, name, self.loaded_resources, cb) def show_footnote(self, data): if not self.iframe_wrapper: self.create_iframe() self.current_footnote_data = data c = self.container.firstChild header = c.firstChild s = header.style s.paddingLeft = s.paddingRight = s.paddingBottom = s.paddingTop = '0' s.marginLeft = s.marginRight = s.marginBottom = s.marginTop = '0' s.borderBottom = s.borderTop = s.borderLeft = s.borderRight = 'solid currentColor 0' bs = 'solid currentColor 2px' if self.current_footnote_data.vertical_writing_mode: c.style.width = str(50 // data.cols_per_screen) + 'vw' self.iframe.style.height = '80vh' c.style.writingMode = 'vertical-rl' if self.current_footnote_data.rtl else 'vertical-lr' if self.current_footnote_data.rtl: s.paddingLeft = s.marginLeft = '1ex' s.borderLeft = bs else: s.paddingRight = s.marginRight = '1ex' s.borderRight = bs else: c.style.width = str(100 // data.cols_per_screen) + 'vw' self.iframe.style.height = '12ex' c.style.writingMode = 'horizontal-rl' if self.current_footnote_data.rtl else 'horizontal-lr' s.paddingBottom = s.marginBottom = '1ex' s.borderBottom = bs self.create_footnote_header(header) self.load_doc(data.name, self.show_footnote_item) self.iframe_wrapper.send_message('clear', text=_('Loading note, please wait...')) def show_footnote_item(self, resource_data): self.pending_load = resource_data, self.show_footnote_item_stage2 if self.iframe_wrapper.ready: self.do_pending_load() else: self.iframe_wrapper.init() def do_pending_load(self): if self.pending_load: data, func = self.pending_load self.pending_load = None func(data) def show_footnote_item_stage2(self, resource_data): self.iframe_wrapper.send_unencrypted_message('display', resource_data=resource_data, book=self.view.book, name=self.current_footnote_data.name, frag=self.current_footnote_data.frag, settings=self.view.currently_showing.settings) def on_content_loaded(self, data): self.iframe.style.height = f'{data.height}px'
7,159
Python
.py
159
36.245283
154
0.63176
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,527
settings.pyj
kovidgoyal_calibre/src/pyj/read_book/settings.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from elementmaker import E from read_book.globals import dark_link_color, runtime from session import session_defaults opts = {} def update_settings(settings): settings = Object.assign({}, session_defaults(), settings) opts.base_font_size = max(8, min(settings.base_font_size, 64)) opts.bg_image_fade = settings.bg_image_fade or 'transparent' opts.color_scheme = settings.color_scheme opts.columns_per_screen = settings.columns_per_screen opts.cover_preserve_aspect_ratio = v'!!settings.cover_preserve_aspect_ratio' opts.hide_tooltips = settings.hide_tooltips opts.is_dark_theme = v'!!settings.is_dark_theme' opts.lines_per_sec_auto = settings.lines_per_sec_auto opts.lines_per_sec_smooth = settings.lines_per_sec_smooth opts.margin_left = max(0, settings.margin_left) opts.margin_right = max(0, settings.margin_right) opts.margin_top = max(0, settings.margin_top) opts.margin_bottom = max(0, settings.margin_bottom) opts.override_book_colors = settings.override_book_colors opts.paged_wheel_scrolls_by_screen = v'!!settings.paged_wheel_scrolls_by_screen' opts.paged_wheel_section_jumps = v'!!settings.paged_wheel_section_jumps' opts.paged_pixel_scroll_threshold = settings.paged_pixel_scroll_threshold opts.scroll_auto_boundary_delay = settings.scroll_auto_boundary_delay opts.scroll_stop_boundaries = v'!!settings.scroll_stop_boundaries' opts.reverse_page_turn_zones = v'!!settings.reverse_page_turn_zones' opts.user_stylesheet = settings.user_stylesheet opts.gesture_overrides = settings.gesture_overrides update_settings() def apply_font_size(): if not runtime.is_standalone_viewer: document.documentElement.style.fontSize = '{}px'.format(opts.base_font_size) def default_selection_colors(): if opts.is_dark_theme: return dark_link_color, '#111' return '#3297FD', '#fff' def make_selection_background_opaque(selbg): # see https://stackoverflow.com/questions/7224445/css3-selection-behaves-differently-in-ff-chrome if selbg and selbg.startsWith('#') and len(selbg) is 7: selbg += 'fe' return selbg styles_id = 'calibre-color-scheme-style-overrides' def apply_colors(is_content_popup): des = document.documentElement.style des.setProperty('--calibre-viewer-background-color', opts.color_scheme.background) des.setProperty('--calibre-viewer-foreground-color', opts.color_scheme.foreground) des.colorScheme = 'dark' if opts.is_dark_theme else 'light' if opts.color_scheme.link: des.setProperty('--calibre-viewer-link-color', opts.color_scheme.link) for elem in (document.documentElement, document.body): elem.style.color = opts.color_scheme.foreground # set background color to transparent so that the users background # color which is set on the iframe is used instead elem.style.backgroundColor = 'transparent' des.backgroundColor = opts.bg_image_fade ss = document.getElementById('calibre-color-scheme-style-overrides') if not ss: ss = E.style(id=styles_id, type='text/css') document.documentElement.appendChild(ss) text = '' if runtime.is_standalone_viewer and 'macos' in window.navigator.userAgent: # Change the hyphenate character to a plain ASCII minus (U+002d) the default # is U+2010 but that does not render with the default Times font on macOS as of Monterey # and Qt 15.5 See https://bugs.launchpad.net/bugs/1951467 and can be easily reproduced # by converting a plain text file with the --pdf-hyphenate option # https://bugs.chromium.org/p/chromium/issues/detail?id=1267606 (fix released Feb 1 2022 v98) # See also pdf-preprint.js text += '\n* { -webkit-hyphenate-character: "-" !important }\n' if opts.override_book_colors is not 'never': text = 'body' if opts.override_book_colors is 'dark': text += '.calibre-viewer-dark-colors' text += f''' * {{ color: {opts.color_scheme.foreground} !important; /**/ background-color: {opts.color_scheme.background} !important; /**/ border-color: {opts.color_scheme.foreground} !important; /**/ }}''' if opts.color_scheme.link: c = opts.color_scheme.link # we use the html > body form so that these selectors have higher # priority than the override all selectors above text += f'\nhtml > body :link, html > body :link * {{ color: {c} !important }} html > body :visited, html > body :visited * {{ color: {c} !important }}' selbg, selfg = default_selection_colors() selbg = make_selection_background_opaque(selbg) text += f'\n::selection {{ background-color: {selbg}; color: {selfg} }}' text += f'\n::selection:window-inactive {{ background-color: {selbg}; color: {selfg} }}' if not is_content_popup: # In Chrome when content overflows in RTL and vertical layouts on the left side, # it is not displayed properly when scrolling unless overflow:visible is set, # but this causes scrollbars to appear. # Force disable scrollbars in Chrome, Safari, and Firefox to address this side effect. text += '\nhtml::-webkit-scrollbar, body::-webkit-scrollbar { display: none !important }' # for firefox: https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width text += '\nhtml, body { scrollbar-width: none !important }' # show a dot after highlights that have notes text += '''\n\n .crw-has-dot::after { content: "";\ vertical-align: text-top;\ background-color: currentColor !important;\ text-decoration: none !important;\ display: inline-block;\ height: 0.7ex;\ width: 0.7ex;\ border-radius: 50%;\ } ''' hints_box_css = f''' display: inline-block !important;\ position: absolute !important;\ text-indent: 0 !important;\ text-decoration: none !important;\ font-weight: bold !important;\ color: {selfg} !important;\ background: {selbg} !important;\ cursor: default !important;\ padding: 1px !important;\ border: solid 1px {opts.color_scheme.foreground} !important;\ ''' # reference mode hint box text += f'''\n\n .calibre-reference-mode [data-calibre-ref-num]::before {{ content: attr(data-calibre-ref-num) !important;\ {hints_box_css} }} ''' # follow links hint box text += f'''\n\n .calibre-hint-visible::before {{ content: attr(data-calibre-hint-render) !important;\ {hints_box_css} }} .calibre-hint-enter::before {{ background: #FF5733 !important; \ }} .calibre-animated-hint {{ animation-name: calibre-animate-hint; \ animation-duration: 0.3s; \ animation-timing-function: ease-out; \ display: inline-block !important; \ text-indent: 0 !important; \ }} @keyframes calibre-animate-hint {{ from {{ transform: scale(1); }} to {{ transform: scale(2); }} }} ''' ss.textContent = text def set_selection_style(style): if not style: selbg, selfg = default_selection_colors() style = {'color': selfg, 'background-color': selbg} sheet = document.getElementById(styles_id) if not sheet: return css_text = '' if style.selbg: style.selbg = make_selection_background_opaque(style.selbg) for prop in Object.keys(style): css_text += f'{prop}: {style[prop]}; ' for rule in sheet.sheet.cssRules: if rule.type is rule.STYLE_RULE and rule.selectorText.indexOf('selection') > -1: rule.style.cssText = css_text def set_color_scheme_class(): document.documentElement.classList.add('is-calibre-viewer') if opts.is_dark_theme: document.body.classList.add('calibre-viewer-dark-colors') document.body.classList.remove('calibre-viewer-light-colors') else: document.body.classList.add('calibre-viewer-light-colors') document.body.classList.remove('calibre-viewer-dark-colors') def apply_stylesheet(): sid = 'calibre-browser-viewer-user-stylesheet' style = document.getElementById(sid) if not style: if not opts.user_stylesheet: return style = E.style(type='text/css', id=sid) document.documentElement.appendChild(style) style.textContent = opts.user_stylesheet def apply_settings(is_content_popup): apply_font_size() apply_colors(is_content_popup) apply_stylesheet()
8,966
Python
.py
188
40.090426
160
0.663619
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,528
resources.pyj
kovidgoyal_calibre/src/pyj/read_book/resources.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from elementmaker import E from encodings import base64decode, utf8_decode from dom import clear, remove_all_attributes from read_book.globals import runtime, ui_operations from read_book.settings import opts JSON_XHTML_MIMETYPE = 'application/calibre+xhtml+json' def decode_component(x): return utf8_decode(base64decode(x)) def decode_url(x): parts = x.split('#', 1) return decode_component(parts[0]), parts[1] or '' def create_link_pat(book): return RegExp(book.manifest.link_uid + r'\|([^|]+)\|', 'g') def load_resources(book, root_name, previous_resources, proceed): ans = Object.create(None) pending_resources = v'[root_name]' link_pat = create_link_pat(book) def do_one(): name = pending_resources.shift() if not name: for k in previous_resources: v'delete previous_resources[k]' if book.manifest.files[root_name].has_maths: return load_mathjax(book, ans, proceed) return proceed(ans) if ans[name]: return setTimeout(do_one, 0) if previous_resources[name]: ans[name] = data = previous_resources[name] if jstype(data[0]) is 'string': find_virtualized_resources(data[0]) return setTimeout(do_one, 0) ui_operations.get_file(book, name, got_one) def got_one(data, name, mimetype): ans[name] = v'[data, mimetype]' if jstype(data) is 'string' and book.manifest.files[name]?.is_virtualized: find_virtualized_resources(data) return setTimeout(do_one, 0) def find_virtualized_resources(text): seen = set() already_pending = {x.name for x in pending_resources} link_pat.lastIndex = 0 while True: m = link_pat.exec(text) if not m: break name = decode_url(m[1])[0] if name in seen or name in already_pending: continue seen.add(name) pending_resources.push(name) do_one() mathjax_data = None def load_mathjax(book, resource_data, proceed): if mathjax_data is None: ui_operations.get_mathjax_files(def(data): nonlocal mathjax_data mathjax_data = data resource_data['..mathjax-files..'] = data proceed(resource_data) ) else: resource_data['..mathjax-files..'] = mathjax_data proceed(resource_data) def finalize_resources(book, root_name, resource_data): blob_url_map = Object.create(None) root_data = None link_pat = create_link_pat(book) mathjax = resource_data['..mathjax-files..'] v'delete resource_data["..mathjax-files.."]' # Resolve the non virtualized resources immediately for name in resource_data: data, mimetype = resource_data[name] if jstype(data) is not 'string': blob_url_map[name] = window.URL.createObjectURL(data) for name in blob_url_map: v'delete resource_data[name]' def add_virtualized_resource(name, text, mimetype): nonlocal root_data if name is root_name: root_data = JSON.parse(text) else: blob_url_map[name] = window.URL.createObjectURL(Blob([text], {'type': mimetype})) def replace_deps(text): replacements = v'[]' unresolved_deps = set() link_pat.lastIndex = 0 while True: m = link_pat.exec(text) if not m: break dname, frag = decode_url(m[1]) if blob_url_map[dname]: rtext = blob_url_map[dname] if frag: rtext += '#' + frag replacements.push(v'[m.index, m[0].length, rtext]') else: unresolved_deps.add(dname) for index, sz, repl in reversed(replacements): text = text[:index] + repl + text[index + sz:] return unresolved_deps, text unresolved_deps_map = {} def has_unresolvable_deps(name): deps = unresolved_deps_map[name] if not deps or not deps.length: return False for x in deps: if not blob_url_map[x]: return True return False while True: resolved = v'[]' num = 0 for name in resource_data: if not blob_url_map[name]: num += 1 text, mimetype = resource_data[name] if not has_unresolvable_deps(name): unresolved_deps, text = replace_deps(text) unresolved_deps_map[name] = unresolved_deps if not unresolved_deps.length: add_virtualized_resource(name, text, mimetype) resolved.push(name) if not num: break if not resolved.length: unresolved = [name for name in resource_data if not blob_url_map[name]] print('ERROR: Could not resolve all dependencies of {} because of a cyclic dependency. Remaining deps: {}'.format(root_name, unresolved)) # Add the items anyway, without resolving remaining deps for name in resource_data: if not blob_url_map[name]: text, mimetype = resource_data[name] text = replace_deps(text)[1] add_virtualized_resource(name, text, mimetype) break for name in resolved: v'delete resource_data[name]' return root_data, mathjax, blob_url_map js_types = {k: True for k in 'text/javascript text/ecmascript application/javascript application/ecmascript'.split(' ')} resource_tag_names = {'script':'src', 'link':'href', 'img':'src', 'image':'xlink:href'} ns_rmap = {'http://www.w3.org/2000/svg':'svg', 'http://www.w3.org/1999/xlink':'xlink', 'http://www.w3.org/1998/Math/MathML':'math', 'http://www.w3.org/XML/1998/namespace': 'xml', 'http://www.idpf.org/2007/ops': 'epub'} ns_count = 0 hide_tooltips = False def get_prefix(ns): nonlocal ns_count ans = ns_rmap[ns] if not ans: ns_rmap[ns] = ans = 'ns' + ns_count ns_count += 1 return ans + ':' def apply_attributes(src, elem, ns_map): attributes = src.a if not attributes: return for a in attributes: if a[2]: ns = ns_map[a[2]] elem.setAttributeNS(ns, get_prefix(ns) + a[0], a[1]) else: name = a[0] if hide_tooltips and (name is 'title' or name is 'alt'): continue elem.setAttribute(name, a[1]) def is_loadable_link(attributes): for a in attributes: if a[0].toLowerCase() is 'rel' and a[1]: for x in a[1].split(' '): if x.toLowerCase() is 'stylesheet': return True return False def process_stack(stack, tag_map, ns_map, load_required, onload): while stack.length: node, parent = stack.pop() if tag_map: tag_id = node[0] src = tag_map[tag_id] else: src = node tag_id = v'process_stack.tag_id++' if src.s: if src.n: elem = document.createElementNS(ns_map[src.s], src.n) else: if src.l: parent.appendChild(document.createTextNode(src.l)) continue else: elem = document.createElement(src.n) loadable = False attr = resource_tag_names[src.n] if attr: if attr.indexOf(':') != -1: attr = attr.replace('xlink:', '') if src.a: for a in src.a: if a[0] is attr: loadable = is_loadable_link(src.a) if src.n is 'link' else True break if loadable: load_required.add(tag_id) load_callback = onload.bind(tag_id) elem.addEventListener('load', load_callback) elem.addEventListener('error', load_callback) apply_attributes(src, elem, ns_map) parent.appendChild(elem) if src.x: if src.n is 'script' and js_types[(elem.getAttribute('type') or 'text/javascript').toLowerCase()] is True: elem.text = src.x else: elem.appendChild(document.createTextNode(src.x)) if src.l: parent.appendChild(document.createTextNode(src.l)) if tag_map: for v'var i = node.length - 1; i >= 1; i--': # noqa: unused-local stack.push(v'[node[i], elem]') elif node.c: for v'var i = node.c.length; i-- > 0;': # noqa: unused-local stack.push(v'[node.c[i], elem]') def unserialize_html(serialized_data, proceed, postprocess_dom, root_name): nonlocal hide_tooltips hide_tooltips = opts.hide_tooltips if serialized_data.tag_map: return unserialize_html_legacy(serialized_data, proceed, postprocess_dom, root_name) html = serialized_data.tree ns_map = serialized_data.ns_map remove_all_attributes(document.documentElement, document.head, document.body) clear(document.head, document.body) apply_attributes(html, document.documentElement, ns_map) # hide browser scrollbars while loading since they will anyway be hidden # after loading and this prevents extra layouts document.head.appendChild( E.style(type='text/css', 'html::-webkit-scrollbar, body::-webkit-scrollbar { display: none !important }') ) if runtime.is_standalone_viewer and root_name: if root_name.indexOf('/') > -1: base = window.location.pathname.rpartition('/')[0] base = f'{window.location.protocol}//{window.location.hostname}{base}/' + root_name document.head.appendChild(E.base(href=base)) # Default stylesheet if not runtime.is_standalone_viewer: # for the standalone viewer the default font family is set # in the viewer settings document.head.appendChild(E.style(type='text/css', 'html {{ font-family: {} }}'.format(window.default_font_family or "sans-serif"))) load_required = set() proceeded = False hang_timeout = 5 def hangcheck(): nonlocal proceeded if not proceeded: proceeded = True print(f'WARNING: All resources did not load in {hang_timeout} seconds, proceeding anyway ({load_required.length} resources left)') proceed() def onload(): nonlocal proceeded load_required.discard(this) if not load_required.length and not proceeded: proceeded = True proceed() def process_children(node, parent): if not node.c: return stack = v'[]' for v'var i = node.c.length; i-- > 0;': # noqa: unused-local child = v'node.c[i]' if child.n is not 'meta' and child.n is not 'base': stack.push(v'[child, parent]') process_stack(stack, None, ns_map, load_required, onload) body_done = False process_stack.tag_id = 1 for child in html.c: if child.n is 'head': process_children(child, document.head) elif child.n is 'body': if not document.body: document.documentElement.appendChild(document.createElement('body')) if not body_done: body_done = True apply_attributes(child, document.body, ns_map) if child.x: document.body.appendChild(document.createTextNode(child.x)) process_children(child, document.body) if postprocess_dom: postprocess_dom() ev = document.createEvent('Event') ev.initEvent('DOMContentLoaded', True, True) document.dispatchEvent(ev) if load_required.length: setTimeout(hangcheck, hang_timeout * 1000) else: proceeded = True proceed() def unserialize_html_legacy(serialized_data, proceed, postprocess_dom, root_name): tag_map = serialized_data.tag_map tree = serialized_data.tree ns_map = serialized_data.ns_map html = tag_map[0] remove_all_attributes(document.documentElement) apply_attributes(html, document.documentElement, ns_map) head, body = tree[1], tree[2] # noqa: unused-local clear(document.head, document.body) remove_all_attributes(document.head, document.body) # hide browser scrollbars while loading since they will anyway be hidden # after loading and this prevents extra layouts document.head.appendChild( E.style(type='text/css', 'html::-webkit-scrollbar, body::-webkit-scrollbar { display: none !important }') ) if runtime.is_standalone_viewer and root_name: if root_name.indexOf('/') > -1: base = window.location.pathname.rpartition('/')[0] base = f'{window.location.protocol}//{window.location.hostname}{base}/' + root_name document.head.appendChild(E.base(href=base)) # Default stylesheet if not runtime.is_standalone_viewer: # for the standalone viewer the default font family is set # in the viewer settings document.head.appendChild(E.style(type='text/css', 'html {{ font-family: {} }}'.format(window.default_font_family or "sans-serif"))) load_required = set() proceeded = False hang_timeout = 5 def hangcheck(): nonlocal proceeded if not proceeded: proceeded = True print(f'WARNING: All resources did not load in {hang_timeout} seconds, proceeding anyway ({load_required.length} resources left)') proceed() def onload(): nonlocal proceeded load_required.discard(this) if not load_required.length and not proceeded: proceeded = True proceed() stack = v'[]' for v'var i = head.length - 1; i >= 1; i--': stack.push(v'[head[i], document.head]') process_stack(stack, tag_map, ns_map, load_required, onload) bnode = tag_map[body[0]] apply_attributes(bnode, document.body, ns_map) if bnode.x: document.body.appendChild(document.createTextNode(bnode.x)) for v'var i = body.length - 1; i >= 1; i--': # noqa: unused-local stack.push(v'[body[i], document.body]') process_stack(stack, tag_map, ns_map, load_required, onload) if postprocess_dom: postprocess_dom() ev = document.createEvent('Event') ev.initEvent('DOMContentLoaded', True, True) document.dispatchEvent(ev) if load_required.length: setTimeout(hangcheck, hang_timeout * 1000) else: proceeded = True proceed() def text_from_serialized_html(data, get_anchor_offset_map): serialized_data = JSON.parse(data) tag_map = serialized_data.tag_map ans = v'[]' no_visit = {'script': True, 'style': True, 'title': True, 'head': True} ignore_text = {'img': True, 'math': True, 'rt': True, 'rp': True, 'rtc': True} ignore_text if tag_map: stack = v'[[serialized_data.tree[2], false]]' else: stack = v'[]' for child in serialized_data.tree.c: if child.n is 'body': stack.push(v'[child, false]') anchor_offset_map = {} text_pos = 0 while stack.length: node, text_ignored_in_parent = stack.pop() if jstype(node) is 'string': ans.push(node) text_pos += node.length continue src = tag_map[node[0]] if tag_map else node if get_anchor_offset_map and src.a: for v'var i = 0; i < src.a.length; i++': x = src.a[i] if x[0] is 'id': aid = x[1] if jstype(anchor_offset_map[aid]) is not 'number': anchor_offset_map[aid] = text_pos if no_visit[src.n]: continue ignore_text_in_node_and_children = text_ignored_in_parent or v'!!ignore_text[src.n]' if not ignore_text_in_node_and_children and src.x: ans.push(src.x) text_pos += src.x.length if not text_ignored_in_parent and src.l: stack.push(v'[src.l, ignore_text_in_node_and_children]') if tag_map: for v'var i = node.length - 1; i >= 1; i--': stack.push(v'[node[i], ignore_text_in_node_and_children]') else: if src.c: for v'var i = src.c.length; i-- > 0;': stack.push(v'[src.c[i], ignore_text_in_node_and_children]') ans = ans.join('') if get_anchor_offset_map: return ans, anchor_offset_map return ans
16,865
Python
.py
405
31.975309
218
0.596527
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,529
selection_bar.pyj
kovidgoyal_calibre/src/pyj/read_book/selection_bar.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from book_list.theme import get_color from dom import change_icon_image, clear, svgicon, unique_id from gettext import gettext as _ from modals import create_custom_dialog, error_dialog, question_dialog from read_book.globals import runtime, ui_operations from read_book.highlights import ( ICON_SIZE, EditNotesAndColors, HighlightStyle, all_styles, get_current_link_prefix, link_to_epubcfi, render_notes ) from read_book.shortcuts import shortcut_for_key_event from read_book.toc import family_for_toc_node, get_toc_nodes_bordering_spine_item from uuid import short_uuid from widgets import create_button from utils import parse_url_params DRAG_SCROLL_ZONE_MIN_HEIGHT = 10 BUTTON_MARGIN = '0.5rem' # Utils {{{ def get_margins(): return { 'top': document.getElementById('book-top-margin').offsetHeight, 'left': document.getElementById('book-left-margin').offsetWidth, } def map_boundaries(cs, vertical, rtl): margins = get_margins() def map_boundary(b): x_offset = y_offset = 0 if vertical: if b.selected_prev: y_offset = b.height else: if rtl: # Horizontal RTL if not b.selected_prev: x_offset = b.width else: # Horizontal LTR if b.selected_prev: x_offset = b.width return {'x': (b.x or 0) + x_offset + margins.left, 'y': (b.y or 0) + y_offset + margins.top, 'height': b.height or 0, 'width': b.width or 0, 'onscreen': b.onscreen} return map_boundary(cs.start), map_boundary(cs.end) def map_to_iframe_coords(point, margins): point.x -= margins.left point.y -= margins.top return point def near_element(elem, x, y): r = elem.getBoundingClientRect() extend_by = 15 left = r.left - extend_by top = r.top - extend_by right = r.right + extend_by bottom = r.bottom + extend_by return left <= x <= right and top <= y <= bottom def position_bar_avoiding_handles(lh, rh, left, top, bar_width, bar_height, available_width, available_height, buffer): # adjust position to minimize overlap with handles def bar_rect(left, top): return {'left': left, 'top': top, 'right': left + bar_width, 'bottom': top + bar_height} def overlaps_a_handle(left, top): b = bar_rect(left, top) if elements_overlap(lh, b): return lh if elements_overlap(rh, b): return rh if not overlaps_a_handle(left, top): return if Math.abs(lh.top - rh.top) < lh.height + buffer: # handles close vertically, place either above or below bottom = max(lh.bottom, rh.bottom) has_space_below = bottom + bar_height < available_height - buffer if has_space_below: return {'top': bottom, 'put_below': True} return {'top': min(lh.top, rh.top), 'put_below': False} b = bar_rect(left, top) if lh.left > rh.left: lh, rh = rh, lh left_overlaps = elements_overlap(lh, b) right_overlaps = elements_overlap(rh, b) if not left_overlaps or not right_overlaps: # overlapping a single handle, see if we can move horizontally h = lh if left_overlaps else rh d1 = d2 = 2 * available_width q1 = h.left - bar_width - 1 if q1 > -buffer and not overlaps_a_handle(q1, top): d1 = abs(left - q1) q2 = h.right + 1 if q2 + bar_width < available_width + buffer and not overlaps_a_handle(q2, top): d2 = abs(left - q2) d = min(d1, d2) if d < available_width: return {'left': q1 if d is d1 else q2} # try to place either to left of both handles, between both handles, to # the right of both d1 = d2 = d3 = 2 * available_width q1 = lh.left - bar_width - 1 if q1 > -buffer and not overlaps_a_handle(q1, top): d1 = abs(left - q1) q2 = lh.right + 1 if q2 + bar_width < rh.left + buffer and not overlaps_a_handle(q2, top): d2 = abs(left - q2) q3 = rh.right + 1 if q3 + bar_width < available_width + buffer and not overlaps_a_handle(q3, top): d3 = abs(left - q3) d = min(d1, d2, d3) if d < available_width: return {'left': q1 if d is d1 else (q2 if d is d2 else q3)} # look above both vertically, between both and below both th, bh = v'[lh, rh]' if lh.top <= rh.top else v'[rh, lh]' d1 = d2 = d3 = 2 * available_height q1 = th.top - bar_height - 1 if q1 > -buffer and not overlaps_a_handle(left, q1): d1 = abs(top - q1) q2 = th.bottom + 1 if q2 + bar_height < bh.top + buffer and not overlaps_a_handle(left, q2): d2 = abs(top - q2) q3 = bh.bottom + 1 if q3 + bar_height < available_height + buffer and not overlaps_a_handle(left, q3): d3 = abs(top - q3) d = min(d1, d2, d3) if d < available_height: return {'top': (q1 + bar_height) if d is d1 else (q2 if d is d2 else q3), 'put_below': d is not d1} # look in the four corners if not overlaps_a_handle(buffer, buffer): return {'left': buffer, 'top': buffer + bar_height, 'put_below': False} if not overlaps_a_handle(available_width - bar_width, buffer): return {'left': available_width - bar_width, 'top': buffer + bar_height, 'put_below': False} if not overlaps_a_handle(buffer, available_height - bar_height): return {'left': buffer, 'top': available_height - bar_height, 'put_below': True} if not overlaps_a_handle(available_width - bar_width, available_height - bar_height): return {'left': available_width - bar_width, 'top': available_height - bar_height, 'put_below': True} # give up should be relatively rare def quick_highlight_icon(name, tooltip, hcolor): svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg') svg.setAttribute('style', f'fill: currentColor; height: 2ex; width: 2ex; vertical-align: text-top; margin: 0') u = document.createElementNS('http://www.w3.org/2000/svg', 'use') svg.appendChild(u) svg.firstChild.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#icon-' + name) ans = E.div( style=f'width: {ICON_SIZE}; height: {ICON_SIZE}; display: flex; flex-direction: column', title=tooltip or '', svg, E.div(style=f'width: {ICON_SIZE}; height: 1ex; background-color: {hcolor}; color: {hcolor}; margin: 0') ) return ans def all_actions(): def a(icon, text, func, needs_highlight): return { 'icon': icon, 'text': text, 'function_name': func, 'needs_highlight': v'!!needs_highlight', 'icon_function': def (hcolor): return svgicon(icon, ICON_SIZE, ICON_SIZE, text) } if not all_actions.ans: all_actions.ans = { 'copy': a('copy', _('Copy to clipboard') + ' [Ctrl+C]', 'copy_to_clipboard'), 'lookup': a('library', _('Lookup/search selected word') + ' [L]', 'lookup'), 'quick_highlight': a('highlight', _('Quick highlight in current style') + ' [Q]', 'quick_highlight'), 'highlight': a('highlight', _('Highlight selection') + ' [H]', 'create_highlight'), 'search': a('search', _('Search for selection in the book') + ' [F]', 'book_search'), 'bookmark': a('bookmark', _('Create a bookmark') + ' [Ctrl+Alt+B]', 'new_bookmark'), 'search_net': a('global-search', _('Search for selection on the net') + ' [S]', 'internet_search'), 'remove_highlight': a('trash', _('Remove this highlight') + _(' [Delete or D]'), 'remove_highlight', True), 'clear': a('close', _('Clear selection') + ' [Esc]', 'clear_selection'), 'speak': a('bullhorn', _('Read aloud') + ' [T]', 'speak_aloud'), 'cite': a('reference-mode', _('Copy a citation to this text') + ' [X]', 'cite'), } qh = all_actions.ans.quick_highlight qh.icon_function = quick_highlight_icon.bind(None, qh.icon, qh.text) return all_actions.ans def selection_handle(): ans = svgicon('selection-handle') s = ans.style s.position = 'absolute' s.boxSizing = 'border-box' s.touchAction = 'none' return ans def set_handle_color(handle, bg, fg): use = handle.querySelector('use') use.style.stroke = fg use.style.fill = bg def elements_overlap(a, b): return a.left < b.right and b.left < a.right and a.top < b.bottom and b.top < a.bottom HIDDEN = 0 WAITING = 1 DRAGGING = 2 EDITING = 3 # }}} class SelectionBar: def __init__(self, view): self.view = view self.current_highlight_style = HighlightStyle(get_session_data().get('highlight_style')) self.current_notes = '' self.state = HIDDEN self.start_handle_id = unique_id('handle') self.end_handle_id = unique_id('handle') self.bar_id = unique_id('bar') self.editor_id = unique_id('editor') self.quick_highlight_styles = v'[]' # Sensible defaults until we get information from a selection message. self.ltr = True self.rtl = False self.vertical = False container = self.container container.style.overflow = 'hidden' container.addEventListener('click', self.container_clicked, {'passive': False}) container.addEventListener('contextmenu', self.container_context_menu_requested, {'passive': False}) container.addEventListener('mouseup', self.mouseup_on_container, {'passive': False}) container.addEventListener('mousemove', self.mousemove_on_container, {'passive': False}) container.addEventListener('touchmove', self.touchmove_on_container, {'passive': False}) container.addEventListener('touchend', self.touchend_on_container, {'passive': False}) container.addEventListener('touchcancel', self.touchend_on_container, {'passive': False}) container.addEventListener('keydown', self.on_keydown, {'passive': False}) container.addEventListener('wheel', self.on_wheel, {'passive': False}) container.setAttribute('tabindex', '0') self.dragging_handle = None self.position_in_handle = {'x': 0, 'y': 0} self.active_touch = None self.drag_scroll_timer = None self.last_drag_scroll_at = None self.start_line_length = self.end_line_length = 0 self.current_editor = None start_handle = selection_handle() start_handle.id = self.start_handle_id end_handle = selection_handle() end_handle.id = self.end_handle_id for h in (start_handle, end_handle): h.addEventListener('mousedown', self.mousedown_on_handle, {'passive': False}) h.addEventListener('touchstart', self.touchstart_on_handle, {'passive': False}) container.appendChild(h) container.appendChild(E.div( id=self.bar_id, style='position: absolute; border: solid 1px currentColor; border-radius: 5px;' 'left: 0; top: 0; display: flex; flex-direction: column;' )) editor_div = E.div(id=self.editor_id, style='position: absolute') container.appendChild(editor_div) editor_div.addEventListener('click', self.editor_container_clicked, {'passive': False}) editor_div.addEventListener('wheel', def(ev):ev.stopPropagation();, {'passive': True}) # bar and handles markup {{{ def set_handle_colors(self): handle_fill = get_color('window-background') fg = self.view.current_color_scheme.foreground for h in (self.start_handle, self.end_handle): set_handle_color(h, handle_fill, fg) def build_bar(self, annot_id): notes = self.annotations_manager.notes_for_highlight(annot_id) bar_container = self.bar clear(bar_container) bar_container.style.maxWidth = 'min(50rem, 90vw)' if self.supports_css_min_max else '50rem' bar_container.style.backgroundColor = get_color("window-background") notes_container = E.div() notes_container.addEventListener('wheel', def(evt): evt.stopPropagation();, {'passive': False}) for x in [ E.div(style='height: 4ex; display: flex; align-items: center; padding: 5px; justify-content: center'), E.hr(style='border-top: solid 1px; margin: 0; padding: 0; display: none'), E.div( style='display: none; padding: 5px;', notes_container, ) ]: bar_container.appendChild(x) bar = bar_container.firstChild hs = self.current_highlight_style.highlight_shade(self.view.current_color_scheme.is_dark_theme) def cb(ac, callback): ans = ac.icon_function(hs) ans.addEventListener('click', def(ev): ev.stopPropagation(), ev.preventDefault() callback(ev) self.view.focus_iframe() ) ans.classList.add('simple-link') ans.style.marginLeft = ans.style.marginRight = BUTTON_MARGIN return ans actions = all_actions() sd = get_session_data() for acname in sd.get('selection_bar_actions'): ac = actions[acname] if ac and (not ac.needs_highlight or v'!!annot_id'): bar.appendChild(cb(ac, self[ac.function_name])) selection_bar_quick_highlights = sd.get('selection_bar_quick_highlights') self.quick_highlight_styles = v'[]' if selection_bar_quick_highlights?.length: self.show_quick_highlight_buttons(bar, selection_bar_quick_highlights) self.show_notes(bar_container, notes) return bar_container def show_quick_highlight_buttons(self, bar, actions): all = {x.key:x for x in all_styles()} actions = [a for a in actions if all[a]] if not actions.length: return actions.pysort(key=def (a): return (all[a].friendly_name or '').toLowerCase();) self.quick_highlight_styles = actions bar.appendChild(E.div( style=f'background: currentColor; width: 1px; height: {ICON_SIZE}; margin-left: {BUTTON_MARGIN}; margin-right: {BUTTON_MARGIN}' )) dark = self.view.current_color_scheme.is_dark_theme for i, key in enumerate(actions): hs = all[key] if i < 9: sc = i + 1 elif i == 10: sc = 0 else: sc = None sw = E.div( class_='simple-link', style=f'margin-left: {BUTTON_MARGIN}; margin-right: {BUTTON_MARGIN}', title=_('Highlight using: {name}{sc}').format(name=hs.friendly_name, sc=f' [{sc}]' if sc is not None else ''), onclick=self.quick_highlight_with_style.bind(None, hs), ) hs.make_swatch(sw, dark) bar.appendChild(sw) def show_notes(self, bar, notes): notes = (notes or "").strip() if not notes: return notes_container = bar.lastChild c = notes_container.lastChild notes_container.style.display = notes_container.previousSibling.style.display = 'block' c.style.overflow = 'auto' if self.supports_css_min_max: c.style.maxHeight = 'min(20ex, 40vh)' else: c.style.maxHeight = '20ex' render_notes(notes, c, True) # }}} # accessors {{{ @property def supports_css_min_max(self): return not runtime.is_standalone_viewer or runtime.QT_VERSION >= 0x050f00 @property def container(self): return document.getElementById('book-selection-bar-overlay') @property def bar(self): return document.getElementById(self.bar_id) @property def start_handle(self): return document.getElementById(self.start_handle_id) @property def end_handle(self): return document.getElementById(self.end_handle_id) @property def editor(self): return document.getElementById(self.editor_id) @property def annotations_manager(self): return self.view.annotations_manager @property def current_handle_position(self): sh, eh = self.start_handle, self.end_handle sbr, ebr = sh.getBoundingClientRect(), eh.getBoundingClientRect() if not self.vertical: # Horizontal LTR (i.e. English) if not self.rtl: return { 'start': { 'onscreen': sh.style.display is not 'none', 'x': Math.round(sbr.right), 'y': Math.round(sbr.bottom - self.start_line_length // 2) }, 'end': { 'onscreen': eh.style.display is not 'none', 'x': Math.round(ebr.left), 'y': Math.round(ebr.bottom - self.end_line_length // 2) } } # Horizontal RTL (i.e. Hebrew, Arabic) else: return { 'start': { 'onscreen': sh.style.display is not 'none', 'x': Math.round(sbr.left), 'y': Math.round(sbr.bottom - self.start_line_length // 2) }, 'end': { 'onscreen': eh.style.display is not 'none', 'x': Math.round(ebr.right), 'y': Math.round(ebr.bottom - self.end_line_length // 2) } } # Vertical RTL (i.e. Traditional Chinese, Japanese) else if self.rtl: return { 'start': { 'onscreen': sh.style.display is not 'none', 'x': Math.round(sbr.left + self.start_line_length // 2), 'y': Math.round(sbr.bottom) }, 'end': { 'onscreen': eh.style.display is not 'none', 'x': Math.round(ebr.right - self.end_line_length // 2), 'y': Math.round(ebr.top) } } # Vertical LTR (i.e. Mongolian) else: return { 'start': { 'onscreen': sh.style.display is not 'none', 'x': Math.round(sbr.right - self.end_line_length // 2), 'y': Math.round(sbr.bottom) }, 'end': { 'onscreen': eh.style.display is not 'none', 'x': Math.round(ebr.left + self.start_line_length // 2), 'y': Math.round(ebr.top) } } # }}} # event handlers {{{ def mousedown_on_handle(self, ev): ev.stopPropagation(), ev.preventDefault() if self.state is WAITING: self.start_handle_drag(ev, ev.currentTarget) def touchstart_on_handle(self, ev): ev.stopPropagation(), ev.preventDefault() if self.state is WAITING: for touch in ev.changedTouches: self.active_touch = touch.identifier self.start_handle_drag(touch, ev.currentTarget) break def start_handle_drag(self, ev, handle): self.state = DRAGGING self.dragging_handle = handle.id r = handle.getBoundingClientRect() self.position_in_handle.x = Math.round(ev.clientX - r.left) self.position_in_handle.y = Math.round(ev.clientY - r.top) def container_context_menu_requested(self, ev): pos = {'x': ev.clientX, 'y': ev.clientY} map_to_iframe_coords(pos, get_margins()) self.send_message('extend-to-point', pos=pos) def container_clicked(self, ev): ev.stopPropagation(), ev.preventDefault() if self.state is EDITING: self.hide_editor(True) if self.state is WAITING: now = window.performance.now() if ev.shiftKey: pos = {'x': ev.clientX, 'y': ev.clientY} map_to_iframe_coords(pos, get_margins()) self.send_message('extend-to-point', pos=pos) return if self.last_double_click_at and now - self.last_double_click_at < 500: self.send_message('extend-to-paragraph') return for x in (self.bar, self.start_handle, self.end_handle): if near_element(x, ev.clientX, ev.clientY): return self.clear_selection() def mousemove_on_container(self, ev): if self.state is not DRAGGING: return ev.stopPropagation(), ev.preventDefault() self.move_handle(ev) def touchmove_on_container(self, ev): if self.state is not DRAGGING: return ev.stopPropagation(), ev.preventDefault() for touch in ev.changedTouches: if touch.identifier is self.active_touch: self.move_handle(touch) return def move_handle(self, ev): handle = document.getElementById(self.dragging_handle) s = handle.style s.left = (ev.clientX - self.position_in_handle.x) + 'px' s.top = (ev.clientY - self.position_in_handle.y) + 'px' margins = get_margins() pos = self.current_handle_position if self.dragging_handle is self.start_handle_id: start = True position = map_to_iframe_coords(pos.start, margins) else: start = False position = map_to_iframe_coords(pos.end, margins) self.send_message('move-end-of-selection', start=start, pos=position) c = self.container rect = c.getBoundingClientRect() t = document.getElementById('book-top-margin').offsetHeight top = rect.top + max(t, DRAG_SCROLL_ZONE_MIN_HEIGHT) t = document.getElementById('book-bottom-margin').offsetHeight bottom = rect.bottom - max(t, DRAG_SCROLL_ZONE_MIN_HEIGHT) if ev.clientY < top or ev.clientY > bottom: self.run_drag_scroll(ev.clientY, top, bottom) else: self.end_drag_scroll() def end_handle_drag(self): self.end_drag_scroll() handle = self.dragging_handle self.dragging_handle = None self.state = WAITING # this is done after the event loop ticks because otherwise if # update_position moves the handle a click event is delivered to the # container, calling container_clicked() and clearing the selection window.setTimeout(self.update_position.bind(None, handle), 0) def mouseup_on_container(self, ev): if self.state is DRAGGING: ev.preventDefault(), ev.stopPropagation() self.end_handle_drag() def touchend_on_container(self, ev): if self.state is DRAGGING: ev.preventDefault(), ev.stopPropagation() for touch in ev.changedTouches: if touch.identifier is self.active_touch: self.active_touch = None self.end_handle_drag() return def on_wheel(self, ev): ev.stopPropagation(), ev.preventDefault() if self.state is not EDITING: self.view.send_wheel_event_to_iframe(ev, 'selection-mode') def on_keydown(self, ev): ev.stopPropagation(), ev.preventDefault() if ev.key is 'Escape': if self.state is EDITING: self.hide_editor() else: self.clear_selection() return if self.state is WAITING and not ev.ctrlKey and not ev.altKey and not ev.metaKey: k = ev.key.toLowerCase() if k is 'l': self.lookup() return if k is 'q': self.quick_highlight() return if k is 'h': self.create_highlight() return if k is 'f': self.book_search() return if k is 's': self.internet_search() return if k is 't': self.speak_aloud() return if k is 'x': self.cite() return if k is 'delete' or k is 'd': self.remove_highlight() return if k in '0123456789': all = {x.key:x for x in all_styles()} k = int(k) if k is 0: k = 9 else: k -= 1 key = self.quick_highlight_styles[k] if key: hs = all[key] if hs: self.quick_highlight_with_style(hs) return sc_name = shortcut_for_key_event(ev, self.view.keyboard_shortcut_map) if not sc_name: return forwarded = { 'toggle_highlights': True, 'edit_book': True, 'select_all': True, 'extend_selection_to_end_of_line': True, 'extend_selection_to_start_of_line': True, } if sc_name is 'show_chrome': self.clear_selection() elif sc_name is 'copy_to_clipboard': self.copy_to_clipboard() elif sc_name is 'toggle_lookup': self.lookup() elif sc_name in ('up', 'down', 'pageup', 'pagedown', 'left', 'right'): self.send_message('trigger-shortcut', name=sc_name) elif sc_name is 'start_search': self.book_search() elif sc_name is 'new_bookmark': self.new_bookmark() elif sc_name.startsWith('shrink_selection_by_') or sc_name.startsWith('extend_selection_by_') or forwarded[sc_name]: self.view.on_handle_shortcut({'name': sc_name}) def report_failed_edit_highlight(self, annot_id): notes = self.annotations_manager.notes_for_highlight(annot_id) has_notes = bool(notes) title = _('Highlight text missing') text = _( 'The text associated with this highlight could not be found in the book.' ' This can happen if the book was modified. This highlight will be automatically removed.' ) if runtime.is_standalone_viewer or not has_notes: if has_notes: ui_operations.copy_selection(notes) text += ' ' + _('The notes for this highlight have been copied to the clipboard.') error_dialog(title, text) else: create_custom_dialog(title, def (parent, close_modal): parent.appendChild(E.div( E.div(text), E.div( class_='button-box', create_button( _('Copy notes to clipboard'), None, def(): ui_operations.copy_selection(notes) close_modal() , highlight=True), '\xa0', create_button(_('OK'), None, close_modal), ) )) ) self.remove_highlight_with_id(annot_id) # }}} # drag scroll {{{ def run_drag_scroll(self, mouse_y, top, bottom): backwards = mouse_y <= top self.do_one_drag_scroll(backwards, top - mouse_y if backwards else mouse_y - bottom) def do_one_drag_scroll(self, backwards, distance_from_boundary): window.clearTimeout(self.drag_scroll_timer) self.drag_scroll_timer = None if self.state is not DRAGGING: return sd = get_session_data() in_flow_mode = sd.get('read_mode') is 'flow' interval = 1000/sd.get('lines_per_sec_smooth') if in_flow_mode else 1200 self.drag_scroll_timer = window.setTimeout(self.do_one_drag_scroll.bind(None, backwards, distance_from_boundary), interval) now = window.performance.now() if self.last_drag_scroll_at is None: # dont jump a page immediately in paged mode if in_flow_mode: self.send_drag_scroll_message(backwards, 'left' if self.dragging_handle is self.start_handle_id else 'right', True) self.last_drag_scroll_at = now elif now - self.last_drag_scroll_at > interval: self.send_drag_scroll_message(backwards, 'left' if self.dragging_handle is self.start_handle_id else 'right', True) self.last_drag_scroll_at = now def send_drag_scroll_message(self, backwards, handle, extend_selection): self.send_message( 'drag-scroll', backwards=backwards, handle=handle, extents=self.current_handle_position, extend_selection=extend_selection) def end_drag_scroll(self): if self.drag_scroll_timer is not None: window.clearTimeout(self.drag_scroll_timer) self.drag_scroll_timer = None self.last_drag_scroll_at = None # }}} # show and hide {{{ def hide(self): was_shown = self.state is not HIDDEN self.state = HIDDEN self.container.style.display = 'none' self.view.focus_iframe() if not was_shown and self.spoken_aloud_at_least_once: ui_operations.speak_simple_text('') # cancel any on-going speech self.spoken_aloud_at_least_once = False def show(self): sd = get_session_data() if self.state is HIDDEN: if sd.get('show_selection_bar'): self.container.style.display = 'block' self.state = WAITING self.focus() @property def is_visible(self): return self.container.style.display is not 'none' def focus(self): self.container.focus() def update_position(self, dragged_handle): container = self.container cs = self.view.currently_showing.selection self.bar.style.display = 'none' self.set_handle_colors() if self.state is DRAGGING: self.show() # needed for drag scrolling self.position_undragged_handle() return if self.state is EDITING: self.start_handle.style.display = 'none' self.end_handle.style.display = 'none' self.show() self.place_editor() return self.start_handle.style.display = 'none' self.end_handle.style.display = 'none' self.editor.style.display = 'none' if not cs or cs.empty or jstype(cs.drag_mouse_position?.x) is 'number' or cs.selection_change_caused_by_search: return self.hide() if not cs.start.onscreen and not cs.end.onscreen: return self.hide() self.rtl = cs.rtl self.ltr = not self.rtl self.vertical = cs.vertical for h in (self.start_handle, self.end_handle): if h.vertical is not self.vertical: h.vertical = self.vertical change_icon_image(h, 'selection-handle-vertical' if h.vertical else 'selection-handle') self.show() self.bar.style.display = self.start_handle.style.display = self.end_handle.style.display = 'block' start, end = map_boundaries(cs, self.vertical, self.rtl) bar = self.build_bar(cs.annot_id) bar_height = bar.offsetHeight bar_width = bar.offsetWidth buffer = 2 limits = { 'top': buffer, 'bottom': container.offsetHeight - bar_height - buffer, # - 10 ensures we dont cover scroll bar 'left': buffer, 'right': container.offsetWidth - bar_width - buffer - 10 } start_handle, end_handle = self.start_handle, self.end_handle self.position_handles(start_handle, end_handle, start, end) def place_vertically(pos, put_below): if put_below: top = pos bar.style.flexDirection = 'column' else: top = pos - bar_height - buffer bar.style.flexDirection = 'column-reverse' bar.style.top = top + 'px' return top # We try to place the bar near the last dragged handle so it shows up # close to current mouse position. We assume it is the "end" handle. if dragged_handle: if dragged_handle is not self.end_handle_id: start, end = end, start else: if not cs.start_is_anchor: start, end = end, start if not end.onscreen and start.onscreen: start, end = end, start end_after_start = start.y < end.y or (start.y is end.y and start.x < end.x) # vertical position if end_after_start: has_space_below = end.y + end.height < container.offsetHeight - bar_height - buffer put_below = has_space_below else: has_space_above = end.y - bar_height - buffer > 0 put_below = not has_space_above top = place_vertically(end.y + end.height if put_below else end.y, put_below) # horizontal position left = end.x - bar_width // 2 left = max(limits.left, min(left, limits.right)) bar.style.left = left + 'px' sh, eh = start_handle.getBoundingClientRect(), end_handle.getBoundingClientRect() changed = position_bar_avoiding_handles(sh, eh, left, top, bar_width, bar_height, container.offsetWidth - 10, container.offsetHeight, buffer) if changed: if changed.top?: place_vertically(changed.top, changed.put_below) if changed.left?: bar.style.left = changed.left + 'px' def place_single_handle(self, selection_size, handle, boundary, is_start): s = handle.style s.display = 'block' if boundary.onscreen else 'none' # Cap this to prevent very large handles when selecting images. selection_size = max(10, min(selection_size, 60)) if self.vertical: width = selection_size * 2 height = int(width * 2 / 3) else: height = selection_size * 2 width = int(height * 2 / 3) s.width = f'{width}px' s.height = f'{height}px' s.transform = 'none' if not self.vertical: bottom = boundary.y + boundary.height top = bottom - height s.top = f'{top}px' if is_start: # Horizontal, start, LTR if self.ltr: s.left = (boundary.x - width) + 'px' self.start_line_length = selection_size # Horizontal, start, RTL else: s.left = (boundary.x) + 'px' self.start_line_length = selection_size s.transform = 'scaleX(-1)' else: # Horizontal, end, LTR if self.ltr: s.left = boundary.x + 'px' self.end_line_length = selection_size s.transform = 'scaleX(-1)' # Horizontal, end, RTL else: s.left = (boundary.x - width) + 'px' self.end_line_length = selection_size else: if is_start: # Vertical, start, RTL if self.rtl: s.top = boundary.y - height + 'px' s.left = boundary.x + 'px' self.start_line_length = selection_size s.transform = 'scaleX(-1) scaleY(-1)' # Vertical, start, LTR else: s.top = boundary.y - height + 'px' s.left = boundary.x - width + boundary.width + 'px' self.start_line_length = selection_size s.transform = 'scaleY(-1)' else: # Vertical, end, RTL if self.rtl: s.top = boundary.y + 'px' s.left = boundary.x - width + boundary.width + 'px' self.end_line_length = selection_size # Vertical, end, LTR else: s.top = boundary.y + 'px' s.left = boundary.x + 'px' self.end_line_length = selection_size s.transform = 'scaleX(-1)' def position_handles(self, start_handle, end_handle, start, end): if self.vertical: selection_size = max(start.width, end.width) else: selection_size = max(start.height, end.height) self.place_single_handle(selection_size, start_handle, start, True) self.place_single_handle(selection_size, end_handle, end, False) def position_undragged_handle(self): cs = self.view.currently_showing.selection start, end = map_boundaries(cs, self.vertical, self.rtl) if not self.vertical: selection_size = max(start.height, end.height) else: selection_size = max(start.width, end.width) if self.dragging_handle is self.start_handle_id: handle = self.end_handle boundary = end is_start = False else: handle = self.start_handle boundary = start is_start = True self.place_single_handle(selection_size, handle, boundary, is_start) # }}} # Editor {{{ def show_editor(self, highlight_style, notes): for x in (self.bar, self.start_handle, self.end_handle): x.style.display = 'none' container = self.editor clear(container) container.style.display = 'block' self.state = EDITING cs = self.view.currently_showing.selection self.current_editor = EditNotesAndColors( container, self.view.current_color_scheme.is_dark_theme, notes, highlight_style, cs.annot_id, self.hide_editor) self.place_editor() def place_editor(self): if self.current_editor is None: return ed = self.editor cs = self.view.currently_showing.selection start, end = map_boundaries(cs, self.vertical, self.rtl) if not start.onscreen and not end.onscreen: return width, height = ed.offsetWidth, ed.offsetHeight if not start.onscreen: start = end if not end.onscreen: end = start top, bottom = v'[start, end]' if start.y <= end.y else v'[end, start]' container = self.container space_above, space_below = top.y, container.offsetHeight - (bottom.y + bottom.height) if height <= min(space_above, space_below): put_above = space_above < space_below else: put_above = space_above > space_below if put_above: y = max(0, top.y - height) else: y = bottom.y + bottom.height if y + height > container.offsetHeight: y = container.offsetHeight - height x = max(0, end.x - width // 2) if x + width > container.offsetWidth: x = container.offsetWidth - width ed.style.left = x + 'px' ed.style.top = y + 'px' def hide_editor(self, apply_changes): if not apply_changes: self.state = WAITING self.update_position() self.focus() return ed = self.current_editor self.current_editor = None self.current_highlight_style = ed.current_style self.current_notes = ed.current_notes self.send_message( 'apply-highlight', style=self.current_highlight_style.style, uuid=short_uuid(), existing=ed.annot_id, has_notes=v'!!self.current_notes' ) self.state = WAITING self.update_position() get_session_data().set('highlight_style', self.current_highlight_style.style) self.focus() def editor_container_clicked(self, ev): ev.stopPropagation(), ev.preventDefault() # }}} # Actions {{{ def copy_to_clipboard(self): self.view.copy_to_clipboard() def lookup(self): if ui_operations.toggle_lookup: ui_operations.toggle_lookup(True) else: self.view.overlay.show_word_actions(self.view.currently_showing.selection.text) def book_search(self): cs = self.view.currently_showing?.selection?.text if not cs or len(str.strip(cs)) < 2: return error_dialog(_('Too little text'), _('Cannot search as too little text is selected. You must select at least two characters.')) self.view.show_search(True) self.clear_selection() def new_bookmark(self): self.view.new_bookmark() def internet_search(self): text = self.view.currently_showing.selection.text if text: q = encodeURIComponent(text) url = get_session_data().get('net_search_url').format(q=q) ui_operations.open_url(url) def clear_selection(self): self.view.on_handle_shortcut({'name': 'clear_selection'}) self.hide() def speak_aloud(self): text = self.view.currently_showing.selection.text if text: ui_operations.speak_simple_text(text) self.spoken_aloud_at_least_once = True def cite(self): self.send_message('cite-current-selection') def create_highlight(self): cs = self.view.currently_showing.selection hs = self.current_highlight_style notes = '' if cs.annot_id: am = self.annotations_manager q = am.style_for_highlight(cs.annot_id) if q: hs = HighlightStyle(q) notes = am.notes_for_highlight(cs.annot_id) or notes self.show() self.show_editor(hs, notes) def quick_highlight(self): cs = self.view.currently_showing.selection if cs.text: if cs.annot_id: am = self.annotations_manager self.current_notes = am.notes_for_highlight(cs.annot_id) or '' self.send_message( 'apply-highlight', style=self.current_highlight_style.style, uuid=short_uuid(), existing=cs.annot_id, has_notes=v'!!self.current_notes' ) else: self.current_notes = '' self.send_message('apply-highlight', style=self.current_highlight_style.style, uuid=short_uuid(), has_notes=False) self.state = WAITING self.update_position() def quick_highlight_with_style(self, hs): self.current_highlight_style = hs self.quick_highlight() def remove_highlight(self): annot_id = self.view.currently_showing.selection.annot_id if annot_id: q = _('Are you sure you want to delete this highlight permanently?') text = self.annotations_manager.text_for_highlight(annot_id) if text and text.length: if text.length > 20: text = text[:20] + '…' notes = self.annotations_manager.notes_for_highlight(annot_id) if notes and notes.length: q = _('Are you sure you want to delete the highlighting of "{}" and the associated notes permanently?').format(text) else: q = _('Are you sure you want to delete the highlighting of "{}" permanently?').format(text) question_dialog( _('Are you sure?'), q, def (yes): if yes: self.remove_highlight_with_id(annot_id) , skip_dialog_name='confirm_remove_highlight' ) def remove_highlight_with_id(self, annot_id): self.send_message('remove-highlight', uuid=annot_id) self.annotations_manager.delete_highlight(annot_id) def edit_highlight(self, annot_id): self.send_message('edit-highlight', uuid=annot_id) # }}} # Interact with iframe {{{ def send_message(self, type, **kw): self.view.iframe_wrapper.send_message('annotations', type=type, **kw) def notes_edited(self, annot_id): notes = self.annotations_manager.notes_for_highlight(annot_id) self.send_message('notes-edited', uuid=annot_id, has_notes=bool(notes)) def handle_message(self, msg): if msg.type is 'highlight-applied': notes = self.current_notes self.current_notes = '' if not msg.ok: return error_dialog( _('Highlighting failed'), _('Failed to apply highlighting, try adjusting extent of highlight') ) toc_family = v'[]' if msg.anchor_before: toc_family = family_for_toc_node(msg.anchor_before.id) else: before = get_toc_nodes_bordering_spine_item()[0] if before: toc_family = family_for_toc_node(before.id) self.annotations_manager.add_highlight( msg, self.current_highlight_style.style, notes, toc_family) elif msg.type is 'highlight-overlapped': question_dialog( _('Are you sure?'), _('This highlight overlaps existing highlights. Creating it will cause notes' ' in the existing highlights to be lost. Create it anyway?'), def (yes): if yes: self.send_message( 'apply-highlight-overwrite', style=msg.style, uuid=msg.uuid, existing=msg.existing, has_notes=msg.has_notes) else: if self.current_notes: self.show_editor(self.current_highlight_style, self.current_notes) , ) elif msg.type is 'edit-highlight': if self.state is WAITING: self.create_highlight() elif msg.type is 'edit-highlight-failed': self.report_failed_edit_highlight(msg.uuid) elif msg.type is 'double-click': self.last_double_click_at = window.performance.now() elif msg.type is 'cite-data': annot_id = self.view.currently_showing.selection.annot_id # If selected text is highlighted if annot_id: data = self.annotations_manager.data_for_highlight(annot_id) spine_index = self.view.currently_showing.spine_index cfi = self.annotations_manager.cfi_for_highlight(annot_id, spine_index) if runtime.is_standalone_viewer: url = get_current_link_prefix() + "?open_at=" + cfi else: url = get_current_link_prefix() + f"bookpos={cfi}" for key, value in Object.entries(parse_url_params()): if key != "bookpos": url = url + f"&{key}={value}" info = { "text" : data.highlighted_text, "url": url, "timestamp": data.timestamp, "style_type": data.style.type, "style_kind": data.style.kind, "style_which": data.style.which, "chapter": data.toc_family_titles[0] if data.toc_family_titles[0] else "", "notes": data.notes if "notes" in data else "", } copy_info = get_session_data().get('cite_hl_template').format(**info) # If selected text isn't highlighted else: spine_index = self.view.currently_showing.spine_index spine_index = (1 + spine_index) * 2 cfi = msg.bounds.start link_prefix = get_current_link_prefix() if not link_prefix: return self.view.show_not_a_library_book_error() text = msg.highlighted_text.replace(/\[/g, r'\[').replace(/\]/g, r'\]') url = link_to_epubcfi(f'epubcfi(/{spine_index}{cfi})', link_prefix) info = { "text" : text, "url": url, } copy_info = get_session_data().get('cite_text_template').format(**info) ui_operations.copy_selection(copy_info) else: print('Ignoring annotations message with unknown type:', msg.type) # }}}
48,834
Python
.py
1,068
34.147004
172
0.574532
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,530
gestures.pyj
kovidgoyal_calibre/src/pyj/read_book/gestures.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from read_book.touch import GESTURE from read_book.settings import opts from gettext import gettext as _ def get_action_descriptions(): if not get_action_descriptions.ans: get_action_descriptions.ans = { 'prev_page': { 'short': _('Previous page'), 'long': _('Scroll to the previous page, if more than one page is displayed on the screen only a single page is scrolled') }, 'next_page': { 'short': _('Next page'), 'long': _('Scroll to the next page, if more than one page is displayed on the screen only a single page is scrolled') }, 'prev_screen': { 'short': _('Previous screen'), 'long': _('Scroll to the previous screen, if more than one page is displayed on the screen all pages are scrolled') }, 'next_screen': { 'short': _('Next screen'), 'long': _('Scroll to the next screen, if more than one page is displayed on the screen all pages are scrolled') }, 'show_chrome': { 'short': _('Show controls'), 'long': _('Show the controls for the viewer including Preferences, Go to, etc.') }, 'highlight_or_inspect': { 'short': _('Highlight or inspect'), 'long': _('Highlight the word under the tap point or view the image under the tap or select the highlight under the tap') }, 'decrease_font_size': { 'short': _('Make text smaller'), 'long': _('Decrease the font size') }, 'increase_font_size': { 'short': _('Make text bigger'), 'long': _('Increase the font size') }, 'next_section': { 'short': _('Next chapter'), 'long': _('Scroll to the start of the next section or chapter in the book') }, 'prev_section': { 'short': _('Previous chapter'), 'long': _('Scroll to the start of the previous section or chapter in the book') }, 'pan': { 'short': _('Pan the contents'), 'long': _('Scroll the screen contents in tandem with finger movement') }, 'animated_scroll': { 'short': _('Flick scroll'), 'long': _('Scroll the screen contents with momentum based on how fast you flick your finger') }, 'none': { 'short': _('No action'), 'long': _('Ignore this gesture performing no action in response to it') }, } return get_action_descriptions.ans only_flow_swipe_mode_actions = {'pan': True, 'animated_scroll': True} only_tap_actions = {'highlight_or_inspect': True} default_actions_for_gesture = { 'common': { GESTURE.back_zone_tap: 'prev_page', GESTURE.forward_zone_tap: 'next_page', GESTURE.control_zone_tap: 'show_chrome', GESTURE.long_tap: 'highlight_or_inspect', GESTURE.two_finger_tap: 'show_chrome', GESTURE.pinch_in: 'decrease_font_size', GESTURE.pinch_out: 'increase_font_size', }, 'flow_mode': { GESTURE.swipe_inline_backward_in_progress: 'pan', GESTURE.swipe_inline_forward_in_progress: 'pan', GESTURE.swipe_block_backward_in_progress: 'pan', GESTURE.swipe_block_forward_in_progress: 'pan', GESTURE.flick_block_forward: 'animated_scroll', GESTURE.flick_block_backward: 'animated_scroll', GESTURE.flick_inline_forward: 'animated_scroll', GESTURE.flick_inline_backward: 'animated_scroll', }, 'paged_mode': { GESTURE.flick_block_forward: 'next_section', GESTURE.flick_block_backward: 'prev_section', GESTURE.flick_inline_forward: 'next_screen', GESTURE.flick_inline_backward: 'prev_screen', GESTURE.swipe_inline_forward_hold: 'next_screen', GESTURE.swipe_inline_backward_hold: 'prev_screen', }, } def current_action_for_gesture_type(overrides, gesture_type, in_flow_mode): mode = 'flow_mode' if in_flow_mode else 'paged_mode' mode_overrides = overrides[mode] or {} if mode_overrides[gesture_type]: return mode_overrides[gesture_type] common_overrides = overrides.common or {} if common_overrides[gesture_type]: return common_overrides[gesture_type] if default_actions_for_gesture[mode][gesture_type]: return default_actions_for_gesture[mode][gesture_type] return default_actions_for_gesture.common[gesture_type] or 'none' def action_for_gesture(gesture, in_flow_mode): return current_action_for_gesture_type(opts.gesture_overrides, gesture.type, in_flow_mode) def allowed_actions_for_tap(): return [ac for ac in Object.keys(get_action_descriptions()) if not only_flow_swipe_mode_actions[ac]] def allowed_actions_for_paged_mode_swipe(): return [ac for ac in Object.keys(get_action_descriptions()) if not only_flow_swipe_mode_actions[ac] and not only_tap_actions[ac]] allowed_actions_for_two_fingers = allowed_actions_for_paged_mode_swipe def allowed_actions_for_flow_mode_flick(): return [ac for ac in Object.keys(get_action_descriptions()) if not only_tap_actions[ac]] def allowed_actions_for_flow_mode_drag(): return ['pan', 'none']
5,607
Python
.py
116
38.482759
137
0.608212
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,531
referencing.pyj
kovidgoyal_calibre/src/pyj/read_book/referencing.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> # noqa: eol-semicolon from __python__ import bound_methods, hash_literals from read_book.globals import current_spine_item def elem_for_ref(refnum): refnum = int(refnum) return document.getElementsByTagName('p')[refnum - 1] def start_reference_mode(): si = current_spine_item().index for i, p in enumerate(document.getElementsByTagName('p')): p.dataset.calibreRefNum = f'{si}.{i + 1}' document.body.classList.add('calibre-reference-mode') def end_reference_mode(): document.body.classList.remove('calibre-reference-mode')
658
Python
.py
15
40.333333
72
0.740973
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,532
open_book.pyj
kovidgoyal_calibre/src/pyj/read_book/open_book.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from book_list.item_list import create_item, create_item_list from dom import clear, unique_id from gettext import gettext as _ from read_book.globals import ui_operations from widgets import create_button current_container_id = None current_opened_book_path = None def create_open_book(container, book): nonlocal current_container_id, current_opened_book_path container.appendChild(E.div(style='margin: 1rem', id=unique_id())) container = container.lastChild current_container_id = container.id current_opened_book_path = None if book: current_opened_book_path = book.manifest.pathtoebook rebuild_open_list(container) def rebuild_open_list(container): clear(container) container.appendChild(create_button(_('Open a book from your computer'), action=ui_operations.ask_for_open.bind(None, None))) sd = get_session_data() rl = sd.get('standalone_recently_opened') if rl?.length: container.appendChild(E.div(id=unique_id())) c = container.lastChild items = [] c.appendChild(E.h2(style='margin-top: 1rem', _('Recently viewed books'))) c.appendChild(E.div()) for entry in rl: if current_opened_book_path and current_opened_book_path is entry.pathtoebook: continue if jstype(entry.pathtoebook) is not 'string': continue fname = entry.pathtoebook.replace(/\\/g, '/') if '/' in fname: fname = fname.rpartition('/')[-1] items.push(create_item(entry.title or _('Unknown'), ui_operations.ask_for_open.bind(None, entry.pathtoebook), fname)) create_item_list(c.lastChild, items) c.appendChild(E.div(style='margin: 1rem')) c.lastChild.appendChild( create_button(_('Clear recent list'), action=clear_recent_list.bind(None, c.id))) def clear_recent_list(container_id): sd = get_session_data() sd.set('standalone_recently_opened', v'[]') document.getElementById(container_id).style.display = 'none' def add_book_to_recently_viewed(book): sd = get_session_data() rl = sd.get('standalone_recently_opened') key = book.manifest.pathtoebook new_entry = { 'key': key, 'pathtoebook': book.manifest.pathtoebook, 'title': book.metadata.title, 'authors': book.metadata.authors, 'timestamp': Date().toISOString(), } ans = v'[]' ans.push(new_entry) for entry in rl: if entry.key is not key: ans.push(entry) sd.set('standalone_recently_opened', ans.slice(0, 25)) return ans def remove_recently_opened(path): sd = get_session_data() rl = sd.get('standalone_recently_opened') newl = v'[]' if path: for entry in rl: if entry.key is not path: newl.push(entry) sd.set('standalone_recently_opened', newl) if current_container_id: container = document.getElementById(current_container_id) if container: rebuild_open_list(container)
3,265
Python
.py
78
35.141026
129
0.671919
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,533
shortcuts.pyj
kovidgoyal_calibre/src/pyj/read_book/shortcuts.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from gettext import gettext as _ from read_book.globals import runtime def parse_key_repr(sc): parts = sc.split('+') if sc.endsWith('++'): parts = parts[:-2] parts.push('+') key = parts[-1] ans = {'key': key, 'altKey': False, 'ctrlKey': False, 'metaKey': False, 'shiftKey': False} for modifier in parts[:-1]: q = modifier.toLowerCase() if q is 'ctrl': ans.ctrlKey = True elif q is 'alt': ans.altKey = True elif q is 'meta' or q is 'cmd': ans.metaKey = True elif q is 'shift': ans.shiftKey = True return ans def desc(sc, group, short, long): if jstype(sc) is 'string': sc = v'[sc]' pkey = v'[]' for x in sc: pkey.push(parse_key_repr(x)) return {'group': group, 'short': short, 'long': long, 'shortcuts': pkey} def keyevent_as_shortcut(evt): key = evt.key if capital_letters[key] and evt.shiftKey: key = key.toLowerCase() return { 'key': key, 'altKey': evt.altKey, 'ctrlKey': evt.ctrlKey, 'metaKey': evt.metaKey, 'shiftKey': evt.shiftKey } def shortcut_differs(a, b): return not (a.key is b.key and a.altKey is b.altKey and a.ctrlKey is b.ctrlKey and a.metaKey is b.metaKey and a.shiftKey is b.shiftKey) capital_letters = {x: True for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} def get_key_text(evt): key = evt.key if key: # on Windows pressing ctrl+alt+ascii char gives capital letters. On all # platforms shift+key gives capital letters we define shortcuts using # lowercase letters, so lowercase them here. if evt.code and key.toLowerCase() is not key and evt.code.startsWith('Key') and capital_letters[key]: key = key.toLowerCase() return key def keyevent_to_index(evt): parts = v'[]' for mod in v"['altKey', 'ctrlKey', 'metaKey', 'shiftKey']": parts.push('y' if evt[mod] else 'n') return parts.join('') + get_key_text(evt) def key_as_text(evt): mods = v'[]' for x in ('alt', 'ctrl', 'meta', 'shift'): if evt[x + 'Key']: if 'macos' in window.navigator.userAgent: if x is 'alt': x = 'option' elif x is 'meta': x = '⌘' mods.push(x.capitalize()) mods = '+'.join(mods) if mods: mods += '+' key = get_key_text(evt) if key is ' ': key = 'Space' return mods + key def common_shortcuts(): # {{{ return { 'start_of_file': desc( v"['Ctrl+ArrowUp', 'Ctrl+ArrowLeft', 'Home']", 'scroll', _('Scroll to the beginning of the current file'), _('When the e-book is made of multiple individual files, scroll to the start of the current file'), ), 'start_of_book': desc( 'Ctrl+Home', 'scroll', _('Scroll to the beginning of the book'), ), 'end_of_book': desc( 'Ctrl+End', 'scroll', _('Scroll to the end of the book'), ), 'end_of_file': desc( v"['Ctrl+ArrowDown', 'Ctrl+ArrowRight', 'End']", 'scroll', _('Scroll to the end of the current file'), _('When the e-book is made of multiple individual files, scroll to the end of the current file'), ), 'up': desc( 'ArrowUp', 'scroll', _('Scroll backwards smoothly (by screen-fulls in paged mode)'), _('Scroll backwards, smoothly in flow mode and by screen fulls in paged mode'), ), 'down': desc( 'ArrowDown', 'scroll', _('Scroll forwards smoothly (by screen-fulls in paged mode)'), _('Scroll forwards, smoothly in flow mode and by screen fulls in paged mode'), ), 'left': desc( 'ArrowLeft', 'scroll', _('Scroll left'), _('Scroll leftwards by a little in flow mode and by a page in paged mode'), ), 'right': desc( 'ArrowRight', 'scroll', _('Scroll right'), _('Scroll rightwards by a little in flow mode and by a page in paged mode'), ), 'pageup': desc( v"['PageUp', 'Shift+ ']", 'scroll', _('Scroll backwards by screen-fulls'), ), 'pagedown': desc( v"[' ', 'PageDown']", 'scroll', _('Scroll forwards by screen-fulls'), ), 'previous_section': desc( 'Ctrl+PageUp', 'scroll', _('Scroll to the previous section') ), 'next_section': desc( 'Ctrl+PageDown', 'scroll', _('Scroll to the next section') ), 'back': desc( v"['Alt+ArrowLeft']", 'scroll', _('Back'), ), 'forward': desc( v"['Alt+ArrowRight']", 'scroll', _('Forward'), ), 'toggle_toc': desc( 'Ctrl+t', 'ui', _('Show/hide Table of Contents'), ), 'read_aloud': desc( 'Ctrl+s', 'ui', _('Read aloud') ), 'toggle_hints': desc( 'Alt+f', 'ui', _('Follow links with the keyboard') ), 'copy_to_clipboard': desc( v"['Ctrl+c', 'Meta+c']", 'ui', _('Copy to clipboard'), ), 'copy_location_to_clipboard': desc( v"['Alt+c']", 'ui', _('Copy current location to clipboard'), ), 'copy_location_as_url_to_clipboard': desc( v"['Ctrl+Shift+c']", 'ui', _('Copy current location as calibre:// URL to clipboard'), ), 'start_search': desc( v"['/', 'Ctrl+f', 'Cmd+f']", 'ui', _('Start search'), ), 'next_match': desc( v"['F3', 'Enter']", 'ui', _('Find next'), ), 'previous_match': desc( v"['Shift+F3', 'Shift+Enter']", 'ui', _('Find previous'), ), 'increase_font_size': desc( v"['Ctrl+=', 'Ctrl++', 'Ctrl+Shift++', 'Ctrl+Shift+=', 'Meta++', 'Meta+Shift++', 'Meta+Shift+=']", 'ui', _('Increase font size'), ), 'decrease_font_size': desc( v"['Ctrl+-', 'Ctrl+_', 'Ctrl+Shift+-', 'Ctrl+Shift+_', 'Meta+-', 'Meta+_']", 'ui', _('Decrease font size'), ), 'default_font_size': desc( "Ctrl+0", 'ui', _('Restore default font size'), ), 'increase_number_of_columns': desc( v"['Ctrl+]']", 'ui', _('Increase number of pages per screen'), ), 'decrease_number_of_columns': desc( v"['Ctrl+[']", 'ui', _('Decrease number of pages per screen'), ), 'reset_number_of_columns': desc( v"['Ctrl+Alt+c']", 'ui', _('Make number of pages per screen automatic'), ), 'toggle_full_screen': desc( v"['F11', 'Ctrl+Shift+f']", 'ui', _('Toggle full screen'), ), 'toggle_paged_mode': desc( 'Ctrl+m', 'ui', _('Toggle between Paged mode and Flow mode for text layout') ), 'toggle_scrollbar': desc( 'Ctrl+w', 'ui', _('Toggle the scrollbar') ), 'toggle_reference_mode': desc( 'Ctrl+x', 'ui', _('Toggle the Reference mode') ), 'toggle_bookmarks': desc( v"['Ctrl+b']", 'ui', _('Show/hide bookmarks'), ), 'new_bookmark': desc( v"['Ctrl+Alt+b']", 'ui', _('Create a new bookmark'), ), 'metadata': desc( v"['Ctrl+n', 'Ctrl+e']", 'ui', _('Show the book metadata') ), 'show_profiles': desc( v"['Alt+p']", 'ui', _('Change settings quickly by creating and switching to "profiles"') ), 'reload_book': desc( v"['Ctrl+Alt+F5', 'Ctrl+Alt+r']", 'ui', _('Reload book'), ), 'extend_selection_by_word': desc( v"['Ctrl+Shift+ArrowRight']", 'ui', _('Alter the current selection forward by a word'), ), 'shrink_selection_by_word': desc( v"['Ctrl+Shift+ArrowLeft']", 'ui', _('Alter the current selection backwards by a word'), ), 'extend_selection_by_character': desc( v"['Shift+ArrowRight']", 'ui', _('Alter the current selection forward by a character'), ), 'shrink_selection_by_character': desc( v"['Shift+ArrowLeft']", 'ui', _('Alter the current selection backwards by a character'), ), 'extend_selection_by_line': desc( v"['Shift+ArrowDown']", 'ui', _('Alter the current selection forward by a line'), ), 'extend_selection_to_start_of_line': desc( v"['Shift+Home']", 'ui', _('Extend the current selection to the start of the line'), ), 'extend_selection_to_end_of_line': desc( v"['Shift+End']", 'ui', _('Extend the current selection to the end of the line'), ), 'select_all': desc( v'["Ctrl+a"]', 'ui', _('Select all') ), 'shrink_selection_by_line': desc( v"['Shift+ArrowUp']", 'ui', _('Alter the current selection backwards by a line'), ), 'extend_selection_by_paragraph': desc( v"['Ctrl+Shift+ArrowDown']", 'ui', _('Alter the current selection forward by a paragraph'), ), 'shrink_selection_by_paragraph': desc( v"['Ctrl+Shift+ArrowUp']", 'ui', _('Alter the current selection backwards by a paragraph'), ), 'show_chrome': desc( v"['Escape', 'ContextMenu']", 'ui', _('Show the E-book viewer controls'), ), 'preferences': desc( v"['Ctrl+,', 'Ctrl+Escape', 'Meta+Escape', 'Meta+,']", 'ui', _('Show E-book viewer preferences'), ), 'goto_location': desc( v"[';', ':', 'Shift+:', 'Shift+;', 'Ctrl+g']", 'ui', _('Go to a specified book location or position'), ), 'toggle_autoscroll': desc( "Ctrl+ ", 'scroll', _('Toggle auto-scroll'), ), 'scrollspeed_increase': desc( "Alt+ArrowUp", 'scroll', _('Auto scroll faster'), ), 'scrollspeed_decrease': desc( "Alt+ArrowDown", 'scroll', _('Auto scroll slower'), ), } # }}} def shortcuts_definition(): ans = shortcuts_definition.ans if not ans: ans = shortcuts_definition.ans = common_shortcuts() if runtime.is_standalone_viewer: add_standalone_viewer_shortcuts(ans) else: ans['sync_book'] = desc( v"[]", 'ui', _('Sync last read position/annotations'), ) return ans def shortcuts_group_desc(): ans = shortcuts_group_desc.ans if not ans: ans = shortcuts_group_desc.ans = { 'scroll': _('Navigation'), 'ui': _('Interface'), } return ans def add_standalone_viewer_shortcuts(sc): ismacos = 'macos' in window.navigator.userAgent sc['toggle_inspector'] = desc( v"['Ctrl+i']", 'ui', _('Show/hide Inspector'), ) sc['toggle_lookup'] = desc( v"['Ctrl+l']", 'ui', _('Show/hide the word lookup panel'), ) quit_shortcut = 'Meta+q' if ismacos else 'Ctrl+q' sc['quit'] = desc( quit_shortcut, 'ui', _('Quit the E-book viewer'), ) sc['print'] = desc( "Ctrl+p", 'ui', _('Print book to PDF'), ) sc['toggle_toolbar'] = desc( "Ctrl+F11", 'ui', _('Toggle the toolbar'), ) sc['toggle_highlights'] = desc( "Ctrl+h", 'ui', _('Toggle the highlights panel') ) sc['edit_book'] = desc( "Ctrl+d", 'ui', _('Edit this book') ) def create_shortcut_map(custom_shortcuts): ans = {} scd = shortcuts_definition() for sc_name in Object.keys(scd): entry = scd[sc_name] shortcuts = entry.shortcuts if custom_shortcuts and custom_shortcuts[sc_name]: shortcuts = custom_shortcuts[sc_name] for sc in shortcuts: ans[keyevent_to_index(sc)] = sc_name return ans def shortcut_for_key_event(evt, shortcut_map): idx = keyevent_to_index(evt) return shortcut_map[idx]
12,517
Python
.py
429
21.594406
139
0.526935
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,534
ui.pyj
kovidgoyal_calibre/src/pyj/read_book/ui.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # globals: __RENDER_VERSION__ from __python__ import hash_literals from elementmaker import E import traceback from ajax import ajax, ajax_send from book_list.constants import read_book_container_id from book_list.library_data import current_library_id, library_data from book_list.router import home, push_state, read_book_mode, update_window_title from book_list.ui import show_panel from dom import clear from gettext import gettext as _ from modals import create_simple_dialog_markup, error_dialog from read_book.db import get_db from read_book.globals import ui_operations from read_book.tts import Client from read_book.view import View from session import get_interface_data from utils import debounce, full_screen_element, human_readable, request_full_screen from widgets import create_button from image_popup import show_image RENDER_VERSION = __RENDER_VERSION__ MATHJAX_VERSION = "__MATHJAX_VERSION__" class ReadUI: def __init__(self): self.base_url_data = {} self.current_metadata = {'title': _('Unknown book')} self.current_book_id = None self.manifest_xhr = None self.pending_load = None self.downloads_in_progress = [] self.progress_id = 'book-load-progress' self.display_id = 'book-iframe-container' self.error_id = 'book-global-error-container' self.stacked_widgets = [self.progress_id, self.display_id, self.error_id] container = document.getElementById(read_book_container_id) container.appendChild(E.div( id=self.progress_id, style='display:none; text-align: center', E.h3(style='margin-top:30vh; margin-bottom: 1ex;'), E.progress(style='margin: 1ex'), E.div(style='margin: 1ex') )) container.appendChild(E.div( id=self.error_id, style='display:none;', )) container.appendChild(E.div( id=self.display_id, style='display:none', )) self.view = View(container.lastChild) self.tts_client = Client() self.windows_to_listen_for_messages_from = [] window.addEventListener('resize', debounce(self.on_resize.bind(self), 250)) window.addEventListener('message', self.message_from_other_window.bind(self)) self.db = get_db(self.db_initialized.bind(self), self.show_error.bind(self)) ui_operations.get_file = self.db.get_file ui_operations.get_mathjax_files = self.db.get_mathjax_files ui_operations.update_url_state = self.update_url_state.bind(self) ui_operations.update_last_read_time = self.db.update_last_read_time ui_operations.show_error = self.show_error.bind(self) ui_operations.update_reading_rates = self.update_reading_rates.bind(self) ui_operations.redisplay_book = self.redisplay_book.bind(self) ui_operations.reload_book = self.reload_book.bind(self) ui_operations.forward_gesture = self.forward_gesture.bind(self) ui_operations.update_color_scheme = self.update_color_scheme.bind(self) ui_operations.update_font_size = self.update_font_size.bind(self) ui_operations.goto_cfi = self.goto_cfi.bind(self) ui_operations.goto_frac = self.goto_frac.bind(self) ui_operations.goto_book_position = self.goto_book_position.bind(self) ui_operations.goto_reference = self.goto_reference.bind(self) ui_operations.delete_book = self.delete_book.bind(self) ui_operations.focus_iframe = self.focus_iframe.bind(self) ui_operations.toggle_toc = self.toggle_toc.bind(self) ui_operations.toggle_full_screen = self.toggle_full_screen.bind(self) ui_operations.annots_changed = self.annots_changed.bind(self) ui_operations.annotations_synced = self.annotations_synced.bind(self) ui_operations.wait_for_messages_from = self.wait_for_messages_from.bind(self) ui_operations.stop_waiting_for_messages_from = self.stop_waiting_for_messages_from.bind(self) ui_operations.update_metadata = self.update_metadata.bind(self) ui_operations.close_book = self.close_book.bind(self) ui_operations.copy_image = self.copy_image.bind(self) ui_operations.view_image = self.view_image.bind(self) ui_operations.speak_simple_text = self.speak_simple_text.bind(self) ui_operations.tts = self.tts.bind(self) ui_operations.search_result_discovered = self.view.search_overlay.search_result_discovered ui_operations.search_result_not_found = self.view.search_overlay.search_result_not_found ui_operations.find_next = self.view.search_overlay.find_next ui_operations.open_url = def(url): window.open(url, '_blank') ui_operations.show_help = def(which): if which is 'viewer': path = '/viewer.html' else: return if get_interface_data().lang_code_for_user_manual: path = f'/{get_interface_data().lang_code_for_user_manual}{path}' url = 'https://manual.calibre-ebook.com' + path window.open(url, '_blank') ui_operations.copy_selection = def(text, html): # try using document.execCommand which on chrome allows the # copy on non-secure origin if this is close to a user # interaction event active_elem = document.activeElement ta = document.createElement("textarea") ta.value = text ta.style.position = 'absolute' ta.style.top = window.innerHeight + 'px' ta.style.left = window.innerWidth + 'px' document.body.appendChild(ta) ta.focus() ta.select() ok = False try: ok = document.execCommand('copy') except: pass document.body.removeChild(ta) if active_elem: active_elem.focus() if ok: return if not window.navigator.clipboard: return error_dialog(_('No clipboard access'), _( 'Your browser requires you to access the Content server over an HTTPS connection' ' to be able to copy to clipboard.')) window.navigator.clipboard.writeText(text or '').then(def (): pass;, def(): error_dialog(_('Could not copy to clipboard'), _('No permission to write to clipboard')) ) ui_operations.get_all_profiles = def(proceed): ajax('reader-profiles/get-all', def(end_type, xhr, ev): if end_type is not 'load': if end_type is 'abort': return return self.show_error(_('Failed to load profiles'), _( 'Could not load profiles: with error: {}').format(xhr.error_html)) try: result = JSON.parse(xhr.responseText) except Exception: return self.show_error(_('Failed to parse profiles'), _('Unparseable data received for profiles')) proceed(result) ).send() ui_operations.save_profile = def(profile_name, profile, proceed): ajax_send('reader-profiles/save', {'name': profile_name, 'profile': profile}, def(end_type, xhr, ev): if end_type is not 'load': if end_type is 'abort': return return self.show_error(_('Failed to load profiles'), _( 'Could not load profiles: with error: {}').format(xhr.error_html)) proceed() ) def on_resize(self): self.view.on_resize() def show_stack(self, name): ans = None for w in self.stacked_widgets: d = document.getElementById(w) v = 'none' if name is w: ans = d v = 'block' d.style.display = v return ans def show_error(self, title, msg, details): div = self.show_stack(self.error_id) clear(div) if self.current_metadata: book = self.current_metadata.title elif self.current_book_id: book = _('Book id #{}').format(self.current_book_id) else: book = _('book') div.appendChild(E.div(style='padding: 2ex 2rem; display:table; margin: auto')) div = div.lastChild dp = E.div() create_simple_dialog_markup(title, _('Could not open {}. {}').format(book, msg), details, 'bug', '', 'red', dp) div.appendChild(dp) div.appendChild(E.div( style='margin-top: 1ex; padding-top: 1ex; border-top: solid 1px currentColor', _('Go back to:'), E.br(), E.br(), create_button(_('Home'), 'home', def(): home(True);), )) q = {} if self.current_book_id: q.book_id = self.current_book_id + '' q.close_action = 'home' div.lastChild.appendChild(E.span( '\xa0', create_button(_('Book list'), 'library', def(): show_panel('book_list', q, True);), )) if self.current_book_id: q.close_action = 'book_list' div.lastChild.appendChild(E.span( '\xa0', create_button(_('Book details'), 'book', def(): show_panel('book_details', q, True);), )) def init_ui(self): div = self.show_stack(self.progress_id) if self.current_metadata: div.firstChild.textContent = _( 'Downloading {0} for offline reading, please wait...').format(self.current_metadata.title) else: div.firstChild.textContent = '' pr = div.firstChild.nextSibling pr.removeAttribute('value'), pr.removeAttribute('max') div.lastChild.textContent = _('Downloading book manifest...') def show_progress_message(self, msg): div = document.getElementById(self.progress_id) div.lastChild.textContent = msg or '' def close_book(self): self.base_url_data = {} def copy_image(self, image_file_name): if not self.view?.book: return ui_operations.get_file( self.view.book, image_file_name, def(blob, name, mimetype): try: window.navigator.clipboard.write([new ClipboardItem({mimetype: blob})]) # noqa except Exception as err: error_dialog(_('Could not copy image'), str(err)) ) def view_image(self, image_file_name): if not self.view?.book: return ui_operations.get_file( self.view.book, image_file_name, def(blob, name, mimetype): url = window.URL.createObjectURL(blob) show_image(url) ) def load_book(self, library_id, book_id, fmt, metadata, force_reload): self.base_url_data = {'library_id': library_id, 'book_id':book_id, 'fmt':fmt} if not self.db.initialized: self.pending_load = [book_id, fmt, metadata, force_reload] return if not self.db.is_ok: self.show_error(_('Cannot read books'), self.db.initialize_error_msg) return self.start_load(book_id, fmt, metadata, force_reload) def reload_book(self): library_id, book_id, fmt = self.base_url_data.library_id, self.base_url_data.book_id, self.base_url_data.fmt metadata = self.metadata or library_data.metadata[book_id] self.load_book(library_id, book_id, fmt, metadata, True) def redisplay_book(self): self.view.redisplay_book() def forward_gesture(self, gesture): self.view.forward_gesture(gesture) def update_font_size(self): self.view.update_font_size() def goto_cfi(self, bookpos): return self.view.goto_cfi(bookpos) def goto_frac(self, frac): return self.view.goto_frac(frac) def goto_book_position(self, bpos): return self.view.goto_book_position(bpos) def goto_reference(self, ref): return self.view.goto_reference(ref) def delete_book(self, book, proceed): self.db.delete_book(book, proceed) def focus_iframe(self): self.view.focus_iframe() def toggle_toc(self): self.view.overlay.show_toc() def toggle_full_screen(self): if full_screen_element(): document.exitFullscreen() else: request_full_screen(document.documentElement) def update_color_scheme(self): self.view.update_color_scheme() def annots_changed(self, amap): library_id = self.base_url_data.library_id book_id = self.base_url_data.book_id fmt = self.base_url_data.fmt self.db.update_annotations_data_from_key(library_id, book_id, fmt, {'annotations_map': amap}) ajax_send(f'book-update-annotations/{library_id}/{book_id}/{fmt}', amap, def (): pass;) def annotations_synced(self, amap): library_id = self.base_url_data.library_id book_id = self.base_url_data.book_id fmt = self.base_url_data.fmt self.db.update_annotations_data_from_key(library_id, book_id, fmt, {'annotations_map': amap}) @property def url_data(self): ans = {'library_id':self.base_url_data.library_id, 'book_id':self.base_url_data.book_id, 'fmt': self.base_url_data.fmt} bookpos = self.view.currently_showing.bookpos if bookpos: ans.bookpos = bookpos return ans def db_initialized(self): if not self.db.is_ok: error_dialog(_('Could not initialize database'), self.db.initialize_error_msg) return if self.pending_load is not None: pl, self.pending_load = self.pending_load, None if self.db.initialize_error_msg: self.show_error(_('Failed to initialize IndexedDB'), self.db.initialize_error_msg) else: self.start_load(*pl) def start_load(self, book_id, fmt, metadata, force_reload): self.current_book_id = book_id self.current_book_fmt = fmt metadata = metadata or library_data.metadata[book_id] self.current_metadata = metadata or {'title':_('Book id #') + book_id} update_window_title('', self.current_metadata.title) self.init_ui() if jstype(self.db) is 'string': self.show_error(_('Cannot read book'), self.db) return self.db.get_book(current_library_id(), book_id, fmt, metadata, self.got_book.bind(self, force_reload)) def got_book(self, force_reload, book): if not book.manifest or book.manifest.version is not RENDER_VERSION or not book.is_complete: # We re-download the manifest when the book is not complete to ensure we have the # correct manifest, even though doing so is not strictly necessary self.get_manifest(book, force_reload) else: self.display_book(book) def get_manifest(self, book, force_reload): library_id, book_id, fmt = book.key if self.manifest_xhr: self.manifest_xhr.abort() query = {'library_id': library_id} if force_reload: query.force_reload = '1' self.manifest_xhr = ajax(('book-manifest/' + encodeURIComponent(book_id) + '/' + encodeURIComponent(fmt)), self.got_manifest.bind(self, book), query=query) self.manifest_xhr.send() def got_manifest(self, book, end_type, xhr, ev): self.manifest_xhr = None if end_type is 'abort': return if end_type is not 'load': if xhr.status is 404: fmt = (self.current_book_fmt or 'UNKNOWN').toUpperCase() if 'cannot be viewed' in xhr.error_html: return self.show_error( _('Failed to view book'), _('Viewing of the {} format is not supported.').format(fmt), xhr.error_html) return self.show_error(_('Failed to view book'), _('The {} format is not available.').format(fmt), xhr.error_html) return self.show_error(_('Failed to load book manifest'), _('The book manifest failed to load, click "Show details" for more information.').format(title=self.current_metadata.title), xhr.error_html) try: manifest = JSON.parse(xhr.responseText) except Exception: return self.show_error(_('Failed to load book manifest'), _('The manifest for {title} is not valid').format(title=self.current_metadata.title), traceback.format_exc()) if manifest.version is not undefined: if manifest.version is not RENDER_VERSION: print('calibre upgraded: RENDER_VERSION={} manifest.version={}'.format(RENDER_VERSION, manifest.version)) return self.show_error(_('calibre upgraded!'), _( 'A newer version of calibre is available, please click the Reload button in your browser.')) self.current_metadata = manifest.metadata self.db.save_manifest(book, manifest, self.download_book.bind(self, book)) return # Book is still being processed msg = _('Downloading book manifest...') if manifest.job_status is 'finished': if manifest.aborted: return self.show_error(_('Failed to prepare book for reading'), _('Preparation of book for reading was aborted because it took too long')) if manifest.traceback: return self.show_error(_('Failed to prepare book for reading'), _( 'There was an error processing the book, click "Show details" for more information'), manifest.traceback or '') elif manifest.job_status is 'waiting': msg = _('Book is queued for processing on the server...') elif manifest.job_status is 'running': msg = _('Book is being prepared for reading on the server...') self.show_progress_message(msg) setTimeout(self.get_manifest.bind(self, book), 100) def download_book(self, book): files = book.manifest.files total = 0 cover_total_updated = False for name in files: total += files[name].size files_left = set(book.manifest.files) failed_files = [] for xhr in self.downloads_in_progress: xhr.abort() self.downloads_in_progress = [] progress = document.getElementById(self.progress_id) pbar = progress.firstChild.nextSibling library_id, book_id, fmt = book.key base_path = 'book-file/{}/{}/{}/{}/'.format(encodeURIComponent(book_id), encodeURIComponent(fmt), encodeURIComponent(book.manifest.book_hash.size), encodeURIComponent(book.manifest.book_hash.mtime)) query = {'library_id': library_id} progress_track = {} pbar.setAttribute('max', total + '') raster_cover_name = book.manifest.raster_cover_name if not raster_cover_name: nnum = 1 base = 'raster-cover-image-{}.jpg' inserted_name = base.format(nnum) while inserted_name in files_left: nnum += 1 inserted_name = base.format(nnum) raster_cover_name = inserted_name files_left.add(raster_cover_name) raster_cover_size = 0 def update_progress(): x = 0 for name in progress_track: x += progress_track[name] pbar.setAttribute('value', x + '') if x is total: msg = _('Downloaded {}, saving to disk. This may take a few seconds...').format(human_readable(total)) else: msg = _('Downloaded {0}, {1} left').format(human_readable(x), human_readable(total - x)) progress.lastChild.textContent = msg def show_failure(): det = ['<h4>{}</h4><div>{}</div><hr>'.format(fname, err_html) for fname, err_html in failed_files].join('') self.show_error(_('Could not download book'), _( 'Failed to download some book data, click "Show details" for more information'), det) def on_stored(err): files_left.discard(this) if err: failed_files.append([this, err]) if len(files_left): return if failed_files.length: return show_failure() self.db.finish_book(book, self.display_book.bind(self, book)) def on_complete(end_type, xhr, ev): self.downloads_in_progress.remove(xhr) progress_track[this] = raster_cover_size if this is raster_cover_name else files[this].size update_progress() if len(queued): for fname in queued: start_download(fname, base_path + encodeURIComponent(fname).replace(/%2[fF]/g, '/')) queued.discard(fname) break if end_type is 'abort': files_left.discard(this) return if end_type is 'load': self.db.store_file(book, this, xhr, on_stored.bind(this), this is raster_cover_name) else: failed_files.append([this, xhr.error_html]) files_left.discard(this) if not len(files_left): show_failure() def on_progress(loaded, ftotal): nonlocal total, cover_total_updated, raster_cover_size if this is raster_cover_name and not cover_total_updated: raster_cover_size = ftotal cover_total_updated = True total = total - (files[raster_cover_name]?.size or 0) + raster_cover_size pbar.setAttribute('max', total + '') progress_track[this] = loaded update_progress() def start_download(fname, path): xhr = ajax(path, on_complete.bind(fname), on_progress=on_progress.bind(fname), query=query, progress_totals_needed=fname is raster_cover_name) xhr.responseType = 'text' if not book.manifest.files[fname]?.is_virtualized: xhr.responseType = 'blob' if self.db.supports_blobs else 'arraybuffer' xhr.send() self.downloads_in_progress.append(xhr) if raster_cover_name: start_download(raster_cover_name, 'get/cover/' + book_id + '/' + encodeURIComponent(library_id)) count = 0 queued = set() for fname in files_left: if fname is not raster_cover_name: count += 1 # Chrome starts killing AJAX requests if there are too many in flight, unlike Firefox # which is smart enough to queue them if count < 20: start_download(fname, base_path + encodeURIComponent(fname).replace(/%2[fF]/g, '/')) else: queued.add(fname) def ensure_maths(self, proceed): self.db.get_mathjax_info(def(mathjax_info): if mathjax_info.version is MATHJAX_VERSION: return proceed() print('Upgrading MathJax, previous version:', mathjax_info.version) self.db.clear_mathjax(def(): self.get_mathjax_manifest(mathjax_info, proceed) ) ) def get_mathjax_manifest(self, mathjax_info, proceed): ajax('mathjax', def(end_type, xhr, event): if end_type is 'abort': return if end_type is not 'load': return self.show_error(_('Failed to load MathJax manifest'), _('The MathJax manifest failed to load, click "Show details" for more information.').format(title=self.current_metadata.title), xhr.error_html) try: manifest = JSON.parse(xhr.responseText) except Exception: return self.show_error(_('Failed to load MathJax manifest'), _('The MathJax manifest is not valid'), traceback.format_exc()) if manifest.etag is not MATHJAX_VERSION: print('calibre upgraded: MATHJAX_VERSION={} manifest.etag={}'.format(MATHJAX_VERSION, manifest.etag)) return self.show_error(_('calibre upgraded!'), _( 'A newer version of calibre is available, please click the Reload button in your browser.')) mathjax_info.version = manifest.etag mathjax_info.files = manifest.files self.download_mathjax(mathjax_info, proceed) ).send() def download_mathjax(self, mathjax_info, proceed): files = mathjax_info.files total = 0 progress_track = {} files_left = set() failed_files = [] for key in files: total += files[key] progress_track[key] = 0 files_left.add(key) progress = document.getElementById(self.progress_id) progress.firstChild.textContent = _( 'Downloading MathJax to render mathematics in this book...') pbar = progress.firstChild.nextSibling pbar.setAttribute('max', total + '') for xhr in self.downloads_in_progress: xhr.abort() self.downloads_in_progress = [] def update_progress(): x = 0 for name in progress_track: x += progress_track[name] pbar.setAttribute('value', x + '') if x is total: msg = _('Downloaded {}, saving to disk. This may take a few seconds...').format(human_readable(total)) else: msg = _('Downloaded {0}, {1} left').format(human_readable(x), human_readable(total - x)) progress.lastChild.textContent = msg def on_progress(loaded, ftotal): progress_track[this] = loaded update_progress() def show_failure(): det = ['<h4>{}</h4><div>{}</div><hr>'.format(fname, err_html) for fname, err_html in failed_files].join('') self.show_error(_('Could not download MathJax'), _( 'Failed to download some MathJax data, click "Show details" for more information'), det) def on_complete(end_type, xhr, ev): self.downloads_in_progress.remove(xhr) progress_track[this] = files[this] update_progress() if end_type is 'abort': files_left.discard(this) return if end_type is 'load': self.db.store_mathjax_file(this, xhr, on_stored.bind(this)) else: failed_files.append([this, xhr.error_html]) files_left.discard(this) if not len(files_left): show_failure() def on_stored(err): files_left.discard(this) if err: failed_files.append([this, err]) if len(files_left): return if failed_files.length: return show_failure() self.db.finish_mathjax(mathjax_info, proceed) def start_download(name): path = 'mathjax/' + name xhr = ajax(path, on_complete.bind(name), on_progress=on_progress.bind(name), progress_totals_needed=False) xhr.responseType = 'blob' if self.db.supports_blobs else 'arraybuffer' xhr.send() self.downloads_in_progress.push(xhr) for fname in files_left: start_download(fname) def display_book(self, book): if book.manifest.has_maths: self.ensure_maths(self.display_book_stage2.bind(self, book)) else: self.display_book_stage2(book) def display_book_stage2(self, book): self.current_metadata = book.metadata update_window_title('', self.current_metadata.title) self.show_stack(self.display_id) self.view.display_book(book) def apply_url_state(self, current_query): same = True current_state = self.url_data same = current_query.library_id is current_state.library_id and str(current_query.book_id) is str(current_state.book_id) and current_query.fmt is current_state.fmt self.view.overlay.hide() window.scrollTo(0, 0) # Ensure we are at the top of the window if same: if current_state.bookpos is not current_query.bookpos and current_query.bookpos: self.view.goto_cfi(current_query.bookpos) else: self.load_book(current_query.library_id, int(current_query.book_id), current_query.fmt, library_data.metadata[current_query.book_id]) def update_url_state(self, replace): push_state(self.url_data, replace=replace, mode=read_book_mode) def update_metadata(self, book, metadata): self.db.update_metadata(book, metadata) def wait_for_messages_from(self, w, callback): self.windows_to_listen_for_messages_from.push(v'[w, callback]') def stop_waiting_for_messages_from(self, w): self.windows_to_listen_for_messages_from = [x for x in self.windows_to_listen_for_messages_from if x[0] is not w] def message_from_other_window(self, msg): if not self.windows_to_listen_for_messages_from.length: return old = self.windows_to_listen_for_messages_from for x in old: w, callback = x if w is msg.source: callback(msg) def check_for_speech_capability(self): if not window.speechSynthesis: error_dialog(_('No speech support'), _( 'Your browser does not have support for Text-to-Speech')) return False return True def speak_simple_text(self, text): if not self.check_for_speech_capability(): return self.tts_client.speak_simple_text(text) def tts(self, event, data): if not self.check_for_speech_capability(): return if event is 'play': self.tts_client.speak_marked_text(data.marked_text, self.view.read_aloud.handle_tts_event) else: getattr(self.tts_client, event)() def update_reading_rates(self, rates): if not self.view?.book: return book = self.view.book self.db.save_reading_rates(book, rates)
30,667
Python
.py
620
37.993548
171
0.60321
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,535
__init__.pyj
kovidgoyal_calibre/src/pyj/read_book/__init__.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
101
Python
.py
2
48
72
0.770833
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,536
highlights.pyj
kovidgoyal_calibre/src/pyj/read_book/highlights.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from ajax import encode_query from book_list.globals import get_current_query, get_session_data from book_list.theme import get_color from complete import create_search_bar from dom import add_extra_css, build_rule, clear, svgicon, unique_id from gettext import gettext as _, ngettext from modals import ( create_custom_dialog, error_dialog, get_text_dialog, question_dialog, warning_dialog ) from read_book.globals import current_book, is_dark_theme, runtime, ui_operations from widgets import create_button ICON_SIZE_VAL = 3 ICON_SIZE_UNIT = 'ex' ICON_SIZE = f'{ICON_SIZE_VAL}{ICON_SIZE_UNIT}' builtin_colors_light = v'''__BUILTIN_COLORS_LIGHT__''' builtin_colors_dark = v'''__BUILTIN_COLORS_DARK__''' builtin_decorations_light = builtin_decorations_dark = v'''__BUILTIN_DECORATIONS__''' def builtin_friendly_name(kind, which): if kind is 'color': return { 'yellow': _('Yellow highlight'), 'green': _('Green highlight'), 'blue': _('Blue highlight'), 'red': _('Pink highlight'), 'purple': _('Purple highlight'), }[which] or _('Unknown highlight') return { 'wavy': _('Red wavy underline'), 'strikeout': _('Red strikeout'), }[which] or _('Unknown underline') def builtin_color(which, is_dark): return (builtin_colors_dark[which] if is_dark else builtin_colors_light[which]) or builtin_colors_light.yellow def default_color(is_dark): return builtin_color('yellow', is_dark) def all_builtin_styles(): ans = v'[]' for col in builtin_colors_light: ans.push({'type': 'builtin', 'kind': 'color', 'which': col}) for which in builtin_decorations_light: ans.push({'type': 'builtin', 'kind': 'decoration', 'which': which}) return ans all_style_keys = v"'type kind which light dark background-color text-decoration-line text-decoration-color text-decoration-style'.split(' ')" def custom_color_theme(name, lightbg, darkbg): return {'type': 'custom', 'kind': 'color', 'light': lightbg, 'dark': darkbg, 'friendly_name': name} def custom_decoration_theme(name, line_position, line_style, line_color): return { 'type': 'custom', 'kind': 'decoration', 'text-decoration-line': line_position, 'text-decoration-style': line_style, 'text-decoration-color': line_color, 'friendly_name': name } def style_key(style): return [f'{k}:{style[k]}' for k in all_style_keys].join(';') class HighlightStyle: def __init__(self, style): if jstype(style) is 'string': style = JSON.parse(style) self.style = style or {'type': 'builtin', 'kind': 'color', 'which': 'yellow'} self.key = style_key(self.style) def make_swatch(self, container, is_dark): style = container.style style.width = style.height = style.minimumWidth = style.minimumHeight = style.maximumWidth = style.maximumHeight = ICON_SIZE s = self.style br = ICON_SIZE_VAL / 4 if s.kind is 'decoration': tdl = tds = tdc = None if s.type is 'builtin': q = builtin_decorations_dark[s.which] if is_dark else builtin_decorations_dark[s.which] else: q = s tdl = q['text-decoration-line'] or None tds = q['text-decoration-style'] or None tdc = q['text-decoration-color'] or None container.textContent = 'ab' style.paddingLeft = style.paddingRight = style.paddingTop = style.paddingBottom = '0.25ex' style.borderStyle = 'solid' style.borderWidth = '1px' style.borderRadius = f'{br}{ICON_SIZE_UNIT}' style.fontSize = 'smaller' style.fontWeight = 'bold' if tdl: style.textDecorationLine = tdl if tds: style.textDecorationStyle = tds if tdc: style.textDecorationColor = tdc return container bg = None if s.type is 'builtin': bg = builtin_color(s.which, is_dark) elif s.type is 'custom': bg = s.dark if is_dark else s.light if bg is None and s['background-color']: bg = s['background-color'] if bg: style.backgroundColor = bg style.borderRadius = f'{br}{ICON_SIZE_UNIT}' return container def highlight_shade(self, is_dark): s = self.style if s.kind is 'decoration': if s.type is 'builtin': defs = builtin_decorations_dark[s.which] if is_dark else builtin_decorations_light[s.which] else: defs = s return defs['text-decoration-color'] or 'red' if s.type is 'builtin': return builtin_color(s.which, is_dark) if s.type is 'custom': return s.dark if is_dark else s.light return s['background-color'] or default_color(is_dark) def serialized(self): return JSON.stringify(self.style) @property def friendly_name(self): s = self.style if s.type is 'builtin': return builtin_friendly_name(s.kind, s.which) return s.friendly_name or _('Custom style') def highlight_style_as_css(s, is_dark, foreground): def styler(node): def set(name, val): if val: node.style.setProperty(name, val, 'important') if s.kind is 'decoration': if s.type is 'builtin': keys = builtin_decorations_dark[s.which] if is_dark else builtin_decorations_light[s.which] else: keys = s set('text-decoration-line', keys['text-decoration-line']) set('text-decoration-color', keys['text-decoration-color']) set('text-decoration-style', keys['text-decoration-style']) return bg = None fg = foreground or None if s.type is 'builtin': bg = builtin_color(s.which, is_dark) elif s.type is 'custom': bg = s.dark if is_dark else s.light elif s.color: fg = s.color set('background-color', bg or s['background-color'] or default_color(is_dark)) set('color', fg or s.color or foreground) return styler def custom_styles_equal(a, b): seen = {} for k in a: seen[k] = True if a[k] is not b[k]: return False for k in b: if not seen[k]: if a[k] is not b[k]: return False return True def all_styles(): ans = v'[]' custom_highlight_styles = get_session_data().get('custom_highlight_styles') for raw in custom_highlight_styles: ans.push(HighlightStyle(raw)) for raw in all_builtin_styles(): ans.push(HighlightStyle(raw)) return ans class AddStyle: # {{{ def __init__(self, get_container, hide_self): self.get_container = get_container self.hide_self = hide_self def onkeydown(ev): ev.stopPropagation() if ev.key is 'Escape': hide_self(None) get_container().appendChild(E.div( style='margin: 1rem; text-align: left', E.div(_('Style name:'), ' ', E.input(name='friendly_name', onkeydown=onkeydown, placeholder=_('Name for this style'))), E.div('\xa0'), E.div( _('Type of style:'), ' ', E.label(E.input(type='radio', name='style_type', value='color', onchange=self.change_type, checked=True), _('Color')), '\xa0\xa0', E.label(E.input(type='radio', name='style_type', value='decoration', onchange=self.change_type), _('Underline')), ), E.div( name='color-container', style='margin-top:1rem; border-top: solid; padding-top: 1rem', E.div(E.label(_('Color for light color themes: '), E.input(type='color', name='light_color', value='#ffff00'))), E.div('\xa0'), E.div(E.label(_('Color for dark color themes: '), E.input(type='color', name='dark_color', value='#cccc00'))), ), E.div( name='decoration-container', style='margin-top:1rem; border-top: solid; padding-top: 1rem', E.div( _('Color for the line: '), E.label(E.input(type='radio', name='color_type', value='currentColor', checked=True), _('Text color')), '\xa0', E.label(E.input(type='radio', name='color_type', value='custom_color'), _('Custom color:')), '\xa0', E.input(type='color', name='decoration_color', value='#ff0000', onchange=def(): self.get_container().querySelector('input[value=custom_color]').checked = True ) ), E.div('\xa0'), E.div( E.label(_('Position of line: '), E.select(name='text_decoration_line', E.option(_('Underline'), value='underline'), E.option(_('Over-line'), value='overline'), E.option(_('Strikeout'), value='strike-through'), )) ), E.div('\xa0'), E.div( E.label(_('Style of line: '), E.select(name='text_decoration_style', E.option(_('Solid'), value='solid'), E.option(_('Double'), value='double'), E.option(_('Dotted'), value='dotted'), E.option(_('Dashed'), value='dashed'), E.option(_('Wavy'), value='wavy'), )) ), ), E.div( style='margin-top:1rem; border-top: solid; padding-top: 1rem; display: flex; width: 100%; justify-content: space-between', create_button(_('Discard'), 'close', def(ev): ev.stopPropagation() hide_self(None) ), create_button(_('Save'), 'check', def(ev): ev.stopPropagation() if not self.friendly_name: return error_dialog(_('No name specified'), _('You must give your custom style a name'), on_close=self.focus) hide_self(self.created_style) ), ), )) self.change_type() def focus(self): self.get_container().querySelector('input[name=friendly_name]').focus() def init(self): self.get_container().querySelector('input[name=friendly_name]').value = '' self.focus() @property def style_type(self): return self.get_container().querySelector('input[name=style_type]:checked').value @property def color_type(self): return self.get_container().querySelector('input[name=color_type]:checked').value def change_type(self): c = self.get_container() q = self.style_type c.querySelector('[name=color-container]').style.display = 'block' if q is 'color' else 'none' c.querySelector('[name=decoration-container]').style.display = 'block' if q is 'decoration' else 'none' @property def friendly_name(self): return self.get_container().querySelector('input[name=friendly_name]').value @property def created_style(self): c = self.get_container() name = self.friendly_name if self.style_type is 'color': return custom_color_theme(name, c.querySelector('input[name=light_color]').value, c.querySelector('input[name=dark_color]').value) if self.color_type is 'currentColor': col = 'currentColor' else: col = c.querySelector('input[name=decoration_color]').value return custom_decoration_theme( name, c.querySelector('select[name=text_decoration_line]').value, c.querySelector('select[name=text_decoration_style]').value, col) # }}} class EditNotesAndColors: # {{{ def __init__(self, container, is_dark_theme, current_notes, current_style, annot_id, close_editor): self.initial_style = current_style self.is_dark_theme = is_dark_theme self.annot_id = annot_id def finish(): close_editor(True) def abort(): close_editor(False) def handle_keypress(ev): ev.stopPropagation() if ev.key is 'Escape': abort() elif ev.key is 'Enter' and ev.ctrlKey: finish() remove_button = create_button(_('Remove style'), 'trash', self.remove_custom_color, _('Remove this custom highlight style')) remove_button.classList.add('remove-custom-color') apply_button = create_button( _('Apply') if self.annot_id else _('Create'), 'check', finish, (_('Finish editing highlight') if self.annot_id else _('Create highlight')) + ' [Ctrl+Enter]', True ) apply_button.style.marginLeft = apply_button.style.marginTop = 'auto' stop_propagation = def(ev): ev.stopPropagation() c = E.div( style=f'background: {get_color("window-background")}; margin: auto; text-align: center; padding: 1ex;', onclick=stop_propagation, id=unique_id(), E.div( ontouchstart=stop_propagation, ontouchmove=stop_propagation, ontouchend=stop_propagation, ontouchcancel=stop_propagation, oncontextmenu=stop_propagation, E.textarea( placeholder=_('Add notes for this highlight. Double click or long tap on a highlight to read its notes.'), rows='10', spellcheck='true', style='width: 90%;', onkeydown=handle_keypress, ), E.div( class_='color-block', style=f'display: flex; flex-wrap: wrap; width: 100%; justify-content: center', ), E.div( style='width: 100%; display: flex; flex-wrap: wrap', create_button(_('Cancel'), 'close', abort, _('Abort') + ' [Esc]'), E.span('\xa0'), remove_button, apply_button ), )) self.container_id = c.id container.appendChild(c) container.style.maxWidth = '40rem' container.style.width = '90%' c.appendChild(E.div(style='display:none')) self.add_style = AddStyle(def(): return self.container.lastChild;, self.hide_add_style) self.seen_colors = {} custom_highlight_styles = get_session_data().get('custom_highlight_styles') for raw in custom_highlight_styles: self.add_color(HighlightStyle(raw)).classList.add('custom-style') for raw in all_builtin_styles(): self.add_color(HighlightStyle(raw)) if not c.querySelector('.current-swatch'): self.add_color(self.initial_style, True) parent = c.getElementsByClassName('color-block')[0] parent.appendChild(E.div( svgicon('plus', ICON_SIZE, ICON_SIZE), style='padding: 4px; margin: 4px;', title=_('Add a new highlight style'), class_='simple-link', onclick=def(ev): ev.stopPropagation() c = self.container c.firstChild.style.display = 'none' c.lastChild.style.display = 'block' self.add_style.init() )) self.set_visibility_of_remove_button() window.setTimeout(self.notes_edit.focus.bind(self.notes_edit), 0) if current_notes: self.notes_edit.value = current_notes def hide_add_style(self, new_style): c = self.container c.firstChild.style.display = 'block' c.lastChild.style.display = 'none' if new_style: self.add_new_style(new_style) self.notes_edit.focus() def add_new_style(self, new_style): hs = HighlightStyle(new_style) item = self.add_color(hs, True) if not item: # happens if the newly created style is the same as some existing # style for q in self.container.getElementsByClassName('swatch'): if q.dataset.key is hs.key: item = q break if item: item.classList.add('custom-style') self.make_swatch_current(item) sd = get_session_data() new_styles = v'[new_style]' seen = {hs.key: True} for style in sd.get('custom_highlight_styles'): hso = HighlightStyle(style) if not seen[hso.key]: new_styles.push(style) sd.set('custom_highlight_styles', new_styles) def set_visibility_of_remove_button(self): c = self.container item = c.querySelector('.current-swatch.custom-style') c.querySelector('.remove-custom-color').style.display = 'flex' if item else 'none' def add_color(self, hs, at_start): if self.seen_colors[hs.key]: return self.seen_colors[hs.key] = True ic = E.div() hs.make_swatch(ic, self.is_dark_theme) ic.classList.add('simple-link') is_current = hs.key is self.initial_style.key sqbg = get_color('window-background2') if is_current else 'unset' item = E.div( ic, style=f'padding: 4px; background-color: {sqbg}; margin: 4px; border-radius: {ICON_SIZE_VAL/4}{ICON_SIZE_UNIT}', onclick=self.change_color, title=hs.friendly_name ) if is_current: item.classList.add('current-swatch') item.classList.add('swatch') item.dataset.style = hs.serialized() item.dataset.key = hs.key parent = self.container.getElementsByClassName('color-block')[0] if at_start: parent.insertBefore(item, parent.firstChild) else: parent.appendChild(item) return item def remove_custom_color(self): question_dialog(_('Are you sure?'), _( 'Do you want to permanently delete this highlighting style?'), def (yes): if yes: self.do_remove_custom_color() ) def do_remove_custom_color(self): item = self.container.getElementsByClassName('current-swatch')[0] cct = JSON.parse(item.dataset.style) p = item.parentNode p.removeChild(item) self.make_swatch_current(p.firstChild) sd = get_session_data() custom_highlight_styles = sd.get('custom_highlight_styles') ans = v'[]' for x in custom_highlight_styles: if not custom_styles_equal(x, cct): ans.push(x) sd.set('custom_highlight_styles', ans) @property def container(self): return document.getElementById(self.container_id) @property def notes_edit(self): return self.container.getElementsByTagName('textarea')[0] def change_color(self, evt): evt.stopPropagation() self.make_swatch_current(evt.currentTarget) def make_swatch_current(self, item): for child in item.parentNode.childNodes: child.style.backgroundColor = 'unset' child.classList.remove('current-swatch') item.style.backgroundColor = get_color('window-background2') item.classList.add('current-swatch') self.notes_edit.focus() self.set_visibility_of_remove_button() @property def current_notes(self): return self.notes_edit.value or '' @property def current_style(self): style = self.container.getElementsByClassName('current-swatch')[0].dataset.style return HighlightStyle(JSON.parse(style)) # }}} # Browse highlights panel {{{ def get_container_id(): if not get_container_id.ans: get_container_id.ans = unique_id() return get_container_id.ans def get_container(): return document.getElementById(get_container_id()) def get_current_link_prefix(): if runtime.is_standalone_viewer: return current_book().calibre_book_url link_prefix = window.location.href return link_prefix[:link_prefix.indexOf('#') + 1] def link_to_epubcfi(epubcfi, link_prefix, current_query): if runtime.is_standalone_viewer: current_query = {'open_at': epubcfi} link = encode_query(current_query) else: if not current_query: current_query = Object.assign({}, get_current_query()) current_query.bookpos = epubcfi link = encode_query(current_query)[1:] return link_prefix + link.replace(/\)/g, '%29').replace(/\(/g, '%28') def render_highlight_as_text(hl, lines, link_prefix, current_query, as_markdown=False): lines.push(hl.highlighted_text) date = Date(hl.timestamp).toLocaleString() if as_markdown: cfi = hl.start_cfi spine_index = (1 + hl.spine_index) * 2 link = link_to_epubcfi(f'epubcfi(/{spine_index}{cfi})', link_prefix, current_query) date = f'[{date}]({link})' lines.push(date) notes = hl.notes if notes: lines.push('') lines.push(notes) lines.push('') if as_markdown: lines.push('-' * 20) else: lines.push('───') lines.push('') class ChapterGroup: def __init__(self, title, level): self.level = level or 0 self.title = title or '' self.subgroups = v'{}' self.subgroups_in_order = v'[]' self.annotations = v'[]' def add_annot(self, a): titles = a['toc_family_titles'] if not titles: titles = [_('Unknown chapter')] node = self for title in titles: node = node.group_for_title(title) node.annotations.push(a) def group_for_title(self, title): ans = self.subgroups[title] if not ans: ans = ChapterGroup(title, self.level+1) self.subgroups[title] = ans self.subgroups_in_order.push(title) return ans def render_as_text(self, lines, link_prefix, current_query, as_markdown): if self.title: lines.push('#' * self.level + ' ' + self.title) lines.push('') for hl in self.annotations: render_highlight_as_text(hl, lines, link_prefix, current_query, as_markdown) for title in self.subgroups_in_order: sg = self.subgroups[title] sg.render_as_text(lines, link_prefix, current_query, as_markdown) def show_export_dialog(annotations_manager, book_metadata): sd = get_session_data() fmt = sd.get('highlights_export_format') if v"['text', 'markdown', 'calibre_annotations_collection']".indexOf(fmt) < 0: fmt = 'text' all_highlights = annotations_manager.all_highlights() selected_highlight_items = all_selected_entries() if selected_highlight_items.length: key = {e.dataset.uuid: True for e in selected_highlight_items} all_highlights = [h for h in all_highlights if key[h.uuid]] ta_id = unique_id() href = window.location.href idx = href.indexOf('#') href = href[:idx+1] current_query = Object.assign({}, get_current_query()) link_prefix = get_current_link_prefix() def update_text(): if fmt is 'calibre_annotations_collection': data = { 'version': 1, 'type': 'calibre_annotation_collection', 'annotations': all_highlights, } document.getElementById(ta_id).textContent = JSON.stringify(data, None, 2) return as_markdown = fmt is 'markdown' lines = v'[]' root = ChapterGroup() for a in all_highlights: root.add_annot(a) root.render_as_text(lines, link_prefix, current_query, as_markdown) document.getElementById(ta_id).textContent = lines.join('\n') def fmt_item(text, val): ans = E.label(E.input(type='radio', name='format', value=val, checked=val is fmt), '\xa0', text) ans.style.marginRight = '1rem' ans.firstChild.addEventListener('change', def(ev): nonlocal fmt fmt = this.value sd.set('highlights_export_format', this.value) update_text() ) return ans create_custom_dialog(_('Export highlights'), def (modal_container, close_modal): modal_container.appendChild(E.div( E.div(_('Format for exported highlights:')), E.div( fmt_item(_('Plain text'), 'text'), fmt_item(_('Markdown'), 'markdown'), fmt_item('calibre', 'calibre_annotations_collection'), ), E.textarea(style='margin-top: 1ex; resize: none; max-height: 25vh', readonly=True, rows='20', cols='80', id=ta_id), E.div( class_='button-box', create_button(_('Copy'), 'copy', def (ev): x = document.getElementById(ta_id) x.focus() x.select() document.execCommand('copy') ), '\xa0', create_button(_('Download'), 'cloud-download', def (ev): nonlocal fmt text = document.getElementById(ta_id).textContent ext = 'md' if fmt is 'markdown' else ('txt' if fmt is 'text' else 'json') mt = 'text/markdown' if fmt is 'markdown' else ('text/plain' if fmt is 'text' else 'application/json') title = book_metadata?.title or _('Unknown') filename = _('{title} - highlights').format(title=title) + f'.{ext}' file = new Blob([text], {'type': mt}) url = window.URL.createObjectURL(file) a = E.a(href=url, download=filename) document.body.appendChild(a) a.click() window.setTimeout(def(): document.body.removeChild(a) window.URL.revokeObjectURL(url) , 0) ), ) )) window.setTimeout(update_text, 0) ) def focus_search(): c = get_container() c.querySelector('input').focus() def find(backwards): c = get_container() text = c.querySelector('input').value if not text: return False all_highlights = list(c.querySelectorAll('.highlight')).as_array() current = c.querySelector('.highlight.current') if current: start = all_highlights.indexOf(current) if backwards: all_highlights = all_highlights[:start].reverse().concat(all_highlights[start:].reverse()) else: all_highlights = all_highlights[start+1:].concat(all_highlights[:start+1]) elif backwards: all_highlights.reverse() q = text.toLowerCase() for h in all_highlights: if h.dataset.title.toLowerCase().indexOf(q) > -1 or h.dataset.notes.toLowerCase().indexOf(q) > -1: set_current_highlight_entry(h) h.scrollIntoView() if h is current: warning_dialog(_('Not found'), _('No other matches found for: {}').format(text), on_close=focus_search) return True warning_dialog(_('Not found'), _('No matches found for: {}').format(text), on_close=focus_search) return False def find_previous(): return find(True) def find_next(): return find(False) add_extra_css(def(): ans = '' sel = '#' + get_container_id() ans += build_rule(sel + ' .ac-button', margin_left='1rem', margin_top='1ex') ans += build_rule(sel + ' .sel-button', display='none') sel += ' .toc-group' ans += build_rule(sel + ' h3', display='flex', align_items='center', cursor='pointer', margin_top='1ex') ans += build_rule(sel + '.expanded .caret-right', display='none') ans += build_rule(sel + '.collapsed .caret-down', display='none') ans += build_rule(sel + '.collapsed > div', display='none') qsel = sel + ' .highlight' ans += build_rule(qsel, margin_top='1ex', border_top='solid 1px', padding_top='1ex', cursor='pointer') ans += build_rule(qsel + ' .notes', display='none', margin_top='1ex', max_height='20ex', overflow='auto') ans += build_rule(qsel + ' .actions', display='none', margin_top='1ex', justify_content='space-between') ans += build_rule(qsel + ' .title', display='flex', align_items='center') ans += build_rule(qsel + ' .title-row', display='flex', align_items='center', justify_content='space-between') current = qsel + '.current' ans += build_rule(current + ' .title', font_weight='bold', font_size='larger') ans += build_rule(current + ' .notes', display='block') ans += build_rule(current + ' .actions', display='flex') return ans ) url_pat = /\bhttps?:\/\/\S{3,}/ig closing_bracket_map = {'(': ')', '[': ']', '{': '}', '<': '>', '*': '*', '"': '"', "'": "'"} opening_brackets = Object.keys(closing_bracket_map).join('') def url(text: str, s: int, e: int): while '.,?!'.indexOf(text[e-1]) > -1 and e > 1: # remove trailing punctuation e -= 1 # truncate url at closing bracket/quote if s > 0 and e <= text.length and closing_bracket_map[text[s-1]]: q = closing_bracket_map[text[s-1]] idx = text.indexOf(q, s) if idx > s: e = idx return s, e def render_notes(notes, container, make_urls_clickable): current_para = E.p() def add_para(): nonlocal current_para container.appendChild(current_para) if container.childNodes.length > 1: container.lastChild.style.marginTop = '2ex' current_para = E.p() def add_line(line): url_pat.lastIndex = 0 urls = v'[]' while make_urls_clickable: m = url_pat.exec(line) if not m: break urls.push(url(line, m.index, url_pat.lastIndex)) if not urls.length: current_para.appendChild(document.createTextNode(line)) return pos = 0 for (s, e) in urls: if s > pos: current_para.appendChild(document.createTextNode(line[pos:s])) current_para.appendChild(E.a(line[s:e], href='javascript: void(0)', class_='blue-link', onclick=ui_operations.open_url.bind(None, line[s:e]))) if urls[-1][1] < line.length: current_para.appendChild(document.createTextNode(line[urls[-1][1]:])) for line in notes.splitlines(): if not line or not line.strip(): if current_para.childNodes.length: add_para() continue add_line(line) if current_para.childNodes.length: add_para() return container def highlight_entry_clicked(ev): set_current_highlight_entry(ev.currentTarget) def set_current_highlight_entry(entry): c = get_container() for h in c.querySelectorAll('.highlight'): h.classList.remove('current') entry.classList.add('current') def show_in_text(annot_id, view): view.highlight_action(annot_id, 'goto') def remove_highlight(annot_id, view, ev): entry = ev.currentTarget.closest('.highlight') question_dialog(_('Are you sure?'), _( 'Do you want to permanently delete this highlight?'), def (yes): if yes: entry.style.display = 'none' view.highlight_action(annot_id, 'delete') ) def edit_notes(annot_id, notes, view, ev): entry = ev.currentTarget.closest('.highlight') get_text_dialog(_('Notes'), def(ok, text): if not ok: return text = text or '' nc = entry.querySelector('.notes') clear(nc) view.set_notes_for_highlight(annot_id, text) render_notes(text, nc) , initial_text=notes or None) def all_selected_entries(): return [e.closest('.highlight') for e in document.querySelectorAll('.highlight input:checked')] def item_select_toggled(): entries = all_selected_entries() for e in document.querySelectorAll(f'#{get_container_id()} .sel-button'): e.style.display = 'block' if entries.length else 'none' def clear_selection(): for e in document.querySelectorAll('.highlight input:checked'): e.checked = False item_select_toggled() def select_all(): for e in document.querySelectorAll('.highlight input'): e.checked = True def delete_selection(annotations_manager, view): selected_highlight_items = all_selected_entries() if not selected_highlight_items.length: return text = ngettext( 'Do you want to permanently delete the selected highlight?', 'Do you want to permanently delete the {} selected highlights?', selected_highlight_items.length ).format(selected_highlight_items.length) question_dialog(_('Are you sure?'), text, def(yes): if yes: for entry in selected_highlight_items: entry.style.display = 'none' view.highlight_action(entry.dataset.uuid, 'delete') ) def highlight_entry(h, onclick, view, hide_panel): def action(func, ev): ev.stopPropagation(), ev.preventDefault() onclick(func) def button(text, func): return E.a(text, class_='blue-link', onclick=func) hs = HighlightStyle(h.style) swatch = E.div() hs.make_swatch(swatch, is_dark_theme()) ans = E.div( class_='highlight', data_uuid=h.uuid, onclick=highlight_entry_clicked, E.div( class_='title-row', E.div(class_='title', swatch, E.div(style='margin-left: 1rem', h.highlighted_text)), E.div(style='margin-left: 1rem', onclick=def(ev): ev.stopPropagation();, E.input(type='checkbox', onchange=item_select_toggled, onkeydown=def(ev): if ev.key is 'Escape': ev.stopPropagation() ev.preventDefault() hide_panel() )), ), E.div( class_='actions', button(_('Show in book'), action.bind(None, show_in_text.bind(None, h.uuid))), E.span('\xa0'), button(_('Edit notes'), edit_notes.bind(None, h.uuid, h.notes, view)), E.span('\xa0'), button(_('Remove highlight'), remove_highlight.bind(None, h.uuid, view)), ), E.div(class_='notes') ) if h.notes: render_notes(h.notes, ans.querySelector('.notes'), True) ans.dataset.notes = h.notes or '' ans.dataset.title = h.highlighted_text or '' return ans def create_highlights_panel(annotations_manager, hide_panel, book, container, onclick): next_button = E.div(class_='simple-link ac-button', svgicon('chevron-down'), title=_('Next match')) prev_button = E.div(class_='simple-link ac-button', svgicon('chevron-up'), title=_('Previous match')) prev_button.addEventListener('click', def(ev): find_previous();) sb = create_search_bar(find_next, 'search-in-highlights', placeholder=_('Search') + '…', button=next_button, associated_widgets=[prev_button]) sb.style.flexGrow = '10' sb.classList.add('ac-button') clear_button = create_button( _('Clear'), 'close', clear_selection, _('Clear selection'), class_='ac-button sel-button') delete_button = create_button( _('Remove'), 'trash', delete_selection.bind(None, annotations_manager, annotations_manager.view), _('Remove selected highlights'), class_='ac-button sel-button') all_button = create_button( _('All'), 'plus', select_all, _('Select all highlights'), class_='ac-button sel-button') export_button = create_button( _('Export'), 'cloud-download', show_export_dialog.bind(None, annotations_manager, book.metadata), _('Export all or selected highlights'), class_='ac-button') c = E.div( style='padding: 1rem', id=get_container_id(), E.div( style='display: flex; flex-wrap: wrap; margin-top: -1ex; align-items: center', sb, next_button, prev_button, clear_button, all_button, delete_button, export_button ), ) container.appendChild(c) toc_groups = {} toc_tt = {} for h in annotations_manager.all_highlights(): toc = _('Unknown') if h.toc_family_titles?.length: toc = h.toc_family_titles[-1] if not toc_groups[toc]: toc_groups[toc] = v'[]' if h.toc_family_titles?.length: lines = v'[]' for i, node in enumerate(h.toc_family_titles): lines.push('\xa0\xa0' * i + '➤ ' + node) tt = ngettext('Table of Contents section:', 'Table of Contents sections:', lines.length) tt += '\n' + '\n'.join(lines) toc_tt[toc] = tt toc_groups[toc].push(h) def tree_icon(which): ans = svgicon(which) ans.classList.add(which) return ans for group in Object.keys(toc_groups): highlights = toc_groups[group] g = E.div( class_='toc-group expanded', E.h3( title=toc_tt[group] or '', tree_icon('caret-right'), tree_icon('caret-down'), E.div('\xa0' + group), onclick=def (ev): tg = ev.currentTarget.closest('.toc-group') if tg.classList.contains('expanded'): tg.classList.remove('expanded') tg.classList.add('collapsed') else: tg.classList.remove('collapsed') tg.classList.add('expanded') ), E.div(style='margin-left: 1rem') ) c.appendChild(g) ic = g.lastChild for h in highlights: ic.appendChild(highlight_entry(h, onclick, annotations_manager.view, hide_panel)) # }}}
38,499
Python
.py
873
33.864834
154
0.584085
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,537
toc.pyj
kovidgoyal_calibre/src/pyj/read_book/toc.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from elementmaker import E from complete import create_search_bar from dom import ensure_id, set_css, svgicon from gettext import gettext as _ from modals import error_dialog from read_book.anchor_visibility import position_for_anchor from read_book.globals import ( current_book, current_layout_mode, current_spine_item, get_boss, set_toc_anchor_map, toc_anchor_map ) from read_book.viewport import scroll_viewport from widgets import create_tree, find_text_in_tree, scroll_tree_item_into_view def update_visible_toc_nodes(visible_anchors): update_visible_toc_nodes.data = visible_anchors update_visible_toc_nodes.data = {} def iter_toc_descendants(node, callback): for child in node.children: if callback(child): return iter_toc_descendants(child, callback) def get_toc_nodes_bordering_spine_item(toc, csi): # Find the ToC entries that point to the closest files on either side of the # spine item toc = toc or current_book().manifest.toc csi = csi or current_spine_item() spine = current_book().manifest.spine spine_before, spine_after = {}, {} which = spine_before before = after = prev = None for name in spine: if name is csi: which = spine_after else: which[name] = True iter_toc_descendants(toc, def(node): nonlocal prev, before, after if node.dest: if spine_before[node.dest]: prev = node elif spine_after[node.dest]: if not before: before = prev if not after: after = node return True ) if not before and prev is not None: before = prev return before, after def get_border_nodes(toc, id_map): data = update_visible_toc_nodes.data before, after = data.before, data.after if before: before = id_map[before] if after: after = id_map[after] if before and after: # Both border nodes are in the current spine item return before, after sb, sa = get_toc_nodes_bordering_spine_item(toc) before = before or sb after = after or sa return before, after def family_for_toc_node(toc_node_id, parent_map, id_map): if not id_map or not parent_map: toc = current_book().manifest.toc parent_map, id_map = get_toc_maps(toc) family = v'[]' node = id_map[toc_node_id] while node and node.title: family.unshift(node) parent = parent_map[node.id] node = None if parent: node = id_map[parent.id] return family def get_page_list_id_map(page_list): return {x.id: x for x in page_list} def get_page_list_before(page_list, id_map): # Find the page list entries that point to the closest files on either side of the spine item csi = csi or current_spine_item() spine = current_book().manifest.spine spine_before, spine_after = {}, {} which = spine_before before = prev = None for name in spine: if name is csi: which = spine_after else: which[name] = True for item in page_list: if item.dest: if spine_before[item.dest]: prev = item elif spine_after[item.dest]: if not before: before = prev break return before def get_current_pagelist_items(): ans = {} page_list = current_book().manifest.page_list data = update_visible_toc_nodes.data?.page_list if not data or not page_list: return ans id_map = get_page_list_id_map(page_list) if data.has_visible: ans = data.visible_anchors else: if data.before?: ans[data.before] = True else: before = get_page_list_before(page_list, id_map) if before?: ans[before.id] = True return [id_map[x] for x in Object.keys(ans)] def get_current_toc_nodes(): toc = current_book().manifest.toc parent_map, id_map = get_toc_maps(toc) data = update_visible_toc_nodes.data ans = {} if data.has_visible: ans = data.visible_anchors else: if data.before: ans[data.before] = True else: before = get_border_nodes(toc, id_map)[0] if before: ans[before.id] = True r = v'[]' for x in Object.keys(ans): fam = family_for_toc_node(x, parent_map, id_map) if fam?.length: r.push(fam) return r def get_highlighted_toc_nodes(toc, parent_map, id_map, skip_parents): data = update_visible_toc_nodes.data ans = {} if data.has_visible: ans = data.visible_anchors else: if data.before: ans[data.before] = True else: before = get_border_nodes(toc, id_map)[0] if before: ans[before.id] = True if not skip_parents: for node_id in Object.keys(ans): p = parent_map[node_id] while p and p.title: ans[p.id] = True p = parent_map[p.id] return ans def get_toc_maps(toc): if not toc: toc = current_book().manifest.toc parent_map, id_map = {}, {} def process_node(node, parent): id_map[node.id] = node parent_map[node.id] = parent for c in node.children: process_node(c, node) process_node(toc) return parent_map, id_map def get_book_mark_title(): toc = current_book().manifest.toc parent_map, id_map = get_toc_maps(toc) highlighted_toc_nodes = get_highlighted_toc_nodes(toc, parent_map, id_map, True) for node_id in Object.keys(highlighted_toc_nodes): node = id_map[node_id] if node.title: return node.title return '' def create_toc_tree(toc, onclick): parent_map, id_map = get_toc_maps(toc) highlighted_toc_nodes = get_highlighted_toc_nodes(toc, parent_map, id_map) def populate_data(node, li, a): li.dataset.tocDest = node.dest or '' li.dataset.tocFrag = node.frag or '' title = node.title or '' if highlighted_toc_nodes[node.id]: a.appendChild(E.b(E.i(title))) else: a.textContent = title return create_tree(toc, populate_data, onclick) def do_search(text): container = document.getElementById(this) a = find_text_in_tree(container, text) if not text: return if not a: return error_dialog(_('No matches found'), _( 'The text "{}" was not found in the Table of Contents').format(text)) scroll_tree_item_into_view(a) def create_toc_panel(book, container, onclick): def handle_click(event, li): if event.button is 0: onclick(li.dataset.tocDest, li.dataset.tocFrag) toc_panel = create_toc_tree(book.manifest.toc, handle_click) toc_panel_id = ensure_id(toc_panel) set_css(container, display='flex', flex_direction='column', height='100%', min_height='100%', overflow='hidden', max_height='100vh', max_width='100vw') set_css(toc_panel, flex_grow='10') container.appendChild(toc_panel) search_button = E.div(class_='simple-link', svgicon('search')) t = _('Search Table of Contents') search_bar = create_search_bar(do_search.bind(toc_panel_id), 'search-book-toc', button=search_button, placeholder=t) set_css(search_bar, flex_grow='10', margin_right='1em') container.appendChild(E.div(style='margin: 1ex 1em; display: flex; align-items: center', search_bar, search_button)) for child in container.childNodes: child.style.flexShrink = '0' toc_panel.style.flexGrow = '100' toc_panel.style.flexShrink = '1' toc_panel.style.overflow = 'auto' def recalculate_toc_anchor_positions(tam, plam): name = current_spine_item().name am = {} anchors = v'[]' pos_map = {} for i, anchor in enumerate(tam[name] or v'[]'): am[anchor.id] = position_for_anchor(anchor.frag) anchors.push(anchor.id) pos_map[anchor.id] = i anchor_funcs = get_boss().anchor_funcs # stable sort by position in document anchors.sort(def (a, b): return anchor_funcs.cmp(am[a], am[b]) or (pos_map[a] - pos_map[b]);) current_map = {'layout_mode': current_layout_mode(), 'width': scroll_viewport.width(), 'height': scroll_viewport.height(), 'pos_map': am, 'sorted_anchors':anchors} am = {} anchors = v'[]' pos_map = {} if plam: for i, anchor in enumerate(plam[name] or v'[]'): am[anchor.id] = position_for_anchor(anchor.frag, True) anchors.push(anchor.id) pos_map[anchor.id] = i # stable sort by position in document anchors.sort(def (a, b): return anchor_funcs.cmp(am[a], am[b]) or (pos_map[a] - pos_map[b]);) current_map.page_list_pos_map = am current_map.page_list_sorted_anchors = anchors set_toc_anchor_map(current_map) return current_map def current_toc_anchor_map(tam, plam): current_map = toc_anchor_map() if not (current_map and current_map.layout_mode is current_layout_mode() and current_map.width is scroll_viewport.width() and current_map.height is scroll_viewport.height()): current_map = recalculate_toc_anchor_positions(tam, plam) return current_map def update_visible_toc_anchors(toc_anchor_map, page_list_anchor_map, recalculate): if recalculate: recalculate_toc_anchor_positions(toc_anchor_map, page_list_anchor_map) anchor_funcs = get_boss().anchor_funcs tam = current_toc_anchor_map(toc_anchor_map, page_list_anchor_map) before = after = None visible_anchors = {} has_visible = False for anchor_id in tam.sorted_anchors: pos = tam.pos_map[anchor_id] visibility = anchor_funcs.visibility(pos) if visibility < 0: before = anchor_id elif visibility is 0: has_visible = True visible_anchors[anchor_id] = True elif visibility > 0: after = anchor_id break ans = {'visible_anchors':visible_anchors, 'has_visible':has_visible, 'before':before, 'after':after, 'sorted_anchors':tam.sorted_anchors} before = after = None visible_anchors = {} has_visible = False for anchor_id in tam.page_list_sorted_anchors: pos = tam.page_list_pos_map[anchor_id] visibility = anchor_funcs.visibility(pos) if visibility < 0: before = anchor_id elif visibility is 0: has_visible = True visible_anchors[anchor_id] = True elif visibility > 0: after = anchor_id break ans.page_list = {'visible_anchors':visible_anchors, 'has_visible':has_visible, 'before':before, 'after':after, 'sorted_anchors':tam.page_list_sorted_anchors} return ans def find_anchor_before_range(r, toc_anchor_map, page_list_anchor_map): name = current_spine_item().name prev_anchor = None tam = current_toc_anchor_map(toc_anchor_map, page_list_anchor_map) anchors = toc_anchor_map[name] if anchors: amap = {x.id: x for x in anchors} for anchor_id in tam.sorted_anchors: anchor = amap[anchor_id] is_before = True if anchor.frag: elem = document.getElementById(anchor.frag) if elem: q = document.createRange() q.selectNode(elem) if q.compareBoundaryPoints(window.Range.START_TO_START, r) > 0: is_before = False if is_before: prev_anchor = anchor else: break return prev_anchor
11,881
Python
.py
308
30.808442
178
0.62564
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,538
paged_mode.pyj
kovidgoyal_calibre/src/pyj/read_book/paged_mode.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # Notes of paged mode scrolling: # All the math in paged mode is based on the block and inline directions. # Inline is "the direction lines of text go." # In horizontal scripts such as English and Hebrew, the inline is horizontal # and the block is vertical. # In vertical languages such as Japanese and Mongolian, the inline is vertical # and block is horizontal. # Regardless of language, paged mode scrolls by column in the inline direction, # because by the CSS spec, columns are laid out in the inline direction. # # In horizontal RTL books, such as Hebrew, the inline direction goes right to left. # |<------| # This means that the column positions become negative as you scroll. # This is hidden from paged mode by the viewport, which transparently # negates any inline coordinates sent in to the viewport_to_document* functions # and the various scroll_to/scroll_by functions, as well as the reported X position. # # The result of all this is that paged mode's math can safely pretend that # things scroll in the positive inline direction. from __python__ import hash_literals, bound_methods import traceback from elementmaker import E from dom import set_important_css from read_book.cfi import ( at_current as cfi_at_current, at_point as cfi_at_point, scroll_to as cfi_scroll_to ) from read_book.globals import current_spine_item, get_boss, rtl_page_progression from read_book.settings import opts from read_book.viewport import scroll_viewport, line_height, rem_size, get_unit_size_in_pixels from utils import ( get_elem_data, set_elem_data ) def first_child(parent): c = parent.firstChild count = 0 while c?.nodeType is not Node.ELEMENT_NODE and count < 20: c = c?.nextSibling count += 1 if c?.nodeType is Node.ELEMENT_NODE: return c def has_start_text(elem): # Returns true if elem has some non-whitespace text before its first child # element for c in elem.childNodes: if c.nodeType is not Node.TEXT_NODE: break if c.nodeType is Node.TEXT_NODE and c.nodeValue and /\S/.test(c.nodeValue): return True return False def handle_rtl_body(body_style): if body_style.direction is "rtl": # If this in not set, Chrome scrolling breaks for some RTL and vertical content. document.documentElement.style.overflow = 'visible' def create_page_div(elem): div = E('blank-page-div', ' \n ') document.body.appendChild(div) # the min-height is needed to get firefox to always insert a column break before this div set_important_css(div, break_before='column', break_inside='avoid', display='block', white_space='pre', background_color='transparent', background_image='none', border_width='0', float='none', position='static', min_height='100vh') _in_paged_mode = False def in_paged_mode(): return _in_paged_mode col_size = screen_inline = screen_block = cols_per_screen = gap = col_and_gap = last_scrolled_to_column = 0 is_full_screen_layout = False def get_number_of_cols(dont_return_integer): # we dont store this because of the chrome resize bug where the document width # sometimes changes a few milliseconds after layout in paged mode if is_full_screen_layout: return 1 ans = (scroll_viewport.paged_content_inline_size() + gap) / col_and_gap if not dont_return_integer: ans = Math.floor(ans) return ans def reset_paged_mode_globals(): nonlocal _in_paged_mode, col_size, col_and_gap, screen_block, gap, screen_inline, is_full_screen_layout, cols_per_screen, last_scrolled_to_column scroll_viewport.reset_globals() col_size = screen_inline = screen_block = cols_per_screen = gap = col_and_gap = last_scrolled_to_column = 0 is_full_screen_layout = _in_paged_mode = False resize_manager.reset() def column_at(pos): # Return the (zero-based) number of the column that contains pos si = scroll_viewport.paged_content_inline_size() if pos >= si - col_and_gap: pos = si - col_size + 10 # we subtract 1 here so that a point at the absolute trailing (right in # horz-LTR) edge of a column remains in the column and not at the next column return max(0, (pos + gap - 1)) // col_and_gap def fit_images(): # Ensure no images are wider than the available size of a column. Note # that this method use getBoundingClientRect() which means it will # force a relayout if the render tree is dirty. inline_limited_images = v'[]' block_limited_images = v'[]' img_tags = document.getElementsByTagName('img') bounding_rects = v'[]' for img_tag in img_tags: bounding_rects.push(get_bounding_client_rect(img_tag)) maxb = screen_block for i in range(img_tags.length): img = img_tags[i] br = bounding_rects[i] previously_limited = get_elem_data(img, 'inline-limited', False) data = get_elem_data(img, 'img-data', None) if data is None: data = {'left':br.left, 'right':br.right, 'height':br.height, 'display': img.style.display} set_elem_data(img, 'img-data', data) # Get start of image bounding box in the column direction (inline) image_start = scroll_viewport.viewport_to_document_inline(scroll_viewport.rect_inline_start(br), img.ownerDocument) col_start = column_at(image_start) * col_and_gap # Get inline distance from the start of the column to the start of the image bounding box column_start_to_image_start = image_start - col_start image_block_size = scroll_viewport.rect_block_size(br) image_inline_size = scroll_viewport.rect_inline_size(br) # Get the inline distance from the start of the column to the end of the image image_inline_end = column_start_to_image_start + image_inline_size # If the end of the image goes past the column, add it to the list of inline_limited_images if previously_limited or image_inline_end > col_size: inline_limited_images.push(v'[img, col_size - column_start_to_image_start]') previously_limited = get_elem_data(img, 'block-limited', False) if previously_limited or image_block_size > maxb or (image_block_size is maxb and image_inline_size > col_size): block_limited_images.push(img) if previously_limited: set_important_css(img, break_before='auto', display=data.display) set_important_css(img, break_inside='avoid') for img_tag, max_inline_size in inline_limited_images: if scroll_viewport.vertical_writing_mode: img_tag.style.setProperty('max-height', max_inline_size+'px') else: img_tag.style.setProperty('max-width', max_inline_size+'px') set_elem_data(img_tag, 'inline-limited', True) for img_tag in block_limited_images: if scroll_viewport.vertical_writing_mode: set_important_css(img_tag, break_before='always', max_width='100vw') else: set_important_css(img_tag, break_before='always', max_height='100vh') set_elem_data(img_tag, 'block-limited', True) def cps_by_em_size(): ans = cps_by_em_size.ans fs = window.getComputedStyle(document.body).fontSize if not ans or cps_by_em_size.at_font_size is not fs: if fs is 0: ans = cps_by_em_size.ans = 16 else: ans = cps_by_em_size.ans = max(2, get_unit_size_in_pixels('rem')) cps_by_em_size.at_font_size = fs return ans def calc_columns_per_screen(): cps = opts.columns_per_screen or {} cps = cps.landscape if scroll_viewport.width() > scroll_viewport.height() else cps.portrait try: cps = int(cps) except: cps = 0 if not cps: cps = int(Math.floor(scroll_viewport.inline_size() / (35 * cps_by_em_size()))) cps = max(1, min(cps or 1, 20)) return cps def get_columns_per_screen_data(): which = 'landscape' if scroll_viewport.width() > scroll_viewport.height() else 'portrait' return {'which': which, 'cps': calc_columns_per_screen()} def will_columns_per_screen_change(): return calc_columns_per_screen() != cols_per_screen class ScrollResizeBugWatcher: # In Chrome sometimes after layout the scrollWidth of body increases after a # few milliseconds, this can cause scrolling to the end to not work # immediately after layout. This happens without a resize event, and # without triggering the ResizeObserver and only in paged mode. def __init__(self): self.max_time = 750 self.last_layout_at = 0 self.last_command = None self.doc_size = 0 self.timer = None def layout_done(self): self.last_layout_at = window.performance.now() self.last_command = None self.cancel_timer() def scrolled(self, pos, limit): self.cancel_timer() now = window.performance.now() if now - self.last_layout_at < self.max_time and self.last_command is not None: self.doc_size = scroll_viewport.paged_content_inline_size() self.check_for_resize_bug() def cancel_timer(self): if self.timer is not None: window.clearTimeout(self.timer) self.timer = None def check_for_resize_bug(self): sz = scroll_viewport.paged_content_inline_size() if sz != self.doc_size: return self.redo_scroll() now = window.performance.now() if now - self.last_layout_at < self.max_time: window.setTimeout(self.check_for_resize_bug, 10) else: self.timer = None def redo_scroll(self): if self.last_command: self.last_command() self.last_command = None self.timer = None self.doc_size = 0 scroll_resize_bug_watcher = ScrollResizeBugWatcher() def layout(is_single_page, on_resize): nonlocal _in_paged_mode, col_size, col_and_gap, screen_block, gap, screen_inline, is_full_screen_layout, cols_per_screen line_height(True) rem_size(True) body_style = window.getComputedStyle(document.body) scroll_viewport.initialize_on_layout(body_style) first_layout = not _in_paged_mode cps = calc_columns_per_screen() if first_layout: handle_rtl_body(body_style) # Check if the current document is a full screen layout like # cover, if so we treat it specially. single_screen = scroll_viewport.document_block_size() < (scroll_viewport.block_size() + 75) first_layout = True svgs = document.getElementsByTagName('svg') has_svg = svgs.length > 0 imgs = document.getElementsByTagName('img') only_img = imgs.length is 1 and document.getElementsByTagName('div').length < 3 and document.getElementsByTagName('p').length < 2 if only_img and window.getComputedStyle(imgs[0]).zIndex < 0: # Needed for some stupidly coded fixed layout EPUB comics, see for # instance: https://bugs.launchpad.net/calibre/+bug/1667357 imgs[0].style.zIndex = '0' if not single_screen and cps > 1: num = cps - 1 elems = document.querySelectorAll('body > *') if elems.length is 1: # Workaround for the case when the content is wrapped in a # 100% height <div>. This causes the generated page divs to # not be in the correct location, at least in WebKit. See # https://bugs.launchpad.net/bugs/1594657 for an example. elems[0].style.height = 'auto' while num > 0: num -= 1 create_page_div() n = cols_per_screen = cps # Calculate the column size so that cols_per_screen columns fit exactly in # the window inline dimension, with their separator margins col_size = screen_inline = scroll_viewport.inline_size() margin_size = (opts.margin_left + opts.margin_right) if scroll_viewport.horizontal_writing_mode else (opts.margin_top + opts.margin_bottom) # a zero margin causes scrolling issues, see https://bugs.launchpad.net/calibre/+bug/1918437 margin_size = max(1, margin_size) gap = margin_size if n > 1: # Adjust the margin so that the window inline dimension satisfies # col_size * n + (n-1) * 2 * margin = window_inline overhang = (screen_inline + gap) % n if overhang is not 0: gap += n - overhang # now (screen_inline + gap) is a multiple of n col_size = ((screen_inline + gap) // n) - gap screen_block = scroll_viewport.block_size() col_and_gap = col_size + gap set_important_css(document.body, column_gap=gap + 'px', column_width=col_size + 'px', column_rule='0px inset blue', min_width='0', max_width='none', min_height='0', max_height='100vh', column_fill='auto', margin='0', border_width='0', padding='0', box_sizing='content-box', width=scroll_viewport.width() + 'px', height=scroll_viewport.height() + 'px', overflow_wrap='break-word' ) # Without this, webkit bleeds the margin of the first block(s) of body # above the columns, which causes them to effectively be added to the # page margins (the margin collapse algorithm) document.body.style.setProperty('-webkit-margin-collapse', 'separate') c = first_child(document.body) if c: # Remove page breaks on the first few elements to prevent blank pages # at the start of a chapter set_important_css(c, break_before='avoid') if c.tagName.toLowerCase() is 'div': c2 = first_child(c) if c2 and not has_start_text(c): # Common pattern of all content being enclosed in a wrapper # <div>, see for example: https://bugs.launchpad.net/bugs/1366074 # In this case, we also modify the first child of the div # as long as there was no text before it. set_important_css(c2, break_before='avoid') if first_layout: # Because of a bug in webkit column mode, svg elements defined with # width 100% are wider than body and lead to a blank page after the # current page (when cols_per_screen == 1). Similarly img elements # with height=100% overflow the first column is_full_screen_layout = is_single_page if not is_full_screen_layout: has_no_more_than_two_columns = (scroll_viewport.paged_content_inline_size() < 2*screen_inline + 10) if has_no_more_than_two_columns and single_screen: if only_img and imgs.length and get_bounding_client_rect(imgs[0]).left < screen_inline: is_full_screen_layout = True if has_svg and svgs.length == 1 and get_bounding_client_rect(svgs[0]).left < screen_inline: is_full_screen_layout = True if is_full_screen_layout and only_img and cols_per_screen > 1: cols_per_screen = 1 col_size = screen_inline col_and_gap = col_size + gap document.body.style.columnWidth = f'100vw' def check_column_sizes(): nc = get_number_of_cols(True) if Math.floor(nc) is not nc: data = { 'col_size':col_size, 'gap':gap, 'scrollWidth':scroll_viewport.paged_content_inline_size(), 'ncols':nc, 'screen_inline': screen_inline } print('WARNING: column layout broken, probably because there is some non-reflowable content in the book whose inline size is greater than the column size', data) check_column_sizes() _in_paged_mode = True fit_images() scroll_resize_bug_watcher.layout_done() return gap def current_scroll_offset(): return scroll_viewport.inline_pos() def scroll_to_offset(offset): scroll_viewport.scroll_to_in_inline_direction(offset) def scroll_to_column(number, notify=False, duration=1000): nonlocal last_scrolled_to_column last_scrolled_to_column = number pos = number * col_and_gap limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size() pos = min(pos, limit) scroll_to_offset(pos) scroll_resize_bug_watcher.scrolled(pos, limit) def scroll_to_pos(pos, notify=False, duration=1000): nonlocal last_scrolled_to_column # Scroll to the column containing pos if jstype(pos) is not 'number': print(pos, 'is not a number, cannot scroll to it!') return if is_full_screen_layout: scroll_to_offset(0) last_scrolled_to_column = 0 return scroll_to_column(column_at(pos), notify=notify, duration=duration) def scroll_to_previous_position(fsd): fsd = fsd or next_spine_item.forward_scroll_data next_spine_item.forward_scroll_data = None if 0 < fsd.cols_left < cols_per_screen and cols_per_screen < get_number_of_cols(): scroll_resize_bug_watcher.last_command = scroll_to_previous_position.bind(None, fsd) scroll_to_column(fsd.current_col) return True def scroll_to_fraction(frac, on_initial_load): # Scroll to the position represented by frac (number between 0 and 1) if on_initial_load and frac is 1 and is_return() and scroll_to_previous_position(): return scroll_resize_bug_watcher.last_command = scroll_to_fraction.bind(None, frac, False) pos = Math.floor(scroll_viewport.paged_content_inline_size() * frac) scroll_to_pos(pos) def column_boundaries(): # Return the column numbers at the left edge and after the right edge # of the viewport l = column_at(current_scroll_offset() + 10) return l, l + cols_per_screen def column_at_current_scroll_offset(): return column_at(current_scroll_offset() + 10) def current_column_location(): # The location of the starting edge of the first column currently # visible in the viewport if is_full_screen_layout: return 0 return column_at_current_scroll_offset() * col_and_gap def number_of_cols_left(): current_col = column_at(current_scroll_offset() + 10) cols_left = get_number_of_cols() - (current_col + cols_per_screen) return Math.max(0, cols_left) def next_screen_location(): # The position to scroll to for the next screen (which could contain # more than one pages). Returns -1 if no further scrolling is possible. if is_full_screen_layout: return -1 cc = current_column_location() ans = cc + screen_inline + 1 if cols_per_screen > 1 and 0 < number_of_cols_left() < cols_per_screen: return -1 # Only blank, dummy pages left limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size() if limit < col_and_gap: return -1 if ans > limit: current_pos = Math.ceil(current_scroll_offset()) ans = limit if current_pos < limit else -1 if cols_per_screen is 1 and ans is not -1 and ans - current_pos < col_size: ans = -1 # cant scroll partial columns return ans def previous_screen_location(): # The position to scroll to for the previous screen (which could contain # more than one pages). Returns -1 if no further scrolling is possible. if is_full_screen_layout: return -1 cc = current_column_location() ans = cc - cols_per_screen * col_and_gap if ans < 0: # We ignore small scrolls (less than 15px) when going to previous # screen ans = 0 if current_scroll_offset() > 15 else -1 return ans def next_col_location(): # The position to scroll to for the next column (same as # next_screen_location() if columns per screen == 1). Returns -1 if no # further scrolling is possible. if is_full_screen_layout: return -1 cc = current_column_location() ans = cc + col_and_gap limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size() # print(f'cc={cc} col_and_gap={col_and_gap} ans={ans} limit={limit} content_inline_size={scroll_viewport.paged_content_inline_size()} inline={scroll_viewport.inline_size()} current_scroll_offset={current_scroll_offset()}') if ans > limit: if Math.ceil(current_scroll_offset()) < limit and column_at(limit) > column_at_current_scroll_offset(): ans = limit else: ans = -1 return ans def previous_col_location(): # The position to scroll to for the previous column (same as # previous_screen_location() if columns per screen == 1). Returns -1 if # no further scrolling is possible. if is_full_screen_layout: return -1 cc = current_column_location() ans = cc - col_and_gap if ans < 0: if Math.floor(current_scroll_offset()) > 0 and column_at(0) < column_at_current_scroll_offset(): ans = 0 else: ans = -1 return ans def jump_to_anchor(name): # Jump to the element identified by anchor name. elem = document.getElementById(name) if not elem: elems = document.getElementsByName(name) if elems: elem = elems[0] if not elem: return scroll_to_elem(elem) def scrollable_element(elem): # bounding rect calculation for an inline element containing a block # element that spans multiple columns is incorrect. Detect the common case # of this and avoid it. See https://bugs.launchpad.net/calibre/+bug/1918437 # for a test case. if not in_paged_mode() or window.getComputedStyle(elem).display.indexOf('inline') < 0 or not elem.firstElementChild: return elem if window.getComputedStyle(elem.firstElementChild).display.indexOf('block') > -1 and elem.getBoundingClientRect().top < -100: return elem.firstElementChild return elem def scroll_to_elem(elem): elem = scrollable_element(elem) scroll_viewport.scroll_into_view(elem) if in_paged_mode(): # Ensure we are scrolled to the column containing elem # Because of a bug in WebKit's getBoundingClientRect() in column # mode, this position can be inaccurate, see # https://bugs.launchpad.net/calibre/+bug/1132641 for a test case. # The usual symptom of the inaccuracy is br.top is highly negative. br = get_bounding_client_rect(elem) if br.top < -100: # This only works because of the preceding call to # elem.scrollIntoView(). However, in some cases it gives # inaccurate results, so we prefer the bounding client rect, # when possible. # In horizontal writing, the inline start position depends on the direction if scroll_viewport.horizontal_writing_mode: inline_start = elem.scrollLeft if scroll_viewport.ltr else elem.scrollRight # In vertical writing, the inline start position is always the top since # vertical text only flows top-to-bottom else: inline_start = elem.scrollTop else: # If we can use the rect, just use the simpler viewport helper function inline_start = scroll_viewport.rect_inline_start(br) scroll_to_pos(scroll_viewport.viewport_to_document_inline(inline_start+2, elem.ownerDocument)) def snap_to_selection(): # Ensure that the viewport is positioned at the start of the column # containing the start of the current selection if in_paged_mode(): sel = window.getSelection() r = sel.getRangeAt(0).getBoundingClientRect() node = sel.anchorNode # Columns are in the inline direction, so get the beginning of the element in the inline pos = scroll_viewport.viewport_to_document_inline( scroll_viewport.rect_inline_start(r), doc=node.ownerDocument) # Ensure we are scrolled to the column containing the start of the # selection scroll_to_pos(pos+5) def ensure_selection_boundary_visible(use_end): sel = window.getSelection() try: rr = sel.getRangeAt(0) except: rr = None if rr: r = rr.getBoundingClientRect() if r: cnum = column_at_current_scroll_offset() scroll_to_column(cnum) node = sel.focusNode if use_end else sel.anchorNode # Columns are in the inline direction, so get the beginning of the element in the inline x = scroll_viewport.rect_inline_end(r) if use_end else scroll_viewport.rect_inline_start(r) if x < 0 or x >= scroll_viewport.inline_size(): pos = scroll_viewport.viewport_to_document_inline(x, doc=node.ownerDocument) scroll_to_pos(pos+5) def jump_to_cfi(cfi): # Jump to the position indicated by the specified conformal fragment # indicator. scroll_resize_bug_watcher.last_command = jump_to_cfi.bind(None, cfi) cfi_scroll_to(cfi, def(x, y): if scroll_viewport.horizontal_writing_mode: scroll_to_pos(x) else: scroll_to_pos(y) ) def current_cfi(): # The Conformal Fragment Identifier at the current position, returns # null if it could not be calculated. ans = None if in_paged_mode(): for cnum in range(cols_per_screen): left = cnum * (col_and_gap + gap) right = left + col_size top, bottom = 0, scroll_viewport.height() midx = (right - left) // 2 deltax = (right - left) // 24 deltay = (bottom - top) // 24 midy = (bottom - top) // 2 yidx = 0 while True: yb, ya = midy - yidx * deltay, midy + yidx * deltay if yb <= top or ya >= bottom: break yidx += 1 ys = v'[ya]' if ya is yb else v'[yb, ya]' for cury in ys: xidx = 0 while True: xb, xa = midx - xidx * deltax, midx + xidx * deltax if xb <= left or xa >= right: break xidx += 1 xs = v'[xa]' if xa is xb else v'[xb, xa]' for curx in xs: cfi = cfi_at_point(curx, cury) if cfi: # print('Viewport cfi:', cfi) return cfi else: try: ans = cfi_at_current() or None except: traceback.print_exc() # if ans: # print('Viewport cfi:', ans) return ans def progress_frac(frac): # The current scroll position as a fraction between 0 and 1 if in_paged_mode(): limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size() if limit <= 0: return 1 # ensures that if the book ends with a single page file the last shown percentage is 100% return current_scroll_offset() / limit # In flow mode, we scroll in the block direction, so use that limit = scroll_viewport.document_block_size() - scroll_viewport.block_size() if limit <= 0: return 1 return Math.max(0, Math.min(scroll_viewport.block_pos() / limit, 1)) def page_counts(): if in_paged_mode(): return {'current': column_at_current_scroll_offset(), 'total': get_number_of_cols(), 'pages_per_screen': cols_per_screen} doc_size = scroll_viewport.document_block_size() screen_size = scroll_viewport.block_size() pos = scroll_viewport.block_pos() return { 'current': (pos + 10) // screen_size, 'total': doc_size // screen_size, 'pages_per_screen': 1 } def next_spine_item(backward): if not backward: csi = current_spine_item() next_spine_item.forward_scroll_data = { 'cols_per_screen': cols_per_screen, 'cols_left': number_of_cols_left(), 'spine_index': csi.index, 'spine_name': csi.name, 'current_col': column_at(current_scroll_offset() + 10) } get_boss().send_message('next_spine_item', previous=backward) def is_return(): fsd = next_spine_item.forward_scroll_data csi = current_spine_item() return fsd and fsd.cols_per_screen is cols_per_screen and fsd.spine_index is csi.index and fsd.spine_name is csi.name class WheelState: last_event_mode = 'page' last_event_at = -10000 last_event_backwards = False accumulated_scroll = 0 def reset(self): self.last_event_mode = WheelState.last_event_mode self.last_event_at = WheelState.last_event_at self.last_event_backwards = WheelState.last_event_backwards self.accumulated_scroll = WheelState.accumulated_scroll def add_pixel_scroll(self, backward, delta, scroll_func): now = window.performance.now() if now - self.last_event_at > 1000 or self.last_event_backwards is not backward or self.last_event_mode is not 'pixel': self.accumulated_scroll = 0 self.last_event_mode = 'pixel' self.last_event_at = now self.last_event_backwards = backward self.accumulated_scroll += delta if self.accumulated_scroll > opts.paged_pixel_scroll_threshold: self.reset() scroll_func(backward) class HandleWheel: def __init__(self): self.vertical_state = WheelState() self.horizontal_state = WheelState() def onwheel(self, evt): if not (evt.deltaY or evt.deltaX): return major_axis_vertical = True if evt.deltaY: if evt.deltaX: major_axis_vertical = Math.abs(evt.deltaY) >= Math.abs(evt.deltaX) else: major_axis_vertical = False if major_axis_vertical: backward = evt.deltaY < 0 if evt.deltaMode is window.WheelEvent.DOM_DELTA_PIXEL: self.vertical_state.add_pixel_scroll(backward, Math.abs(evt.deltaY), self.do_scroll) else: self.vertical_state.reset() self.do_scroll(backward) else: if opts.paged_wheel_section_jumps: backward = evt.deltaX < 0 if evt.deltaMode is window.WheelEvent.DOM_DELTA_PIXEL: self.horizontal_state.add_pixel_scroll(backward, Math.abs(evt.deltaX), self.do_section_jump) else: self.horizontal_state.reset() self.do_section_jump(backward) def do_scroll(self, backward): if opts.paged_wheel_scrolls_by_screen: pos = previous_screen_location() if backward else next_screen_location() else: pos = previous_col_location() if backward else next_col_location() if pos is -1: next_spine_item(backward) else: scroll_to_pos(pos) def do_section_jump(self, backward): get_boss().send_message('next_section', forward=not backward) wheel_handler = HandleWheel() onwheel = wheel_handler.onwheel def scroll_by_page(backward, by_screen, flip_if_rtl_page_progression): if flip_if_rtl_page_progression and rtl_page_progression(): backward = not backward if by_screen: pos = previous_screen_location() if backward else next_screen_location() pages = cols_per_screen else: pos = previous_col_location() if backward else next_col_location() pages = 1 if pos is -1: # dont report human scroll since we dont know if a full page was # scrolled or not next_spine_item(backward) else: if not backward: nc = get_number_of_cols() scrolled_frac = (pages / nc) if nc > 0 else 0 get_boss().report_human_scroll(scrolled_frac) else: get_boss().report_human_scroll() scroll_to_pos(pos) def scroll_to_extend_annotation(backward): pos = previous_col_location() if backward else next_col_location() if pos is -1: return False scroll_to_pos(pos) return True def handle_shortcut(sc_name, evt): if sc_name is 'up': scroll_by_page(backward=True, by_screen=True, flip_if_rtl_page_progression=False) return True if sc_name is 'down': scroll_by_page(backward=False, by_screen=True, flip_if_rtl_page_progression=False) return True if sc_name is 'start_of_file': get_boss().report_human_scroll() scroll_to_offset(0) return True if sc_name is 'end_of_file': get_boss().report_human_scroll() scroll_to_offset(scroll_viewport.document_inline_size()) return True if sc_name is 'left': scroll_by_page(backward=True, by_screen=False, flip_if_rtl_page_progression=True) return True if sc_name is 'right': scroll_by_page(backward=False, by_screen=False, flip_if_rtl_page_progression=True) return True if sc_name is 'start_of_book': get_boss().report_human_scroll() get_boss().send_message('goto_doc_boundary', start=True) return True if sc_name is 'end_of_book': get_boss().report_human_scroll() get_boss().send_message('goto_doc_boundary', start=False) return True if sc_name is 'pageup': scroll_by_page(backward=True, by_screen=True, flip_if_rtl_page_progression=False) return True if sc_name is 'pagedown': scroll_by_page(backward=False, by_screen=True, flip_if_rtl_page_progression=False) return True if sc_name is 'toggle_autoscroll': auto_scroll_action('toggle') return True return False def handle_gesture(gesture): # Gesture progression direction is determined in the gesture code, # don't set flip_if_rtl_page_progression=True here. if gesture.resolved_action is 'next_section': get_boss().send_message('next_section', forward=True) elif gesture.resolved_action is 'prev_section': get_boss().send_message('next_section', forward=False) elif gesture.resolved_action is 'next_screen': scroll_by_page(False, True) elif gesture.resolved_action is 'prev_screen': scroll_by_page(True, True) elif gesture.resolved_action is 'prev_page': scroll_by_page(True, False) elif gesture.resolved_action is 'next_page': scroll_by_page(False, False) def get_bounding_client_rect(elem): br = elem.getBoundingClientRect() if br.width is 0 and br.height is 0: # getBoundingClientRect() fails sometimes, see https://bugs.launchpad.net/calibre/+bug/2037543 r = document.createRange() r.selectNodeContents(elem) br = r.getBoundingClientRect() return br anchor_funcs = { 'pos_for_elem': def pos_for_elem(elem): if not elem: return 0 elem = scrollable_element(elem) br = get_bounding_client_rect(elem) pos = scroll_viewport.viewport_to_document_inline( scroll_viewport.rect_inline_start(br)) return column_at(pos) , 'visibility': def visibility(pos): first = column_at(current_scroll_offset() + 10) if pos < first: return -1 if pos < first + cols_per_screen: return 0 return 1 , 'cmp': def cmp(a, b): return a - b , 'get_bounding_client_rect': get_bounding_client_rect, } class ResizeManager: def __init__(self): self.reset() def reset(self): self.resize_in_progress = None self.last_transition = None def start_resize(self, width, height): self.resize_in_progress = {'width': width, 'height': height, 'column': last_scrolled_to_column} def end_resize(self): if not self.resize_in_progress: return rp, self.resize_in_progress = self.resize_in_progress, None transition = {'before': rp, 'after': { 'width': scroll_viewport.width(), 'height': scroll_viewport.height(), 'column': last_scrolled_to_column}} if self.is_inverse_transition(transition): if transition.after.column is not self.last_transition.before.column: scroll_to_column(transition.after.column) transition.after.column = last_scrolled_to_column self.last_transition = transition def is_inverse_transition(self, transition): p = self.last_transition if not p: return False p = p.after n = transition.before return p.column is n.column and p.width is n.width and p.height is n.height resize_manager = ResizeManager() def prepare_for_resize(width, height): resize_manager.start_resize(width, height) def resize_done(): resize_manager.end_resize() def auto_scroll_action(action): if action is 'toggle': get_boss().send_message('error', errkey='no-auto-scroll-in-paged-mode', is_non_critical=True) return False class DragScroller: INTERVAL = 500 def __init__(self): self.backward = False self.timer_id = None def is_running(self): return self.timer_id is not None def start(self, backward): if not self.is_running() or backward is not self.backward: self.stop() self.backward = backward self.timer_id = window.setTimeout(self.do_one_page_turn, self.INTERVAL) def do_one_page_turn(self): pos = previous_col_location() if self.backward else next_col_location() if pos >= 0: scroll_to_pos(pos) self.timer_id = window.setTimeout(self.do_one_page_turn, self.INTERVAL * 2) else: self.stop() def stop(self): if self.timer_id is not None: window.clearTimeout(self.timer_id) self.timer_id = None drag_scroller = DragScroller() def cancel_drag_scroll(): drag_scroller.stop() def start_drag_scroll(delta): drag_scroller.start(delta < 0)
38,037
Python
.py
823
38.144593
226
0.650749
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,539
touch.pyj
kovidgoyal_calibre/src/pyj/read_book/touch.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from gettext import gettext as _ from read_book.globals import get_boss, ltr_page_progression, ui_operations from read_book.settings import opts from read_book.viewport import get_unit_size_in_pixels, scroll_viewport HOLD_THRESHOLD = 750 # milliseconds TAP_THRESHOLD = 8 # pixels SWIPE_THRESHOLD = 64 # pixels TAP_LINK_THRESHOLD = 5 # pixels PINCH_THRESHOLD = 20 # pixels GESTURE = {k:k for k in v"""[ 'back_zone_tap', 'forward_zone_tap', 'control_zone_tap', 'long_tap', 'two_finger_tap', 'pinch_in', 'pinch_out', 'flick_inline_backward', 'flick_inline_forward', 'flick_block_backward', 'flick_block_forward', 'swipe_inline_backward_in_progress', 'swipe_inline_forward_in_progress', 'swipe_block_backward_in_progress', 'swipe_block_forward_in_progress', 'swipe_inline_backward_hold', 'swipe_inline_forward_hold', 'swipe_block_backward_hold', 'swipe_block_forward_hold', 'tap', 'swipe', 'pinch', ]"""} def GESTURE_NAMES(): ans = GESTURE_NAMES.ans if not ans: GESTURE_NAMES.ans = ans = { 'back_zone_tap': _('Tap on back zone'), 'forward_zone_tap': _('Tap on forward zone'), 'control_zone_tap': _('Tap in the controls zone'), 'long_tap': _('Long tap'), 'two_finger_tap': _('Two finger tap'), 'pinch_in': _('Pinch in'), 'pinch_out': _('Pinch out'), 'flick_inline_backward': _('Flick in writing direction, to go back'), 'flick_inline_forward': _('Flick in writing direction, to go forward'), 'flick_block_backward': _('Flick perpendicular to writing direction, to go forward'), 'flick_block_forward': _('Flick perpendicular to writing direction, to go back'), 'swipe_inline_backward_in_progress': _('Drag finger in writing direction, to go back'), 'swipe_inline_forward_in_progress': _('Drag finger in writing direction, to go forward'), 'swipe_block_backward_in_progress': _('Drag finger perpendicular to writing direction, to go back'), 'swipe_block_forward_in_progress': _('Drag finger perpendicular to writing direction, to go forward'), 'swipe_inline_backward_hold': _('Drag and hold finger in writing direction, to go back'), 'swipe_inline_forward_hold': _('Drag and hold finger in writing direction, to go forward'), 'swipe_block_backward_hold': _('Drag and hold finger perpendicular to writing direction, to go back'), 'swipe_block_forward_hold': _('Drag and hold finger perpendicular to writing direction, to go forward'), } return ans gesture_id = 0 def touch_id(touch): # On Safari using touch.identifier as dict key yields a key of "NaN" for some reason return touch.identifier + '' def copy_touch(t): now = window.performance.now() return { 'identifier':touch_id(t), 'page_x':v'[t.pageX]', 'page_y':v'[t.pageY]', 'viewport_x':v'[t.clientX]', 'viewport_y':v'[t.clientY]', 'active':True, 'mtimes':v'[now]', 'ctime':now, 'is_held':False, 'x_velocity': 0, 'y_velocity': 0 } def update_touch(t, touch): now = window.performance.now() t.mtimes.push(now) t.page_x.push(touch.pageX), t.page_y.push(touch.pageY) t.viewport_x.push(touch.clientX), t.viewport_y.push(touch.clientY) def max_displacement(points): ans = 0 first = points[0] if not first?: return ans for p in points: delta = abs(p - first) if delta > ans: ans = delta return ans def interpret_single_gesture(touch, gesture_id): max_x_displacement = max_displacement(touch.viewport_x) max_y_displacement = max_displacement(touch.viewport_y) ans = {'active':touch.active, 'is_held':touch.is_held, 'id':gesture_id, 'start_time': touch.ctime} if max(max_x_displacement, max_y_displacement) < TAP_THRESHOLD: ans.type = GESTURE.tap ans.viewport_x = touch.viewport_x[0] ans.viewport_y = touch.viewport_y[0] return ans if touch.viewport_y.length < 2: return ans delta_x = abs(touch.viewport_x[-1] - touch.viewport_x[0]) delta_y = abs(touch.viewport_y[-1] - touch.viewport_y[0]) max_disp = max(delta_y, delta_x) if max_disp > SWIPE_THRESHOLD and min(delta_x, delta_y)/max_disp < 0.35: ans.type = GESTURE.swipe ans.axis = 'vertical' if delta_y > delta_x else 'horizontal' ans.points = pts = touch.viewport_y if ans.axis is 'vertical' else touch.viewport_x ans.times = touch.mtimes positive = pts[-1] > pts[0] if ans.axis is 'vertical': ans.direction = 'down' if positive else 'up' ans.velocity = touch.y_velocity else: ans.direction = 'right' if positive else 'left' ans.velocity = touch.x_velocity return ans return ans def interpret_double_gesture(touch1, touch2, gesture_id): ans = {'active':touch1.active or touch2.active, 'is_held':touch1.is_held or touch2.is_held, 'id':gesture_id} max_x_displacement1 = max_displacement(touch1.viewport_x) max_x_displacement2 = max_displacement(touch2.viewport_x) max_y_displacement1 = max_displacement(touch1.viewport_y) max_y_displacement2 = max_displacement(touch2.viewport_y) if max(max_x_displacement1, max_y_displacement1) < TAP_THRESHOLD and max(max_x_displacement2, max_y_displacement2) < TAP_THRESHOLD: ans.type = GESTURE.two_finger_tap ans.viewport_x1 = touch1.viewport_x[0] ans.viewport_y1 = touch1.viewport_y[0] ans.viewport_x2 = touch2.viewport_x[0] ans.viewport_y2 = touch2.viewport_y[0] return ans initial_distance = Math.sqrt((touch1.viewport_x[0] - touch2.viewport_x[0])**2 + (touch1.viewport_y[0] - touch2.viewport_y[0])**2) final_distance = Math.sqrt((touch1.viewport_x[-1] - touch2.viewport_x[-1])**2 + (touch1.viewport_y[-1] - touch2.viewport_y[-1])**2) distance = abs(final_distance - initial_distance) if distance > PINCH_THRESHOLD: ans.type = GESTURE.pinch ans.direction = 'in' if final_distance < initial_distance else 'out' ans.distance = distance return ans return ans def element_from_point(x, y): # This does not currently support detecting links inside iframes, but since # iframes are not common in books, I am going to ignore that for now return document.elementFromPoint(x, y) def find_link(x, y): p = element_from_point(x, y) while p: if p.tagName and p.tagName.toLowerCase() is 'a' and p.hasAttribute('href'): return p p = p.parentNode def tap_on_link(gesture): for delta_x in [0, TAP_LINK_THRESHOLD, -TAP_LINK_THRESHOLD]: for delta_y in [0, TAP_LINK_THRESHOLD, -TAP_LINK_THRESHOLD]: x = gesture.viewport_x + delta_x y = gesture.viewport_y + delta_y link = find_link(x, y) if link: link.click() return True return False class TouchHandler: def __init__(self): self.ongoing_touches = {} self.gesture_id = None self.hold_timer = None self.handled_tap_hold = False def prune_expired_touches(self): now = window.performance.now() expired = v'[]' for tid in self.ongoing_touches: t = self.ongoing_touches[tid] if t.active: if now - t.mtimes[-1] > 3000: expired.push(touch_id(t)) for tid in expired: v'delete self.ongoing_touches[tid]' @property def has_active_touches(self): for tid in self.ongoing_touches: t = self.ongoing_touches[tid] if t.active: return True return False def reset_handlers(self): self.stop_hold_timer() self.ongoing_touches = {} self.gesture_id = None self.handled_tap_hold = False def start_hold_timer(self): self.stop_hold_timer() self.hold_timer = window.setTimeout(self.check_for_hold, 50) def stop_hold_timer(self): if self.hold_timer is not None: window.clearTimeout(self.hold_timer) self.hold_timer = None def check_for_hold(self): if len(self.ongoing_touches) > 0: now = window.performance.now() found_hold = False for touchid in self.ongoing_touches: touch = self.ongoing_touches[touchid] if touch.active and now - touch.mtimes[-1] > HOLD_THRESHOLD: touch.is_held = True found_hold = True if found_hold: self.dispatch_gesture() self.start_hold_timer() def handle_touchstart(self, ev): if jstype(ev.cancelable) is not 'boolean' or ev.cancelable: ev.preventDefault() ev.stopPropagation() self.prune_expired_touches() for touch in ev.changedTouches: self.ongoing_touches[touch_id(touch)] = copy_touch(touch) if self.gesture_id is None: nonlocal gesture_id gesture_id += 1 self.gesture_id = gesture_id self.handled_tap_hold = False if len(self.ongoing_touches) > 0: self.start_hold_timer() def handle_touchmove(self, ev): if jstype(ev.cancelable) is not 'boolean' or ev.cancelable: ev.preventDefault() ev.stopPropagation() for touch in ev.changedTouches: t = self.ongoing_touches[touch_id(touch)] if t: update_touch(t, touch) self.dispatch_gesture() def handle_touchend(self, ev): if jstype(ev.cancelable) is not 'boolean' or ev.cancelable: ev.preventDefault() ev.stopPropagation() for touch in ev.changedTouches: t = self.ongoing_touches[touch_id(touch)] if t: t.active = False update_touch(t, touch) self.prune_expired_touches() if not self.has_active_touches: self.dispatch_gesture() self.reset_handlers() def handle_touchcancel(self, ev): if jstype(ev.cancelable) is not 'boolean' or ev.cancelable: ev.preventDefault() ev.stopPropagation() for touch in ev.changedTouches: tid = touch_id(touch) # noqa: unused-local v'delete self.ongoing_touches[tid]' self.gesture_id = None self.handled_tap_hold = False def dispatch_gesture(self): touches = self.ongoing_touches num = len(touches) gesture = {} if num is 1: gesture = interpret_single_gesture(touches[Object.keys(touches)[0]], self.gesture_id) elif num is 2: t = Object.keys(touches) gesture = interpret_double_gesture(touches[t[0]], touches[t[1]], self.gesture_id) if not gesture?.type: return self.handle_gesture(gesture) def inch_in_pixels(): ans = inch_in_pixels.ans if not ans: ans = inch_in_pixels.ans = max(2, get_unit_size_in_pixels('in')) return ans class BookTouchHandler(TouchHandler): def __init__(self, for_side_margin=None): self.for_side_margin = for_side_margin TouchHandler.__init__(self) def handle_gesture(self, gesture): if gesture.type is GESTURE.tap: if gesture.is_held: if not self.for_side_margin and not self.handled_tap_hold and window.performance.now() - gesture.start_time >= HOLD_THRESHOLD: self.handled_tap_hold = True gesture.type = GESTURE.long_tap get_boss().handle_gesture(gesture) return if not gesture.active: if self.for_side_margin or not tap_on_link(gesture): inch = inch_in_pixels() if gesture.viewport_y < min(100, scroll_viewport.height() / 4): gesture.type = GESTURE.control_zone_tap else: limit = inch # default, books that go left to right. if ltr_page_progression() and not opts.reverse_page_turn_zones: if gesture.viewport_x < min(limit, scroll_viewport.width() / 4): gesture.type = GESTURE.back_zone_tap else: gesture.type = GESTURE.forward_zone_tap # We swap the sizes in RTL mode, so that going to the next page is always the bigger touch region. else: # The "going back" area should not be more than limit units big, # even if 1/4 of the scroll viewport is more than limit units. # Checking against the larger of the width minus the limit units and 3/4 of the width will accomplish that. if gesture.viewport_x > max(scroll_viewport.width() - limit, scroll_viewport.width() * (3/4)): gesture.type = GESTURE.back_zone_tap else: gesture.type = GESTURE.forward_zone_tap elif gesture.type is GESTURE.pinch: if gesture.active: return gesture.type = GESTURE.pinch_in if gesture.direction is 'in' else GESTURE.pinch_out elif gesture.type is GESTURE.two_finger_tap: if gesture.active: return elif gesture.type is 'swipe': backward_dir = 'down' if gesture.axis is 'vertical' else ('right' if ltr_page_progression() else 'left') direction = 'backward' if gesture.direction is backward_dir else 'forward' inline_dir = 'vertical' if scroll_viewport.vertical_writing_mode else 'horizontal' axis = 'inline' if gesture.axis is inline_dir else 'block' if gesture.active: gesture.type = GESTURE[f'swipe_{axis}_{direction}' + ('_hold' if gesture.is_held else '_in_progress')] elif not gesture.is_held: gesture.type = GESTURE[f'flick_{axis}_{direction}'] if self.for_side_margin: ui_operations.forward_gesture(gesture) else: get_boss().handle_gesture(gesture) def __repr__(self): return 'BookTouchHandler:for_side_margin:' + self.for_side_margin main_touch_handler = BookTouchHandler() left_margin_handler = BookTouchHandler('left') right_margin_handler = BookTouchHandler('right') def install_handlers(elem, handler, passive): options = {'capture': True, 'passive': v'!!passive'} elem.addEventListener('touchstart', handler.handle_touchstart, options) elem.addEventListener('touchmove', handler.handle_touchmove, options) elem.addEventListener('touchend', handler.handle_touchend, options) elem.addEventListener('touchcancel', handler.handle_touchcancel, options) def create_handlers(): # Safari does not work if we register the handler # on window instead of document install_handlers(document, main_touch_handler) # See https://github.com/kovidgoyal/calibre/pull/1101 # for why we need touchAction none document.body.style.touchAction = 'none' def reset_handlers(): main_touch_handler.reset_handlers() def set_left_margin_handler(elem): install_handlers(elem, left_margin_handler) def set_right_margin_handler(elem): install_handlers(elem, right_margin_handler)
15,720
Python
.py
344
36.363372
142
0.623556
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,540
anchor_visibility.pyj
kovidgoyal_calibre/src/pyj/read_book/anchor_visibility.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from read_book.globals import current_layout_mode, get_boss from read_book.viewport import scroll_viewport anchor_position_cache = {} def invalidate_anchor_position_cache(): nonlocal anchor_position_cache anchor_position_cache = { 'layout_mode': current_layout_mode(), 'width': scroll_viewport.width(), 'height': scroll_viewport.height(), 'positions': v'{}', } def ensure_anchor_cache_valid(): a = anchor_position_cache if a.layout_mode is not current_layout_mode() or a.width is not scroll_viewport.width() or a.height is not scroll_viewport.height(): invalidate_anchor_position_cache() def ensure_page_list_target_is_displayed(elem): # The stupid EPUB 3 examples have page list links pointing to # display:none divs. Sigh. if elem and window.getComputedStyle(elem).display is 'none': elem.textContent = '' elem.setAttribute('style', 'all: revert') def position_for_anchor(anchor, is_page_list_anchor): ensure_anchor_cache_valid() cache = anchor_position_cache.positions val = cache[anchor] if val?: return val anchor_funcs = get_boss().anchor_funcs if anchor: elem = document.getElementById(anchor) if not elem: q = document.getElementsByName(anchor) if q and q.length: elem = q[0] else: elem = document.body if is_page_list_anchor: ensure_page_list_target_is_displayed(elem) val = anchor_funcs.pos_for_elem(elem) if elem else anchor_funcs.pos_for_elem() cache[anchor] = val return val def is_anchor_on_screen(anchor): pos = position_for_anchor(anchor) anchor_funcs = get_boss().anchor_funcs return anchor_funcs.visibility(pos) is 0
1,904
Python
.py
46
35.630435
136
0.69464
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,541
db.pyj
kovidgoyal_calibre/src/pyj/read_book/db.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from encodings import base64decode, base64encode from gettext import gettext as _ from book_list.router import is_reading_book from modals import error_dialog from read_book.annotations import merge_annotation_maps from session import get_interface_data from utils import username_key def upgrade_schema(idb, old_version, new_version, transaction): print('upgrade_schema:', old_version, new_version) if not idb.objectStoreNames.contains('books'): idb.createObjectStore('books', {'keyPath':'key'}) if not idb.objectStoreNames.contains('files'): idb.createObjectStore('files') if not idb.objectStoreNames.contains('mathjax'): idb.createObjectStore('mathjax') if not idb.objectStoreNames.contains('objects'): idb.createObjectStore('objects', {'keyPath':'key'}) # Create indices books_store = transaction.objectStore('books') if not books_store.indexNames.contains('recent_index'): books_store.createIndex('recent_index', 'recent_date') def file_store_name(book, name): return book.book_hash + ' ' + name def get_error_details(event): desc = event.target if desc.error and desc.error.toString: desc = desc.error.toString() elif desc.errorCode: desc = desc.errorCode elif desc.error: desc = desc.error if desc.name is 'QuotaExceededError': desc = _('Offline storage quota exceeded! Try deleting some stored books first.') elif desc.name: desc = desc.name return desc or 'Unknown Error' def new_book(key, metadata): return { 'key':key, 'is_complete':False, 'stored_files': {}, 'book_hash':None, 'metadata': metadata, 'manifest': None, 'cover_width': None, 'cover_height': None, 'cover_name': None, 'recent_date': new Date(), 'last_read': {}, 'last_read_position': {}, 'saved_reading_rates': {}, 'annotations_map': {}, } DB_NAME = 'calibre' DB_VERSION = 1 def indexed_db_api(): if window?: return window.indexedDB if self?: return self.indexedDB class DB: def __init__(self, callback, show_read_book_error): self.initialized = False self.is_ok = False self.initialize_error_msg = None self.callback = callback self.show_read_book_error = show_read_book_error self.initialize_stage1() def show_error(self, title, msg, det_msg): if not window? or is_reading_book(): self.show_read_book_error(title, msg, det_msg) else: error_dialog(title, msg, det_msg) def initialize_stage1(self): idb = indexed_db_api() if not idb: self.initialize_error_msg = _('Your browser does not support IndexedDB. Cannot read books. Consider using a modern browser, such as Chrome or Firefox.') self.initialized = True # Callers assume __init__ has finished before the callback is # called, since we are called in __init__, only callback after # event loop ticks over setTimeout(self.callback, 0) return request = idb.open(DB_NAME, DB_VERSION) request.onupgradeneeded = def(event): upgrade_schema(event.target.result, event.oldVersion, event.newVersion, event.target.transaction) request.onblocked = def(event): self.initialize_error_msg = _('Please close all other browser tabs with calibre open') self.initialized = True console.log(event) self.callback() request.onerror = def(event): self.initialize_error_msg = _('You must allow calibre to use IndexedDB storage in your browser to read books') self.initialized = True console.log(event) self.callback() request.onsuccess = def(event): blob = Blob(['test'], {'type':"text/plain"}) idb = event.target.result store = idb.transaction(['files'], 'readwrite').objectStore('files') try: req = store.put(blob, ':-test-blob-:') except: self.initialize_stage2(idb, False) return req.onsuccess = def(event): self.initialize_stage2(idb, True) req.onerror = def(event): # We use setTimeout as otherwise the idb.onerror handler is # called with this error on Safari setTimeout(self.initialize_stage2.bind(None, idb, False), 0) def initialize_stage2(self, idb, supports_blobs): self.idb = idb self.supports_blobs = supports_blobs self.initialized = True self.is_ok = True if not supports_blobs: print('WARNING: browser does not support blob storage, calibre falling back to base64 encoding') idb.onerror = def(event): self.display_error(None, event) if console.dir: console.dir(event) else: console.log(event) idb.onversionchange = def(event): idb.close() self.show_error(_('Database upgraded!'), _( 'A newer version of calibre is available, please click the Reload button in your browser.')) self.callback() def display_error(self, msg, event): if event.already_displayed_by_calibre: return event.already_displayed_by_calibre = True msg = msg or _( 'There was an error while interacting with the' ' database used to store books for offline reading. Click "Show details" for more information.') self.show_error(_('Cannot read book'), msg, get_error_details(event)) def do_op(self, stores, data, error_msg, proceed, op='get', store=None): store = store or stores[0] if op is 'get': transaction = self.idb.transaction(stores) req = transaction.objectStore(store).get(data) req.onsuccess = def(event): if proceed: proceed(req.result) elif op is 'put': transaction = self.idb.transaction(stores, 'readwrite') req = transaction.objectStore(store).put(data) if proceed: req.onsuccess = proceed req.onerror = def(event): self.display_error(error_msg, event) def get_book(self, library_id, book_id, fmt, metadata, proceed): fmt = fmt.toUpperCase() # The key has to be a JavaScript array as otherwise it cannot be stored # into indexed db, because the RapydScript list has properties that # refer to non-serializable objects like functions. book_id = int(book_id) key = v'[library_id, book_id, fmt]' self.do_op(['books'], key, _('Failed to read from the books database'), def(result): if result and not result.annotations_map: result.annotations_map = {} proceed(result or new_book(key, metadata)) ) def get_mathjax_info(self, proceed): self.do_op(['objects'], 'mathjax-info', _('Failed to read from the objects database'), def(result): proceed(result or {'key':'mathjax-info'}) ) def save_manifest(self, book, manifest, proceed): book.manifest = manifest book.metadata = manifest.metadata book.book_hash = manifest.book_hash.hash book.stored_files = {} book.is_complete = False newest_epoch = newest_pos = None for pos in manifest.last_read_positions: if newest_epoch is None or pos.epoch > newest_epoch: newest_epoch = pos.epoch newest_pos = pos.cfi username = get_interface_data().username unkey = username_key(username) if newest_pos and username: book.last_read[unkey] = new Date(newest_epoch * 1000) book.last_read_position[unkey] = newest_pos if manifest.annotations_map: book.annotations_map[unkey] = manifest.annotations_map v'delete manifest.metadata' v'delete manifest.last_read_positions' v'delete manifest.annotations_map' self.do_op(['books'], book, _('Failed to write to the books database'), proceed, op='put') def store_file(self, book, name, xhr, proceed, is_cover): store_as_text = xhr.responseType is 'text' or not xhr.responseType fname = file_store_name(book, name) needs_encoding = not store_as_text and not self.supports_blobs mt = book.manifest.files[name]?.mimetype if not mt and is_cover: mt = 'image/jpeg' book.stored_files[fname] = {'encoded':needs_encoding, 'mimetype':mt, 'store_as_text':store_as_text} if is_cover: self.store_cover(book, needs_encoding, xhr.response, name, fname, proceed) else: self.store_file_stage2(needs_encoding, xhr.response, name, fname, proceed) def store_cover(self, book, needs_encoding, data, name, fname, proceed): blob = data if needs_encoding: blob = Blob([data], {'type':'image/jpeg'}) url = window.URL.createObjectURL(blob) img = new Image() book.cover_name = name proceeded = False def done(): nonlocal proceeded if not proceeded: proceeded = True window.URL.revokeObjectURL(url) self.store_file_stage2(needs_encoding, data, name, fname, proceed) img.onload = def(): book.cover_width = this.width book.cover_height = this.height done() img.onerror = def(): print('WARNING: Failed to read dimensions of cover') done() img.src = url def store_file_stage2(self, needs_encoding, data, name, fname, proceed): if needs_encoding: data = base64encode(Uint8Array(data)) req = self.idb.transaction(['files'], 'readwrite').objectStore('files').put(data, fname) req.onsuccess = def(event): proceed() req.onerror = def(event): proceed(_('Failed to store book data ({0}) with error: {1}').format(name, get_error_details(event))) def clear_mathjax(self, proceed): self.idb.transaction(['mathjax'], 'readwrite').objectStore('mathjax').clear().onsuccess = proceed def store_mathjax_file(self, name, xhr, proceed): data = xhr.response if not self.supports_blobs: data = base64encode(Uint8Array(data)) req = self.idb.transaction(['mathjax'], 'readwrite').objectStore('mathjax').put(data, name) req.onsuccess = def(event): proceed() req.onerror = def(event): proceed(_('Failed to store mathjax file ({0}) with error: {1}').format(name, get_error_details(event))) def finish_book(self, book, proceed): book.is_complete = True self.do_op(['books'], book, _('Failed to write to the books database'), proceed, op='put') def finish_mathjax(self, mathjax_info, proceed): self.do_op(['objects'], mathjax_info, _('Failed to write to the objects database'), proceed, op='put') def update_last_read_time(self, book): unkey = username_key(get_interface_data().username) now = new Date() book.last_read[unkey] = book.recent_date = now self.do_op(['books'], book, _('Failed to write to the books database'), op='put') def update_metadata(self, book, new_metadata): if book.metadata: for key in Object.keys(new_metadata): book.metadata[key] = new_metadata[key] self.do_op(['books'], book, _('Failed to write to the books database'), def(): None;, op='put') def save_reading_rates(self, book, rates): book.saved_reading_rates = rates self.do_op(['books'], book, _('Failed to write to the books database'), def(): None;, op='put') def update_annotations_data_from_key(self, library_id, book_id, fmt, new_data): unkey = username_key(get_interface_data().username) self.get_book(library_id, book_id, fmt, None, def(book): if book.metadata: # book exists changed = False if new_data.last_read_position: book.last_read[unkey] = book.recent_date = new_data.last_read book.last_read_position[unkey] = new_data.last_read_position changed = True if not book.annotations_map: book.annotations_map = v'{}' if new_data.annotations_map: existing = book.annotations_map[unkey] if not existing: changed = True book.annotations_map[unkey] = new_data.annotations_map else: updated, merged = merge_annotation_maps(existing, new_data.annotations_map) if updated: changed = True book.annotations_map[unkey] = merged if changed: self.do_op(['books'], book, _('Failed to write to the books database'), def(): None;, op='put') ) def get_file(self, book, name, proceed): key = file_store_name(book, name) err = _( 'Failed to read the file {0} for the book {1} from the browser offline cache.' ).format(name, book.metadata.title) self.do_op(['files'], key, err, def (result): if not result: # File was not found in the cache, this happens in Chrome if # the Application Cache is full. IndexedDB put succeeds, # but get fails. Browsers are a horrible travesty. bad = err + _( ' This usually means the cache is close to full. Clear the browser' ' cache from the browser settings.') self.show_error(_('Cannot read file from book'), bad) return fdata = book.stored_files[key] mt = fdata.mimetype or 'application/octet-stream' if fdata.encoded: result = Blob([base64decode(result)], {'type':mt}) proceed(result, name, mt, book) ) def get_book_file(self, book_hash, stored_files, name, proceed): stores = ['files'] key = file_store_name({'book_hash': book_hash}, name) transaction = self.idb.transaction(stores) req = transaction.objectStore(stores[0]).get(key) req.onsuccess = def(event): if not req.result: proceed({'ok': False, 'name': name, 'details': 'ENOENT'}) return fdata = stored_files[key] mt = fdata.mimetype or 'application/octet-stream' if fdata.encoded: result = Blob([base64decode(result)], {'type':mt}) proceed({'ok': True, 'result': req.result, 'name': name, 'mt': mt}) req.onerror = def(event): details = get_error_details(event) proceed({'ok': False, 'name': name, 'details': details}) def get_mathjax_files(self, proceed): c = self.idb.transaction('mathjax').objectStore('mathjax').openCursor() c.onerror = def(event): err = _('Failed to read the MathJax files from the browser offline cache.') self.display_error(err, event) data = {} c.onsuccess = def(event): cursor = event.target.result if cursor: name, result = cursor.key, cursor.value if not isinstance(result, Blob): mt = 'application/x-font-woff' if name.endswith('.woff') else 'text/javascript' result = Blob([base64decode(result)], {'type':mt}) data[name] = result cursor.continue() else: proceed(data) def get_recently_read_books(self, proceed, limit): limit = limit or 3 c = self.idb.transaction(['books'], 'readonly').objectStore('books').index('recent_index').openCursor(None, 'prev') books = v'[]' c.onerror = def(event): err = _('Failed to read recent books from local storage') self.display_error(err, event) c.onsuccess = def (ev): cursor = ev.target.result if cursor: books.push(cursor.value) if books.length >= limit or not cursor: proceed(books) return if cursor: cursor.continue() def has_book_matching(self, library_id, book_id, proceed): # Should really be using a multiEntry index to avoid iterating over all # books in JS, but since the number of stored books is not that large, # I can't be bothered. c = self.idb.transaction(['books'], 'readonly').objectStore('books').index('recent_index').openCursor(None, 'prev') c.onerror = def(event): proceed(False) book_id = int(book_id) c.onsuccess = def (ev): cursor = ev.target.result if cursor: book = cursor.value if book.key[0] is library_id and book.key[1] is book_id: proceed(True) return cursor.continue() else: proceed(False) def delete_book(self, book, proceed): c = self.idb.transaction(['books', 'files'], 'readwrite') files = c.objectStore('files') books = c.objectStore('books') filenames = Object.keys(book.stored_files) c.oncomplete = def(event): proceed(book) c.onerror = def (event): proceed(book, c.error.toString()) def next_step(): if filenames.length: r = files.delete(filenames.pop()) r.onsuccess = next_step else: books.delete(book.key) next_step() def delete_books_matching(self, library_id, book_id, proceed): c = self.idb.transaction(['books'], 'readonly').objectStore('books').index('recent_index').openCursor(None, 'prev') c.onerror = def(event): pass book_id = int(book_id) matches = v'[]' def delete_all(): if matches.length: book = matches.pop() self.delete_book(book, delete_all) else: if proceed: proceed() c.onsuccess = def (ev): cursor = ev.target.result if cursor: book = cursor.value if book.key[0] is library_id and book.key[1] is book_id: matches.push(book) cursor.continue() else: delete_all() def get_db(callback, show_read_book_error): if not get_db.ans: get_db.ans = DB(callback, show_read_book_error) return get_db.ans
19,306
Python
.py
418
35.009569
164
0.588582
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,542
find.pyj
kovidgoyal_calibre/src/pyj/read_book/find.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals ignored_tags = { 'style': True, 'script': True, 'noscript': True, 'title': True, 'meta': True, 'head': True, 'link': True, 'html': True, 'img': True, 'rt': True, 'rp': True, 'rtc': True, } block_tags_for_tts = { 'h1': True, 'h2': True, 'h3': True, 'h4': True, 'h5': True, 'h6': True, 'p': True, 'div': True, 'table': True, 'th': True, 'tr': True, 'td': True, 'section': True, 'article': True, } def build_text_map(for_tts): node_list = v'[]' flat_text = '' text_node_type = Node.TEXT_NODE element_node_type = Node.ELEMENT_NODE in_ruby = 0 def process_node(node): nonlocal flat_text, in_ruby nt = node.nodeType if nt is text_node_type: text = node.nodeValue if text and text.length: if in_ruby: rtext = text.trim() if rtext.length: node_list.push(v"{node: node, offset: flat_text.length, length: rtext.length, offset_in_node: text.length - text.trimStart().length}") flat_text += rtext else: node_list.push(v"{node: node, offset: flat_text.length, length: text.length}") flat_text += text elif nt is element_node_type: if not node.hasChildNodes(): return tag = node.tagName.toLowerCase() if ignored_tags[tag]: return is_ruby_tag = tag is 'ruby' if is_ruby_tag: in_ruby += 1 children = node.childNodes for i in range(children.length): process_node(v'children[i]') if is_ruby_tag: in_ruby -= 1 if for_tts and block_tags_for_tts[tag]: # add a paragraph separator after block tags so that sentence splitting works if flat_text.length and ' \n\t\r'.indexOf(flat_text[-1]) > -1: flat_text = flat_text[:-1] + '\u2029' elif node_list.length: flat_text += '\u2029' node_list[-1].length += 1 process_node(document.body) return {'timestamp': window.performance.now(), 'flat_text': flat_text, 'node_list': node_list} def index_for_node(node, node_list): for entry in node_list: if entry.node.isSameNode(node): return entry.offset def tts_word_regex(): # Cf is Other, formatting, including soft hyphens zero-width joiners, etc return /[\p{Letter}\p{Mark}\p{Number}\p{Punctuation}\p{Cf}]{1,50}/gu def cached_tts_text_map(): if not cache.tts_text_map: cache.tts_text_map = build_text_map(True) return cache.tts_text_map def tts_data(text_node, offset): offset_in_flat_text = offset or 0 text_map = cached_tts_text_map() if text_node: offset_in_flat_text += index_for_node(text_node, text_map.node_list) or 0 match = None first = True last = None marked_text = v'[]' text = text_map.flat_text[offset_in_flat_text:] for v'match of text.matchAll(tts_word_regex())': start = match.index if first: first = False if start: marked_text.push(text[:start]) elif start > last: marked_text.push(text[last:start]) marked_text.push(start + offset_in_flat_text) marked_text.push(match[0]) last = start + match[0].length if last is None: marked_text.push(text) else: trailer = text[last:] if trailer: marked_text.push(trailer) return marked_text def find_node_for_index_binary(node_list, idx_in_flat_text, start): # Do a binary search for idx start = start or 0 end = node_list.length - 1 while start <= end: mid = Math.floor((start + end)/2) q = node_list[mid] limit = q.offset + q.length if q.offset <= idx_in_flat_text and limit > idx_in_flat_text: start_node = q.node start_offset = idx_in_flat_text - q.offset return start_node, start_offset + (q.offset_in_node or 0), mid if limit <= idx_in_flat_text: start = mid + 1 else: end = mid - 1 return None, None, None def get_occurrence_data(node_list, start, end): start_node, start_offset, start_pos = find_node_for_index_binary(node_list, start) if start_node is not None: end_node, end_offset, node_pos = find_node_for_index_binary(node_list, end, start_pos) if end_node is not None: return { 'start_node': start_node, 'start_offset': start_offset, 'start_pos': start_pos, 'end_node': end_node, 'end_offset': end_offset, 'end_pos': node_pos, } def find_specific_occurrence(q, num, before_len, after_len, text_map, from_offset): if not q or not q.length: return from_idx = from_offset or 0 flat_text = text_map.flat_text match_num = -1 while True: idx = flat_text.indexOf(q, from_idx) if idx < 0: break match_num += 1 from_idx = idx + 1 if match_num < num: continue return get_occurrence_data(text_map.node_list, idx + before_len, idx + q.length - after_len) cache = {} def reset_find_caches(): nonlocal cache cache = {} def select_find_result(match): sel = window.getSelection() try: sel.setBaseAndExtent(match.start_node, match.start_offset, match.end_node, match.end_offset) except: # if offset is outside node return False return bool(sel.rangeCount and sel.toString()) def select_search_result(sr): window.getSelection().removeAllRanges() if not cache.text_map: cache.text_map = build_text_map() q = '' before_len = after_len = 0 if sr.before: q = sr.before[-15:] before_len = q.length q += sr.text if sr.after: after = sr.after[:15] after_len = after.length q += after match = find_specific_occurrence(q, int(sr.index), before_len, after_len, cache.text_map, sr.from_offset) if not match: return False return select_find_result(match) def find_word_length(text_map, idx): r = tts_word_regex() r.lastIndex = idx match = v'r.exec(text_map.flat_text)' word_length = 5 if match: word_length = match[0]?.length or 5 return word_length def select_tts_mark(idx_in_flat_text, last_idx_in_flat_text): window.getSelection().removeAllRanges() text_map = cached_tts_text_map() if idx_in_flat_text is last_idx_in_flat_text: match = get_occurrence_data(text_map.node_list, idx_in_flat_text, idx_in_flat_text + find_word_length(text_map, idx_in_flat_text)) else: match = get_occurrence_data(text_map.node_list, idx_in_flat_text, last_idx_in_flat_text + find_word_length(text_map, last_idx_in_flat_text)) if not match: return False return select_find_result(match)
7,181
Python
.py
180
31.377778
184
0.595149
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,543
read_audio_ebook.pyj
kovidgoyal_calibre/src/pyj/read_book/read_audio_ebook.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2023, DO LE DUY <duy.dole.00ece at gmail.com> # Public domain audio eBooks can be found on https://www.readbeyond.it/ebooks.html. # ReadBeyond also offers Aeneas (https://github.com/readbeyond/aeneas), # an open-source tool for force-alignment of audio and text to generate smil files. # Another notable tool is https://github.com/r4victor/syncabook, # builds upon Aeneas to complete a workflow for creating EPUB3 with Media Overlays. from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.theme import get_color from dom import change_icon_image, svgicon from gettext import gettext as _ from modals import error_dialog from read_book.globals import ui_operations from read_book.highlights import ICON_SIZE from read_book.selection_bar import BUTTON_MARGIN, get_margins, map_to_iframe_coords from read_book.shortcuts import shortcut_for_key_event from read_book.smil import ( find_next_audio_in_spine, get_smil_id_for_timestamp, next_audio_file_for_spine_item ) HIDDEN, PLAYING, PAUSED = 'HIDDEN', 'PLAYING', 'PAUSED' def seconds_to_ms(seconds): minutes = Math.floor(seconds / 60) remaining_seconds = int(seconds % 60) return str(minutes) + ':' + (str(remaining_seconds).zfill(2)) class ReadAudioEbook: dont_hide_on_content_loaded = True prevent_navigation = True CONTAINER_DISPLAY = 'flex' def __init__(self, view): self.view = view self._state = HIDDEN self.initialized = False self.current_audio_src = '' def initialize(self): if self.initialized: return self.initialized = True container = self.container container.style.backgroundColor = "rgba(0, 0, 0, 0)" container.style.justifyContent = 'center' container.style.alignItems = 'flex-end' container.setAttribute("tabindex", "0") container.appendChild(E.div( data_component='bar', style=f'position: absolute; bottom: 0; width: min(600px, 80vw); height: 2em; border-radius: 1em; padding:0.5em; display: flex; justify-content: center; align-items: center; background-color: {get_color("window-background")};' )) bar_container = container.lastChild container.appendChild(E.style( f'#{container.id} .speaking '+'{ opacity: 0.5 }\n\n', f'#{container.id} .speaking:hover '+'{ opacity: 1.0 }\n\n', )) container.addEventListener("keydown", self.on_keydown, {"passive": False}) container.addEventListener("click", self.on_container_clicked, {"passive": False}) container.addEventListener("contextmenu", self.toggle, {"passive": False}) def create_button(name, icon, text): ans = svgicon(icon, ICON_SIZE, ICON_SIZE, text) if name: ans.addEventListener("click", def(ev): ev.stopPropagation(), ev.preventDefault() self[name](ev) self.view.focus_iframe() ) ans.dataset.button = name ans.classList.add("simple-link") ans.style.marginLeft = ans.style.marginRight = BUTTON_MARGIN return ans for x in [ E.div ( style='height: 3ex; display: flex; align-items: center; justify-content: center', create_button("toggle", "pause", _('Pause audio')), ), E.div( data_component="time_display", E.text("") ), E.div( data_component="progress_bar", style=f'height:1.5em; border-radius: 0.75em; overflow: hidden; flex-grow: 100; display:block; background-color:{get_color("window-background2")}; margin:1em; cursor: pointer', E.div(style=f'display:block; width: 0%; background-color:{get_color("window-foreground")}; height:100%'), ), E.div( style='height: 3ex; display: flex; align-items: center; justify-content: center', create_button("slower", "slower", _("Slow down audio")), create_button("faster", "faster", _("Speed up audio")), create_button("hide", "off", _("Close Read aloud")) ) ]: bar_container.appendChild(x) bar_container.addEventListener("click", self.on_bar_clicked, {"passive": False}) self.container.appendChild(E.audio(data_component='audio', style="display:none")) ap = self.container.lastChild ap.addEventListener("timeupdate", def(): if self.state is not HIDDEN: ap = self.audio_player if ap.duration: audio_current_time = ap.currentTime progress = (audio_current_time / ap.duration) * 100 self.progress_bar.firstChild.style.width = progress + "%" self.time_display.textContent = f'{seconds_to_ms(audio_current_time)}/{seconds_to_ms(ap.duration)}' self.mark_for_timeupdate(audio_current_time) else: self.time_display.textContent = "00:00" self.progress_bar.firstChild.style.width = "0%" ) ap.addEventListener("ended", def(): self.play_next_audio_file() ) self.progress_bar.addEventListener("click", def(event): ap = self.audio_player if ap.duration: rect = self.progress_bar.getBoundingClientRect() x = event.clientX - rect.left total_width = rect.width if total_width: skip_time = (x / total_width) * ap.duration ap.currentTime = skip_time ) @property def bar(self): return self.container.querySelector('[data-component=bar]') @property def time_display(self): return self.container.querySelector('[data-component=time_display]') @property def progress_bar(self): return self.container.querySelector('[data-component=progress_bar]') def mark_for_timeupdate(self, audio_time): sam = self.view.currently_showing.smil_audio_map if sam: smil_id, idx = get_smil_id_for_timestamp(self.current_audio_src, audio_time, sam, self.last_marked_smil_idx) if smil_id and smil_id is not self.last_marked_smil_id: self.send_message('mark', anchor=smil_id, idx=idx) def play_next_audio_file(self): next_audio_file, par = next_audio_file_for_spine_item(self.current_audio_src, self.view.currently_showing.smil_audio_map) if next_audio_file: self.set_audio_src(next_audio_file, def(): self.audio_player.currentTime = par.audio?.start or 0 self.play() ) return spine_name, par = find_next_audio_in_spine(self.view.currently_showing.spine_index, self.view.book.manifest) if spine_name: self.view.show_name(spine_name, initial_position={'type': 'smil_id', 'anchor': par.anchor}) else: self.hide() def set_audio_src(self, name, proceed): if self.current_audio_src is name: proceed() return self.last_marked_smil_id = self.last_marked_smil_idx = None self.current_audio_src = name ap = self.audio_player if ui_operations.get_url_for_book_file_name: ap.onloadeddata = def(): proceed() ap.onerror = def(evt): console.error(evt) error_dialog(_('Could not load audio'), _( 'Could not load the audio file: {} with error: {}').format(name, evt.message)) ap.src = ui_operations.get_url_for_book_file_name(name) return if ap.src: ap.onloadeddata = def(): pass ap.onerror = def(): pass window.URL.revokeObjectURL(ap.src) ap.src = '' ui_operations.get_file(self.view.book, name, def(blob, name, mimetype): ap = self.audio_player ap.onloadeddata = def(): proceed() ap.onerror = def(evt): console.error(evt) error_dialog(_('Could not load audio'), _( 'Could not load the audio file: {} with error: {}').format(name, evt.message)) ap.src = window.URL.createObjectURL(blob) ) def start_playback(self): cn = self.view.currently_showing.name if self.view.book.manifest.files[cn]?.smil_map: self.send_message('play') return spine_name, par = find_next_audio_in_spine(self.view.currently_showing.spine_index, self.view.book.manifest) if not spine_name: spine_name, par = find_next_audio_in_spine(-1, self.view.book.manifest) if spine_name: self.view.show_name(spine_name, initial_position={'type': 'smil_id', 'anchor': par.anchor}) else: self.hide() error_dialog(_('No audio'), _('No audio found in this book')) @property def container(self): return document.getElementById("audio-ebooks-overlay") @property def audio_player(self): return self.container.querySelector('[data-component=audio]') @property def is_visible(self): return self.container.style.display is not "none" @property def state(self): return self._state @state.setter def state(self, val): if val is not self._state: speaking = False if val is HIDDEN: self._state = HIDDEN elif val is PLAYING: self._state = PLAYING speaking = True elif val is PAUSED: self._state = PAUSED if speaking: self.bar.classList.add('speaking') else: self.bar.classList.remove('speaking') def hide(self): if self.state is not HIDDEN: self.send_message("mark") self.pause() self.container.style.display = "none" self.view.focus_iframe() self.state = HIDDEN if ui_operations.read_aloud_state_changed: ui_operations.read_aloud_state_changed(False) @property def play_pause_button(self): return self.container.querySelector('[data-button="toggle"]') def show(self): if self.state is HIDDEN: self.initialize() self.state = PLAYING change_icon_image(self.play_pause_button, "pause", _('Pause audio')) self.start_playback() self.container.style.display = self.CONTAINER_DISPLAY self.focus() if ui_operations.read_aloud_state_changed: ui_operations.read_aloud_state_changed(True) def focus(self): self.container.focus() def slower(self): self.audio_player.playbackRate -= 0.1 def faster(self): self.audio_player.playbackRate += 0.1 def play(self): self.state = PLAYING change_icon_image(self.play_pause_button, "pause", _('Pause audio')) ap = self.audio_player if ap.getAttribute("src"): ap.play() def pause(self): self.state = PAUSED change_icon_image(self.play_pause_button, "play", _('Play audio')) ap = self.audio_player if ap.getAttribute("src"): ap.pause() def toggle(self): if self.state is PLAYING: self.pause() elif self.state is PAUSED: self.play() def on_bar_clicked(self, ev): # prevent the container click handler from handling this ev.stopPropagation(), ev.preventDefault() def on_container_clicked(self, ev): if ev.button is not 0: return ev.stopPropagation(), ev.preventDefault() margins = get_margins() pos = {"x": ev.clientX, "y": ev.clientY} pos = map_to_iframe_coords(pos, margins) self.send_message("play", pos=pos) def on_keydown(self, ev): ev.stopPropagation(), ev.preventDefault() if ev.key is "Escape": self.hide() return if ev.key is " " or ev.key is "MediaPlayPause" or ev.key is "PlayPause": self.toggle() return if ev.key is "Play" or ev.key is "MediaPlay": self.play() return if ev.key is "Pause" or ev.key is "MediaPause": self.pause() return sc_name = shortcut_for_key_event(ev, self.view.keyboard_shortcut_map) if not sc_name: return if sc_name is "show_chrome": self.hide() elif sc_name is "quit": self.hide() def send_message(self, message_type, **kw): self.view.iframe_wrapper.send_message("audio-ebook", type=message_type, **kw) def handle_message(self, message): if message.type is 'start_play_at': if message.par: self.set_audio_src( message.par.audio, def(): self.audio_player.currentTime = message.par.start or 0 self.play() ) else: if message.anchor: # start playing from where we are self.send_message('play') return if message.pos: # this is a click ignore it as no smil element was found at # click location pass else: self.pause() error_dialog(_('Audio element not found'), _( 'Could not play audio as no associated audio was found')) elif message.type is 'marked': if message.anchor: self.last_marked_smil_id = message.anchor self.last_marked_smil_idx = message.idx else: self.last_marked_smil_id = self.last_marked_smil_idx = None else: console.error(f'Unknown audio ebook message type from iframe: {message.type}')
14,362
Python
.py
326
32.745399
237
0.585544
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,544
tts.pyj
kovidgoyal_calibre/src/pyj/read_book/tts.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from dom import unique_id from gettext import gettext as _ from book_list.globals import get_session_data from modals import create_custom_dialog, error_dialog from widgets import create_button class Tracker: def __init__(self): self.clear() def clear(self): self.positions = v'[]' self.last_pos = 0 self.queue = v'[]' def parse_marked_text(self, marked_text): self.clear() text = v'[]' text_len = chunk_len = index_in_positions = offset_in_text = 0 limit = 2048 def commit(): self.queue.push({ 'text': ''.join(text), 'index_in_positions': index_in_positions, 'offset_in_text': offset_in_text, 'reached_offset': 0}) for x in marked_text: if jstype(x) is 'number': self.positions.push({'mark': x, 'offset_in_text': text_len}) else: text_len += x.length chunk_len += x.length text.push(x) if chunk_len > limit: commit() chunk_len = 0 text = v'[]' index_in_positions = max(0, self.positions.length - 1) offset_in_text = text_len if text.length: commit() self.marked_text = marked_text return self.current_text() def pop_first(self): self.queue.splice(0, 1) def current_text(self): if self.queue.length: return self.queue[0].text return '' def resume(self): self.last_pos = 0 if self.queue.length: self.last_pos = self.queue[0].index_in_positions if self.queue[0].reached_offset: o = self.queue[0].reached_offset # make sure positions remain the same for word tracking self.queue[0].text = (' ' * o) + self.queue[0].text[o:] return self.current_text() def boundary_reached(self, start): if self.queue.length: self.queue[0].reached_offset = start def mark_word(self, start, length): if not self.queue.length: return start += self.queue[0].offset_in_text end = start + length matches = v'[]' while self.last_pos < self.positions.length: pos = self.positions[self.last_pos] if start <= pos.offset_in_text < end: matches.push(pos) elif pos.offset_in_text >= end: break self.last_pos += 1 if matches.length: return matches[0].mark, matches[-1].mark return None class Client: min_rate = 0.1 max_rate = 2 def __init__(self): self.stop_requested_at = None self.status = {'synthesizing': False, 'paused': False} self.tracker = Tracker(v'[]') self.last_reached_mark = None self.onevent = def(): pass data = get_session_data().get('tts_backend') self.current_voice_uri = data.voice or '' self.current_rate = data.rate or None def create_utterance(self, text): ut = new window.SpeechSynthesisUtterance(text) ut.onstart = self.utterance_started ut.onpause = self.utterance_paused ut.onend = self.utterance_ended ut.onerror = self.utterance_failed ut.onresume = self.utterance_resumed ut.addEventListener('boundary', self.utterance_boundary_reached) if self.current_voice_uri: for voice in window.speechSynthesis.getVoices(): if voice.voiceURI is self.current_voice_uri: ut.voice = voice break if self.current_rate: ut.rate = self.current_rate return ut def utterance_started(self, event): self.status = {'synthesizing': True, 'paused': False} self.onevent('begin') def utterance_paused(self, event): self.status = {'synthesizing': True, 'paused': True} self.onevent('pause') def speak(self, text): self.current_utterance = None if text and text.length: self.current_utterance = self.create_utterance(text) window.speechSynthesis.speak(self.current_utterance) def utterance_ended(self, event): self.status = {'synthesizing': False, 'paused': False} if self.stop_requested_at? and window.performance.now() - self.stop_requested_at < 1000: self.stop_requested_at = None return self.tracker.pop_first() text = self.tracker.current_text() if text and text.length: self.speak(text) else: self.onevent('end') def utterance_failed(self, event): self.status = {'synthesizing': False, 'paused': False} self.tracker.clear() if event.error is not 'interrupted' and event.error is not 'canceled': if event.error is 'synthesis-unavailable': msg = _('Text-to-Speech not available in this browser. You may need to install some Text-to-Speech software.') else: msg = _('An error has occurred with speech synthesis: ') + event.error error_dialog(_('Speaking failed'), msg) self.onevent('cancel') def utterance_boundary_reached(self, event): self.tracker.boundary_reached(event.charIndex) if event.name is 'word': x = self.tracker.mark_word(event.charIndex, event.charLength or 2) if x: first, last = x[0], x[1] self.onevent('mark', {'first': first, 'last': last}) def utterance_resumed(self, event): self.status = {'synthesizing': True, 'paused': False} self.onevent('resume') def pause(self): window.speechSynthesis.pause() def resume(self): window.speechSynthesis.resume() def pause_for_configure(self): if self.current_utterance: ut = self.current_utterance self.current_utterance = None ut.onstart = ut.onpause = ut.onend = ut.onerror = ut.onresume = None window.speechSynthesis.cancel() def resume_after_configure(self): text = self.tracker.resume() if text and text.length: self.speak(text) def stop(self): self.tracker.clear() self.stop_requested_at = window.performance.now() window.speechSynthesis.cancel() self.status = {'synthesizing': False, 'paused': False} def speak_simple_text(self, text): self.stop() text = self.tracker.parse_marked_text(v'[text]') if text and text.length: self.speak(text) def speak_marked_text(self, text_segments, onevent): self.stop() self.onevent = onevent text = self.tracker.parse_marked_text(text_segments) if text and text.length: self.speak(text) def faster(self): self.change_rate(steps=1) def slower(self): self.change_rate(steps=-1) def save_settings(self): sd = get_session_data() sd.set('tts_backend', {'voice': self.current_voice_uri, 'rate': self.current_rate}) def change_rate(self, steps=1): rate = current_rate = (self.current_rate or 1) * 10 rate += steps rate /= 10 rate = max(self.min_rate, min(rate, self.max_rate)) if rate is not current_rate: is_speaking = bool(window.speechSynthesis.speaking) if is_speaking: self.pause_for_configure() self.current_rate = rate self.save_settings() if is_speaking: self.resume_after_configure() def configure(self): voice_id = unique_id() rate_id = unique_id() default_voice = None def restore_defaults(): document.getElementById(voice_id).selectedIndex = -1 document.getElementById(rate_id).value = 10 create_custom_dialog(_('Configure Text-to-Speech'), def (parent_div, close_modal): nonlocal default_voice select = E.select(size='5', id=voice_id) voices = window.speechSynthesis.getVoices() voices.sort(def (a, b): a = a.name.toLowerCase() b = b.name.toLowerCase() return -1 if a < b else (0 if a is b else 1) ) for voice in voices: dflt = '' if voice.default: default_voice = voice.voiceURI dflt = '-- {}'.format(_('default')) option = E.option(f'{voice.name} ({voice.lang}){dflt}', value=voice.voiceURI) if (self.current_voice_uri and voice.voiceURI is self.current_voice_uri) or (not self.current_voice_uri and voice.default): option.setAttribute('selected', 'selected') select.appendChild(option) parent_div.appendChild(E.div(_('Speed of speech:'))) parent_div.appendChild(E.input(type='range', id=rate_id, min=(self.min_rate * 10) + '', max=(self.max_rate * 10) + '', value=((self.current_rate or 1) * 10) + '')) parent_div.appendChild(E.div(_('Pick a voice below:'))) parent_div.appendChild(select) if select.options.selectedIndex? and select.options[select.options.selectedIndex]: select.options[select.options.selectedIndex].scrollIntoView() parent_div.appendChild(E.div( style='margin: 1rem; display: flex; justify-content: space-between; align-items: flex-start', create_button(_('Restore defaults'), action=restore_defaults), create_button(_('Close'), action=close_modal) )) , on_close=def(): voice = document.getElementById(voice_id).value rate = int(document.getElementById(rate_id).value) / 10 if rate is 1: rate = None if voice is default_voice: voice = '' changed = voice is not self.current_voice_uri or rate is not self.current_rate if changed: self.current_voice_uri = voice self.current_rate = rate is_speaking = bool(window.speechSynthesis.speaking) if is_speaking: self.pause_for_configure() self.save_settings() if is_speaking: self.resume_after_configure() self.onevent('configured') )
10,993
Python
.py
252
31.742063
179
0.569306
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,545
timers.pyj
kovidgoyal_calibre/src/pyj/read_book/timers.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from read_book.globals import ui_operations THRESHOLD = 5 FILTER_THRESHOLD = 25 MAX_SAMPLES = 256 class Timers: def __init__(self): self.reset_read_timer() self.rates = v'[]' self.average = self.stddev = 0 def start_book(self, book): self.reset_read_timer() self.rates = v'[]' if book?.saved_reading_rates?.rates: self.rates = book.saved_reading_rates.rates.slice(0) self.calculate() def reset_read_timer(self): self.last_scroll_at = None def calculate(self): rates = self.rates rlen = rates.length if rlen >= THRESHOLD: avg = 0 for v'var i = 0; i < rlen; i++': avg += rates[i] avg /= rlen self.average = avg sq = 0 for v'var i = 0; i < rlen; i++': x = rates[i] - avg sq += x * x self.stddev = Math.sqrt(sq / (rlen - 1)) else: self.average = self.stddev = 0 def on_human_scroll(self, amt_scrolled): last_scroll_at = self.last_scroll_at self.last_scroll_at = now = window.performance.now() if last_scroll_at is None: return time_since_last_scroll = (now - last_scroll_at) / 1000 if time_since_last_scroll <= 0 or time_since_last_scroll >= 300: return if time_since_last_scroll < 2: return rate = amt_scrolled / time_since_last_scroll if self.rates.length >= FILTER_THRESHOLD and Math.abs(rate - self.average) > 2 * self.stddev: return if self.rates.length >= MAX_SAMPLES: self.rates.shift() self.rates.push(rate) self.calculate() if ui_operations.update_reading_rates: ui_operations.update_reading_rates({'rates': self.rates.slice(0)}) def time_for(self, length): if length >= 0 and self.rates.length >= THRESHOLD and self.average > 0: return length / self.average return None
2,211
Python
.py
59
28.254237
101
0.575362
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,546
scrollbar.pyj
kovidgoyal_calibre/src/pyj/read_book/scrollbar.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from book_list.theme import cached_color_to_rgba from dom import unique_id from read_book.globals import ui_operations SIZE = 10 class BookScrollbar: def __init__(self, view): self.view = view self.container_id = unique_id('book-scrollbar') self.sync_to_contents_timer = 0 self.sync_contents_timer = 0 @property def container(self): return document.getElementById(self.container_id) def create(self): self.on_bob_mousedown = self.on_bob_mouse_event.bind(None, 'down') self.on_bob_mousemove = self.on_bob_mouse_event.bind(None, 'move') self.on_bob_mouseup = self.on_bob_mouse_event.bind(None, 'up') return E.div( id=self.container_id, style=f'height: 100vh; background-color: #aaa; width: {SIZE}px; border-radius: 5px', onclick=self.bar_clicked, oncontextmenu=self.context_menu, E.div( style=f'position: relative; width: 100%; height: {int(2.2*SIZE)}px; background-color: #444; border-radius: 5px', onmousedown=self.on_bob_mousedown, ), E.div( style='position: absolute; z-index: 2147483647; width: 100vw; height: 100vh; left: 0; top: 0; display: none;' ) ) def context_menu(self, ev): if ui_operations.scrollbar_context_menu: ev.preventDefault(), ev.stopPropagation() c = self.container bob = c.firstChild height = c.clientHeight - bob.clientHeight top = max(0, min(ev.clientY - bob.clientHeight, height)) frac = max(0, min(top / height, 1)) ui_operations.scrollbar_context_menu(ev.screenX, ev.screenY, frac) def bar_clicked(self, evt): if evt.button is 0: c = self.container b = c.firstChild bob_top = b.offsetTop bob_bottom = bob_top + b.offsetHeight if evt.clientY < bob_top: self.view.side_margin_clicked('left', evt) elif evt.clientY > bob_bottom: self.view.side_margin_clicked('right', evt) def on_bob_mouse_event(self, which, evt): c = self.container bob = c.firstChild mouse_grab = bob.nextSibling if which is 'move': top = evt.pageY - self.down_y height = c.clientHeight - bob.clientHeight top = max(0, min(top, height)) bob.style.top = f'{top}px' evt.preventDefault(), evt.stopPropagation() frac = bob.offsetTop / height if self.sync_contents_timer: window.clearTimeout(self.sync_contents_timer) self.sync_contents_timer = window.setTimeout(self.view.goto_frac.bind(None, frac), 2) elif which is 'down': if evt.button is not 0: return evt.preventDefault(), evt.stopPropagation() self.down_y = evt.clientY - bob.getBoundingClientRect().top mouse_grab.style.display = 'block' window.addEventListener('mousemove', self.on_bob_mousemove, {'capture': True, 'passive': False}) window.addEventListener('mouseup', self.on_bob_mouseup, {'capture': True, 'passive': False}) elif which is 'up': self.down_y = 0 window.removeEventListener('mousemove', self.on_bob_mousemove, {'capture': True, 'passive': False}) window.removeEventListener('mouseup', self.on_bob_mouseup, {'capture': True, 'passive': False}) window.setTimeout(def(): self.container.firstChild.nextSibling.style.display = 'none';, 10) evt.preventDefault(), evt.stopPropagation() def apply_visibility(self): sd = get_session_data() self.container.style.display = 'block' if sd.get('book_scrollbar') else 'none' @property def effective_width(self): return SIZE if self.container.style.display is 'block' else 0 def set_position(self, frac): c = self.container frac = max(0, min(frac, 1)) c.firstChild.style.top = f'{frac * (c.clientHeight - c.firstChild.clientHeight)}px' def _sync_to_contents(self, frac): self.sync_to_contents_timer = 0 self.set_position(frac) def sync_to_contents(self, frac): if not self.sync_to_contents_timer: self.sync_to_contents_timer = window.setTimeout(self._sync_to_contents.bind(None, frac), 50) def apply_color_scheme(self, colors): fg = cached_color_to_rgba(colors.foreground) bg = cached_color_to_rgba(colors.background) def mix(fg, bg, frac): def m(x): # noqa: unused-local return frac * fg[x] + (1-frac) * bg[x] return v'[m[0], m[1], m[2]]' rbg = mix(fg, bg, 0.3) rfg = mix(fg, bg, 0.7) c = self.container c.style.backgroundColor = f'rgb({rbg[0]}, {rbg[1]}, {rbg[2]})' c.firstChild.style.backgroundColor = f'rgb({rfg[0]}, {rfg[1]}, {rfg[2]})'
5,252
Python
.py
109
38.119266
128
0.611751
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,547
extract.pyj
kovidgoyal_calibre/src/pyj/read_book/extract.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from read_book.globals import annot_id_uuid_map def get_elements(x, y): nonlocal img_id_counter ans = {'link': None, 'img': None, 'highlight': None, 'crw': None} for elem in document.elementsFromPoint(x, y): tl = elem.tagName.toLowerCase() if tl is 'a' and elem.getAttribute('href') and not ans.link: ans.link = elem.getAttribute('href') elif (tl is 'img' or tl is 'image') and elem.getAttribute('data-calibre-src') and not ans.img: ans.img = elem.getAttribute('data-calibre-src') elif elem.dataset?.calibreRangeWrapper: ans.crw = elem.dataset.calibreRangeWrapper annot_id = annot_id_uuid_map[ans.crw] if annot_id: ans.highlight = annot_id return ans
929
Python
.py
19
41.157895
102
0.655629
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,548
viewport.pyj
kovidgoyal_calibre/src/pyj/read_book/viewport.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals FUNCTIONS = 'x y scroll_to scroll_into_view reset_globals __reset_transforms window_scroll_pos content_size'.split(' ') from read_book.globals import get_boss, viewport_mode_changer from utils import document_height, document_width, ios_major_version class ScrollViewport: def __init__(self): self.set_mode('flow') self.window_width_from_parent = self.window_height_from_parent = None # In RTL mode, we hide the fact that we are scrolling to the left by negating the # current X position and the requested X scroll position, which fools the reader # code into thinking that it's always scrolling in positive X. self.rtl = False self.ltr = True self.vertical_writing_mode = False self.horizontal_writing_mode = True def set_mode(self, mode): prefix = ('flow' if mode is 'flow' else 'paged') + '_' for attr in FUNCTIONS: self[attr] = self[prefix + attr] def initialize_on_layout(self, body_style): self.horizontal_writing_mode = True self.vertical_writing_mode = False self.ltr = True self.rtl = False if body_style.direction is "rtl": self.rtl = True self.ltr = False css_vertical_rl = body_style.getPropertyValue("writing-mode") is "vertical-rl" if css_vertical_rl: self.vertical_writing_mode = True self.horizontal_writing_mode = False self.rtl = True self.ltr = False else: css_vertical_lr = body_style.getPropertyValue("writing-mode") is "vertical-lr" if css_vertical_lr: self.vertical_writing_mode = True self.horizontal_writing_mode = False self.ltr = True self.rtl = False def flow_x(self): if self.rtl: return -window.pageXOffset return window.pageXOffset def flow_y(self): return window.pageYOffset def flow_window_scroll_pos(self): return window.pageXOffset, window.pageYOffset def inline_pos(self): if self.vertical_writing_mode: return self.y() return self.x() def block_pos(self): if self.horizontal_writing_mode: return self.y() return self.x() def flow_scroll_to(self, x, y): if self.rtl: window.scrollTo(-x,y) else: window.scrollTo(x, y) def scroll_to_in_inline_direction(self, pos, preserve_other): # Lines flow vertically, so inline is vertical. if self.vertical_writing_mode: self.scroll_to(self.x() if preserve_other else 0, pos) else: self.scroll_to(pos, self.y() if preserve_other else 0) def scroll_to_in_block_direction(self, pos, preserve_other): # In horizontal modes, the block direction is vertical. if self.horizontal_writing_mode: self.scroll_to(self.x() if preserve_other else 0, pos) # In vertical modes, the block direction is horizontal. else: self.scroll_to(pos, self.y() if preserve_other else 0) def flow_scroll_into_view(self, elem): elem.scrollIntoView() def scroll_by(self, x, y): if self.ltr: window.scrollBy(x, y) # Swap inline direction if in RTL mode. else: window.scrollBy(-x,y) def scroll_by_in_inline_direction(self, offset): # Same logic as scroll_to_in_inline_direction if self.vertical_writing_mode: self.scroll_by(0, offset) else: self.scroll_by(offset, 0) def scroll_by_in_block_direction(self, offset): # Same logic as scroll_to_in_block_direction if self.horizontal_writing_mode: self.scroll_by(0, offset) else: self.scroll_by(offset, 0) def flow_reset_globals(self): pass def flow___reset_transforms(self): pass def flow_content_size(self): return document.documentElement.scrollWidth, document.documentElement.scrollHeight def paged_content_inline_size(self): w, h = self.content_size() return w if self.horizontal_writing_mode else h def paged_content_block_size(self): w, h = self.content_size() return h if self.horizontal_writing_mode else w def inline_size(self): if self.horizontal_writing_mode: return self.width() return self.height() def block_size(self): if self.horizontal_writing_mode: return self.height() return self.width() def update_window_size(self, w, h): self.window_width_from_parent = w self.window_height_from_parent = h def width(self): return window.innerWidth def height(self): return window.innerHeight def document_inline_size(self): if self.horizontal_writing_mode: return document_width() return document_height() def document_block_size(self): if self.horizontal_writing_mode: return document_height() return document_width() # Assure that the viewport position returned is corrected for the RTL # mode of ScrollViewport. def viewport_to_document(self, x, y, doc): # Convert x, y from the viewport (window) co-ordinate system to the # document (body) co-ordinate system doc = doc or window.document topdoc = window.document while doc is not topdoc and doc.defaultView: # We are in a frame frame = doc.defaultView.frameElement rect = frame.getBoundingClientRect() x += rect.left y += rect.top doc = frame.ownerDocument wx, wy = self.window_scroll_pos() x += wx y += wy if self.rtl: x *= -1 return x, y def rect_inline_start(self, rect): # Lines start on the left in LTR mode, right in RTL mode if self.horizontal_writing_mode: return rect.left if self.ltr else rect.right # Only top-to-bottom vertical writing is supported return rect.top def rect_inline_end(self, rect): # Lines end on the right in LTR mode, left in RTL mode if self.horizontal_writing_mode: return rect.right if self.ltr else rect.left # In top-to-bottom (the only vertical mode supported), bottom: return rect.bottom def rect_block_start(self, rect): # Block flows top to bottom in horizontal modes if self.horizontal_writing_mode: return rect.top # Block flows either left or right in vertical modes return rect.left if self.ltr else rect.right def rect_block_end(self, rect): # Block flows top to bottom in horizontal modes if self.horizontal_writing_mode: return rect.bottom # Block flows either left or right in vertical modes return rect.right if self.ltr else rect.left def rect_inline_size(self, rect): # Lines go horizontally in horizontal writing, so use width if self.horizontal_writing_mode: return rect.width return rect.height def rect_block_size(self, rect): # The block is vertical in horizontal writing, so use height if self.horizontal_writing_mode: return rect.height return rect.width # Returns document inline coordinate (1 value) at viewport inline coordinate def viewport_to_document_inline(self, pos, doc): # Lines flow horizontally in horizontal mode if self.horizontal_writing_mode: return self.viewport_to_document(pos, 0, doc)[0] # Inline is vertical in vertical mode return self.viewport_to_document(0, pos, doc)[1] # Returns document block coordinate (1 value) at viewport block coordinate def viewport_to_document_block(self, pos, doc): # Block is vertical in horizontal mode if self.horizontal_writing_mode: return self.viewport_to_document(0, pos, doc)[1] # Horizontal in vertical mode return self.viewport_to_document(pos, 0, doc)[0] def viewport_to_document_inline_block(self, inline, block, doc): if self.horizontal_writing_mode: return self.viewport_to_document(inline, block, doc) return self.viewport_to_document(block, inline, doc) class IOSScrollViewport(ScrollViewport): def width(self): return self.window_width_from_parent or window.innerWidth def height(self): return self.window_height_from_parent or window.innerHeight def _scroll_implementation(self, x, y): if x is 0 and y is 0: document.documentElement.style.transform = 'none' else: x *= -1 y *= -1 document.documentElement.style.transform = f'translateX({x}px) translateY({y}px)' def paged_scroll_to(self, x, y): x = x or 0 y = y or 0 if self.ltr: self._scroll_implementation(x, y) else: self._scroll_implementation(-x, y) boss = get_boss() if boss: boss.onscroll() def transform_val(self, y): raw = document.documentElement.style.transform if not raw or raw is 'none': return 0 idx = raw.lastIndexOf('(') if y else raw.indexOf('(') raw = raw[idx + 1:] ans = parseInt(raw) if isNaN(ans): ans = 0 return ans def paged_x(self): ans = self.transform_val() if self.ltr: ans *= -1 return ans def paged_y(self): return -1 * self.transform_val(True) def paged_scroll_into_view(self, elem): left = elem.offsetLeft if left is None: return # element has display: none elem.scrollIntoView() window.scrollTo(0, 0) p = elem.offsetParent while p: left += p.offsetLeft p = p.offsetParent # left -= window_width() // 2 self._scroll_implementation(max(0, left), 0) def paged_window_scroll_pos(self): return self.transform_val(), self.transform_val(True) def paged_content_size(self): w = document.documentElement.scrollWidth h = document.documentElement.scrollHeight return w - self.transform_val(), h - self.transform_val(True) def paged___reset_transforms(self): s = document.documentElement.style if s.transform is not 'none': s.transform = 'none' def paged_reset_globals(self): self.__reset_transforms() if 1 < ios_major_version < 15: scroll_viewport = IOSScrollViewport() else: scroll_viewport = ScrollViewport() for attr in FUNCTIONS: if not scroll_viewport['paged_' + attr]: scroll_viewport['paged_' + attr] = scroll_viewport[attr] viewport_mode_changer(scroll_viewport.set_mode) def get_unit_size_in_pixels(unit): d = document.createElement('span') d.style.position = 'absolute' d.style.visibility = 'hidden' d.style.width = f'1{unit}' d.style.fontSize = f'1{unit}' d.style.paddingTop = d.style.paddingBottom = d.style.paddingLeft = d.style.paddingRight = '0' d.style.marginTop = d.style.marginBottom = d.style.marginLeft = d.style.marginRight = '0' d.style.borderStyle = 'none' document.body.appendChild(d) ans = d.clientWidth document.body.removeChild(d) return ans def rem_size(reset): if reset: rem_size.ans = None return if not rem_size.ans: d = document.createElement('span') d.style.position = 'absolute' d.style.visibility = 'hidden' d.style.width = '1rem' d.style.fontSize = '1rem' d.style.paddingTop = d.style.paddingBottom = d.style.paddingLeft = d.style.paddingRight = '0' d.style.marginTop = d.style.marginBottom = d.style.marginLeft = d.style.marginRight = '0' d.style.borderStyle = 'none' document.body.appendChild(d) rem_size.ans = max(2, d.clientWidth) document.body.removeChild(d) return rem_size.ans def line_height(reset): if reset: line_height.ans = None return if not line_height.ans: ds = window.getComputedStyle(document.body) try: # will fail if line-height = "normal" lh = float(ds.lineHeight) except: try: lh = 1.2 * float(ds.fontSize) except: lh = 15 line_height.ans = max(5, lh) return line_height.ans
12,831
Python
.py
320
31.278125
119
0.629368
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,549
globals.pyj
kovidgoyal_calibre/src/pyj/read_book/globals.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from aes import random_bytes from encodings import hexlify from gettext import gettext as _, register_callback, gettext as gt _boss = None dark_link_color = '__DARK_LINK_COLOR__' def set_boss(b): nonlocal _boss _boss = b def get_boss(): return _boss def current_book(): return current_book.book current_book.book = None def rtl_page_progression(): # Other options are "ltr" and "default." For Calibre, "default" is LTR. return current_book().manifest.page_progression_direction == 'rtl' def ltr_page_progression(): # Only RTL and LTR are supported, so it must be LTR if not RTL. return not rtl_page_progression() uid = 'calibre-' + hexlify(random_bytes(12)) def viewport_mode_changer(val): if val: viewport_mode_changer.val = val return viewport_mode_changer.val def current_layout_mode(): return current_layout_mode.value current_layout_mode.value = 'flow' def set_layout_mode(val): current_layout_mode.value = val viewport_mode_changer()(val) def current_spine_item(): return current_spine_item.value current_spine_item.value = None def set_current_spine_item(val): current_spine_item.value = val def toc_anchor_map(): return toc_anchor_map.value def set_toc_anchor_map(val): toc_anchor_map.value = val default_color_schemes = { 'system':{'foreground':'#000000', 'background':'#ffffff', 'name':_('System')}, 'white':{'foreground':'#000000', 'background':'#ffffff', 'name':_('White')}, 'black':{'foreground':'#ffffff', 'background':'#000000', 'link': '#4f81bd', 'name':_('Black')}, 'sepia-light':{'foreground':'#39322B', 'background':'#F6F3E9', 'name':_('Sepia light')}, 'sepia-dark': {'background':'#39322B', 'foreground':'#F6F3E9', 'link': '#4f81bd', 'name':_('Sepia dark')}, } def set_system_colors(spec): c = default_color_schemes.system c.foreground = spec.foreground c.background = spec.background v'delete c.link' if spec.link: c.link = spec.link register_callback(def(): # Ensure the color scheme names are translated for key in default_color_schemes: scheme = default_color_schemes[key] scheme.name = gt(scheme.name) # set the system colors if in dark mode if window.matchMedia and window.matchMedia('(prefers-color-scheme: dark)').matches: set_system_colors({'background': '#111', 'foreground': '#ddd', 'link': dark_link_color}) ) IN_DEVELOP_MODE = '__IN_DEVELOP_MODE__' runtime = { 'is_standalone_viewer': False, 'viewer_in_full_screen': False, 'in_develop_mode': IN_DEVELOP_MODE is '1', 'QT_VERSION': 0, } ui_operations = { 'get_file': None, 'get_mathjax_files': None, 'update_url_state': None, 'update_last_read_time': None, 'show_error': None, 'redisplay_book': None, 'reload_book': None, 'forward_gesture': None, 'update_color_scheme': None, 'update_font_size': None, 'goto_cfi': None, 'delete_book': None, 'focus_iframe': None, 'toggle_toc': None, 'toggle_full_screen': None, } annot_id_uuid_map = {} def clear_annot_id_uuid_map(): for key in Object.keys(annot_id_uuid_map): v'delete annot_id_uuid_map[key]' def is_dark_theme(set_val): if set_val?: is_dark_theme.ans = set_val return v'!!is_dark_theme.ans'
3,457
Python
.py
97
31.56701
110
0.677177
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,550
overlay.pyj
kovidgoyal_calibre/src/pyj/read_book/overlay.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.book_details import CLASS_NAME as BD_CLASS_NAME, render_metadata from book_list.globals import get_session_data from book_list.library_data import ( current_library_id, set_book_metadata, sync_library_books ) from book_list.router import home from book_list.theme import get_color from book_list.top_bar import create_top_bar from book_list.ui import query_as_href, show_panel from dom import ( add_extra_css, build_rule, clear, ensure_id, set_css, svgicon, unique_id ) from gettext import gettext as _ from modals import error_dialog, question_dialog from read_book.bookmarks import create_bookmarks_panel from read_book.globals import runtime, ui_operations from read_book.goto import create_goto_panel, create_location_overlay, create_page_list_overlay from read_book.highlights import create_highlights_panel from read_book.profiles import create_profiles_panel from read_book.open_book import create_open_book from read_book.prefs.font_size import create_font_size_panel from read_book.prefs.head_foot import time_formatter from read_book.prefs.main import create_prefs_panel from read_book.toc import create_toc_panel from read_book.word_actions import create_word_actions_panel from session import session_defaults, get_device_uuid from utils import ( default_context_menu_should_be_allowed, full_screen_element, full_screen_supported, is_ios, safe_set_inner_html ) from uuid import short_uuid from widgets import create_button, create_spinner class LoadingMessage: # {{{ def __init__(self, msg, current_color_scheme): self.msg = msg or '' self.current_color_scheme = current_color_scheme self.is_not_escapable = True # prevent Esc key from closing def show(self, container): self.container_id = container.getAttribute('id') container.style.backgroundColor = self.current_color_scheme.background container.style.color = self.current_color_scheme.foreground container.appendChild( E.div( style='text-align:center', E.div(create_spinner('100px', '100px')), E.h2() )) safe_set_inner_html(container.firstChild.lastChild, self.msg) set_css(container.firstChild, position='relative', top='50%', transform='translateY(-50%)') def set_msg(self, msg): self.msg = msg container = document.getElementById(self.container_id) safe_set_inner_html(container.firstChild.lastChild, self.msg) def on_container_click(self, evt): pass # Dont allow panel to be closed by a click # }}} class DeleteBook: # {{{ def __init__(self, overlay, question, ok_icon, ok_text, reload_book): self.overlay = overlay self.question = question or _( 'Are you sure you want to remove this book from local storage? You will have to re-download it from calibre if you want to read it again.') self.ok_icon = ok_icon or 'trash' self.ok_text = ok_text or _('Delete book') self.reload_book = reload_book def show(self, container): self.container_id = container.getAttribute('id') set_css(container, background_color=get_color('window-background')) container.appendChild(E.div( style='display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%', tabindex='0', E.div(style='margin:1ex 1em; max-width: 80%', E.h2(self.question), E.div(style='display:flex; justify-content:flex-end; margin-top:1rem', create_button(self.ok_text, self.ok_icon, action=self.delete_book, highlight=True), E.span('\xa0'), create_button(_('Cancel'), action=self.cancel), ) ), onkeyup=def(ev): if ev.key is 'Escape': ev.stopPropagation(), ev.preventDefault() self.cancel() elif ev.key is 'Enter' or ev.key is 'Return': ev.stopPropagation(), ev.preventDefault() self.delete_book() )) window.setTimeout(self.focus_me, 0) def focus_me(self): document.getElementById(self.container_id).lastChild.focus() def show_working(self): container = document.getElementById(self.container_id) clear(container) container.appendChild( E.div( style='text-align:center', E.div(create_spinner('100px', '100px')), E.h2() )) safe_set_inner_html(container.lastChild.lastChild, _('Deleting local book copy, please wait...')) def on_container_click(self, evt): pass # Dont allow panel to be closed by a click def delete_book(self): if runtime.is_standalone_viewer: if self.reload_book: self.overlay.view.reload_book() return self.show_working() view = self.overlay.view ui_operations.delete_book(view.book, def(book, errmsg): self.overlay.hide_current_panel() if errmsg: view.ui.show_error(_('Failed to delete book'), _('Failed to delete book from local storage, click "Show details" for more information.'), errmsg) else: if self.reload_book: self.overlay.view.reload_book() else: home() ) def cancel(self): self.overlay.hide_current_panel() # }}} class SyncBook: # {{{ def __init__(self, overlay): self.overlay = overlay self.canceled = False def show(self, container): self.container_id = container.getAttribute('id') set_css(container, background_color=get_color('window-background')) book = self.overlay.view.book to_sync = v'[[book.key, new Date(0)]]' self.overlay.view.annotations_manager.sync_annots_to_server() sync_library_books(book.key[0], to_sync, self.sync_data_received) container.appendChild(E.div( style='display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%', E.div(style='margin:1ex 1em; max-width: 80vw', E.h2(_('Syncing last read position and annotations')), E.p(_('Downloading data from server, please wait...')), E.div(style='display:flex; justify-content:flex-end', create_button(_('Cancel'), action=self.cancel), ) ) )) def on_container_click(self, evt): pass # Dont allow panel to be closed by a click def cancel(self): self.canceled = True self.overlay.hide_current_panel() def sync_data_received(self, library_id, lrmap, load_type, xhr, ev): if self.canceled: return self.overlay.hide() if load_type is not 'load': if xhr.responseText is 'login required for sync': error_dialog(_('Failed to fetch sync data'), _('You must setup user accounts and login to use the sync functionality')) else: error_dialog(_('Failed to fetch sync data'), _('Failed to download sync data from server, click "Show details" for more information.'), xhr.error_html) return data = JSON.parse(xhr.responseText) book = self.overlay.view.book dev = get_device_uuid() epoch = 0 ans = None new_annotations_map = None for key in data: book_id, fmt = key.partition(':')[::2] if book_id is str(book.key[1]) and fmt.upper() is book.key[2].upper(): new_vals = data[key] last_read_positions = new_vals.last_read_positions new_annotations_map = new_vals.annotations_map for d in last_read_positions: if d.device is not dev and d.epoch > epoch: epoch = d.epoch ans = d break cfi = ans?.cfi if new_annotations_map or cfi: self.overlay.view.sync_data_received(cfi, new_annotations_map) # }}} # CSS {{{ MAIN_OVERLAY_TS_CLASS = 'read-book-main-overlay-top-section' MAIN_OVERLAY_ACTIONS_CLASS = 'read-book-main-overlay-actions' def timer_id(): if not timer_id.ans: timer_id.ans = unique_id() return timer_id.ans add_extra_css(def(): style = '' sel = '.' + MAIN_OVERLAY_TS_CLASS + ' > .' + MAIN_OVERLAY_ACTIONS_CLASS + ' ' style += build_rule(sel, overflow='hidden') sel += '> ul ' style += build_rule(sel, display='flex', list_style='none', border_bottom='1px solid currentColor') sel += '> li' style += build_rule(sel, border_right='1px solid currentColor', padding='0.5em 1ex', display='flex', flex_wrap='wrap', align_items='center', cursor='pointer') style += build_rule(sel + ':last-child', border_right_style='none') style += build_rule(sel + ':hover > *:first-child, .main-overlay-button:hover > *:first-child', color=get_color('window-hover-foreground')) style += build_rule(sel + ':active > *:first-child, .main-overlay-button:active > *:first-child', transform='scale(1.8)') style += f'@media screen and (max-width: 350px) {{ #{timer_id()} {{ display: none; }} }}' return style ) # }}} def simple_overlay_title(title, overlay, container, close_action): container.style.backgroundColor = get_color('window-background') def action(): event = this event.stopPropagation() overlay.hide_current_panel(event) create_top_bar(container, title=title, icon='close', action=close_action or action) class MainOverlay: # {{{ def __init__(self, overlay, elements): self.overlay = overlay self.elements = elements or {} self.timer = None if window.Intl?.DateTimeFormat: self.date_formatter = window.Intl.DateTimeFormat(undefined, {'hour':'numeric', 'minute':'numeric'}) else: self.date_formatter = {'format': def(date): return '{}:{}'.format(date.getHours(), date.getMinutes()) } def show(self, container): self.container_id = container.getAttribute('id') icon_size = '3.5ex' sd = get_session_data() def ac(text, tooltip, action, icon, is_text_button): if is_text_button: icon = E.span(icon, style='font-size: 175%; font-weight: bold') else: icon = svgicon(icon, icon_size, icon_size) if icon else '' icon.style.marginRight = '0.5ex' return E.li(icon, text, onclick=action, title=tooltip) sync_action = ac(_('Sync'), _('Get last read position and annotations from the server'), self.overlay.sync_book, 'cloud-download') delete_action = ac(_('Delete'), _('Delete this book from local storage'), self.overlay.delete_book, 'trash') reload_action = ac(_('Reload'), _('Reload this book from the {}').format( _('computer') if runtime.is_standalone_viewer else _('server')), self.overlay.reload_book, 'refresh') back_action = ac(_('Back'), _('Go back'), self.back, 'arrow-left') forward_action = ac(_('Forward'), _('Go forward'), self.forward, 'arrow-right') nav_actions = E.ul(back_action, forward_action) if runtime.is_standalone_viewer: reload_actions = E.ul( ac(_('Open book'), _('Open a book'), self.overlay.open_book, 'book'), reload_action ) else: reload_actions = E.ul(sync_action, delete_action, reload_action) bookmarks_action = ac(_('Bookmarks'), _('Browse all bookmarks'), self.overlay.show_bookmarks, 'bookmark') highlights_action = ac( _('Highlights'), _('Browse all highlights'), def(): self.overlay.show_highlights() , 'image') toc_actions = E.ul(ac(_('Table of Contents'), _('Browse the Table of Contents'), self.overlay.show_toc, 'toc')) toc_actions.appendChild(ac(_('Reference mode'), _('Toggle the Reference mode'), self.overlay.toggle_reference_mode, 'reference-mode')) actions_div = E.div( # actions nav_actions, E.ul( ac(_('Search'), _('Search for text in this book'), self.overlay.show_search, 'search'), ac(_('Go to'), _('Go to a specific location in the book'), self.overlay.show_goto, 'chevron-right'), ), reload_actions, toc_actions, E.ul(highlights_action, bookmarks_action), E.ul( ac(_('Font size'), _('Change text size'), self.overlay.show_font_size_chooser, 'Aa', True), ac(_('Preferences'), _('Configure the E-book viewer'), self.overlay.show_prefs, 'cogs'), ), class_=MAIN_OVERLAY_ACTIONS_CLASS ) if not runtime.is_standalone_viewer: home_action = ac(_('Home'), _('Return to the home page'), def(): home() ui_operations.close_book() , 'home') library_action = ac(_('Library'), _('Return to the library page'), self.overlay.show_library, 'library') book_action = ac(_('Book'), _('Return to the book\'s page'), self.overlay.show_book_page, 'book') actions_div.insertBefore(E.ul(home_action, library_action, book_action), actions_div.firstChild) full_screen_actions = [] if runtime.is_standalone_viewer: text = _('Exit full screen') if runtime.viewer_in_full_screen else _('Enter full screen') full_screen_actions.push( ac(text, _('Toggle full screen mode'), def(): self.overlay.hide(), ui_operations.toggle_full_screen();, 'full-screen')) full_screen_actions.push( ac(_('Print'), _('Print book to PDF'), def(): self.overlay.hide(), ui_operations.print_book();, 'print')) else: if not is_ios and full_screen_supported(): text = _('Exit full screen') if full_screen_element() else _('Enter full screen') # No fullscreen on iOS, see http://caniuse.com/#search=fullscreen full_screen_actions.push( ac(text, _('Toggle full screen mode'), def(): self.overlay.hide(), ui_operations.toggle_full_screen();, 'full-screen') ) if sd.get('read_mode') is 'flow': asa = self.overlay.view.autoscroll_active full_screen_actions.append(ac( _('Stop auto scroll') if asa else _('Auto scroll'), _('Toggle auto-scrolling'), def(): self.overlay.hide() window.setTimeout(self.overlay.view.toggle_autoscroll, 0) , 'auto-scroll')) actions_div.appendChild(E.ul( ac(_('Read aloud'), _('Read the book aloud'), def(): self.overlay.hide() self.overlay.view.start_read_aloud() , 'bullhorn'), ac(_('Profiles'), _('Quickly switch between different settings'), def(): self.overlay.show_profiles() , 'convert') )) if full_screen_actions.length: actions_div.appendChild(E.ul(*full_screen_actions)) no_selection_bar = not sd.get('show_selection_bar') if runtime.is_standalone_viewer: if no_selection_bar: actions_div.appendChild(E.ul( ac(_('Lookup/search word'), _('Lookup or search for the currently selected word'), def(): self.overlay.hide(), ui_operations.toggle_lookup(True);, 'library') )) copy_actions = E.ul() if self.elements.link: copy_actions.appendChild(ac(_('Copy link'), _('Copy the current link'), def(): self.overlay.hide(), ui_operations.copy_selection(self.elements.link) , 'link')) if self.elements.img: copy_actions.appendChild(ac(_('View image'), _('View the current image'), def(): self.overlay.hide(), ui_operations.view_image(self.elements.img) , 'image')) copy_actions.appendChild(ac(_('Copy image'), _('Copy the current image'), def(): self.overlay.hide(), ui_operations.copy_image(self.elements.img) , 'copy')) if copy_actions.childNodes.length: actions_div.appendChild(copy_actions) actions_div.appendChild(E.ul( ac(_('Inspector'), _('Show the content inspector'), def(): self.overlay.hide(), ui_operations.toggle_inspector();, 'bug'), ac(_('Reset interface'), _('Reset E-book viewer panels, toolbars and scrollbars to defaults'), def(): question_dialog( _('Are you sure?'), _( 'Are you sure you want to reset the viewer interface' ' to its default appearance?' ), def (yes): if yes: self.overlay.hide() ui_operations.reset_interface() sd = get_session_data() sd.set('skipped_dialogs', session_defaults().skipped_dialogs) ) , 'window-restore'), ac(_('Quit'), _('Close the E-book viewer'), def(): self.overlay.hide(), ui_operations.quit();, 'remove'), )) else: copy_actions = E.ul() if self.elements.link: copy_actions.appendChild(ac(_('Copy link'), _('Copy the current link'), def(): self.overlay.hide(), ui_operations.copy_selection(self.elements.link) , 'link')) if self.elements.img: copy_actions.appendChild(ac(_('View image'), _('View the current image'), def(): self.overlay.hide(), ui_operations.view_image(self.elements.img) , 'image')) if window.navigator.clipboard: copy_actions.appendChild(ac(_('Copy image'), _('Copy the current image'), def(): self.overlay.hide(), ui_operations.copy_image(self.elements.img) , 'copy')) if copy_actions.childNodes.length: actions_div.appendChild(copy_actions) container.appendChild(set_css(E.div(class_=MAIN_OVERLAY_TS_CLASS, # top section onclick=def (evt):evt.stopPropagation();, set_css(E.div( # top row E.div(self.overlay.view.book?.metadata?.title or _('Unknown'), style='max-width: 90%; text-overflow: ellipsis; font-weight: bold; white-space: nowrap; overflow: hidden'), E.div(time_formatter.format(Date()), id=timer_id(), style='max-width: 9%; white-space: nowrap; overflow: hidden'), ), display='flex', justify_content='space-between', align_items='baseline', font_size='smaller', padding='0.5ex 1ex', border_bottom='solid 1px currentColor' ), actions_div, ), user_select='none', background_color=get_color('window-background'))) container.appendChild( E.div( # bottom bar style='position: fixed; width: 100%; bottom: 0; display: flex; justify-content: space-between; align-items: center;' 'user-select: none; background-color: {}'.format(get_color('window-background')), E.div( style='display: flex; justify-content: space-between; align-items: center;', E.div( style='display: flex; align-items: center; cursor: pointer; padding: 0.5ex 1rem', class_='main-overlay-button', title=_('Close the viewer controls'), svgicon('close', icon_size, icon_size), '\xa0', _('Close') ), E.div( style='display: flex; align-items: center; cursor: pointer; padding: 0.5ex 1rem', class_='main-overlay-button', svgicon('help', icon_size, icon_size), '\xa0', _('Help'), onclick=def(ev): ui_operations.show_help('viewer') ) ), E.div(style='padding: 0.5ex 1rem', '\xa0'), E.div(style='padding: 0.5ex 1rem', '\xa0'), ), ) renderer = self.overlay.view.create_template_renderer() if renderer: c = container.lastChild.lastChild b = c.previousSibling renderer(b, 'controls_footer', 'middle', '') renderer(c, 'controls_footer', 'right', '') self.on_hide() self.timer = setInterval(self.update_time, 1000) def update_time(self): tm = document.getElementById(timer_id()) if tm: tm.textContent = self.date_formatter.format(Date()) def on_hide(self): if self.timer is not None: clearInterval(self.timer) self.timer = None def back(self): window.history.back() self.overlay.hide() def forward(self): window.history.forward() self.overlay.hide() # }}} class SimpleOverlay: # {{{ def __init__(self, overlay, create_func, title): self.overlay = overlay self.create_func = create_func self.title = title def on_container_click(self, evt): pass # Dont allow panel to be closed by a click def show(self, container): simple_overlay_title(self.title, self.overlay, container) self.create_func(self.overlay, container) # }}} class TOCOverlay(SimpleOverlay): # {{{ def __init__(self, overlay, create_func, title): self.overlay = overlay self.create_func = create_func or create_toc_panel self.title = title or _('Table of Contents') def show(self, container): container.appendChild(E.div()) container = container.firstChild simple_overlay_title(self.title, self.overlay, container) self.create_func(self.overlay.view.book, container, self.handle_activate) def handle_activate(self, dest, frag): self.overlay.hide() if jstype(dest) is 'function': dest(self.overlay.view, frag) else: self.overlay.view.goto_named_destination(dest, frag) # }}} class WordActionsOverlay: # {{{ def __init__(self, word, overlay): self.word = word self.overlay = overlay def on_container_click(self, evt): pass # Dont allow panel to be closed by a click def show(self, container): simple_overlay_title(_('Lookup: {}').format(self.word), self.overlay, container) create_word_actions_panel(container, self.word, self.overlay.hide) # }}} class PrefsOverlay: # {{{ def __init__(self, overlay): self.overlay = overlay self.changes_occurred = False def on_container_click(self, evt): pass # Dont allow panel to be closed by a click def create_panel_impl(self, container): return create_prefs_panel(container, self.overlay.hide_current_panel, self.on_change) def show(self, container): self.changes_occurred = False container.style.backgroundColor = get_color('window-background') self.prefs = self.create_panel_impl(container) def on_change(self): self.changes_occurred = True def handle_escape(self): self.prefs.onclose() def on_hide(self): if self.changes_occurred: self.changes_occurred = False self.overlay.view.preferences_changed() class ProfilesOverlay(PrefsOverlay): def create_panel_impl(self, container): return create_profiles_panel(container, self.overlay.hide_current_panel, self.on_change) def handle_escape(self): self.overlay.hide_current_panel() # }}} class FontSizeOverlay: # {{{ def __init__(self, overlay): self.overlay = overlay def show(self, container): create_font_size_panel(container, self.overlay.hide_current_panel) # }}} class OpenBook: # {{{ def __init__(self, overlay, closeable): self.overlay = overlay self.closeable = closeable def handle_escape(self): if self.closeable: self.overlay.hide_current_panel() else: if self.overlay.handling_context_menu_event is None: ui_operations.quit() def on_container_click(self, evt): pass # Dont allow panel to be closed by a click def show(self, container): simple_overlay_title(_('Open a book'), self.overlay, container, def (): ev = this ev.stopPropagation(), ev.preventDefault() if self.closeable: self.overlay.hide_current_panel(ev) else: ui_operations.quit() ) create_open_book(container, self.overlay.view?.book) # }}} class Overlay: def __init__(self, view): self.view = view self.handling_context_menu_event = None c = self.clear_container() c.addEventListener('click', self.container_clicked) c.addEventListener('contextmenu', self.oncontextmenu, {'passive': False}) self.panels = [] def oncontextmenu(self, evt): if default_context_menu_should_be_allowed(evt): return evt.preventDefault() self.handling_context_menu_event = evt self.handle_escape() self.handling_context_menu_event = None def clear_container(self): c = self.container clear(c) c.style.backgroundColor = 'transparent' c.style.color = get_color('window-foreground') if c.style.display is not 'block': c.style.display = 'block' return c @property def container(self): return document.getElementById('book-overlay') @property def is_visible(self): return self.container.style.display is not 'none' def update_visibility(self): if self.panels.length: self.container.style.display = 'block' self.view.overlay_visibility_changed(True) elif self.container.style.display is 'block': self.container.style.display = 'none' self.view.focus_iframe() self.view.overlay_visibility_changed(False) def container_clicked(self, evt): if self.panels.length and jstype(self.panels[-1].on_container_click) is 'function': self.panels[-1].on_container_click(evt) else: self.hide_current_panel() def show_loading_message(self, msg): if ui_operations.show_loading_message: ui_operations.show_loading_message(msg) else: lm = LoadingMessage(msg, self.view.current_color_scheme) self.panels.push(lm) self.show_current_panel() def hide_loading_message(self): if ui_operations.show_loading_message: ui_operations.show_loading_message(None) else: self.panels = [p for p in self.panels if not isinstance(p, LoadingMessage)] self.show_current_panel() def hide_current_panel(self): p = self.panels.pop() if p and callable(p.on_hide): p.on_hide() self.show_current_panel() def handle_escape(self): if self.panels.length: p = self.panels[-1] if not p.is_not_escapable: if p.handle_escape: p.handle_escape() else: self.hide_current_panel() return True return False def show_current_panel(self): if self.panels.length: c = self.clear_container() self.panels[-1].show(c) self.update_visibility() def show(self, elements): self.panels = [MainOverlay(self, elements)] self.show_current_panel() def hide(self): while self.panels.length: self.hide_current_panel() self.update_visibility() def delete_book(self): self.hide_current_panel() self.panels = [DeleteBook(self)] self.show_current_panel() def reload_book(self): self.hide_current_panel() self.panels = [DeleteBook(self, _('Are you sure you want to reload this book?'), 'refresh', _('Reload book'), True)] self.show_current_panel() def open_book(self, closeable): self.hide_current_panel() if jstype(closeable) is not 'boolean': closeable = True self.panels = [OpenBook(self, closeable)] self.show_current_panel() def sync_book(self): self.hide_current_panel() self.panels = [SyncBook(self)] self.show_current_panel() def show_toc(self): self.hide_current_panel() if runtime.is_standalone_viewer: ui_operations.toggle_toc() return self.panels.push(TOCOverlay(self)) self.show_current_panel() def toggle_reference_mode(self): self.hide_current_panel() self.view.toggle_reference_mode() def show_bookmarks(self): self.hide_current_panel() if runtime.is_standalone_viewer: ui_operations.toggle_bookmarks() return def do_it(action, data): self.panels.push(TOCOverlay(self, create_bookmarks_panel.bind(None, self.view.annotations_manager, data), _('Bookmarks'))) self.show_current_panel() self.view.get_current_cfi('show-bookmarks', do_it) def show_highlights(self): self.hide_current_panel() if ui_operations.toggle_highlights: self.hide() ui_operations.toggle_highlights() return self.panels.push(TOCOverlay(self, create_highlights_panel.bind(None, self.view.annotations_manager, self.hide_current_panel), _('Highlights'))) self.show_current_panel() def show_profiles(self): self.hide_current_panel() self.panels.push(ProfilesOverlay(self)) self.show_current_panel() def show_goto(self): self.hide_current_panel() self.panels.push(TOCOverlay(self, create_goto_panel.bind(None, self.view.current_position_data), _('Go to…'))) self.show_current_panel() def show_metadata(self): self.hide_current_panel() from_read_book = short_uuid() def show_metadata_overlay(mi, pathtoebook, calibre_book_in_library_url, lname, book_id, overlay, container): container_id = ensure_id(container) container.appendChild(E.div(class_=BD_CLASS_NAME, style='padding: 1ex 1em')) table = E.table(class_='metadata') def handle_message(msg): data = msg.data if data.from_read_book is not from_read_book: return if data.type is 'edit_metadata_closed': ui_operations.stop_waiting_for_messages_from(this) self.hide_current_panel() return if data.type is 'update_cached_book_metadata' and data.metadata: if current_library_id() is data.library_id: mi = data.metadata book_id = int(data.book_id) set_book_metadata(book_id, mi) book = self.view.book if book and book.key[0] is data.library_id and book.key[1] is book_id: ui_operations.update_metadata(book, mi) if not runtime.is_standalone_viewer and lname: container.lastChild.appendChild(E.div( style='text-align: right', E.a(_('Edit the metadata for this book in the library'), class_='blue-link', onclick=def(): container = document.getElementById(container_id) clear(container) container.appendChild(E.iframe( style='position: absolute; left: 0; top: 0; width: 100vw; height: 100vh; border-width: 0', src=query_as_href({ 'from_read_book': from_read_book, 'library_id': lname, 'book_id': book_id + ''}, 'edit_metadata') )) w = container.lastChild.contentWindow ui_operations.wait_for_messages_from(w, handle_message.bind(w)) ) )) container.lastChild.appendChild(table) render_metadata(mi, table, None, f'html {{ font-size: {document.documentElement.style.fontSize} }}') for a in table.querySelectorAll('a[href]'): a.removeAttribute('href') a.removeAttribute('title') a.classList.remove('blue-link') if pathtoebook: container.lastChild.appendChild(E.div( style='margin-top: 1ex; padding-top: 1ex; border-top: solid 1px', _('Path:'), ' ', E.a( href='javascript: void(0)', class_='blue-link', title=_('Click to open the folder the book is in'), onclick=def(): ui_operations.show_book_folder() , pathtoebook) ) ) if calibre_book_in_library_url: container.lastChild.appendChild(E.div( style='margin-top: 1ex; padding-top: 1ex;', E.a( href=calibre_book_in_library_url, class_='blue-link', title=_('Click to see this book in the main calibre program book list'), _('Show book in the main calibre program')) ) ) book = self.view.book key = book.key or v'[null, 0]' lname, book_id = key book_id = int(book_id or 0) panel = SimpleOverlay(self, show_metadata_overlay.bind(None, book.metadata, book.manifest.pathtoebook, book.calibre_book_in_library_url, lname, book_id), self.view.book.metadata.title) panel.from_read_book = from_read_book self.panels.push(panel) self.show_current_panel() def show_ask_for_location(self): self.hide_current_panel() self.panels.push(SimpleOverlay( self, create_location_overlay.bind(None, self.view.current_position_data, self.view.book), _('Go to location, position or reference…'))) self.show_current_panel() def show_page_list(self): self.hide_current_panel() self.panels.push(SimpleOverlay( self, create_page_list_overlay.bind(None, self.view.book), _('Go to page'))) self.show_current_panel() def show_search(self): self.hide() self.view.show_search() def show_prefs(self): self.hide_current_panel() self.panels.push(PrefsOverlay(self)) self.show_current_panel() def show_library(self): self.hide_current_panel() book = self.view.book show_panel('book_list', {'library_id': book.key[0], 'book_id': book.key[1] + ''}, replace=False) ui_operations.close_book() def show_book_page(self): self.hide_current_panel() self.view.open_book_page() ui_operations.close_book() def show_font_size_chooser(self): self.hide_current_panel() self.panels.push(FontSizeOverlay(self)) self.show_current_panel() def show_word_actions(self, word): self.hide_current_panel() self.panels.push(WordActionsOverlay(word, self)) self.show_current_panel()
36,450
Python
.py
756
36.588624
192
0.588497
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,551
selection.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/selection.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from complete import create_simple_input_with_history from dom import clear, svgicon, unique_id from gettext import gettext as _ from read_book.globals import is_dark_theme from read_book.highlights import all_styles from read_book.prefs.utils import create_button_box from read_book.selection_bar import all_actions from session import session_defaults CONTAINER = unique_id('selection-settings') def set_actions(use_defaults): c = get_container() adef = all_actions() sd = get_session_data() actions = session_defaults().selection_bar_actions if use_defaults else sd.get('selection_bar_actions') current = [x for x in actions if adef[x]] c.querySelector('.current-actions').dataset.actions = JSON.stringify(current) available_actions = [x for x in adef if current.indexOf(x) is -1] c.querySelector('.available-actions').dataset.actions = JSON.stringify(available_actions) update_action_tables() quick_actions = session_defaults().selection_bar_quick_highlights if use_defaults else sd.get('selection_bar_quick_highlights') c.querySelector('.quick-actions').dataset.actions = JSON.stringify(quick_actions) update_quick_action_table() def restore_defaults(): container = get_container() sd = session_defaults() for control in container.querySelectorAll('input[name]'): val = sd[control.getAttribute('name')] if control.type is 'checkbox': control.checked = val elif control.type is 'number': control.valueAsNumber = val else: control.value = val for ta in container.querySelectorAll('textarea[name]'): val = sd[ta.getAttribute('name')] ta.value = val set_actions(True) def get_container(): return document.getElementById(CONTAINER) def transfer(name, frm, to_): c = get_container().querySelector('.' + frm) actions = JSON.parse(c.dataset.actions) idx = actions.indexOf(name) actions.splice(idx, 1) c.dataset.actions = JSON.stringify(actions) c = get_container().querySelector('.' + to_) actions = JSON.parse(c.dataset.actions) if to_ is 'current-actions': actions.unshift(name) else: actions.push(name) c.dataset.actions = JSON.stringify(actions) update_action_tables() def add_action(name): transfer(name, 'available-actions', 'current-actions') def remove_action(name): transfer(name, 'current-actions', 'available-actions') def move_action(name, up): c = get_container().querySelector('.current-actions') actions = JSON.parse(c.dataset.actions) idx = actions.indexOf(name) delta = -1 if up else 1 new_idx = (idx + delta + len(actions)) % len(actions) a, b = actions[idx], actions[new_idx] actions[new_idx], actions[idx] = a, b c.dataset.actions = JSON.stringify(actions) update_action_tables() def build_action_table(container, is_current): clear(container) adef = all_actions() table = E.table(style='margin-left: 2rem') container.appendChild(table) for action_name in JSON.parse(container.dataset.actions): ac = adef[action_name] if is_current: buttons = E.td( E.span(_('Remove'), class_='simple-link', onclick=remove_action.bind(None, action_name)), E.span('\xa0', style='min-width: 2rem; display: inline-block'), E.span(_('Up'), class_='simple-link', onclick=move_action.bind(None, action_name, True)), E.span('\xa0', style='min-width: 2rem; display: inline-block'), E.span(_('Down'), class_='simple-link', onclick=move_action.bind(None, action_name, False)), ) else: buttons = E.td( E.span(_('Add'), class_='simple-link', onclick=add_action.bind(None, action_name)), ) buttons.style.paddingLeft = '2rem' if ac.icon_function: icon = ac.icon_function('#add8ff') else: icon = svgicon(ac.icon) table.appendChild(E.tr(E.td(style='padding: 1ex', icon), E.td(ac.text), buttons)) def update_action_tables(): c = get_container() current = c.querySelector('.current-actions') build_action_table(current, True) current = c.querySelector('.available-actions') build_action_table(current, False) def update_quick_action_table(): c = get_container().querySelector('.quick-actions') clear(c) c.style.display = 'flex' c.style.flexWrap = 'wrap' current = {x: True for x in JSON.parse(c.dataset.actions)} actions = list(all_styles()) actions.pysort(key=def (a): return (a.friendly_name or '').toLowerCase();) for hs in actions: c.appendChild(E.label( style='margin: 1ex; display: flex; align-contents: center', hs.make_swatch(E.span(), is_dark_theme()), '\xa0', E.input(type='checkbox', value=hs.key, checked=current[hs.key]), '\xa0', hs.friendly_name, )) def selected_quick_actions(): ans = v'[]' c = get_container().querySelector('.quick-actions') for inp in c.querySelectorAll('input:checked'): if inp.value: ans.push(inp.value) return ans def create_selection_panel(container, apply_func, cancel_func): container.appendChild(E.div(id=CONTAINER, style='margin: 1rem')) container = container.lastChild sd = get_session_data() def cb(name, text): ans = E.input(type='checkbox', name=name) if sd.get(name): ans.checked = True return E.div(style='margin-top:1ex', E.label(ans, '\xa0' + text)) def url(name, text, title): ans = create_simple_input_with_history(name, input_type='url') inp = ans.querySelector(f'input[name={name}]') inp.value = sd.get(name) or '' inp.setAttribute('size', '50') inp.style.marginTop = '1ex' return E.div(style='margin-top:1ex', E.label(text, E.br(), ans)) def cite_template_textarea(name, text, title): ans = E.textarea(name=name, style='width: 100%; margin-top: 1ex; box-sizing: border-box; flex-grow: 10') ans.value = sd.get(name) return E.div(style='margin-top:1ex', E.label(text, E.br(), ans)) container.appendChild(cb( 'show_selection_bar', _('Show a popup bar with common actions next to selected text'))) container.appendChild(url( 'net_search_url', _('URL to query when searching the internet'), _('The {q} in the URL is replaced by the selected text'))) container.appendChild(E.div( style='margin-top: 2ex; border-top: solid 1px; padding-top: 1ex;', _('Customize which actions are shown in the selection popup bar') )) container.appendChild(E.div(style='padding: 1ex; border-bottom: solid 1px; margin-bottom: 1ex', E.h3(_('Current actions')), E.div(class_='current-actions'), E.h3(_('Available actions')), E.div(class_='available-actions') )) container.appendChild(E.div(style='padding: 1ex; border-bottom: solid 1px; margin-bottom: 1ex', E.h3(_('Quick highlight actions')), E.div(_('Choose highlight styles that will have dedicated buttons in the selection bar to create highlights with a single click')), E.div(class_='quick-actions'), )) container.appendChild(E.h3(_('Citing text'))) container.appendChild(cite_template_textarea( 'cite_text_template', _('Template for citing plain text:'))) container.appendChild(cite_template_textarea( 'cite_hl_template', _('Template for citing highlighted text:'))) container.appendChild(E.div( E.div( style='margin-top: 2ex', _('{text} and {url} are available in both types of template. Additionally, {timestamp},' ' {chapter}, {notes}, {style_type}, {style_kind} and {style_which} are available when citing a highlight.' ).format(text='{text}', url='{url}', chapter='{chapter}', notes='{notes}', style_type='{style_type}', style_kind='{style_kind}', style_which='{style_which}', timestamp='{timestamp}', ) ), E.div( style='margin-top: 2ex; margin-bottom: 2ex; border-bottom: solid 1px; padding-bottom: 1ex;', _('Use "}}" and "{{" to escape "}" and "{".') ) )) set_actions() container.appendChild(create_button_box(restore_defaults, apply_func, cancel_func)) develop = create_selection_panel def commit_selection(onchange): sd = get_session_data() container = get_container() changed = False save_ev = new Event('save_history') for x in container.querySelectorAll('[data-calibre-history-input]'): x.dispatchEvent(save_ev) for control in container.querySelectorAll('input[name]'): name = control.getAttribute('name') if control.type is 'checkbox': val = control.checked elif control.type is 'number': val = control.valueAsNumber else: val = control.value if val is not sd.get(name) and control.validity.valid: sd.set(name, val) changed = True actions = JSON.parse(container.querySelector('.current-actions').dataset.actions) if list(actions) != list(sd.get('selection_bar_actions')): changed = True sd.set('selection_bar_actions', actions) quick_highlights = selected_quick_actions() if list(quick_highlights) != list(sd.get('selection_bar_quick_highlights')): changed = True sd.set('selection_bar_quick_highlights', quick_highlights) # Save textarea for ta in container.querySelectorAll('textarea[name]'): name = ta.getAttribute('name') val = (ta.value or '').strip() or session_defaults()[name] old = sd.get(name) if old is not val: sd.set(name, val) changed = True if changed: onchange()
10,196
Python
.py
225
38.031111
139
0.649315
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,552
misc.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/misc.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from dom import unique_id from gettext import gettext as _ from read_book.globals import ui_operations from read_book.prefs.utils import create_button_box from session import session_defaults, standalone_reader_defaults as DEFAULTS from widgets import create_button CONTAINER = unique_id('standalone-misc-settings') def restore_defaults(): container = get_container() for q in Object.keys(DEFAULTS): control = container.querySelector(f'[name={q}]') if jstype(DEFAULTS[q]) is 'boolean': control.checked = DEFAULTS[q] else: control.value = DEFAULTS[q] container.querySelector(f'[name=hide_tooltips]').checked = session_defaults().hide_tooltips def get_container(): return document.getElementById(CONTAINER) def create_misc_panel(container, apply_func, cancel_func): container.appendChild(E.div(id=CONTAINER, style='margin: 1rem')) container = container.lastChild sd = get_session_data() settings = sd.get('standalone_misc_settings') settings.hide_tooltips = sd.get('hide_tooltips') def cb(name, text): ans = E.input(type='checkbox', name=name) ans.checked = settings[name] if jstype(settings[name]) is 'boolean' else DEFAULTS[name] return E.div(style='margin-top:1ex', E.label(ans, '\xa0' + text)) sai = E.input(name='sync_annots_user', title=_( 'The username of a Content server user that you want all annotations synced with.' ' Use the special value * to sync with anonymous users' )) sai.value = settings.sync_annots_user if jstype(settings.sync_annots_user) is 'string' else DEFAULTS.sync_annots_user sync_annots = E.div( style='margin-top: 1ex; margin-left: 3px', E.label(_('Sync bookmarks/highlights with Content server user:') + '\xa0', sai) ) container.append(cb('remember_window_geometry', _('Remember last used window size and position'))) container.append(cb('show_actions_toolbar', _('Show a toolbar with the most useful actions'))) container.lastChild.append(E.span('\xa0')) container.lastChild.append( create_button(_('Customize toolbar'), action=ui_operations.customize_toolbar)) container.append(cb('show_actions_toolbar_in_fullscreen', _('Keep the toolbar in full screen mode (needs restart)'))) container.append(cb('remember_last_read', _('Remember current page when quitting'))) container.append(cb('restore_docks', _('Restore open panels such as Table of Contents, Search, etc. on restart'))) container.append(cb('save_annotations_in_ebook', _('Keep a copy of annotations/bookmarks in the e-book file, for easy sharing'))) container.append(sync_annots) container.append(cb('singleinstance', _('Allow only a single instance of the viewer (needs restart)'))) container.append(cb('hide_tooltips', _('Hide mouse-over tooltips in the book text'))) container.append(cb('auto_hide_mouse', _('Auto hide the mouse cursor when unused for a few seconds'))) container.appendChild(create_button_box(restore_defaults, apply_func, cancel_func)) develop = create_misc_panel def commit_misc(onchange): sd = get_session_data() container = get_container() vals = {} for q in Object.keys(DEFAULTS): control = container.querySelector(f'[name={q}]') if jstype(DEFAULTS[q]) is 'boolean': val = control.checked else: val = control.value.strip() if val is not DEFAULTS[q]: vals[q] = val sd.set('standalone_misc_settings', vals) hide_tooltips = container.querySelector(f'[name=hide_tooltips]').checked sd.set('hide_tooltips', None if hide_tooltips is session_defaults().hide_tooltips else hide_tooltips) onchange()
3,972
Python
.py
73
48.753425
133
0.710018
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,553
font_size.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/font_size.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.globals import get_session_data from book_list.theme import get_color from dom import add_extra_css, rule, unique_id from read_book.globals import ui_operations from widgets import create_button from session import session_defaults CONTAINER = unique_id('font-size-prefs') MIN_FONT_SIZE = 8 MAX_FONT_SIZE = 80 add_extra_css(def(): style = rule(CONTAINER, 'option.current', background_color=get_color('window-background2')) style += rule(CONTAINER, 'option:hover', background_color=get_color('window-background2')) style += rule(CONTAINER, 'a:hover', color=get_color('window-hover-foreground')) style += rule(CONTAINER, 'a.calibre-push-button:hover', color=get_color('button-text')) return style ) def change_font_size(sz): sd = get_session_data() if sd.get('base_font_size') is not sz: sd.set('base_font_size', sz) ui_operations.update_font_size() def apply_font_size(): fs = int(document.getElementById(CONTAINER).dataset.cfs) change_font_size(fs) def set_quick_size(ev): newval = ev.currentTarget.value try: int(newval) except: return if newval is not document.getElementById(CONTAINER).dataset.cfs: display_changed_font_size(newval) def change_font_size_by(frac): sd = get_session_data() sz = sd.get('base_font_size') amt = sz * frac if abs(amt) < 1: amt = -1 if amt < 0 else 1 nsz = int(sz + amt) nsz = max(MIN_FONT_SIZE, min(nsz, MAX_FONT_SIZE)) change_font_size(nsz) def restore_default_font_size(): change_font_size(session_defaults().base_font_size) def display_changed_font_size(sz): sz = max(MIN_FONT_SIZE, min(int(sz), MAX_FONT_SIZE)) sz += '' c = document.getElementById(CONTAINER) c.dataset.cfs = sz for option in c.querySelectorAll('option'): if option.value is sz: option.classList.add('current') else: option.classList.remove('current') for input in c.querySelectorAll('input'): input.value = sz c.querySelector('.cfs_preview').style.fontSize = f'{sz}px' def create_font_size_panel(container, close): sd = get_session_data() cfs = sd.get('base_font_size') container.appendChild(E.div( style='width: 100%; height: 100%; display: flex; justify-content: center; align-items: center', E.div( id=CONTAINER, style='max-width: 500px; width: 80vw; border-radius: 8px; border: solid 1px currentColor; padding:1ex 1rem;', onclick=def(ev): ev.preventDefault(), ev.stopPropagation() ))) container = container.lastChild.lastChild container.style.backgroundColor = get_color('window-background') container.dataset.cfs = cfs + '' quick = E.datalist(style='display:flex; justify-content:space-around; flex-wrap: wrap; align-items: baseline;') container.appendChild(quick) for sz in (10, 12, 14, 16, 18, 20, 22): quick.appendChild(E.option( 'Aa', title='{} px'.format(sz), class_='current' if cfs is sz else '', value=sz + '', style=f'display: inline-block; font-size:{sz}px; padding: 5px; cursor: pointer; border-radius: 4px; margin: 0 0.5rem', onclick=def(ev): set_quick_size(ev) )) def set_size(ev): newval = ev.currentTarget.value try: q = int(newval) except: return if MIN_FONT_SIZE <= q <= MAX_FONT_SIZE: set_quick_size(ev) container.appendChild(E.div( style='display: flex; margin-top: 1rem', E.input( type='range', min=MIN_FONT_SIZE + '', max=MAX_FONT_SIZE + '', value=cfs + '', style='flex-grow: 4', oninput=set_quick_size, ), E.span('\xa0', E.input( value=f'{cfs}', oninput=set_size, type='number', min=MIN_FONT_SIZE + '', max=MAX_FONT_SIZE + '', step='1', style='width: 3em', ), '\xa0px') )) container.appendChild(E.div( style=f'font-size: {cfs}px; margin-top: 1rem; min-height: 60px; max-height: 60px; overflow: hidden; display: flex;', E.div(class_='cfs_preview', _('Sample to preview font size')) )) container.appendChild(E.div( style='margin-top: 1rem; text-align: right', create_button(_('OK'), highlight=True, action=def(): apply_font_size() close() ), '\xa0\xa0', create_button(_('Cancel'), action=close), )) def develop(container): create_font_size_panel(container, def():pass;)
4,806
Python
.py
119
33.638655
130
0.639502
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,554
main.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/main.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.item_list import build_list, create_item from book_list.top_bar import create_top_bar, set_title from dom import clear, ensure_id from gettext import gettext as _ from read_book.globals import runtime from read_book.prefs.colors import commit_colors, create_colors_panel from read_book.prefs.fonts import commit_fonts, create_fonts_panel from read_book.prefs.head_foot import commit_head_foot, create_head_foot_panel from read_book.prefs.keyboard import commit_keyboard, create_keyboard_panel from read_book.prefs.layout import commit_layout, create_layout_panel from read_book.prefs.misc import commit_misc, create_misc_panel from read_book.prefs.scrolling import commit_scrolling, create_scrolling_panel from read_book.prefs.selection import commit_selection, create_selection_panel from read_book.prefs.touch import commit_touch, create_touch_panel from read_book.prefs.user_stylesheet import ( commit_user_stylesheet, create_user_stylesheet_panel ) class Prefs: def __init__(self, container, close_func, on_change): self.close_func = close_func self.on_change = on_change self.main_title = _('Configure book reader') container.appendChild(E.div( style='contain: paint; width: 100%; height: 100%; display: flex; flex-direction: column', tabindex='-1', onkeydown=def(ev): if ev.key is 'Escape': ev.stopPropagation(), ev.preventDefault() if not self.cancel(): self.close_func() , E.div(), E.div(style='flex-grow: 100; overflow: auto') )) container = container.firstChild create_top_bar(container.firstChild, title=self.main_title, icon='close', action=self.onclose) self.container_id = ensure_id(container.lastChild) self.stack = v'["top"]' self.display_top(container.lastChild) def set_top_title(self, val): set_title(self.container.parentNode, val) def onchange(self): self.on_change() def cancel(self): if self.stack.length > 1: self.stack.pop() self.display_panel(self.stack[-1]) return True def onclose(self): if self.stack.length > 1: which = self.stack.pop() close_func = getattr(self, 'close_' + which, None) if close_func: close_func.bind(self)() self.display_panel(self.stack[-1]) else: self.close_func() def create_panel(self, container, which, create_func, needs_onchange): self.set_top_title(self.title_map[which] or which) if needs_onchange: create_func(container, self.onclose, self.cancel, self.onchange) else: create_func(container, self.onclose, self.cancel) @property def container(self): return document.getElementById(self.container_id) def display_panel(self, which): container = self.container clear(container) getattr(self, 'display_' + which)(container) container.setAttribute('tabindex', '-1') container.focus() def show_panel(self, which): self.stack.push(which) self.display_panel(which) def display_top(self, container): self.set_top_title(self.main_title) c = E.div() container.appendChild(c) self.title_map = {} items = [] def ci(title, which, subtitle): items.push(create_item(title, self.show_panel.bind(None, which), subtitle)) self.title_map[which] = title ci(_('Colors'), 'colors', _('Colors of the page and text')) ci(_('Page layout'), 'layout', _('Page margins and number of pages per screen')) ci(_('Styles'), 'user_stylesheet', _('Style rules for text and background image')) ci(_('Headers and footers'), 'head_foot', _('Customize the headers and footers')) ci(_('Scrolling behavior'), 'scrolling', _('Control how the viewer scrolls')) ci(_('Selection behavior'), 'selection', _('Control how the viewer selects text')) ci(_('Touch behavior'), 'touch', _('Customize what various touchscreen gestures do')) ci(_('Keyboard shortcuts'), 'keyboard', _('Customize the keyboard shortcuts')) if runtime.is_standalone_viewer: ci(_('Fonts'), 'fonts', _('Font choices')) ci(_('Miscellaneous'), 'misc', _('Window size, last read position, toolbar, etc.')) build_list(c, items) def display_fonts(self, container): self.create_panel(container, 'fonts', create_fonts_panel) def close_fonts(self): commit_fonts(self.onchange, self.container) def display_misc(self, container): self.create_panel(container, 'misc', create_misc_panel) def close_misc(self): commit_misc(self.onchange, self.container) def display_colors(self, container): self.create_panel(container, 'colors', create_colors_panel) def close_colors(self): commit_colors(self.onchange, self.container) def display_layout(self, container): self.create_panel(container, 'layout', create_layout_panel) def close_layout(self): commit_layout(self.onchange, self.container) def display_user_stylesheet(self, container): self.create_panel(container, 'user_stylesheet', create_user_stylesheet_panel) def close_user_stylesheet(self): commit_user_stylesheet(self.onchange, self.container) def display_head_foot(self, container): self.create_panel(container, 'head_foot', create_head_foot_panel) def close_head_foot(self): commit_head_foot(self.onchange, self.container) def display_keyboard(self, container): self.create_panel(container, 'keyboard', create_keyboard_panel, True) def close_keyboard(self): commit_keyboard(self.onchange, self.container) def display_scrolling(self, container): self.create_panel(container, 'scrolling', create_scrolling_panel) def close_scrolling(self): commit_scrolling(self.onchange, self.container) def display_selection(self, container): self.create_panel(container, 'selection', create_selection_panel) def close_selection(self): commit_selection(self.onchange, self.container) def display_touch(self, container): self.create_panel(container, 'touch', create_touch_panel) def close_touch(self): commit_touch(self.onchange, self.container) def create_prefs_panel(container, close_func, on_change): return Prefs(container, close_func, on_change)
6,840
Python
.py
141
40.48227
102
0.670571
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,555
user_stylesheet.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/user_stylesheet.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from ajax import absolute_path from book_list.globals import get_session_data from dom import ensure_id, unique_id from encodings import hexlify from gettext import gettext as _ from read_book.globals import runtime, ui_operations from read_book.prefs.utils import create_button_box from session import session_defaults from viewer.constants import FAKE_HOST, FAKE_PROTOCOL from widgets import create_button BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' def change_background_image(img_id): ui_operations.change_background_image(img_id) def clear_image(img_id): i = document.getElementById(img_id) i.src = BLANK i.dataset.url = '' def modify_background_image_url_for_fetch(url): if not url: return BLANK if runtime.is_standalone_viewer: if url.startswith(f'{FAKE_PROTOCOL}:'): return url encoded = hexlify(url) return f'{FAKE_PROTOCOL}://{FAKE_HOST}/reader-background-{encoded}' if url.startswith(f'{FAKE_PROTOCOL}:'): x = str.split(url, '/')[-1].partition('?')[0].partition('-')[2] return absolute_path(f'reader-background/{x}') return url def standalone_background_widget(sd): url = sd.get('background_image') src = modify_background_image_url_for_fetch(url) img_id = unique_id('bg-image') return E.div( style='display: flex; align-items: center', E.div(E.img(src=src, data_url=url, id=img_id, class_='bg-image-preview', style='width: 75px; height: 75px; border: solid 1px')), E.div('\xa0', style='margin: 0.5rem'), create_button(_('Change image'), action=change_background_image.bind(None, img_id)), E.div('\xa0', style='margin: 0.5rem'), create_button(_('Clear image'), action=clear_image.bind(None, img_id)), ) def background_widget(sd): if runtime.is_standalone_viewer: return standalone_background_widget(sd) return E.div(style='margin-bottom: 1ex', E.label( _('Image URL') + ':\xa0', E.input(type='url', name='background_image', value=sd.get('background_image') or '') )) def background_style_widget(sd): ans = E.div(style='margin-bottom: 1ex', E.label( _('Background image style') + ':\xa0', E.select(name='background_image_style', E.option(_('Scaled'), value='scaled'), E.option(_('Tiled'), value='tiled'), ), )) ans.querySelector('select').value = sd.get('background_image_style') return ans def background_fade_widget(sd): return E.div(E.label( _('Background image fade (%)') + ':\xa0', E.input( name='background_image_fade', type='number', max='100', min='0', step='1', value='' + sd.get('background_image_fade'), title=_('Fading of the background image is done by blending it with the background color') ), )) def restore_defaults(): container = document.getElementById(create_user_stylesheet_panel.container_id) container.querySelector('[name=user-stylesheet]').value = '' if runtime.is_standalone_viewer: i = container.querySelector('img') clear_image(i.id) else: container.querySelector('[name=background_image]').value = '' container.querySelector('select[name=background_image_style]').value = session_defaults().background_image_style container.querySelector('input[name=background_image_fade]').value = str(session_defaults().background_image_fade) def create_user_stylesheet_panel(container, apply_func, cancel_func): sd = get_session_data() create_user_stylesheet_panel.container_id = ensure_id(container) container.appendChild( E.div( style='min-height: 75vh; display: flex; flex-flow: column; margin: 1ex 1rem; padding: 1ex 0', E.div( style='border-bottom: solid 1px; margin-bottom: 1.5ex; padding-bottom: 1.5ex', E.div(_('Choose a background image to display behind the book text'), style='margin-bottom: 1.5ex'), background_widget(sd), background_style_widget(sd), background_fade_widget(sd), ), E.div( style='flex-grow: 10; display: flex; flex-flow: column', E.div( _('A CSS style sheet that can be used to control the look and feel of the text. For examples, click'), ' ', E.a(class_='blue-link', title=_("Examples of user style sheets"), target=('_self' if runtime.is_standalone_viewer else '_blank'), href='https://www.mobileread.com/forums/showthread.php?t=51500', _('here.')), ' ', _( 'Note that you can use the selectors body.calibre-viewer-paginated and body.calibre-viewer-scrolling' ' to target the Paged and Flow modes. Similarly, use body.calibre-viewer-light-colors and' ' body.calibre-viewer-dark-colors to target light and dark color schemes.') ), E.textarea(name='user-stylesheet', style='width: 100%; margin-top: 1ex; box-sizing: border-box; flex-grow: 10'), ) ) ) val = sd.get('user_stylesheet') if val: container.querySelector('[name=user-stylesheet]').value = val container.appendChild(E.div(style='margin: 1rem', create_button_box(restore_defaults, apply_func, cancel_func))) develop = create_user_stylesheet_panel def commit_user_stylesheet(onchange, container): sd = get_session_data() ta = container.querySelector('[name=user-stylesheet]') val = ta.value or '' old = sd.get('user_stylesheet') changed = False if old is not val: sd.set('user_stylesheet', val) changed = True if runtime.is_standalone_viewer: bg_image = container.querySelector('img.bg-image-preview').dataset.url if bg_image is BLANK or not bg_image: bg_image = None else: bg_image = container.querySelector('input[name=background_image]').value old = sd.get('background_image') if old is not bg_image: sd.set('background_image', bg_image) changed = True old = sd.get('background_image_style') bis = container.querySelector('select[name=background_image_style]').value if bis is not old: changed = True sd.set('background_image_style', bis) old = int(sd.get('background_image_fade')) bif = int(container.querySelector('input[name=background_image_fade]').value) if old is not bif: changed = True sd.set('background_image_fade', bif) if changed: onchange()
6,906
Python
.py
146
39.356164
136
0.647164
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,556
keyboard.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/keyboard.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.globals import get_session_data from complete import create_search_bar from book_list.item_list import create_item, create_item_list from dom import clear, svgicon, unique_id from read_book.shortcuts import ( key_as_text, keyevent_as_shortcut, shortcut_differs, shortcuts_definition, shortcuts_group_desc ) from widgets import create_button def get_container(): return document.getElementById(get_container.id) def restore_defaults(close_func): get_container().dataset.changed = 'true' for item in get_container().querySelectorAll('[data-user-data]'): q = JSON.parse(item.dataset.userData) q.shortcuts = shortcuts_definition()[q.name].shortcuts item.dataset.userData = JSON.stringify(q) close_func() def as_groups(shortcuts): ans = {} for sc_name in Object.keys(shortcuts): sc = shortcuts[sc_name] if not ans[sc.group]: ans[sc.group] = {} ans[sc.group][sc_name] = sc return ans def sort_group_key(group, sc_name): return group[sc_name].short.toLowerCase() def sc_as_item(sc_name, sc, shortcuts): cuts = shortcuts or sc.shortcuts return create_item(sc.short, action=customize_shortcut.bind(None, sc_name), subtitle=sc.long, data=JSON.stringify({'name': sc_name, 'shortcuts': cuts})) def remove_key(evt): key_container = evt.currentTarget.parentNode.parentNode key_container.parentNode.removeChild(key_container) def key_widget(key): icon = svgicon('remove') icon.style.verticalAlign = 'baseline' return E.tr( data_shortcut=JSON.stringify(keyevent_as_shortcut(key)), E.td(style="padding: 0.5rem; border-right: solid 1px; margin-right: 0.5rem; margin-top: 0.5rem", key_as_text(key)), E.td(style="padding: 0.5rem; margin-top: 0.5rem; vertical-align: bottom", E.a(class_='simple-link', '\xa0', icon, ' ', _('Remove'), onclick=remove_key)), ) def close_customize_shortcut(apply_changes): container = get_container() container.firstChild.style.display = 'flex' container.firstChild.nextSibling.style.display = 'block' container.lastChild.style.display = 'none' if close_customize_shortcut.shortcut_being_customized: for item in container.firstChild.querySelectorAll('[data-user-data]'): q = JSON.parse(item.dataset.userData) if q.name is close_customize_shortcut.shortcut_being_customized: item.scrollIntoView() break if apply_changes: shortcuts = v'[]' for x in container.lastChild.querySelectorAll('[data-shortcut]'): sc = JSON.parse(x.dataset.shortcut) shortcuts.push(sc) sc_name = container.lastChild.dataset.scName for item in container.querySelectorAll('[data-user-data]'): q = JSON.parse(item.dataset.userData) if q.name is sc_name: q.shortcuts = shortcuts item.dataset.userData = JSON.stringify(q) break get_container().dataset.changed = 'true' commit_keyboard(create_keyboard_panel.onchange, None) def add_key_widget(): uid = unique_id('add-new-shortcut') return E.div(style='margin-top: 1ex; margin-bottom: 1ex', id=uid, E.div(create_button(_('Add a new shortcut'), icon="plus", action=def (evt): div = document.getElementById(uid) div.firstChild.style.display = 'none' div.lastChild.style.display = 'block' div.lastChild.querySelector('input').focus() )), E.div(style='display:none', E.input(readonly='readonly', value=_('Press the key combination to use as a shortcut'), style='width: 90vw', onkeydown=def (evt): evt.preventDefault() evt.stopPropagation() if evt.key not in v"['Control', 'Meta', 'Alt', 'Shift']": key_con = get_container().querySelector('.key-container') key_con.appendChild(key_widget(evt)) div = document.getElementById(uid) div.firstChild.style.display = 'block' div.lastChild.style.display = 'none' )) ) def customize_shortcut(sc_name): container = get_container() container.firstChild.style.display = 'none' container.firstChild.nextSibling.style.display = 'none' container.lastChild.style.display = 'block' close_customize_shortcut.shortcut_being_customized = sc_name shortcuts = v'[]' for item in container.querySelectorAll('[data-user-data]'): q = JSON.parse(item.dataset.userData) if q.name is sc_name: shortcuts = q.shortcuts break container = container.lastChild clear(container) container.dataset.scName = sc_name sc = shortcuts_definition()[sc_name] container.appendChild(E.h4(sc.short)) if sc.long: container.appendChild(E.div(sc.long, style='font-style: italic; font-size: smaller; margin-top: 1ex')) container.appendChild(E.div(style='margin-top: 1rem', _('Existing shortcuts:'))) key_con = container.appendChild(E.table(class_="key-container")) for key in shortcuts: key_con.appendChild(key_widget(key)) container.appendChild(E.div(style='margin-top:1ex;', add_key_widget())) container.appendChild(E.div(style='margin-top:1ex; display:flex; justify-content: flex-end', create_button(_('OK'), action=close_customize_shortcut.bind(None, True)), E.span('\xa0'), create_button(_('Cancel'), action=close_customize_shortcut.bind(None, False)), )) def run_search(): container = get_container() query = container.querySelector(f'[name=search-for-sc]').value or '' query = query.toLowerCase() for item in get_container().querySelectorAll('[data-user-data]'): q = item.textContent.toLowerCase() matches = not query or q.indexOf(query) > -1 item.style.display = 'list-item' if matches else 'none' def create_keyboard_panel(container, apply_func, cancel_func, onchange): create_keyboard_panel.onchange = onchange container.appendChild(E.div(id=unique_id('keyboard-settings'), style='margin: 1rem')) container = container.lastChild container.dataset.changed = 'false' get_container.id = container.id search_button = create_button(_('Search'), icon='search') sb = create_search_bar( run_search, 'search-for-sc', placeholder=_('Search for shortcut'), button=search_button) container.appendChild(E.div( style='margin-bottom: 1ex; display: flex; width: 100%; justify-content: space-between', sb, E.span('\xa0\xa0'), search_button )) container.firstChild.firstChild.style.flexGrow = '100' container.appendChild(E.div()) container.appendChild(E.div(style='display: none')) container = container.firstChild.nextSibling sd = get_session_data() custom_shortcuts = sd.get('keyboard_shortcuts') groups = as_groups(shortcuts_definition()) for group_name in Object.keys(groups): container.appendChild(E.h3(style='margin-top: 1ex', shortcuts_group_desc()[group_name])) group = groups[group_name] items = [] for sc_name in sorted(Object.keys(group), key=sort_group_key.bind(None, group)): sc = group[sc_name] items.push(sc_as_item(sc_name, sc, custom_shortcuts[sc_name])) container.appendChild(E.div()) create_item_list(container.lastChild, items) container.appendChild(E.div( style='margin-top: 1rem', create_button(_('Restore defaults'), action=restore_defaults.bind(None, apply_func)) )) develop = create_keyboard_panel def shortcuts_differ(a, b): if a.length is not b.length: return True for x, y in zip(a, b): if shortcut_differs(x, y): return True return False def commit_keyboard(onchange, container): sd = get_session_data() vals = {} for item in get_container().querySelectorAll('[data-user-data]'): q = JSON.parse(item.dataset.userData) if shortcuts_differ(q.shortcuts, shortcuts_definition()[q.name].shortcuts): vals[q.name] = q.shortcuts sd.set('keyboard_shortcuts', vals) if container is not None: create_keyboard_panel.onchange = None if get_container().dataset.changed is 'true': onchange()
8,680
Python
.py
185
39.227027
161
0.66446
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,557
layout.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/layout.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.globals import get_session_data from dom import add_extra_css, build_rule, element, unique_id from read_book.globals import runtime from read_book.prefs.utils import create_button_box from session import session_defaults from utils import safe_set_inner_html CONTAINER = unique_id('reader-page-layout') MARGINS = unique_id('reader-page-margins') READ_MODE = unique_id('read-mode') FS_MODE = unique_id('fs-mode') COLS = unique_id('cols-per-screen') TEXT_AREA = unique_id('text-area') add_extra_css(def(): sel = '#' + MARGINS style = build_rule(sel, margin_left='1rem', margin_top='-1ex') style += build_rule('#{} td'.format(CONTAINER), padding='1ex') return style ) def restore_defaults(): defaults = session_defaults() container = document.getElementById(CONTAINER) for which in 'top bottom left right'.split(' '): container.querySelector('input[name={}]'.format(which)).value = str(defaults['margin_' + which]) for name in 'paged flow'.split(' '): container.querySelector(f'#{READ_MODE} input[data-name={name}]').checked = defaults.read_mode is name if not runtime.is_standalone_viewer: container.querySelector(f'#{FS_MODE} input[value={defaults.fullscreen_when_opening}]').checked = True for name in 'portrait landscape'.split(' '): container.querySelector('input[name={}]'.format(name)).value = str(defaults.columns_per_screen[name]) for which in 'width height'.split(' '): container.querySelector('input[name={}]'.format(which)).value = str(defaults['max_text_' + which]) container.querySelector('input[name=cover_preserve_aspect_ratio]').checked = defaults.cover_preserve_aspect_ratio def create_layout_panel(container, apply_func, cancel_func): container.appendChild(E.div(id=CONTAINER)) container = container.lastChild sd = get_session_data() container.appendChild(E.p(style='margin:1ex 1rem; padding: 1ex 0')) safe_set_inner_html(container.lastChild, _('Current window size is: <b>{0}x{1}</b> pixels').format(window.innerWidth, window.innerHeight)) container.appendChild(E.p(_('Change the page margins (in pixels) below'), style='margin:1ex 1rem; padding: 1ex 0')) container.appendChild(E.table(id=MARGINS)) labels = {'top':_('Top:'), 'bottom':_('Bottom:'), 'left':_('Left:'), 'right':_('Right:')} def item(which, tr): tr.appendChild(E.td(labels[which])) tr.appendChild(E.td(E.input(type='number', max='9999', min='0', step='1', name=which, value=str(sd.get('margin_' + which))))) container.lastChild.appendChild(E.tr()) item('left', container.lastChild.lastChild) item('right', container.lastChild.lastChild) container.lastChild.appendChild(E.tr()) item('top', container.lastChild.lastChild) item('bottom', container.lastChild.lastChild) def sec(text): container.appendChild(E.div(text, style='margin: 2ex 1rem; padding-top:2ex; border-top: solid 1px; max-width: 50em')) sec(_('Choose the page layout mode. In paged mode, the text is split up into individual pages, as in a paper book. In flow mode' ' text is presented as one long scrolling page, as in web browsers.')) container.appendChild(E.div(id=READ_MODE, style='margin: 1ex 2rem; display: flex;')) rm = sd.get('read_mode') rm = 'flow' if rm is 'flow' else 'paged' def rb(name, text): d = container.lastChild d.appendChild(E.label(E.input(type='radio', name='page-layout-mode', data_name=name, checked=rm is name), text)) rb('paged', _('Paged mode')) container.lastChild.appendChild(E.span('\xa0', style='width:3em')) rb('flow', _('Flow mode')) sec(_('In paged mode, control the number of pages per screen. A setting of zero means the number of pages is' ' set based on the screen size.')) cps = sd.get('columns_per_screen') container.appendChild(E.table(style='margin: 1ex 1rem', id=COLS, E.tr( E.td(_('Portrait:')), E.td(E.input(type='number', name='portrait', min='0', step='1', max='20', value=str(cps.portrait))), E.td(_('Landscape:')), E.td(E.input(type='number', name='landscape', min='0', step='1', max='20', value=str(cps.landscape))), ))) sec(_('Change the maximum screen area (in pixels) used to display text.' ' A value of zero means that all available screen area is used.')) container.appendChild(E.table(style='margin: 1ex 1rem', id=TEXT_AREA, E.tr( E.td(_('Width:')), E.td(E.input(type='number', name='width', min='0', step='10', max='99999', value=str(sd.get('max_text_width')))), E.td(_('Height:')), E.td(E.input(type='number', name='height', min='0', step='10', max='99999', value=str(sd.get('max_text_height')))), ))) sec(_('Miscellaneous')) container.appendChild(E.div(style='margin: 1ex 2rem; display: flex;', E.label(E.input(type='checkbox', name='cover_preserve_aspect_ratio', checked=sd.get('cover_preserve_aspect_ratio')), _('Preserve cover aspect ratio')))) if not runtime.is_standalone_viewer: name = 'fullscreen_when_opening' val = sd.get(name) if 'auto always never'.split(' ').indexOf(val or '') < 0: val = session_defaults().fullscreen_when_opening container.appendChild(E.div( E.div(style='margin: 1ex 2rem', id=FS_MODE, _('When opening a book enter fullscreen:'), ' ', E.label(E.input(type='radio', name=name, value='auto', checked=val is 'auto'), _('Auto')), '\xa0', E.label(E.input(type='radio', name=name, value='always', checked=val is 'always'), _('Always')), '\xa0', E.label(E.input(type='radio', name=name, value='never', checked=val is 'never'), _('Never')), ) )) container.appendChild(E.div(style='margin: 1rem', create_button_box(restore_defaults, apply_func, cancel_func))) develop = create_layout_panel def commit_layout(onchange, container): was_changed = False sd = get_session_data() for which in 'top bottom left right'.split(' '): i = element(MARGINS, '[name={}]'.format(which)) try: val = int(i.value) except: continue if val is not sd.get('margin_' + which): was_changed = True sd.set('margin_' + which, val) rm = sd.get('read_mode') rm = 'flow' if rm is 'flow' else 'paged' crm = 'paged' if element(READ_MODE, 'input').checked else 'flow' if rm is not crm: was_changed = True sd.set('read_mode', crm) if not runtime.is_standalone_viewer: fs = sd.get('fullscreen_when_opening') cfs = document.querySelector(f'#{FS_MODE} input[name="fullscreen_when_opening"]:checked').value if cfs is not fs: was_changed = True sd.set('fullscreen_when_opening', cfs) cps = sd.get('columns_per_screen') cps = {'portrait': cps.portrait, 'landscape': cps.landscape} for which in ('portrait', 'landscape'): inp = element(COLS, 'input[name={}]'.format(which)) try: val = int(inp.value) except: continue if cps[which] is not val: cps[which] = val sd.set('columns_per_screen', cps) was_changed = True for which in ('width', 'height'): try: val = int(element(TEXT_AREA, 'input[name={}]'.format(which)).value) except: continue if val is not sd.get('max_text_' + which): was_changed = True sd.set('max_text_' + which, val) cover_preserve_aspect_ratio = element(CONTAINER, 'input[name=cover_preserve_aspect_ratio]').checked if cover_preserve_aspect_ratio is not sd.get('cover_preserve_aspect_ratio'): was_changed = True sd.set('cover_preserve_aspect_ratio', cover_preserve_aspect_ratio) if was_changed: onchange()
8,191
Python
.py
153
46.281046
160
0.643258
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,558
fonts.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/fonts.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.globals import get_session_data from dom import unique_id from read_book.globals import runtime from read_book.prefs.utils import create_button_box CONTAINER = unique_id('standalone-font-settings') DEFAULT_STANDARD_FONT = 'serif' DEFAULT_MINIMUM_FONT_SIZE = 8 DEFAULT_ZOOM_STEP_SIZE = 20 def current_zoom_step_size(): s = get_session_data().get('standalone_font_settings') return s.zoom_step_size or DEFAULT_ZOOM_STEP_SIZE def font_select(name, settings): ans = E.select(name=name) ans.appendChild(E.option(_('— Choose a font —'), value='')) current_val = settings[name] if not current_val: ans.lastChild.setAttribute('selected', 'selected') for family in runtime.all_font_families: if family: ans.appendChild(E.option(family)) if family is current_val: ans.lastChild.setAttribute('selected', 'selected') return ans def standard_font(settings): ans = E.select(name='standard_font') ans.appendChild(E.option(_('Serif'), value='serif')) ans.appendChild(E.option(_('Sans-serif'), value='sans')) ans.appendChild(E.option(_('Monospace'), value='mono')) sf = settings.standard_font or DEFAULT_STANDARD_FONT ans.querySelector(f'[value={sf}]').setAttribute('selected', 'selected') return ans def minimum_font_size(settings): ans = E.input(max='100', min='0', step='1', type='number', name='minimum_font_size') if jstype(settings.minimum_font_size) is 'number': ans.value = settings.minimum_font_size + '' else: ans.value = '' + DEFAULT_MINIMUM_FONT_SIZE return ans def zoom_step_size(settings): ans = E.input(max='100', min='1', step='1', type='number', name='zoom_step_size') if jstype(settings.zoom_step_size) is 'number': ans.value = settings.zoom_step_size + '' else: ans.value = '' + DEFAULT_ZOOM_STEP_SIZE return ans def restore_defaults(): container = get_container() for q in ('serif_family', 'sans_family', 'mono_family'): container.querySelector(f'[name={q}]').value = '' container.querySelector('[name=zoom_step_size]').value = DEFAULT_ZOOM_STEP_SIZE + '' container.querySelector('[name=minimum_font_size]').value = DEFAULT_MINIMUM_FONT_SIZE + '' container.querySelector('[name=standard_font]').value = DEFAULT_STANDARD_FONT def get_container(): return document.getElementById(CONTAINER) def create_fonts_panel(container, apply_func, cancel_func): container.appendChild(E.div(id=CONTAINER, style='margin: 1rem')) container = container.lastChild container.append(E.div(_('Choose fonts to use for un-styled text:'), style='margin-top: 1rem')) sd = get_session_data() settings = sd.get('standalone_font_settings') def row(label, widget): return E.tr(E.td(label + ':\xa0', style='padding-top: 1ex'), E.td(widget, style='padding-top: 1ex')) container.append(E.table(style='margin-top: 1rem', row(_('Serif family'), font_select('serif_family', settings)), row(_('Sans-serif family'), font_select('sans_family', settings)), row(_('Monospace family'), font_select('mono_family', settings)), row(_('Standard font'), standard_font(settings)), )) container.append(E.div(_('Zoom related settings'), style='margin-top: 1rem; padding-top: 1rem; width: 100%; border-top: solid 1px')) container.append(E.table( row(_('Zoom step size (%)'), zoom_step_size(settings)), row(_('Minimum font size (px)'), minimum_font_size(settings)), )) container.appendChild(create_button_box(restore_defaults, apply_func, cancel_func)) develop = create_fonts_panel def commit_fonts(onchange): sd = get_session_data() container = get_container() vals = {} zss = parseInt(container.querySelector('[name=zoom_step_size]').value) if zss is not DEFAULT_ZOOM_STEP_SIZE: vals.zoom_step_size = zss mfs = parseInt(container.querySelector('[name=minimum_font_size]').value) if mfs is not DEFAULT_MINIMUM_FONT_SIZE: vals.minimum_font_size = mfs sf = container.querySelector('[name=standard_font]').value if sf is not DEFAULT_STANDARD_FONT: vals.standard_font = sf for q in ('serif_family', 'sans_family', 'mono_family'): val = container.querySelector(f'[name={q}]').value if val: vals[q] = val sd.set('standalone_font_settings', vals)
4,660
Python
.py
98
42.030612
136
0.682851
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,559
scrolling.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/scrolling.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.globals import get_session_data from dom import unique_id from read_book.prefs.utils import create_button_box from session import session_defaults CONTAINER = unique_id('standalone-scrolling-settings') # Scroll speeds in lines/sec MIN_SCROLL_SPEED_AUTO = 0.05 MAX_SCROLL_SPEED_AUTO = 5 MIN_SCROLL_AUTO_DELAY = -1 MAX_SCROLL_AUTO_DELAY = 50 MIN_SCROLL_SPEED_SMOOTH = 5 MAX_SCROLL_SPEED_SMOOTH = 80 def restore_defaults(): container = get_container() for control in container.querySelectorAll('input[name]'): val = session_defaults()[control.getAttribute('name')] if control.type is 'checkbox': control.checked = val else: control.valueAsNumber = val def get_container(): return document.getElementById(CONTAINER) def change_scroll_speed(amt): sd = get_session_data() lps = sd.get('lines_per_sec_auto') nlps = max(MIN_SCROLL_SPEED_AUTO, min(lps + amt, MAX_SCROLL_SPEED_AUTO)) if nlps != lps: sd.set('lines_per_sec_auto', nlps) return nlps def create_scrolling_panel(container, apply_func, cancel_func): container.appendChild(E.div(id=CONTAINER, style='margin: 1rem')) container = container.lastChild sd = get_session_data() def cb(name, text, title): ans = E.input(type='checkbox', name=name, style='margin-left: 0') if sd.get(name): ans.checked = True return E.div(style='margin-top:1ex', E.label(ans, text, title=title or '')) def spinner(name, text, **kwargs): ans = E.input(type='number', name=name, id=name) for key, val in Object.entries(kwargs): ans[key] = val ans.valueAsNumber = sd.get(name, session_defaults()[name]) return E.label("for"=name, text), ans container.appendChild(E.div(style='margin-top:1ex', _('Control how scrolling works in paged mode'))) container.appendChild(E.div(style='margin-left: 1rem')) container.lastChild.appendChild(cb( 'paged_wheel_scrolls_by_screen', _('Mouse wheel scrolls by screen fulls instead of pages'))) container.lastChild.appendChild(cb( 'paged_wheel_section_jumps', _('Horizontal mouse wheel jumps to next/previous section'))) container.lastChild.appendChild(cb( 'paged_margin_clicks_scroll_by_screen', _('Clicking on the margins scrolls by screen fulls instead of pages'))) container.lastChild.appendChild( E.div(style='display:grid;margin-top:1ex;align-items:center;grid-template-columns:auto min-content;grid-gap:1ex; max-width: 30em', *spinner( 'paged_pixel_scroll_threshold', '\xa0' + _('Pixel scroll threshold:'), title=_('When using a touchpad or mouse wheel that produces scroll events in pixels, set the number of pixels before a page turn is triggered'), step=5, min=0, max=1000 ), )) container.appendChild(E.hr()) container.appendChild(E.div(style='margin-top:1ex', _('Control how smooth scrolling works in flow mode'))) container.appendChild(E.div(style='margin-left: 1rem')) container.lastChild.appendChild(cb( 'scroll_stop_boundaries', _('Stop at internal file boundaries when smooth scrolling by holding down the scroll key') )) container.lastChild.appendChild( E.div(style='display:grid;margin-top:1ex;align-items:center;grid-template-columns:auto min-content;grid-gap:1ex; max-width: 30em', *spinner( 'lines_per_sec_smooth', _('Smooth scrolling speed in lines/sec:'), step=5, min=MIN_SCROLL_SPEED_SMOOTH, max=MAX_SCROLL_SPEED_SMOOTH ), *spinner( 'lines_per_sec_auto', _('Auto scrolling speed in lines/sec:'), step=0.05, min=MIN_SCROLL_SPEED_AUTO, max=MAX_SCROLL_SPEED_AUTO ), *spinner( 'scroll_auto_boundary_delay', _('Seconds to pause before auto-scrolling past internal file boundaries:'), title=_('Use negative values to not auto-scroll past internal file boundaries'), step=0.25, min=MIN_SCROLL_AUTO_DELAY, max=MAX_SCROLL_AUTO_DELAY ) ) ) container.appendChild(E.hr()) container.appendChild(E.div(style='margin-top:1ex', _('Miscellaneous'))) container.appendChild(E.div(style='margin-left: 1rem')) container.lastChild.appendChild(cb('book_scrollbar', _('Show a scrollbar'))) container.lastChild.appendChild(cb( 'reverse_page_turn_zones', _('Invert the page turn tap areas'), _('Have tapping on the left side turn the page forward and the right side backwards') )) container.appendChild(create_button_box(restore_defaults, apply_func, cancel_func)) develop = create_scrolling_panel def commit_scrolling(onchange): sd = get_session_data() container = get_container() changed = False for control in container.querySelectorAll('input[name]'): name = control.getAttribute('name') val = control.checked if control.type is 'checkbox' else control.valueAsNumber if val is not sd.get(name) and control.validity.valid: sd.set(name, val) changed = True if changed: onchange()
5,658
Python
.py
123
37.691057
160
0.654028
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,560
colors.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/colors.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.globals import get_session_data from book_list.theme import cached_color_to_rgba from dom import ( add_extra_css, build_rule, clear, set_css, set_radio_group_value, svgicon, unique_id ) from modals import error_dialog from read_book.globals import default_color_schemes, ui_operations from read_book.prefs.utils import create_button_box from session import session_defaults from widgets import create_button CONTAINER = unique_id('reader-color-scheme') COLOR_LIST = unique_id() ACTION_BUTTONS = unique_id() EDIT_SCHEME = unique_id() MARGINS = ('left', 'right', 'top', 'bottom') add_extra_css(def(): sel = '#' + COLOR_LIST style = build_rule(sel, list_style_type='none', display='flex', flex_wrap='wrap') sel += ' > li' style += build_rule(sel, padding='1ex 1rem', margin='1ex 0.5rem', border_radius='4px', cursor='pointer', border='solid 1px currentColor') style += build_rule(sel + ' svg', visibility='hidden') sel += '.current-color' style += build_rule(sel + ' svg', visibility='visible') style += build_rule('#{} #{} td'.format(CONTAINER, EDIT_SCHEME), padding='1ex 1em') sel = '#' + ACTION_BUTTONS style += sel + '{margin-top:2ex; padding-top:1ex; border-top: solid 1px currentColor; margin-bottom: 2ex; padding-bottom: 1ex; border-bottom: solid 1px currentColor}' style += build_rule(sel + ' > span ', margin='1ex 0.5rem', display='inline-block') return style ) def get_container(): return document.getElementById(CONTAINER) def resolve_color_scheme(current_color_scheme): sd = get_session_data() cs = current_color_scheme or sd.get('current_color_scheme') or session_defaults().current_color_scheme ucs = sd.get('user_color_schemes') if default_color_schemes[cs]: ans = default_color_schemes[cs] elif ucs[cs] and ucs[cs].foreground and ucs[cs].background: ans = ucs[cs] else: for sn in default_color_schemes: ans = default_color_schemes[sn] break rgba = cached_color_to_rgba(ans.background) ans.is_dark_theme = max(rgba[0], rgba[1], rgba[2]) < 115 return ans def change_current_color(ev): ul = ev.currentTarget.parentNode for li in ul.childNodes: li.setAttribute('class', 'current-color' if li is ev.currentTarget else '') set_action_button_visibility(ul.parentNode) def new_color_scheme(ev): container = document.getElementById(EDIT_SCHEME) container.style.display = 'block' for inp in container.querySelectorAll('input'): if inp.name.endswith('_color_type'): inp.checked = inp.value is 'default' elif inp.name.startswith('margin_'): pass else: inp.value = {'name':'', 'bg':'#ffffff', 'fg':'#000000', 'link': '#0000ee'}[inp.name] container.querySelector('input').focus() return container def edit_color_scheme(ev): container = new_color_scheme(ev) ccs = current_color_scheme(container) all_schemes = all_color_schemes() if all_schemes[ccs]: scheme = all_schemes[ccs] container = document.getElementById(EDIT_SCHEME) container.querySelector('input').value = scheme.name container.querySelector('input[name=bg]').value = scheme.background container.querySelector('input[name=fg]').value = scheme.foreground set_radio_group_value(container, 'link_color_type', 'custom' if scheme.link else 'default') if scheme.link: container.querySelector('input[name=link]').value = scheme.link for which in MARGINS: attr = f'margin_{which}' val = scheme[attr] set_radio_group_value(container, f'{attr}_color_type', 'custom' if val else 'default') if val: bg, fg = val.split(':') container.querySelector(f'input[name={attr}_bg]').value = bg container.querySelector(f'input[name={attr}_fg]').value = fg def remove_color_scheme(ev): ccs = current_color_scheme() if default_color_schemes[ccs]: return error_dialog(_('Cannot remove'), _('Cannot remove a builtin color scheme')) sd = get_session_data() ucs = sd.get('user_color_schemes') v'delete ucs[ccs]' sd.set('user_color_schemes', ucs) create_color_buttons() set_current_color_scheme() def current_color_scheme(): try: return get_container().querySelector('li.current-color').getAttribute('data-name') except Exception: return session_defaults().current_color_scheme def set_current_color_scheme(value): ul = document.getElementById(COLOR_LIST) done = False for li in ul.childNodes: li.classList.remove('current-color') if li.getAttribute('data-name') is value: li.classList.add('current-color') done = True if not done: for li in ul.childNodes: li.classList.add('current-color') break set_action_button_visibility() def add_color_scheme(ev): colors = {} def check_color(col): colors[col] = div.querySelector(f'input[name={col}]').value if not /^#[0-9A-F]{6}$/i.test(colors[col]): error_dialog(_('Invalid color'), _( 'The color {} is not a valid color').format(colors[col])) return False return True div = document.getElementById(EDIT_SCHEME) if this is not 'cancel': name = div.querySelector('input[name=name]').value if not name: error_dialog(_('Name not specified'), _( 'You must specify a name for the color scheme')) return for col in ('bg', 'fg', 'link'): if not check_color(col): return for margin in MARGINS: for which in ('fg', 'bg'): if not check_color(f'margin_{margin}_{which}'): return key = '*' + name sd = get_session_data() ucs = Object.assign({}, sd.get('user_color_schemes')) ucs[key] = {'name':name, 'foreground':colors.fg, 'background':colors.bg} if div.querySelector('input[name=link_color_type]:checked').value is 'custom': ucs[key].link = colors.link for margin in MARGINS: if div.querySelector(f'input[name=margin_{margin}_color_type]:checked').value is 'custom': ucs[key][f'margin_{margin}'] = colors[f'margin_{margin}_bg'] + ':' + colors[f'margin_{margin}_fg'] sd.set('user_color_schemes', ucs) create_color_buttons() set_current_color_scheme(key) div.style.display = 'none' def all_color_schemes(): all_schemes = {} for k in default_color_schemes: all_schemes[k] = default_color_schemes[k] sd = get_session_data() ucs = sd.get('user_color_schemes') for k in ucs: all_schemes[k] = ucs[k] return all_schemes def create_color_buttons(): ul = document.getElementById(COLOR_LIST) sd = get_session_data() clear(ul) all_schemes = all_color_schemes() ccs = sd.get('current_color_scheme') if not all_schemes[ccs]: ccs = session_defaults().current_color_scheme for name in sorted(all_schemes, key=def(k):return all_schemes[k].name.toLowerCase();): scheme = all_schemes[name] is_current = name is ccs item = set_css(E.li(svgicon('check'), '\xa0' + scheme.name, data_name=name, onclick=change_current_color, class_='current-color' if is_current else ''), color=scheme.foreground, background_color=scheme.background) ul.appendChild(item) def set_action_button_visibility(): container = get_container() ccs = current_color_scheme(container) is_custom = ccs.startswith('*') is_first = True for button in container.querySelectorAll('#' + ACTION_BUTTONS + ' > span'): if is_first: is_first = False else: button.style.display = 'inline-block' if is_custom else 'none' def create_colors_panel(container, apply_func, cancel_func): container.appendChild(E.div(id=CONTAINER)) container = container.lastChild sd = get_session_data() cs = resolve_color_scheme() container.dataset.bg = cs.background container.dataset.fg = cs.foreground container.dataset.link = cs.link or '' container.appendChild(E.p(_('Choose a color scheme below'), style='margin:1ex 1em; padding: 1ex 0')) ul = E.ul(id=COLOR_LIST) container.appendChild(ul) container.appendChild(E.div( E.span(_('Override all book colors:') + '\xa0'), E.label(E.input(type='radio', name='override_book_colors', value='never'), _('Never')), ' ', E.label(E.input(type='radio', name='override_book_colors', value='dark'), _('In dark mode')), ' ', E.label(E.input(type='radio', name='override_book_colors', value='always'), _('Always')), style='margin:1ex 1em; padding: 1ex 0; white-space: pre-wrap' )) try: container.lastChild.querySelector(f'[name=override_book_colors][value={sd.get("override_book_colors")}]').checked = True except: container.lastChild.querySelector('[name=override_book_colors][value=never]').checked = True create_color_buttons() container.appendChild(E.div( E.span(create_button(_('New scheme'), 'plus', new_color_scheme)), E.span(create_button(_('Edit scheme'), 'pencil', edit_color_scheme)), E.span(create_button(_('Remove scheme'), 'trash', remove_color_scheme)), id=ACTION_BUTTONS, )) def margin_row(title, which): return E.tr( E.td(title), E.td( E.label(E.input(type='radio', name=f'margin_{which}_color_type', value='default'), _('Default')), '\xa0\xa0', E.label(E.input(type='radio', name=f'margin_{which}_color_type', value='custom'), _('Custom')), '\xa0\xa0', E.label(E.input(name=f'margin_{which}_bg', type='color', value='#ffffff', onclick=def (ev): set_radio_group_value(ev.currentTarget.closest('td'), f'margin_{which}_color_type', 'custom') ), '\xa0' + _('Background')), '\xa0\xa0', E.label(E.input(name=f'margin_{which}_fg', type='color', value='#000000', onclick=def (ev): set_radio_group_value(ev.currentTarget.closest('td'), f'margin_{which}_color_type', 'custom') ), '\xa0' + _('Foreground')), ) ) container.appendChild(E.div(id=EDIT_SCHEME, style='display:none', E.table( E.tr(E.td(_('Name:')), E.td(E.input(name='name'))), E.tr(E.td(_('Background:')), E.td(E.input(name='bg', type='color', value='#ffffff'))), E.tr(E.td(_('Foreground:')), E.td(E.input(name='fg', type='color', value='#000000'))), E.tr(E.td(_('Link:')), E.td( E.label(E.input(type='radio', name='link_color_type', value='default'), _('Default')), '\xa0\xa0', E.label(E.input(type='radio', name='link_color_type', value='custom'), _('Custom')), '\xa0', E.input(name='link', type='color', value='#000000', onclick=def (ev): set_radio_group_value(ev.currentTarget.closest('td'), 'link_color_type', 'custom') ) )), margin_row(_('Top margin:'), 'top'), margin_row(_('Bottom margin:'), 'bottom'), margin_row(_('Left margin:'), 'left'), margin_row(_('Right margin:'), 'right'), ), E.div(style="display:flex; justify-content: flex-end; margin: 1ex 1em", create_button(_('Apply'), 'check', add_color_scheme), E.span('\xa0'), create_button(_('Discard'), 'close', add_color_scheme.bind('cancel')) ))) set_action_button_visibility() container.appendChild(E.div(style='margin: 1rem', create_button_box(None, apply_func, cancel_func))) develop = create_colors_panel def commit_colors(onchange): ccs = current_color_scheme() rcs = resolve_color_scheme(ccs) c = get_container() sd = get_session_data() prev_obc = sd.get('override_book_colors') cur_obc = c.querySelector('[name=override_book_colors]:checked').value sd.set('current_color_scheme', ccs) if cur_obc is not prev_obc: sd.set('override_book_colors', cur_obc) if rcs.foreground is not c.dataset.fg or rcs.background is not c.dataset.bg or c.dataset.link is not rcs.link or cur_obc is not prev_obc: ui_operations.update_color_scheme() onchange()
12,838
Python
.py
273
38.992674
170
0.623683
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,561
touch.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/touch.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.globals import get_session_data from dom import unique_id from gettext import gettext as _ from read_book.gestures import ( allowed_actions_for_flow_mode_drag, allowed_actions_for_flow_mode_flick, allowed_actions_for_paged_mode_swipe, allowed_actions_for_tap, allowed_actions_for_two_fingers, current_action_for_gesture_type, get_action_descriptions ) from read_book.prefs.utils import create_button_box from read_book.touch import GESTURE, GESTURE_NAMES CONTAINER = unique_id('touch-settings') def restore_defaults(): apply_settings_to_ui({}) def get_container(): return document.getElementById(CONTAINER) def apply_settings_to_ui(overrides): overrides = overrides or {} for group in get_container().querySelectorAll('[data-group]'): group_name = group.dataset.group in_flow_mode = group_name.indexOf('flow') >= 0 for select in group.querySelectorAll('select'): allowed_actions = v'[]' for option in select.querySelectorAll('option'): allowed_actions.push(option.value) gesture_type = select.name current_action = current_action_for_gesture_type(overrides, gesture_type, in_flow_mode) if allowed_actions.indexOf(current_action) < 0: current_action = current_action_for_gesture_type({}, gesture_type, in_flow_mode) if not current_action or allowed_actions.indexOf(current_action) < 0: current_action = 'none' select.value = current_action select.dispatchEvent(new Event('change', {'view': window,'bubbles': True})) def get_overrides_from_ui(): ans = {} for group in get_container().querySelectorAll('[data-group]'): group_name = group.dataset.group in_flow_mode = group_name.indexOf('flow') >= 0 if group_name is 'paged_swipe': attr = 'paged_mode' elif group_name is 'flow_swipe': attr = 'flow_mode' else: attr = 'common' if not ans[attr]: ans[attr] = {} for select in group.querySelectorAll('select'): val = select.value defval = current_action_for_gesture_type({}, select.name, in_flow_mode) if val is not defval: ans[attr][select.name] = val for which in Object.keys(ans): if Object.keys(ans[which]).length is 0: v'delete ans[which]' return ans def create_touch_panel(container, apply_func, cancel_func): container.appendChild(E.div(id=CONTAINER, style='margin: 1rem')) container = container.lastChild sd = get_session_data() overrides = sd.get('gesture_overrides') action_descriptions = get_action_descriptions() in_flow_mode = False def on_select_change(ev): select = ev.target ad = action_descriptions[select.value] span = select.parentNode.querySelector('span') span.textContent = ad.long def make_setting(gesture_type, allowed_actions): ans = E.div(style='margin-top: 1ex') title = GESTURE_NAMES()[gesture_type] sid = unique_id(gesture_type) ans.appendChild(E.h4(E.label(title, 'for'=sid))) select = E.select(name=gesture_type, id=sid) for action in allowed_actions: ad = action_descriptions[action] select.appendChild(E.option(ad.short, value=action)) select.addEventListener('change', on_select_change) ans.appendChild(E.div(select, '\xa0', E.span(style='font-size: smaller; font-style: italic'))) on_select_change({'target': select}) return ans container.appendChild(E.h2(_('Tapping'))) container.appendChild(E.div(_( 'There are three tap zones, depending on where on the screen you tap. When the tap is' ' on a link, the link is followed, otherwise a configurable action based on the zone is performed.'))) c = E.div('data-group'='tap') container.appendChild(c) aat = allowed_actions_for_tap() c.appendChild(make_setting(GESTURE.control_zone_tap, aat)) c.appendChild(make_setting(GESTURE.forward_zone_tap, aat)) c.appendChild(make_setting(GESTURE.back_zone_tap, aat)) c.appendChild(make_setting(GESTURE.long_tap, aat)) container.appendChild(E.hr()) container.appendChild(E.h2(_('Two finger gestures'))) c = E.div('data-group'='two_finger') container.appendChild(c) aat = allowed_actions_for_two_fingers() c.appendChild(make_setting(GESTURE.two_finger_tap, aat)) c.appendChild(make_setting(GESTURE.pinch_in, aat)) c.appendChild(make_setting(GESTURE.pinch_out, aat)) container.appendChild(E.hr()) container.appendChild(E.h2(_('Swiping'))) container.appendChild(E.div(_( 'Swiping works differently in paged and flow mode, with different actions. For an English like language, swiping in' ' the writing direction means swiping horizontally. For languages written vertically, it means swiping vertically.' ' For languages written left-to-right "going forward" means swiping right-to-left, like turning a page with your finger.' ))) container.appendChild(E.h3(_('Swiping in paged mode'), style='padding-top: 1ex')) c = E.div('data-group'='paged_swipe') container.appendChild(c) aap = allowed_actions_for_paged_mode_swipe() c.appendChild(make_setting(GESTURE.flick_block_forward, aap)) c.appendChild(make_setting(GESTURE.flick_block_backward, aap)) c.appendChild(make_setting(GESTURE.flick_inline_forward, aap)) c.appendChild(make_setting(GESTURE.flick_inline_backward, aap)) c.appendChild(make_setting(GESTURE.swipe_inline_forward_hold, aap)) c.appendChild(make_setting(GESTURE.swipe_inline_backward_hold, aap)) c.appendChild(make_setting(GESTURE.swipe_block_forward_hold, aap)) c.appendChild(make_setting(GESTURE.swipe_block_backward_hold, aap)) container.appendChild(E.hr()) container.appendChild(E.h3(_('Swiping in flow mode'), style='padding-top: 1ex')) c = E.div('data-group'='flow_swipe') container.appendChild(c) in_flow_mode = True in_flow_mode aaf = allowed_actions_for_flow_mode_flick() c.appendChild(make_setting(GESTURE.flick_block_forward, aaf)) c.appendChild(make_setting(GESTURE.flick_block_backward, aaf)) c.appendChild(make_setting(GESTURE.flick_inline_forward, aaf)) c.appendChild(make_setting(GESTURE.flick_inline_backward, aaf)) aaf = allowed_actions_for_flow_mode_drag() c.appendChild(make_setting(GESTURE.swipe_inline_backward_in_progress, aaf)) c.appendChild(make_setting(GESTURE.swipe_inline_forward_in_progress, aaf)) c.appendChild(make_setting(GESTURE.swipe_block_backward_in_progress, aaf)) c.appendChild(make_setting(GESTURE.swipe_block_forward_in_progress, aaf)) container.appendChild(E.hr()) container.appendChild(create_button_box(restore_defaults, apply_func, cancel_func)) apply_settings_to_ui(overrides) develop = create_touch_panel def commit_touch(onchange): sd = get_session_data() current_overrides = sd.get('gesture_overrides') overrides = get_overrides_from_ui() changed = overrides != current_overrides if changed: sd.set('gesture_overrides', overrides) onchange()
7,469
Python
.py
150
43.026667
129
0.694574
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,562
utils.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/utils.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from widgets import create_button def create_button_box(restore_defaults_func, apply_func, cancel_func): cbutton = create_button(_('Cancel'), action=cancel_func) if restore_defaults_func: rbutton = create_button(_('Restore defaults'), action=restore_defaults_func) else: rbutton = E.div('\xa0') obutton = create_button(_('OK'), action=apply_func) for b in (rbutton, obutton, cbutton): b.style.marginTop = '1ex' return E.div( style='margin-top: 1rem; display: flex; justify-content: space-between; align-items: flex-start', rbutton, E.div(obutton, E.div('\xa0'), cbutton, style='margin-left: 1rem; display: flex; align-items: flex-start; flex-wrap: wrap'), )
948
Python
.py
20
42.4
131
0.698052
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,563
head_foot.pyj
kovidgoyal_calibre/src/pyj/read_book/prefs/head_foot.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from gettext import ngettext from book_list.globals import get_session_data from dom import clear, unique_id from read_book.prefs.utils import create_button_box from session import get_interface_data, session_defaults from utils import fmt_sidx CONTAINER = unique_id('reader-hf-prefs') def create_item(region, label, style): def sep(): return E.option('\xa0', disabled=True) def opt(label, name, selected): return E.option(label, id=name, value=name, selected=bool(selected)) return E.tr( style = style or '', E.td(label + ':', style='padding: 1ex 1rem'), E.td(E.select( data_region=region, opt(_('Empty'), 'empty', True), sep(), opt(_('Book title'), 'title'), opt(_('Authors'), 'authors'), opt(_('Series'), 'series'), sep(), opt(_('Top level section'), 'top-section'), opt(_('Current section'), 'section'), opt(_('View mode'), 'view-mode'), opt(_('View mode as icon'), 'view-mode-icon'), sep(), opt(_('Clock'), 'clock'), opt(_('Controls button on hover'), 'menu-icon-on-hover'), sep(), opt(_('Progress'), 'progress'), opt(_('Time to read book'), 'time-book'), opt(_('Time to read chapter'), 'time-chapter'), opt(_('Time to read chapter and book'), 'time-chapter-book'), opt(_('Position in book'), 'pos-book'), opt(_('Position in chapter'), 'pos-chapter'), opt(_('Pages in chapter'), 'pages-progress'), opt(_('Pages from paper edition'), 'page-list'), )) ) def create_items(which): if which is 'header' or which is 'footer': ans = E.table( data_which=which, create_item('left', _('Left')), create_item('middle', _('Middle')), create_item('right', _('Right')) ) elif which is 'controls_footer': ans = E.table( data_which=which, create_item('left', _('Left'), 'display: none'), create_item('middle', _('Middle')), create_item('right', _('Right')) ) else: ans = E.table( data_which=which, create_item('left', _('Top')), create_item('middle', _('Middle')), create_item('right', _('Bottom')) ) return ans def apply_setting(table, val): for region in 'left middle right'.split(' '): sel = table.querySelector(f'select[data-region={region}]') for opt in sel.selectedOptions: opt.selected = False x = val[region] or 'empty' opt = sel.namedItem(x) if opt: opt.selected = True else: sel.selectedIndex = 0 def get_setting(table): ans = {} for region in 'left middle right'.split(' '): sel = table.querySelector(f'select[data-region={region}]') if sel.selectedIndex > -1: ans[region] = sel.options[sel.selectedIndex].value return ans def groups(): return {'header': _('Header'), 'footer': _('Footer'), 'left-margin': _('Left margin'), 'right-margin': _('Right margin'), 'controls_footer': _('Controls footer'), } def restore_defaults(): container = document.getElementById(CONTAINER) for which in Object.keys(groups()): table = container.querySelector(f'table[data-which={which}]') apply_setting(table, session_defaults()[which] or {}) def create_head_foot_panel(container, apply_func, cancel_func): gr = groups() container.appendChild(E.div(id=CONTAINER)) container = container.lastChild for key in gr: s = 'margin: 1rem;' if container.childNodes.length > 0: s += 'margin-top: 0;' container.appendChild(E.h4(gr[key], style=s)) container.appendChild(create_items(key)) container.appendChild(E.hr()) container.removeChild(container.lastChild) sd = get_session_data() for which in Object.keys(gr): table = container.querySelector(f'table[data-which={which}]') apply_setting(table, sd.get(which) or {}) container.appendChild(E.div(style='margin: 1rem', create_button_box(restore_defaults, apply_func, cancel_func))) def commit_head_foot(onchange, container): sd = get_session_data() changed = False for which in Object.keys(groups()): prev = sd.get(which) or {} table = container.querySelector(f'table[data-which={which}]') current = get_setting(table) for region in 'left middle right'.split(' '): if prev[region] is not current[region]: changed = True sd.set(which, get_setting(table)) if changed: onchange() if window?.Intl?.DateTimeFormat: time_formatter = window.Intl.DateTimeFormat(undefined, {'hour':'numeric', 'minute':'numeric'}) else: time_formatter = {'format': def(date): return '{}:{}'.format(date.getHours(), date.getMinutes()) } def set_time_formatter(func): nonlocal time_formatter time_formatter = {'format': func} def format_time_left(seconds): hours, minutes = divmod(int(seconds / 60), 60) if hours <= 0: if minutes < 1: return _('almost done') minutes = minutes return ngettext('{} min', '{} mins', minutes).format(minutes) if not minutes: return ngettext('{} hour', '{} hours', hours).format(hours) return _('{} h {} mins').format(hours, minutes) def format_pos(progress_frac, length): if length < 1: return '' pages = Math.ceil(length / 1000) pos = progress_frac * pages return f'{pos:.1f} / {pages}' 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): template = get_session_data().get(which) or {} field = template[region] or 'empty' interface_data = get_interface_data() text = '' has_clock = False div.style.textOverflow = 'ellipsis' div.style.overflow = 'hidden' force_display_even_if_overflowed = False if override: text = override elif field is 'menu-icon-on-hover': clear(div) div.appendChild(E.div(class_='visible-on-hover', E.span(_('Show controls')), title=_('Show viewer controls'), style='cursor: pointer')) return has_clock elif field is 'progress': percent = min(100, max(Math.round(pos.progress_frac * 100), 0)) text = percent + '%' force_display_even_if_overflowed = True elif field is 'title': text = metadata.title or _('Untitled') elif field is 'authors': text = ' & '.join(metadata.authors or v'[]') elif field is 'series': if metadata.series: ival = fmt_sidx(metadata.series_index, use_roman=interface_data.use_roman_numerals_for_series_number) text = _('{0} of {1}').format(ival, metadata.series) elif field is 'clock': force_display_even_if_overflowed = True text = time_formatter.format(Date()) has_clock = True elif field is 'section': text = current_toc_node.title if current_toc_node else '' elif field is 'top-section': text = current_toc_toplevel_node.title if current_toc_toplevel_node else '' if not text: text = current_toc_node.title if current_toc_node else '' elif field is 'view-mode': text = _('Paged') if view_mode is 'paged' else _('Flow') elif field is 'view-mode-icon': text = '📄' if view_mode is 'paged' else '📜' elif field.startswith('time-'): if book_time is None or chapter_time is None: text = _('Calculating...') else: if field is 'time-book': text = format_time_left(book_time) elif field is 'time-chapter': text = format_time_left(chapter_time) else: text = '{} ({})'.format(format_time_left(chapter_time), format_time_left(book_time)) elif field.startswith('pos-'): if field is 'pos-book': text = format_pos(pos.progress_frac, pos.book_length) else: text = format_pos(pos.file_progress_frac, pos.chapter_length) elif field is 'pages-progress': if pos.page_counts: text = f'{pos.page_counts.current + 1} / {pos.page_counts.total}' else: text = _('Unknown') elif field is 'page-list': if page_list and page_list.length > 0: if page_list.length is 1: text = page_list[0].pagenum else: text = f'{page_list[0].pagenum} - {page_list[-1].pagenum}' if not text: text = '\xa0' if text is not div.textContent: div.textContent = text if force_display_even_if_overflowed: div.style.textOverflow = 'clip' div.style.overflow = 'visible' return has_clock
9,264
Python
.py
227
32.577093
158
0.59669
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,564
rpdb.py
kovidgoyal_calibre/src/calibre/rpdb.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import atexit import inspect import os import pdb import select import socket import sys import time from contextlib import suppress from calibre.constants import cache_dir PROMPT = '(debug) ' QUESTION = '\x00\x01\x02' class RemotePdb(pdb.Pdb): def __init__(self, addr="127.0.0.1", port=4444, skip=None): # Open a reusable socket to allow for reloads self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.sock.bind((addr, port)) self.sock.listen(1) with suppress(OSError): print("pdb is running on %s:%d" % (addr, port), file=sys.stderr) clientsocket, address = self.sock.accept() clientsocket.setblocking(True) self.clientsocket = clientsocket self.handle = clientsocket.makefile('rw') pdb.Pdb.__init__(self, completekey='tab', stdin=self.handle, stdout=self.handle, skip=skip) self.prompt = PROMPT def prints(self, *args, **kwargs): kwargs['file'] = self.handle kwargs['flush'] = True print(*args, **kwargs) def ask_question(self, query): self.handle.write(QUESTION) self.prints(query, end='') self.handle.write(PROMPT) self.handle.flush() return self.handle.readline() def end_session(self, *args): self.clear_all_breaks() self.reset() self.handle.close() self.clientsocket.shutdown(socket.SHUT_RDWR) self.clientsocket.close() try: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() except OSError: pass return pdb.Pdb.do_continue(self, None) def do_clear(self, arg): if not arg: ans = self.ask_question("Clear all breaks? [y/n]: ") if ans.strip().lower() in {'y', 'yes'}: self.clear_all_breaks() self.prints('All breaks cleared') return return pdb.Pdb.do_clear(self, arg) do_cl = do_clear def do_continue(self, arg): if not self.breaks: ans = self.ask_question( 'There are no breakpoints set. Continuing will terminate this debug session. Are you sure? [y/n]: ') if ans.strip().lower() in {'y', 'yes'}: return self.end_session() return return pdb.Pdb.do_continue(self, arg) do_c = do_cont = do_continue do_EOF = do_quit = do_exit = do_q = end_session def set_trace(port=4444, skip=None): frame = inspect.currentframe().f_back try: debugger = RemotePdb(port=port, skip=skip) debugger.set_trace(frame) except KeyboardInterrupt: print('Debugging aborted by keyboard interrupt') except Exception: print('Failed to run debugger') import traceback traceback.print_exc() def cli(port=4444): print('Connecting to remote debugger on port %d...' % port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(20): try: sock.connect(('127.0.0.1', port)) break except OSError: pass time.sleep(0.1) else: try: sock.connect(('127.0.0.1', port)) except OSError as err: print('Failed to connect to remote debugger:', err, file=sys.stderr) raise SystemExit(1) print('Connected to remote process', flush=True) try: import readline except ImportError: pass else: histfile = os.path.join(cache_dir(), 'rpdb.history') try: readline.read_history_file(histfile) except OSError: pass atexit.register(readline.write_history_file, histfile) p = pdb.Pdb() readline.set_completer(p.complete) readline.parse_and_bind("tab: complete") sock.setblocking(True) with suppress(KeyboardInterrupt): end_of_input = PROMPT.encode('utf-8') while True: recvd = b'' while select.select([sock], [], [], 0)[0] or not recvd.endswith(end_of_input): buf = sock.recv(4096) if not buf: return recvd += buf recvd = recvd.decode('utf-8', 'replace') recvd = recvd[:-len(PROMPT)] raw = '' if recvd.startswith(QUESTION): recvd = recvd[len(QUESTION):] print(recvd, end='', flush=True) raw = sys.stdin.readline() or 'n' else: print(recvd, end='', flush=True) try: raw = input(PROMPT) except (EOFError, KeyboardInterrupt): pass else: raw += '\n' if not raw: raw = 'quit\n' if raw: sock.sendall(raw.encode('utf-8')) if __name__ == '__main__': cli()
5,121
Python
.py
144
26.104167
116
0.573764
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,565
linux.py
kovidgoyal_calibre/src/calibre/linux.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net> ''' Post installation script for linux ''' import errno import os import stat import sys import textwrap from functools import partial from subprocess import check_call, check_output from calibre import CurrentDir, __appname__, guess_type, prints from calibre.constants import isbsd, islinux from calibre.customize.ui import all_input_formats from calibre.ptempfile import TemporaryDirectory from calibre.utils.localization import _ from calibre.utils.resources import get_image_path as I from calibre.utils.resources import get_path as P from polyglot.builtins import iteritems entry_points = { 'console_scripts': [ 'ebook-device = calibre.devices.cli:main', 'ebook-meta = calibre.ebooks.metadata.cli:main', 'ebook-convert = calibre.ebooks.conversion.cli:main', 'ebook-polish = calibre.ebooks.oeb.polish.main:main', 'markdown-calibre = markdown.__main__:run', 'web2disk = calibre.web.fetch.simple:main', 'calibre-server = calibre.srv.standalone:main', 'lrf2lrs = calibre.ebooks.lrf.lrfparser:main', 'lrs2lrf = calibre.ebooks.lrf.lrs.convert_from:main', 'calibre-debug = calibre.debug:main', 'calibredb = calibre.db.cli.main:main', 'calibre-parallel = calibre.utils.ipc.worker:main', 'calibre-customize = calibre.customize.ui:main', 'calibre-complete = calibre.utils.complete:main', 'fetch-ebook-metadata = calibre.ebooks.metadata.sources.cli:main', 'calibre-smtp = calibre.utils.smtp:main', ], 'gui_scripts' : [ __appname__+' = calibre.gui_launch:calibre', 'lrfviewer = calibre.gui2.lrf_renderer.main:main', 'ebook-viewer = calibre.gui_launch:ebook_viewer', 'ebook-edit = calibre.gui_launch:ebook_edit', ], } def polyglot_write(stream): stream_write = stream.write def write(x): if not isinstance(x, bytes): x = x.encode('utf-8') return stream_write(x) return write class PreserveMIMEDefaults: # {{{ def __init__(self): self.initial_values = {} def __enter__(self): def_data_dirs = '/usr/local/share:/usr/share' paths = os.environ.get('XDG_DATA_DIRS', def_data_dirs) paths = paths.split(':') paths.append(os.environ.get('XDG_DATA_HOME', os.path.expanduser( '~/.local/share'))) paths = list(filter(os.path.isdir, paths)) if not paths: # Env var had garbage in it, ignore it paths = def_data_dirs.split(':') paths = list(filter(os.path.isdir, paths)) self.paths = {os.path.join(x, 'applications/defaults.list') for x in paths} self.initial_values = {} for x in self.paths: try: with open(x, 'rb') as f: self.initial_values[x] = f.read() except: self.initial_values[x] = None def __exit__(self, *args): for path, val in iteritems(self.initial_values): if val is None: try: os.remove(path) except: pass elif os.path.exists(path): try: with open(path, 'r+b') as f: if f.read() != val: f.seek(0) f.truncate() f.write(val) except OSError as e: if e.errno != errno.EACCES: raise # }}} # Uninstall script {{{ UNINSTALL = '''\ #!/bin/sh # Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net> search_for_python() {{ # We have to search for python as Ubuntu, in its infinite wisdom decided # to release 18.04 with no python symlink, making it impossible to run polyglot # python scripts. # We cannot use command -v as it is not implemented in the posh shell shipped with # Ubuntu/Debian. Similarly, there is no guarantee that which is installed. # Shell scripting is a horrible joke, thank heavens for python. local IFS=: if [ $ZSH_VERSION ]; then # zsh does not split by default setopt sh_word_split fi local candidate_path local candidate_python local pythons=python3:python2 # disable pathname expansion (globbing) set -f for candidate_path in $PATH do if [ ! -z $candidate_path ] then for candidate_python in $pythons do if [ ! -z "$candidate_path" ] then if [ -x "$candidate_path/$candidate_python" ] then printf "$candidate_path/$candidate_python" return fi fi done fi done set +f printf "python" }} PYTHON=$(search_for_python) echo Using python executable: $PYTHON $PYTHON -c "import sys; exec(sys.stdin.read());" "$0" <<'CALIBRE_LINUX_INSTALLER_HEREDOC' #!{python} # vim:fileencoding=UTF-8 from __future__ import print_function, unicode_literals euid = {euid} import os, subprocess, shutil, tempfile, sys try: raw_input except NameError: raw_input = input sys.stdin = open('/dev/tty') if os.geteuid() != euid: print('The installer was last run as user id:', euid, 'To remove all files you must run the uninstaller as the same user') if raw_input('Proceed anyway? [y/n]:').lower() != 'y': raise SystemExit(1) frozen_path = {frozen_path!r} if not frozen_path or not os.path.exists(os.path.join(frozen_path, 'resources', 'calibre-mimetypes.xml')): frozen_path = None dummy_mime_path = tempfile.mkdtemp(prefix='mime-hack.') for f in {mime_resources!r}: # dummyfile f = os.path.basename(f) file = os.path.join(dummy_mime_path, f) open(file, 'w').close() cmd = ['xdg-mime', 'uninstall', file] print('Removing mime resource:', f) ret = subprocess.call(cmd, shell=False) if ret != 0: print('WARNING: Failed to remove mime resource', f) for x in tuple({manifest!r}) + tuple({appdata_resources!r}) + (sys.argv[-1], frozen_path, dummy_mime_path): if not x or not os.path.exists(x): continue print('Removing', x) try: if os.path.isdir(x): shutil.rmtree(x) else: os.unlink(x) except Exception as e: print('Failed to delete', x) print('\t', e) icr = {icon_resources!r} mimetype_icons = [] def remove_icon(context, name, size, update=False): cmd = ['xdg-icon-resource', 'uninstall', '--context', context, '--size', size, name] if not update: cmd.insert(2, '--noupdate') print('Removing icon:', name, 'from context:', context, 'at size:', size) ret = subprocess.call(cmd, shell=False) if ret != 0: print('WARNING: Failed to remove icon', name) for i, (context, name, size) in enumerate(icr): if context == 'mimetypes': mimetype_icons.append((name, size)) continue remove_icon(context, name, size, update=i == len(icr) - 1) mr = {menu_resources!r} for f in mr: cmd = ['xdg-desktop-menu', 'uninstall', f] print('Removing desktop file:', f) ret = subprocess.call(cmd, shell=False) if ret != 0: print('WARNING: Failed to remove menu item', f) print() if mimetype_icons and raw_input('Remove the e-book format icons? [y/n]:').lower() in ['', 'y']: for i, (name, size) in enumerate(mimetype_icons): remove_icon('mimetypes', name, size, update=i == len(mimetype_icons) - 1) CALIBRE_LINUX_INSTALLER_HEREDOC ''' # }}} # Completion {{{ class ZshCompleter: # {{{ def __init__(self, opts): self.opts = opts self.dest = None base = os.path.dirname(self.opts.staging_sharedir) self.detect_zsh(base) if not self.dest and base == '/usr/share': # Ubuntu puts site-functions in /usr/local/share self.detect_zsh('/usr/local/share') self.commands = {} def detect_zsh(self, base): for x in ('vendor-completions', 'vendor-functions', 'site-functions'): c = os.path.join(base, 'zsh', x) if os.path.isdir(c) and os.access(c, os.W_OK): self.dest = os.path.join(c, '_calibre') break def get_options(self, parser, cover_opts=('--cover',), opf_opts=('--opf',), file_map={}): if hasattr(parser, 'option_list'): options = parser.option_list for group in parser.option_groups: options += group.option_list else: options = parser for opt in options: lo, so = opt._long_opts, opt._short_opts if opt.takes_value(): lo = [x+'=' for x in lo] so = [x+'+' for x in so] ostrings = lo + so ostrings = '{%s}'%','.join(ostrings) if len(ostrings) > 1 else ostrings[0] exclude = '' if opt.dest is None: exclude = "'(- *)'" h = opt.help or '' h = h.replace('"', "'").replace('[', '(').replace( ']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'") h = h.replace('%default', str(opt.default)) arg = '' if opt.takes_value(): arg = ':"%s":'%h if opt.dest in {'extract_to', 'debug_pipeline', 'to_dir', 'outbox', 'with_library', 'library_path'}: arg += "'_path_files -/'" elif opt.choices: arg += "(%s)"%'|'.join(opt.choices) elif set(file_map).intersection(set(opt._long_opts)): k = tuple(set(file_map).intersection(set(opt._long_opts))) exts = file_map[k[0]] if exts: exts = ('*.%s'%x for x in sorted(exts + [x.upper() for x in exts])) arg += "'_files -g \"%s\"'" % ' '.join(exts) else: arg += "_files" elif (opt.dest in {'pidfile', 'attachment'}): arg += "_files" elif set(opf_opts).intersection(set(opt._long_opts)): arg += "'_files -g \"*.opf\"'" elif set(cover_opts).intersection(set(opt._long_opts)): exts = ('*.%s'%x for x in sorted(pics + [x.upper() for x in pics])) arg += "'_files -g \"%s\"'" % ' '.join(exts) help_txt = '"[%s]"'%h yield '%s%s%s%s '%(exclude, ostrings, help_txt, arg) def opts_and_exts(self, name, op, exts, cover_opts=('--cover',), opf_opts=('--opf',), file_map={}): if not self.dest: return exts = sorted({x.lower() for x in exts}) extra = ('''"*:filename:_files -g '(#i)*.(%s)'" ''' % '|'.join(exts),) opts = '\\\n '.join(tuple(self.get_options( op(), cover_opts=cover_opts, opf_opts=opf_opts, file_map=file_map)) + extra) txt = '_arguments -s \\\n ' + opts self.commands[name] = txt def opts_and_words(self, name, op, words, takes_files=False): if not self.dest: return extra = ("'*:filename:_files' ",) if takes_files else () opts = '\\\n '.join(tuple(self.get_options(op())) + extra) txt = '_arguments -s \\\n ' + opts self.commands[name] = txt def do_ebook_convert(self, f): from calibre.customize.ui import available_output_formats from calibre.ebooks.conversion.cli import create_option_parser, group_titles from calibre.ebooks.conversion.plumber import supported_input_formats from calibre.utils.logging import DevNull from calibre.web.feeds.recipes.collection import get_builtin_recipe_titles input_fmts = sorted(set(supported_input_formats())) output_fmts = sorted(set(available_output_formats())) iexts = sorted({x.upper() for x in input_fmts}.union(input_fmts)) oexts = sorted({x.upper() for x in output_fmts}.union(output_fmts)) w = polyglot_write(f) # Arg 1 w('\n_ebc_input_args() {') w('\n local extras; extras=(') w('\n {-h,--help}":Show Help"') w('\n "--version:Show program version"') w('\n "--list-recipes:List builtin recipe names"') for recipe in sorted(set(get_builtin_recipe_titles())): recipe = recipe.replace(':', '\\:').replace('"', '\\"') w('\n "%s.recipe"'%(recipe)) w('\n ); _describe -t recipes "ebook-convert builtin recipes" extras') w('\n _files -g "%s"'%' '.join('*.%s'%x for x in iexts)) w('\n}\n') # Arg 2 w('\n_ebc_output_args() {') w('\n local extras; extras=(') for x in output_fmts: w('\n ".{0}:Convert to a .{0} file with the same name as the input file"'.format(x)) w('\n ); _describe -t output "ebook-convert output" extras') w('\n _files -g "%s"'%' '.join('*.%s'%x for x in oexts)) w('\n _path_files -/') w('\n}\n') log = DevNull() def get_parser(input_fmt='epub', output_fmt=None): of = ('dummy2.'+output_fmt) if output_fmt else 'dummy' return create_option_parser(('ec', 'dummy1.'+input_fmt, of, '-h'), log)[0] # Common options input_group, output_group = group_titles() p = get_parser() opts = p.option_list for group in p.option_groups: if group.title not in {input_group, output_group}: opts += group.option_list opts.append(p.get_option('--pretty-print')) opts.append(p.get_option('--input-encoding')) opts = '\\\n '.join(tuple( self.get_options(opts, file_map={'--search-replace':()}))) w('\n_ebc_common_opts() {') w('\n _arguments -s \\\n ' + opts) w('\n}\n') # Input/Output format options for fmts, group_title, func in ( (input_fmts, input_group, '_ebc_input_opts_%s'), (output_fmts, output_group, '_ebc_output_opts_%s'), ): for fmt in fmts: is_input = group_title == input_group if is_input and fmt in {'rar', 'zip', 'oebzip'}: continue p = (get_parser(input_fmt=fmt) if is_input else get_parser(output_fmt=fmt)) opts = None for group in p.option_groups: if group.title == group_title: opts = [o for o in group.option_list if '--pretty-print' not in o._long_opts and '--input-encoding' not in o._long_opts] if not opts: continue opts = '\\\n '.join(tuple(sorted(self.get_options(opts)))) w('\n%s() {'%(func%fmt)) w('\n _arguments -s \\\n ' + opts) w('\n}\n') w('\n_ebook_convert() {') w('\n local iarg oarg context state_descr state line\n typeset -A opt_args\n local ret=1') w("\n _arguments '1: :_ebc_input_args' '*::ebook-convert output:->args' && ret=0") w("\n case $state in \n (args)") w('\n iarg=${line[1]##*.}; ') w("\n _arguments '1: :_ebc_output_args' '*::ebook-convert options:->args' && ret=0") w("\n case $state in \n (args)") w('\n oarg=${line[1]##*.}') w('\n iarg="_ebc_input_opts_${(L)iarg}"; oarg="_ebc_output_opts_${(L)oarg}"') w('\n _call_function - $iarg; _call_function - $oarg; _ebc_common_opts; ret=0') w('\n ;;\n esac') w("\n ;;\n esac\n return ret") w('\n}\n') def do_ebook_edit(self, f): from calibre.ebooks.oeb.polish.import_book import IMPORTABLE from calibre.ebooks.oeb.polish.main import SUPPORTED from calibre.gui2.tweak_book.main import option_parser tweakable_fmts = sorted(SUPPORTED | IMPORTABLE) parser = option_parser() opt_lines = [] for opt in parser.option_list: lo, so = opt._long_opts, opt._short_opts if opt.takes_value(): lo = [x+'=' for x in lo] so = [x+'+' for x in so] ostrings = lo + so ostrings = '{%s}'%','.join(ostrings) if len(ostrings) > 1 else '"%s"'%ostrings[0] h = opt.help or '' h = h.replace('"', "'").replace('[', '(').replace( ']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'") h = h.replace('%default', str(opt.default)) help_txt = '"[%s]"'%h opt_lines.append(ostrings + help_txt + ' \\') opt_lines = ('\n' + (' ' * 8)).join(opt_lines) polyglot_write(f)(''' _ebook_edit() {{ local curcontext="$curcontext" state line ebookfile expl typeset -A opt_args _arguments -C -s \\ {} "1:ebook file:_files -g '(#i)*.({})'" \\ '*:file in ebook:->files' && return 0 case $state in files) ebookfile=${{~${{(Q)line[1]}}}} if [[ -f "$ebookfile" && "$ebookfile" =~ '\\.[eE][pP][uU][bB]$' ]]; then _zip_cache_name="$ebookfile" _zip_cache_list=( ${{(f)"$(zipinfo -1 $_zip_cache_name 2>/dev/null)"}} ) else return 1 fi _wanted files expl 'file from ebook' \\ _multi_parts / _zip_cache_list && return 0 ;; esac return 1 }} '''.format(opt_lines, '|'.join(tweakable_fmts)) + '\n\n') def do_calibredb(self, f): from calibre.customize.ui import available_catalog_formats from calibre.db.cli.main import COMMANDS, option_parser_for parsers, descs = {}, {} for command in COMMANDS: p = option_parser_for(command)() parsers[command] = p lines = [x.strip().partition('.')[0] for x in p.usage.splitlines() if x.strip() and not x.strip().startswith('%prog')] descs[command] = lines[0] w = polyglot_write(f) w('\n_calibredb_cmds() {\n local commands; commands=(\n') w(' {-h,--help}":Show help"\n') w(' "--version:Show version"\n') for command, desc in iteritems(descs): w(' "%s:%s"\n'%( command, desc.replace(':', '\\:').replace('"', '\''))) w(' )\n _describe -t commands "calibredb command" commands \n}\n') subcommands = [] for command, parser in iteritems(parsers): exts = [] if command == 'catalog': exts = [x.lower() for x in available_catalog_formats()] elif command == 'set_metadata': exts = ['opf'] exts = sorted(set(exts).union(x.upper() for x in exts)) pats = ('*.%s'%x for x in exts) extra = ("'*:filename:_files -g \"%s\"' "%' '.join(pats),) if exts else () if command in {'add', 'add_format'}: extra = ("'*:filename:_files' ",) opts = '\\\n '.join(tuple(self.get_options( parser)) + extra) txt = ' _arguments -s \\\n ' + opts subcommands.append('(%s)'%command) subcommands.append(txt) subcommands.append(';;') w('\n_calibredb() {') w( r''' local state line state_descr context typeset -A opt_args local ret=1 _arguments \ '1: :_calibredb_cmds' \ '*::calibredb subcommand options:->args' \ && ret=0 case $state in (args) case $line[1] in (-h|--help|--version) _message 'no more arguments' && ret=0 ;; %s esac ;; esac return ret '''%'\n '.join(subcommands)) w('\n}\n\n') def write(self): if self.dest: for c in ('calibredb', 'ebook-convert', 'ebook-edit'): self.commands[c] = ' _%s "$@"' % c.replace('-', '_') with open(self.dest, 'wb') as f: w = polyglot_write(f) w('#compdef ' + ' '.join(self.commands)+'\n') self.do_ebook_convert(f) self.do_calibredb(f) self.do_ebook_edit(f) w('case $service in\n') for c, txt in iteritems(self.commands): w('%s)\n%s\n;;\n'%(c, txt)) w('esac\n') # }}} def get_bash_completion_path(root, share, info): if root == '/usr': # Try to get the system bash completion dir since we are installing to # /usr try: path = check_output('pkg-config --variable=completionsdir bash-completion'.split()).decode('utf-8').strip().partition(os.pathsep)[0] except Exception: info('Failed to find directory to install bash completions, using default.') path = '/usr/share/bash-completion/completions' if path and os.path.exists(path) and os.path.isdir(path): return path else: # Use the default bash-completion dir under staging_share return os.path.join(share, 'bash-completion', 'completions') def write_completion(self, bash_comp_dest, zsh): from calibre.customize.ui import available_input_formats from calibre.debug import option_parser as debug_op from calibre.ebooks import BOOK_EXTENSIONS from calibre.ebooks.lrf.lrfparser import option_parser as lrf2lrsop from calibre.ebooks.metadata.cli import filetypes as meta_filetypes from calibre.ebooks.metadata.cli import option_parser as metaop from calibre.ebooks.metadata.sources.cli import option_parser as fem_op from calibre.ebooks.oeb.polish.import_book import IMPORTABLE from calibre.ebooks.oeb.polish.main import SUPPORTED from calibre.ebooks.oeb.polish.main import option_parser as polish_op from calibre.gui2.lrf_renderer.main import option_parser as lrfviewerop from calibre.gui2.main import option_parser as guiop from calibre.gui2.tweak_book.main import option_parser as tweak_op from calibre.gui2.viewer.main import option_parser as viewer_op from calibre.srv.standalone import create_option_parser as serv_op from calibre.utils.smtp import option_parser as smtp_op input_formats = sorted(all_input_formats()) tweak_formats = sorted(x.lower() for x in SUPPORTED|IMPORTABLE) if bash_comp_dest and not os.path.exists(bash_comp_dest): os.makedirs(bash_comp_dest) complete = 'calibre-complete' if getattr(sys, 'frozen_path', None): complete = os.path.join(getattr(sys, 'frozen_path'), complete) def o_and_e(name, *args, **kwargs): bash_compfile = os.path.join(bash_comp_dest, name) with open(bash_compfile, 'wb') as f: f.write(opts_and_exts(name, *args, **kwargs)) self.manifest.append(bash_compfile) zsh.opts_and_exts(name, *args, **kwargs) def o_and_w(name, *args, **kwargs): bash_compfile = os.path.join(bash_comp_dest, name) with open(bash_compfile, 'wb') as f: f.write(opts_and_words(name, *args, **kwargs)) self.manifest.append(bash_compfile) zsh.opts_and_words(name, *args, **kwargs) o_and_e('calibre', guiop, BOOK_EXTENSIONS) o_and_e('lrf2lrs', lrf2lrsop, ['lrf'], file_map={'--output':['lrs']}) o_and_e('ebook-meta', metaop, list(meta_filetypes()), cover_opts=['--cover', '-c'], opf_opts=['--to-opf', '--from-opf']) o_and_e('ebook-polish', polish_op, [x.lower() for x in SUPPORTED], cover_opts=['--cover', '-c'], opf_opts=['--opf', '-o']) o_and_e('lrfviewer', lrfviewerop, ['lrf']) o_and_e('ebook-viewer', viewer_op, input_formats) o_and_e('ebook-edit', tweak_op, tweak_formats) o_and_w('fetch-ebook-metadata', fem_op, []) o_and_w('calibre-smtp', smtp_op, []) o_and_w('calibre-server', serv_op, []) o_and_e('calibre-debug', debug_op, ['py', 'recipe', 'epub', 'mobi', 'azw', 'azw3', 'docx'], file_map={ '--tweak-book':['epub', 'azw3', 'mobi'], '--subset-font':['ttf', 'otf'], '--exec-file':['py', 'recipe'], '--add-simple-plugin':['py'], '--inspect-mobi':['mobi', 'azw', 'azw3'], '--viewer':sorted(available_input_formats()), }) with open(os.path.join(bash_comp_dest, 'ebook-device'), 'wb') as f: f.write(textwrap.dedent('''\ _ebook_device_ls() { local pattern search listing prefix pattern="$1" search="$1" if [[ -n "{$pattern}" ]]; then if [[ "${pattern:(-1)}" == "/" ]]; then pattern="" else pattern="$(basename ${pattern} 2> /dev/null)" search="$(dirname ${search} 2> /dev/null)" fi fi if [[ "x${search}" == "x" || "x${search}" == "x." ]]; then search="/" fi listing="$(ebook-device ls ${search} 2>/dev/null)" prefix="${search}" if [[ "x${prefix:(-1)}" != "x/" ]]; then prefix="${prefix}/" fi echo $(compgen -P "${prefix}" -W "${listing}" "${pattern}") } _ebook_device() { local cur prev cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" COMPREPLY=() case "${prev}" in ls|rm|mkdir|touch|cat ) COMPREPLY=( $(_ebook_device_ls "${cur}") ) return 0 ;; cp ) if [[ ${cur} == dev:* ]]; then COMPREPLY=( $(_ebook_device_ls "${cur:7}") ) return 0 else _filedir return 0 fi ;; dev ) COMPREPLY=( $(compgen -W "cp ls rm mkdir touch cat info books df" "${cur}") ) return 0 ;; * ) if [[ ${cur} == dev:* ]]; then COMPREPLY=( $(_ebook_device_ls "${cur:7}") ) return 0 else if [[ ${prev} == dev:* ]]; then _filedir return 0 else COMPREPLY=( $(compgen -W "dev:" "${cur}") ) return 0 fi return 0 fi ;; esac } complete -o nospace -F _ebook_device ebook-device''').encode('utf-8')) self.manifest.append(os.path.join(bash_comp_dest, 'ebook-device')) with open(os.path.join(bash_comp_dest, 'ebook-convert'), 'wb') as f: f.write(('complete -o nospace -C %s ebook-convert'%complete).encode('utf-8')) self.manifest.append(os.path.join(bash_comp_dest, 'ebook-convert')) zsh.write() # }}} class PostInstall: def task_failed(self, msg): self.warn(msg, 'with error:') import traceback tb = '\n\t'.join(traceback.format_exc().splitlines()) self.info('\t'+tb) print() def warning(self, *args, **kwargs): print('\n'+'_'*20, 'WARNING','_'*20) prints(*args, **kwargs) print('_'*50) print('\n') self.warnings.append((args, kwargs)) sys.stdout.flush() def __init__(self, opts, info=prints, warn=None, manifest=None): self.opts = opts self.info = info self.warn = warn self.warnings = [] if self.warn is None: self.warn = self.warning if not self.opts.staging_bindir: self.opts.staging_bindir = os.path.join(self.opts.staging_root, 'bin') if not self.opts.staging_sharedir: self.opts.staging_sharedir = os.path.join(self.opts.staging_root, 'share', 'calibre') self.opts.staging_etc = '/etc' if self.opts.staging_root == '/usr' else \ os.path.join(self.opts.staging_root, 'etc') prefix = getattr(self.opts, 'prefix', None) if prefix and prefix != self.opts.staging_root: self.opts.staged_install = True os.environ['XDG_DATA_DIRS'] = os.path.join(self.opts.staging_root, 'share') os.environ['XDG_UTILS_INSTALL_MODE'] = 'system' from calibre.utils.serialize import msgpack_loads scripts = msgpack_loads(P('scripts.calibre_msgpack', data=True)) self.manifest = manifest or [] if getattr(sys, 'frozen_path', False): if os.access(self.opts.staging_bindir, os.W_OK): self.info('Creating symlinks...') for exe in scripts: dest = os.path.join(self.opts.staging_bindir, exe) if os.path.lexists(dest): os.unlink(dest) tgt = os.path.join(getattr(sys, 'frozen_path'), exe) self.info('\tSymlinking %s to %s'%(tgt, dest)) os.symlink(tgt, dest) self.manifest.append(dest) else: self.warning(textwrap.fill( 'No permission to write to %s, not creating program launch symlinks,' ' you should ensure that %s is in your PATH or create the symlinks yourself' % ( self.opts.staging_bindir, getattr(sys, 'frozen_path', 'the calibre installation directory')))) self.icon_resources = [] self.menu_resources = [] self.mime_resources = [] self.appdata_resources = [] if islinux or isbsd: self.setup_completion() if islinux or isbsd: self.setup_desktop_integration() if not getattr(self.opts, 'staged_install', False): self.create_uninstaller() from calibre.utils.config import config_dir if os.path.exists(config_dir): os.chdir(config_dir) if islinux or isbsd: for f in os.listdir('.'): if os.stat(f).st_uid == 0: import shutil shutil.rmtree(f) if os.path.isdir(f) else os.unlink(f) if os.stat(config_dir).st_uid == 0: os.rmdir(config_dir) if warn is None and self.warnings: self.info('\n\nThere were %d warnings\n'%len(self.warnings)) for args, kwargs in self.warnings: self.info('*', *args, **kwargs) print() def create_uninstaller(self): base = self.opts.staging_bindir if not os.access(base, os.W_OK) and getattr(sys, 'frozen_path', False): base = sys.frozen_path dest = os.path.join(base, 'calibre-uninstall') self.info('Creating un-installer:', dest) raw = UNINSTALL.format( python='/usr/bin/python', euid=os.geteuid(), manifest=self.manifest, icon_resources=self.icon_resources, mime_resources=self.mime_resources, menu_resources=self.menu_resources, appdata_resources=self.appdata_resources, frozen_path=getattr(sys, 'frozen_path', None)) try: with open(dest, 'wb') as f: f.write(raw.encode('utf-8')) os.chmod(dest, stat.S_IRWXU|stat.S_IRGRP|stat.S_IROTH) if os.geteuid() == 0: os.chown(dest, 0, 0) except: if self.opts.fatal_errors: raise self.task_failed('Creating uninstaller failed') def setup_completion(self): # {{{ try: self.info('Setting up command-line completion...') zsh = ZshCompleter(self.opts) if zsh.dest: self.info('Installing zsh completion to:', zsh.dest) self.manifest.append(zsh.dest) bash_comp_dest = get_bash_completion_path(self.opts.staging_root, os.path.dirname(self.opts.staging_sharedir), self.info) if bash_comp_dest is not None: self.info('Installing bash completion to:', bash_comp_dest+os.sep) write_completion(self, bash_comp_dest, zsh) except TypeError as err: if 'resolve_entities' in str(err): print('You need python-lxml >= 2.0.5 for calibre') sys.exit(1) raise except OSError as e: if e.errno == errno.EACCES: self.warning('Failed to setup completion, permission denied') if self.opts.fatal_errors: raise self.task_failed('Setting up completion failed') except: if self.opts.fatal_errors: raise self.task_failed('Setting up completion failed') # }}} def setup_desktop_integration(self): # {{{ try: self.info('Setting up desktop integration...') self.do_setup_desktop_integration() except Exception: if self.opts.fatal_errors: raise self.task_failed('Setting up desktop integration failed') def do_setup_desktop_integration(self): env = os.environ.copy() cc = check_call if getattr(sys, 'frozen_path', False) and 'LD_LIBRARY_PATH' in env: paths = env.get('LD_LIBRARY_PATH', '').split(os.pathsep) paths = [x for x in paths if x] npaths = [x for x in paths if x != sys.frozen_path+'/lib'] env['LD_LIBRARY_PATH'] = os.pathsep.join(npaths) cc = partial(check_call, env=env) if getattr(self.opts, 'staged_install', False): for d in {'applications', 'desktop-directories', 'icons/hicolor', 'mime/packages'}: os.makedirs(os.path.join(self.opts.staging_root, 'share', d), exist_ok=True) with TemporaryDirectory() as tdir, CurrentDir(tdir): with PreserveMIMEDefaults(): self.install_xdg_junk(cc, env) def install_xdg_junk(self, cc, env): def install_single_icon(iconsrc, basename, size, context, is_last_icon=False): filename = f'{basename}-{size}.png' render_img(iconsrc, filename, width=int(size), height=int(size)) cmd = ['xdg-icon-resource', 'install', '--noupdate', '--context', context, '--size', str(size), filename, basename] if is_last_icon: del cmd[2] cc(cmd) self.icon_resources.append((context, basename, str(size))) def install_icons(iconsrc, basename, context, is_last_icon=False): sizes = (16, 32, 48, 64, 128, 256) for size in sizes: install_single_icon(iconsrc, basename, size, context, is_last_icon and size is sizes[-1]) icons = [x.strip() for x in '''\ mimetypes/lrf.png application-lrf mimetypes mimetypes/lrf.png text-lrs mimetypes mimetypes/mobi.png application-x-mobipocket-ebook mimetypes mimetypes/tpz.png application-x-topaz-ebook mimetypes mimetypes/azw2.png application-x-kindle-application mimetypes mimetypes/azw3.png application-x-mobi8-ebook mimetypes lt.png calibre-gui apps viewer.png calibre-viewer apps tweak.png calibre-ebook-edit apps '''.splitlines() if x.strip()] for line in icons: iconsrc, basename, context = line.split() install_icons(iconsrc, basename, context, is_last_icon=line is icons[-1]) mimetypes = set() for x in all_input_formats(): mt = guess_type('dummy.'+x)[0] if mt and 'chemical' not in mt and 'ctc-posml' not in mt: mimetypes.add(mt) mimetypes.discard('application/octet-stream') mimetypes = sorted(mimetypes) def write_mimetypes(f, extra=''): line = 'MimeType={};'.format(';'.join(mimetypes)) if extra: line += extra + ';' f.write(line.encode('utf-8') + b'\n') from calibre.ebooks.oeb.polish.import_book import IMPORTABLE from calibre.ebooks.oeb.polish.main import SUPPORTED with open('calibre-lrfviewer.desktop', 'wb') as f: f.write(VIEWER.encode('utf-8')) with open('calibre-ebook-viewer.desktop', 'wb') as f: f.write(EVIEWER.encode('utf-8')) write_mimetypes(f) with open('calibre-ebook-edit.desktop', 'wb') as f: f.write(ETWEAK.encode('utf-8')) mt = {guess_type('a.' + x.lower())[0] for x in (SUPPORTED|IMPORTABLE)} - {None, 'application/octet-stream'} mt = sorted(mt) f.write(('MimeType=%s;\n'%';'.join(mt)).encode('utf-8')) with open('calibre-gui.desktop', 'wb') as f: f.write(GUI.encode('utf-8')) write_mimetypes(f, 'x-scheme-handler/calibre') des = ('calibre-gui.desktop', 'calibre-lrfviewer.desktop', 'calibre-ebook-viewer.desktop', 'calibre-ebook-edit.desktop') appdata = os.path.join(os.path.dirname(self.opts.staging_sharedir), 'metainfo') translators = None if not os.path.exists(appdata): try: os.mkdir(appdata) except: self.warning('Failed to create %s not installing appdata files' % appdata) if os.path.exists(appdata) and not os.access(appdata, os.W_OK): self.warning('Do not have write permissions for %s not installing appdata files' % appdata) else: from calibre.utils.localization import get_all_translators translators = dict(get_all_translators()) APPDATA = get_appdata() for x in des: cmd = ['xdg-desktop-menu', 'install', '--noupdate', './'+x] cc(' '.join(cmd), shell=True) self.menu_resources.append(x) ak = x.partition('.')[0] if ak in APPDATA and translators is not None and os.access(appdata, os.W_OK): self.appdata_resources.append(write_appdata(ak, APPDATA[ak], appdata, translators)) MIME_BASE = 'calibre-mimetypes.xml' MIME = P(MIME_BASE) self.mime_resources.append(MIME_BASE) if not getattr(self.opts, 'staged_install', False): cc(['xdg-mime', 'install', MIME]) cc(['xdg-desktop-menu', 'forceupdate']) else: from shutil import copyfile copyfile(MIME, os.path.join(env['XDG_DATA_DIRS'], 'mime', 'packages', MIME_BASE)) # }}} def option_parser(): from calibre.utils.config import OptionParser parser = OptionParser() parser.add_option('--make-errors-fatal', action='store_true', default=False, dest='fatal_errors', help='If set die on errors.') parser.add_option('--root', dest='staging_root', default='/usr', help='Prefix under which to install files') parser.add_option('--bindir', default=None, dest='staging_bindir', help='Location where calibre launcher scripts were installed. Typically /usr/bin') parser.add_option('--sharedir', default=None, dest='staging_sharedir', help='Location where calibre resources were installed, typically /usr/share/calibre') return parser def options(option_parser): parser = option_parser() options = parser.option_list for group in parser.option_groups: options += group.option_list opts = [] for opt in options: opts.extend(opt._short_opts) opts.extend(opt._long_opts) return opts def opts_and_words(name, op, words, takes_files=False): opts = '|'.join(options(op)) words = '|'.join([w.replace("'", "\\'") for w in words]) fname = name.replace('-', '_') return ('_'+fname+'()'+ ''' { local cur opts local IFS=$'|\\t' COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" opts="%s" words="%s" case "${cur}" in -* ) COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) COMPREPLY=( $( echo ${COMPREPLY[@]} | sed 's/ /\\\\ /g' | tr '\\n' '\\t' ) ) return 0 ;; * ) COMPREPLY=( $(compgen -W "${words}" -- ${cur}) ) COMPREPLY=( $( echo ${COMPREPLY[@]} | sed 's/ /\\\\ /g' | tr '\\n' '\\t' ) ) return 0 ;; esac } complete -F _'''%(opts, words) + fname + ' ' + name +"\n\n").encode('utf-8') pics = ['bmp', 'gif', 'jpeg', 'jpg', 'png'] # keep sorted alphabetically def opts_and_exts(name, op, exts, cover_opts=('--cover',), opf_opts=(), file_map={}): opts = ' '.join(options(op)) exts.extend([i.upper() for i in exts]) exts='|'.join(sorted(exts)) fname = name.replace('-', '_') spics = pics + [i.upper() for i in pics] spics = '|'.join(sorted(spics)) special_exts_template = '''\ %s ) _filedir %s return 0 ;; ''' extras = [] for eopts, eexts in ((cover_opts, "${pics}"), (opf_opts, "'@(opf)'")): for opt in eopts: extras.append(special_exts_template%(opt, eexts)) extras = '\n'.join(extras) return ('_'+fname+'()'+ ''' { local cur prev opts COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" opts="%(opts)s" pics="@(%(pics)s)" case "${prev}" in %(extras)s esac case "${cur}" in %(extras)s -* ) COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) return 0 ;; * ) _filedir '@(%(exts)s)' return 0 ;; esac } complete -o filenames -F _'''%dict(pics=spics, opts=opts, extras=extras, exts=exts) + fname + ' ' + name +"\n\n").encode('utf-8') VIEWER = '''\ [Desktop Entry] Version=1.0 Type=Application Name=LRF viewer GenericName=Viewer for LRF files Comment=Viewer for LRF files (SONY ebook format files) TryExec=lrfviewer Exec=lrfviewer %f Icon=calibre-viewer MimeType=application/x-sony-bbeb; Categories=Office;Viewer; Keywords=lrf;viewer; ''' EVIEWER = '''\ [Desktop Entry] Version=1.0 Type=Application Name=E-book viewer GenericName=Viewer for E-books Comment=Viewer for E-books in all the major formats TryExec=ebook-viewer Exec=ebook-viewer --detach %f Icon=calibre-viewer Categories=Office;Viewer; Keywords=epub;ebook;viewer; ''' ETWEAK = '''\ [Desktop Entry] Version=1.0 Type=Application Name=E-book editor GenericName=Editor for E-books Comment=Edit E-books in various formats TryExec=ebook-edit Exec=ebook-edit --detach %f Icon=calibre-ebook-edit Categories=Office;WordProcessor Keywords=epub;ebook;editor; ''' GUI = '''\ [Desktop Entry] Version=1.0 Type=Application Name=calibre GenericName=E-book library management Comment=E-book library management: Convert, view, share, catalogue all your e-books TryExec=calibre Exec=calibre --detach %U Icon=calibre-gui Categories=Office; X-GNOME-UsesNotifications=true Keywords=epub;ebook;manager; ''' def get_appdata(): def _(x): return x # Make sure the text below is not translated, but is marked for translation return { 'calibre-gui': { 'name':'calibre', 'summary':_('The one stop solution to all your e-book needs'), 'description':( _('calibre is the one stop solution to all your e-book needs.'), _('You can use calibre to catalog your books, fetch metadata for them automatically, convert them from and to all the various e-book formats, send them to your e-book reader devices, read the books on your computer, edit the books in a dedicated e-book editor and even make them available over the network with the built-in Content server. You can also download news and periodicals in e-book format from over a thousand different news and magazine websites.') # noqa ), 'screenshots':( (1408, 792, 'https://lh4.googleusercontent.com/-bNE1hc_3pIc/UvHLwKPGBPI/AAAAAAAAASA/8oavs_c6xoU/w1408-h792-no/main-default.png',), (1408, 792, 'https://lh4.googleusercontent.com/-Zu2httSKABE/UvHMYK30JJI/AAAAAAAAATg/dQTQUjBvV5s/w1408-h792-no/main-grid.png'), (1408, 792, 'https://lh3.googleusercontent.com/-_trYUjU_BaY/UvHMYSdKhlI/AAAAAAAAATc/auPA3gyXc6o/w1408-h792-no/main-flow.png'), ), 'desktop-id': 'calibre-gui.desktop', 'include-releases': True, }, 'calibre-ebook-edit': { 'name':'calibre - E-book Editor', 'summary':_('Edit the text and styles inside e-books'), 'description':( _('The calibre E-book editor allows you to edit the text and styles inside the book with a live preview of your changes.'), _('It can edit books in both the EPUB and AZW3 (Kindle) formats. It includes various useful tools for checking the book for errors, editing the Table of Contents, performing automated cleanups, etc.'), # noqa ), 'screenshots':( (1408, 792, 'https://lh5.googleusercontent.com/-M2MAVc3A8e4/UvHMWqGRa8I/AAAAAAAAATA/cecQeWUYBVs/w1408-h792-no/edit-default.png',), (1408, 792, 'https://lh4.googleusercontent.com/-WhoMxuRb34c/UvHMWqN8aGI/AAAAAAAAATI/8SDBYWXb7-8/w1408-h792-no/edit-check.png'), (887, 575, 'https://lh6.googleusercontent.com/-KwaOwHabnBs/UvHMWidjyXI/AAAAAAAAAS8/H6xmCeLnSpk/w887-h575-no/edit-toc.png'), ), 'desktop-id': 'calibre-ebook-edit.desktop', }, 'calibre-ebook-viewer': { 'name':'calibre - E-book Viewer', 'summary':_('Read e-books in over a dozen different formats'), 'description': ( _('The calibre E-book viewer allows you to read e-books in over a dozen different formats.'), _('It has a full screen mode for distraction free reading and can display the text with multiple columns per screen.'), ), 'screenshots':( (1408, 792, 'https://lh5.googleusercontent.com/-dzSO82BPpaE/UvHMYY5SpNI/AAAAAAAAATk/I_kF9fYWrZM/w1408-h792-no/viewer-default.png',), (1920, 1080, 'https://lh6.googleusercontent.com/-n32Ae5RytAk/UvHMY0QD94I/AAAAAAAAATs/Zw8Yz08HIKk/w1920-h1080-no/viewer-fs.png'), ), 'desktop-id': 'calibre-ebook-viewer.desktop', }, } def changelog_bullet_to_text(bullet): # It would be great if we could use any fancier formatting here, but the # only allowed inline formatting within the AppData description bullet # points are emphasis (italics) and code (monospaced font) text = [bullet['title']] if 'author' in bullet: text.append(' by ') text.append(bullet['author']) if 'description' in bullet or 'tickets' in bullet: text.append(' (') if 'description' in bullet: text.append(bullet['description']) if 'tickets' in bullet: if 'description' in bullet: text.append(' – ') text.append('Closes tickets: ') text.append(', '.join(map(str, bullet['tickets']))) text.append(')') return ''.join(text) def make_appdata_releases(): import json from lxml.builder import E changelog = json.loads(P('changelog.json', data=True)) releases = E.releases() for revision in changelog: # Formatting of release description tries to resemble that of # https://calibre-ebook.com/whats-new while taking into account the limits imposed by # https://www.freedesktop.org/software/appstream/docs/chap-Metadata.html#tag-description description = E.description() if 'new features' in revision: description.append(E.p('New features:')) description.append(E.ol( *(E.li(changelog_bullet_to_text(bullet)) for bullet in revision['new features']) )) if 'bug fixes' in revision: description.append(E.p('Bug fixes:')) description.append(E.ol( *(E.li(changelog_bullet_to_text(bullet)) for bullet in revision['bug fixes']) )) if 'new recipes' in revision: description.append(E.p('New news sources:')) description.append(E.ol( *(E.li(changelog_bullet_to_text(bullet)) for bullet in revision['new recipes']) )) if 'improved recipes' in revision: description.append(E.p('Improved news sources:')) description.append(E.ol( *(E.li(name) for name in revision['improved recipes']) )) releases.append(E.release( description, version=revision['version'], date=revision['date'] )) return releases def write_appdata(key, entry, base, translators): from lxml.builder import E from lxml.etree import tostring fpath = os.path.join(base, '%s.metainfo.xml' % key) screenshots = E.screenshots() for w, h, url in entry['screenshots']: s = E.screenshot(E.image(url, width=str(w), height=str(h))) screenshots.append(s) screenshots[0].set('type', 'default') description = E.description() for para in entry['description']: description.append(E.p(para)) for lang, t in iteritems(translators): tp = t.gettext(para) if tp != para: description.append(E.p(tp, **{'{http://www.w3.org/XML/1998/namespace}lang': lang})) root = E.component( E.id(key + '.desktop'), E.name(entry['name']), E.metadata_license('CC0-1.0'), E.project_license('GPL-3.0'), E.developer(E.name('Kovid Goyal'), id='kovidgoyal.net'), E.summary(entry['summary']), E.content_rating( # Information Sharing: Using any online API, e.g. a user-counter # Details at https://calibre-ebook.com/dynamic/calibre-usage . E.content_attribute('mild', id='social-info'), # In-App Purchases: Users are encouraged to donate real money, e.g. using Patreon E.content_attribute('mild', id='money-purchasing'), type='oars-1.1' ), description, E.url('https://calibre-ebook.com/', type='homepage'), screenshots, E.launchable(entry['desktop-id'], type='desktop-id'), type='desktop-application' ) for lang, t in iteritems(translators): tp = t.gettext(entry['summary']) if tp != entry['summary']: root.append(E.summary(tp, **{'{http://www.w3.org/XML/1998/namespace}lang': lang})) if entry.get('include-releases', False): try: root.append(make_appdata_releases()) except Exception: import traceback traceback.print_exc() with open(fpath, 'wb') as f: f.write(tostring(root, encoding='utf-8', xml_declaration=True, pretty_print=True)) return fpath def render_img(image, dest, width=128, height=128): from qt.core import QImage, Qt img = QImage(I(image)).scaled(int(width), int(height), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) img.save(dest) def main(): p = option_parser() opts, args = p.parse_args() PostInstall(opts) return 0 def cli_index_strings(): return _('Command Line Interface'), _( 'On macOS, the command line tools are inside the calibre bundle, for example,' ' if you installed calibre in :file:`/Applications` the command line tools' ' are in :file:`/Applications/calibre.app/Contents/MacOS/`. So, for example, to run :file:`ebook-convert`' ' you would use: :file:`/Applications/calibre.app/Contents/MacOS/ebook-convert`.'), _( 'Documented commands'), _('Undocumented commands'), _( 'You can see usage for undocumented commands by executing them without arguments in a terminal.'), _( 'Change language'), _('Search') if __name__ == '__main__': sys.exit(main())
52,404
Python
.py
1,191
34.085642
484
0.568267
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,566
libunzip.py
kovidgoyal_calibre/src/calibre/libunzip.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' import re from calibre.utils import zipfile from calibre.utils.icu import numeric_sort_key def update(pathtozip, patterns, filepaths, names, compression=zipfile.ZIP_DEFLATED, verbose=True): ''' Update files in the zip file at `pathtozip` matching the given `patterns` with the given `filepaths`. If more than one file matches, all of the files are replaced. :param patterns: A list of compiled regular expressions :param filepaths: A list of paths to the replacement files. Must have the same length as `patterns`. :param names: A list of archive names for each file in filepaths. A name can be `None` in which case the name of the existing file in the archive is used. :param compression: The compression to use when replacing files. Can be either `zipfile.ZIP_DEFLATED` or `zipfile.ZIP_STORED`. ''' assert len(patterns) == len(filepaths) == len(names) z = zipfile.ZipFile(pathtozip, mode='a') for name in z.namelist(): for pat, fname, new_name in zip(patterns, filepaths, names): if pat.search(name): if verbose: print(f'Updating {name} with {fname}') if new_name is None: z.replace(fname, arcname=name, compress_type=compression) else: z.delete(name) z.write(fname, new_name, compress_type=compression) break z.close() def extract(filename, dir): """ Extract archive C{filename} into directory C{dir} """ zf = zipfile.ZipFile(filename) zf.extractall(dir) def sort_key(filename): bn, ext = filename.rpartition('.')[::2] if not bn and ext: bn, ext = ext, bn return (numeric_sort_key(bn), numeric_sort_key(ext)) def extract_member(filename, match=re.compile(r'\.(jpg|jpeg|gif|png)\s*$', re.I), sort_alphabetically=False): zf = zipfile.ZipFile(filename) names = list(zf.namelist()) if sort_alphabetically: names.sort(key=sort_key) for name in names: if match.search(name): return name, zf.read(name) comic_exts = {'png', 'jpg', 'jpeg', 'gif', 'webp'} def name_ok(name): return bool(name and not name.startswith('__MACOSX/') and name.rpartition('.')[-1].lower() in comic_exts) def extract_cover_image(filename): with zipfile.ZipFile(filename) as zf: for name in sorted(zf.namelist(), key=sort_key): if name_ok(name): return name, zf.read(name)
2,753
Python
.py
62
36.016129
109
0.62963
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,567
ptempfile.py
kovidgoyal_calibre/src/calibre/ptempfile.py
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' """ Provides platform independent temporary files that persist even after being closed. """ import atexit import os import tempfile from calibre.constants import __appname__, __version__, filesystem_encoding, get_windows_temp_path, ismacos, iswindows def cleanup(path): try: import os as oss if oss.path.exists(path): oss.remove(path) except: pass _base_dir = None def remove_dir(x): try: import shutil shutil.rmtree(x, ignore_errors=True) except: pass def determined_remove_dir(x): for i in range(10): try: import shutil shutil.rmtree(x) return except: import os # noqa if os.path.exists(x): # In case some other program has one of the temp files open. import time time.sleep(0.1) else: return try: import shutil shutil.rmtree(x, ignore_errors=True) except: pass def app_prefix(prefix): if iswindows: return '%s_'%__appname__ return '%s_%s_%s'%(__appname__, __version__, prefix) _osx_cache_dir = None def osx_cache_dir(): global _osx_cache_dir if _osx_cache_dir: return _osx_cache_dir if _osx_cache_dir is None: _osx_cache_dir = False import ctypes libc = ctypes.CDLL(None) buf = ctypes.create_string_buffer(512) l = libc.confstr(65538, ctypes.byref(buf), len(buf)) # _CS_DARWIN_USER_CACHE_DIR = 65538 if 0 < l < len(buf): try: q = buf.value.decode('utf-8').rstrip('\0') except ValueError: pass if q and os.path.isdir(q) and os.access(q, os.R_OK | os.W_OK | os.X_OK): _osx_cache_dir = q return q def base_dir(): global _base_dir if _base_dir is not None and not os.path.exists(_base_dir): # Some people seem to think that running temp file cleaners that # delete the temp dirs of running programs is a good idea! _base_dir = None if _base_dir is None: td = os.environ.get('CALIBRE_WORKER_TEMP_DIR', None) if td is not None: from calibre.utils.serialize import msgpack_loads from polyglot.binary import from_hex_bytes try: td = msgpack_loads(from_hex_bytes(td)) except Exception: td = None if td and os.path.exists(td): _base_dir = td else: base = os.environ.get('CALIBRE_TEMP_DIR', None) if base is not None and iswindows: base = os.getenv('CALIBRE_TEMP_DIR') prefix = app_prefix('tmp_') if base is None: if iswindows: # On windows, if the TMP env var points to a path that # cannot be encoded using the mbcs encoding, then the # python 2 tempfile algorithm for getting the temporary # directory breaks. So we use the win32 api to get a # unicode temp path instead. See # https://bugs.launchpad.net/bugs/937389 base = get_windows_temp_path() elif ismacos: # Use the cache dir rather than the temp dir for temp files as Apple # thinks deleting unused temp files is a good idea. See note under # _CS_DARWIN_USER_TEMP_DIR here # https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/confstr.3.html base = osx_cache_dir() _base_dir = tempfile.mkdtemp(prefix=prefix, dir=base) atexit.register(determined_remove_dir if iswindows else remove_dir, _base_dir) try: tempfile.gettempdir() except Exception: # Widows temp vars set to a path not encodable in mbcs # Use our temp dir tempfile.tempdir = _base_dir return _base_dir def reset_base_dir(): global _base_dir _base_dir = None base_dir() def force_unicode(x): # Cannot use the implementation in calibre.__init__ as it causes a circular # dependency if isinstance(x, bytes): x = x.decode(filesystem_encoding) return x def _make_file(suffix, prefix, base): suffix, prefix = map(force_unicode, (suffix, prefix)) # no2to3 return tempfile.mkstemp(suffix, prefix, dir=base) def _make_dir(suffix, prefix, base): suffix, prefix = map(force_unicode, (suffix, prefix)) # no2to3 return tempfile.mkdtemp(suffix, prefix, base) class PersistentTemporaryFile: """ A file-like object that is a temporary file that is available even after being closed on all platforms. It is automatically deleted on normal program termination. """ _file = None def __init__(self, suffix="", prefix="", dir=None, mode='w+b'): if prefix is None: prefix = "" if dir is None: dir = base_dir() fd, name = _make_file(suffix, prefix, dir) self._file = os.fdopen(fd, mode) self._name = name self._fd = fd atexit.register(cleanup, name) def __getattr__(self, name): if name == 'name': return self.__dict__['_name'] return getattr(self.__dict__['_file'], name) def __enter__(self): return self def __exit__(self, *args): self.close() def __del__(self): try: self.close() except: pass def PersistentTemporaryDirectory(suffix='', prefix='', dir=None): ''' Return the path to a newly created temporary directory that will be automatically deleted on application exit. ''' if dir is None: dir = base_dir() tdir = _make_dir(suffix, prefix, dir) atexit.register(remove_dir, tdir) return tdir class TemporaryDirectory: ''' A temporary directory to be used in a with statement. ''' def __init__(self, suffix='', prefix='', dir=None, keep=False): self.suffix = suffix self.prefix = prefix if dir is None: dir = base_dir() self.dir = dir self.keep = keep def __enter__(self): if not hasattr(self, 'tdir'): self.tdir = _make_dir(self.suffix, self.prefix, self.dir) return self.tdir def __exit__(self, *args): if not self.keep and os.path.exists(self.tdir): remove_dir(self.tdir) class TemporaryFile: def __init__(self, suffix="", prefix="", dir=None, mode='w+b'): if prefix is None: prefix = '' if suffix is None: suffix = '' if dir is None: dir = base_dir() self.prefix, self.suffix, self.dir, self.mode = prefix, suffix, dir, mode self._file = None def __enter__(self): fd, name = _make_file(self.suffix, self.prefix, self.dir) self._file = os.fdopen(fd, self.mode) self._name = name self._file.close() return name def __exit__(self, *args): cleanup(self._name) class SpooledTemporaryFile(tempfile.SpooledTemporaryFile): def __init__(self, max_size=0, suffix="", prefix="", dir=None, mode='w+b', bufsize=-1): if prefix is None: prefix = '' if suffix is None: suffix = '' if dir is None: dir = base_dir() self._name = None tempfile.SpooledTemporaryFile.__init__(self, max_size=max_size, suffix=suffix, prefix=prefix, dir=dir, mode=mode) @property def name(self): return self._name @name.setter def name(self, val): self._name = val # See https://bugs.python.org/issue26175 def readable(self): return self._file.readable() def seekable(self): return self._file.seekable() def writable(self): return self._file.writable() def better_mktemp(*args, **kwargs): fd, path = tempfile.mkstemp(*args, **kwargs) os.close(fd) return path
8,287
Python
.py
232
26.767241
121
0.581436
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,568
live.py
kovidgoyal_calibre/src/calibre/live.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import ast import gzip import os import re import sys import types from contextlib import suppress from datetime import timedelta from enum import Enum, auto from http import HTTPStatus from importlib import import_module from queue import Queue from threading import Lock, Thread import apsw from calibre.constants import cache_dir, numeric_version from calibre.utils.date import utcnow from calibre.utils.https import HTTPError, get_https_resource_securely from calibre.utils.iso8601 import parse_iso8601 download_queue = Queue() default_timeout = object() DEFAULT_TIMEOUT = 5 worker = None worker_lock = Lock() fetcher = None db_path = None old_interval = timedelta(days=1) module_version = 1 minimum_calibre_version = 5, 7, 0 class Strategy(Enum): download_now = auto() download_if_old = auto() fast = auto() def start_worker(): global worker with worker_lock: if worker is None: worker = Thread(name='LiveDownloader', target=download_worker, daemon=True) worker.start() def stop_worker(timeout=2*DEFAULT_TIMEOUT): global worker with worker_lock: if worker is not None: download_queue.put(None) w = worker worker = None w.join(timeout) def async_stop_worker(): t = Thread(name='StopLiveDownloadWorker', target=stop_worker, daemon=True) t.start() return t.join def report_failure(full_name): print(f'Failed to download live module {full_name}', file=sys.stderr) import traceback traceback.print_exc() def download_worker(): while True: x = download_queue.get() if x is None: break try: latest_data_for_module(x) except Exception: report_failure(x) def queue_for_download(full_name): download_queue.put(full_name) def parse_metadata(full_name, raw_bytes): q = raw_bytes[:2048] m = re.search(br'^module_version\s*=\s*(\d+)', q, flags=re.MULTILINE) if m is None: raise ValueError(f'No module_version in downloaded source of {full_name}') module_version = int(m.group(1)) m = re.search(br'^minimum_calibre_version\s*=\s*(.+?)$', q, flags=re.MULTILINE) minimum_calibre_version = 0, 0, 0 if m is not None: minimum_calibre_version = ast.literal_eval(m.group(1).decode('utf-8')) if not isinstance(minimum_calibre_version, tuple) or len(minimum_calibre_version) != 3 or \ not isinstance(minimum_calibre_version[0], int) or not isinstance(minimum_calibre_version[1], int) or\ not isinstance(minimum_calibre_version[2], int): raise ValueError(f'minimum_calibre_version invalid: {minimum_calibre_version!r}') return module_version, minimum_calibre_version def fetch_module(full_name, etag=None, timeout=default_timeout, url=None): if timeout is default_timeout: timeout = DEFAULT_TIMEOUT if url is None: path = '/'.join(full_name.split('.')) + '.py' url = 'https://code.calibre-ebook.com/src/' + path headers = {'accept-encoding': 'gzip'} if etag: headers['if-none-match'] = f'"{etag}"' try: res = get_https_resource_securely(url, headers=headers, get_response=True, timeout=timeout) except HTTPError as e: if e.code == HTTPStatus.NOT_MODIFIED: return None, None raise etag = res.headers['etag'] if etag.startswith('W/'): etag = etag[2:] etag = etag[1:-1] if res.headers['content-encoding'] == 'gzip': data = gzip.GzipFile(fileobj=res).read() else: data = res.read() return etag, data def cache_path(): return db_path or os.path.join(cache_dir(), 'live.sqlite') def db(): ans = apsw.Connection(cache_path()) ans.cursor().execute('pragma busy_timeout=2000') return ans def table_definition(): return ''' CREATE TABLE IF NOT EXISTS modules ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, atime TIMESTAMP DEFAULT CURRENT_TIMESTAMP, full_name TEXT NOT NULL UNIQUE, etag TEXT NOT NULL, module_version INTEGER NOT NULL DEFAULT 1, minimum_calibre_version TEXT NOT NULL DEFAULT "0,0,0", data BLOB NOT NULL ); ''' def write_to_cache(full_name, etag, data): module_version, minimum_calibre_version = parse_metadata(full_name, data) mcv = ','.join(map(str, minimum_calibre_version)) db().cursor().execute( table_definition() + 'INSERT OR REPLACE INTO modules (full_name, etag, data, date, atime, module_version, minimum_calibre_version)' ' VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?)', (full_name, etag, data, module_version, mcv) ) def read_from_cache(full_name): rowid = etag = data = date = None c = db().cursor() with suppress(StopIteration): rowid, etag, data, date = next(c.execute( table_definition() + 'SELECT id, etag, data, date FROM modules WHERE full_name=? LIMIT 1', (full_name,))) if rowid is not None: with suppress(apsw.BusyError): c.execute('UPDATE modules SET atime=CURRENT_TIMESTAMP WHERE id=?', (rowid,)) if date is not None: date = parse_iso8601(date, assume_utc=True) return etag, data, date def clear_cache(): db().cursor().execute(table_definition() + 'DELETE FROM modules') def load_module_from_data(full_name, data): m = import_module(full_name) ans = types.ModuleType(m.__name__) ans.__package__ = m.__package__ ans.__file__ = m.__file__ compiled = compile(data, full_name, 'exec', dont_inherit=True) exec(compiled, ans.__dict__) return ans def latest_data_for_module(full_name, timeout=default_timeout): cached_etag, cached_data = read_from_cache(full_name)[:2] downloaded_etag, downloaded_data = (fetcher or fetch_module)(full_name, etag=cached_etag, timeout=timeout) if downloaded_data is not None: write_to_cache(full_name, downloaded_etag, downloaded_data) cached_etag, cached_data = downloaded_etag, downloaded_data return cached_data def download_module(full_name, timeout=default_timeout, strategy=Strategy.download_now): if strategy is Strategy.download_now: return load_module_from_data(full_name, latest_data_for_module(full_name, timeout=timeout)) cached_etag, cached_data, date = read_from_cache(full_name) if date is None or (utcnow() - date) > old_interval: return load_module_from_data(full_name, latest_data_for_module(full_name, timeout=timeout)) if cached_data is not None: return load_module_from_data(full_name, cached_data) def get_cached_module(full_name): cached_etag, cached_data = read_from_cache(full_name)[:2] if cached_data: return load_module_from_data(full_name, cached_data) def cached_is_suitable(cached, installed): try: v = cached.module_version except Exception: v = -1 try: cv = cached.minimum_calibre_version except Exception: cv = numeric_version return cv <= numeric_version and v > installed.module_version def load_module(full_name, strategy=Strategy.download_now, timeout=default_timeout): ''' Load the specified module from the calibre servers. strategy controls whether to check for the latest version immediately or eventually (strategies other that download_now). Note that you must call start_worker() for eventual checking to work. Remember to call stop_worker() at exit as well. ''' installed = import_module(full_name) try: if strategy is Strategy.fast: cached = get_cached_module(full_name) queue_for_download(full_name) else: cached = download_module(full_name, timeout=timeout, strategy=strategy) if cached_is_suitable(cached, installed): installed = cached except Exception: report_failure(full_name) return installed def find_tests(): import hashlib import tempfile import unittest class LiveTest(unittest.TestCase): ae = unittest.TestCase.assertEqual def setUp(self): global db_path, fetcher fd, db_path = tempfile.mkstemp() os.close(fd) fetcher = self.fetch_module self.fetched_module_version = 99999 self.sentinel_value = 1 self.fetch_counter = 0 self.orig_old_interval = old_interval @property def live_data(self): data = f'module_version = {self.fetched_module_version}\nminimum_calibre_version = (1, 2, 3)\nsentinel = {self.sentinel_value}' return data.encode('ascii') def fetch_module(self, full_name, etag=None, timeout=default_timeout): self.fetch_counter += 1 data = self.live_data q = hashlib.md5(data).hexdigest() if etag and q == etag: return None, None return q, data def tearDown(self): global db_path, fetcher, old_interval os.remove(db_path) db_path = fetcher = None old_interval = self.orig_old_interval def assert_cache_empty(self): self.ae(read_from_cache('live.test'), (None, None, None)) def test_live_cache(self): self.assert_cache_empty() data = self.live_data write_to_cache('live.test', 'etag', data) self.ae(read_from_cache('live.test')[:2], ('etag', data)) def test_module_loading(self): global old_interval self.assert_cache_empty() m = load_module('calibre.live', strategy=Strategy.fast) self.assertEqual(m.module_version, module_version) self.assert_cache_empty() self.ae(self.fetch_counter, 0) start_worker() stop_worker() self.ae(self.fetch_counter, 1) m = load_module('calibre.live', strategy=Strategy.fast) self.assertEqual(m.module_version, self.fetched_module_version) self.ae(self.fetch_counter, 1) m = load_module('calibre.live', strategy=Strategy.download_if_old) self.assertEqual(m.module_version, self.fetched_module_version) self.ae(self.fetch_counter, 1) m = load_module('calibre.live', strategy=Strategy.download_now) self.assertEqual(m.module_version, self.fetched_module_version) self.ae(self.fetch_counter, 2) old_interval = timedelta(days=-1) m = load_module('calibre.live', strategy=Strategy.download_if_old) self.assertEqual(m.module_version, self.fetched_module_version) self.ae(self.fetch_counter, 3) old_interval = self.orig_old_interval clear_cache() m = load_module('calibre.live', strategy=Strategy.download_if_old) self.assertEqual(m.module_version, self.fetched_module_version) self.ae(self.fetch_counter, 4) return unittest.defaultTestLoader.loadTestsFromTestCase(LiveTest) if __name__ == '__main__': from calibre.utils.run_tests import run_cli run_cli(find_tests())
11,427
Python
.py
275
34.043636
139
0.655275
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,569
gui_launch.py
kovidgoyal_calibre/src/calibre/gui_launch.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import sys # For some reason Qt 5 crashes on some linux systems if the fork() is done # after the Qt modules are loaded in calibre.gui2. We also cannot do a fork() # while python is importing a module. So we use this simple launcher module to # launch all the GUI apps, forking before Qt is loaded and not during a # python import. is_detached = False def do_detach(fork=True, setsid=True, redirect=True): global is_detached if fork: # Detach from the controlling process. if os.fork() != 0: raise SystemExit(0) if setsid: os.setsid() if redirect: from calibre_extensions.speedup import detach detach(os.devnull) is_detached = True def setup_qt_logging(): from calibre.constants import DEBUG if not DEBUG: from qt.core import QLoggingCategory QLoggingCategory.setFilterRules('''\ qt.webenginecontext.info=false ''') def detach_gui(): from calibre.constants import DEBUG, isbsd, islinux if (islinux or isbsd) and not DEBUG and '--detach' in sys.argv: do_detach() def register_with_default_programs(): from calibre.constants import iswindows if iswindows: from calibre.gui2 import gprefs from calibre.utils.winreg.default_programs import Register return Register(gprefs) else: class Dummy: def __enter__(self): return self def __exit__(self, *args): pass return Dummy() def calibre(args=sys.argv): from calibre.constants import DEBUG if DEBUG: from calibre.debug import print_basic_debug_info print_basic_debug_info() detach_gui() setup_qt_logging() with register_with_default_programs(): from calibre.gui2.main import main main(args) def is_possible_media_pack_error(e): from ctypes.util import find_library from calibre.constants import iswindows if iswindows and 'QtWebEngine' in str(e): if not find_library('MFTranscode.dll'): return True return False def show_media_pack_error(): import traceback from calibre.gui2 import Application, error_dialog from calibre.utils.localization import _ app = Application([]) error_dialog(None, _('Required component missing'), '<p>' + _( 'This computer is missing the Windows MediaPack, which is needed for calibre. Instructions' ' for installing it are <a href="{0}">available here</a>.').format( 'https://support.medal.tv/support/solutions/articles/48001157311-windows-is-missing-media-pack'), det_msg=traceback.format_exc()).exec() del app def media_pack_error_check(func): def wrapper(*a, **kw): try: return func(*a, **kw) except ImportError as e: if is_possible_media_pack_error(e): show_media_pack_error() else: raise return wrapper @media_pack_error_check def ebook_viewer(args=sys.argv): detach_gui() setup_qt_logging() with register_with_default_programs(): try: from calibre.gui2.viewer.main import main main(args) except ImportError as e: if is_possible_media_pack_error(e): show_media_pack_error() else: raise @media_pack_error_check def store_dialog(args=sys.argv): detach_gui() setup_qt_logging() from calibre.gui2.store.web_store import main main(args) @media_pack_error_check def webengine_dialog(**kw): detach_gui() setup_qt_logging() from calibre.debug import load_user_plugins load_user_plugins() import importlib m = importlib.import_module(kw.pop('module')) getattr(m, kw.pop('entry_func', 'main'))(**kw) @media_pack_error_check def toc_dialog(**kw): detach_gui() setup_qt_logging() from calibre.gui2.toc.main import main main(**kw) @media_pack_error_check def gui_ebook_edit(path=None, notify=None): ' For launching the editor from inside calibre ' from calibre.gui2.tweak_book.main import gui_main setup_qt_logging() gui_main(path, notify) @media_pack_error_check def ebook_edit(args=sys.argv): detach_gui() setup_qt_logging() with register_with_default_programs(): from calibre.gui2.tweak_book.main import main main(args) def option_parser(basename): if basename == 'calibre': from calibre.gui2.main import option_parser elif basename == 'ebook-viewer': from calibre.gui2.viewer.main import option_parser elif basename == 'ebook-edit': from calibre.gui2.tweak_book.main import option_parser return option_parser()
4,855
Python
.py
140
28.242857
109
0.669091
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,570
test_build.py
kovidgoyal_calibre/src/calibre/test_build.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' ''' Test a binary calibre build to ensure that all needed binary images/libraries have loaded. ''' import builtins import ctypes import os import shutil import sys import time import unittest from calibre.constants import islinux, ismacos, iswindows, plugins_loc from calibre.utils.resources import get_image_path as I from calibre.utils.resources import get_path as P from polyglot.builtins import iteritems is_ci = os.environ.get('CI', '').lower() == 'true' is_sanitized = 'libasan' in os.environ.get('LD_PRELOAD', '') def print(*a): builtins.print(*a, flush=True, file=sys.__stdout__) class BuildTest(unittest.TestCase): @unittest.skipUnless(iswindows and not is_ci, 'DLL loading needs testing only on windows (non-continuous integration)') def test_dlls(self): from calibre_extensions import winutil base = winutil.get_dll_directory() for x in os.listdir(base): if x.lower().endswith('.dll'): try: ctypes.WinDLL(os.path.join(base, x)) except Exception as err: self.assertTrue(False, f'Failed to load DLL {x} with error: {err}') def test_pycryptodome(self): from Crypto.Cipher import AES del AES @unittest.skipUnless(islinux, 'DBUS only used on linux') def test_dbus(self): from jeepney.io.blocking import open_dbus_connection if 'DBUS_SESSION_BUS_ADDRESS' in os.environ: bus = open_dbus_connection(bus='SYSTEM', auth_timeout=10.) bus.close() bus = open_dbus_connection(bus='SESSION', auth_timeout=10.) bus.close() del bus def test_loaders(self): import importlib ldr = importlib.import_module('calibre').__spec__.loader.get_resource_reader() self.assertIn('ebooks', ldr.contents()) try: with ldr.open_resource('__init__.py') as f: raw = f.read() except FileNotFoundError: with ldr.open_resource('__init__.pyc') as f: raw = f.read() self.assertGreater(len(raw), 1024) def test_regex(self): import regex self.assertEqual(regex.findall(r'(?i)(a)(b)', 'ab cd AB 1a1b'), [('a', 'b'), ('A', 'B')]) self.assertEqual(regex.escape('a b', literal_spaces=True), 'a b') def test_hunspell(self): from calibre.spell.dictionary import build_test build_test() def test_pychm(self): from chm.chm import CHMFile, chmlib del CHMFile, chmlib def test_chardet(self): from calibre_extensions.uchardet import detect raw = 'mūsi Füße'.encode() enc = detect(raw).lower() self.assertEqual(enc, 'utf-8') # The following is used by html5lib from chardet.universaldetector import UniversalDetector detector = UniversalDetector() self.assertTrue(hasattr(detector, 'done')) detector.feed(raw) detector.close() self.assertEqual(detector.result['encoding'], 'utf-8') def test_lzma(self): import lzma lzma.open def test_zstd(self): from pyzstd import compress, decompress data = os.urandom(4096) cdata = compress(data) self.assertEqual(data, decompress(cdata)) def test_html5lib(self): import html5lib.html5parser # noqa from html5lib import parse # noqa def test_html5_parser(self): from html5_parser import parse parse('<p>xxx') def test_bs4(self): import bs4 import soupsieve del soupsieve, bs4 @unittest.skipUnless(islinux, 'Speech dispatcher only used on Linux') def test_speech_dispatcher(self): from speechd.client import SSIPClient del SSIPClient @unittest.skipIf('SKIP_SPEECH_TESTS' in os.environ, 'Speech support is opted out') def test_piper(self): import subprocess from calibre.constants import piper_cmdline self.assertTrue(piper_cmdline()) raw = subprocess.check_output(piper_cmdline() + ('-h',), stderr=subprocess.STDOUT).decode() self.assertIn('--sentence_silence', raw) def test_zeroconf(self): import ifaddr import zeroconf as z del z del ifaddr def test_plugins(self): exclusions = set() if islinux and not os.path.exists('/dev/bus/usb'): # libusb fails to initialize in containers without USB subsystems exclusions.update(set('libusb libmtp'.split())) from importlib import import_module from importlib.resources import files for name in (path.name for path in files('calibre_extensions').iterdir()): if name in exclusions: if name in ('libusb', 'libmtp'): # Just check that the DLL can be loaded ctypes.CDLL(os.path.join(plugins_loc, name + ('.dylib' if ismacos else '.so'))) continue import_module('calibre_extensions.' + name) def test_lxml(self): from calibre.utils.cleantext import test_clean_xml_chars test_clean_xml_chars() from lxml import etree raw = b'<a/>' root = etree.fromstring(raw, parser=etree.XMLParser(recover=True, no_network=True, resolve_entities=False)) self.assertEqual(etree.tostring(root), raw) from lxml import html html.fromstring("<p>\U0001f63a") def test_certgen(self): from calibre.utils.certgen import create_key_pair create_key_pair() def test_fonttools(self): from fontTools.subset import main main def test_msgpack(self): from calibre.utils.date import utcnow from calibre.utils.serialize import msgpack_dumps, msgpack_loads for obj in ({1:1}, utcnow()): s = msgpack_dumps(obj) self.assertEqual(obj, msgpack_loads(s)) self.assertEqual(type(msgpack_loads(msgpack_dumps(b'b'))), bytes) self.assertEqual(type(msgpack_loads(msgpack_dumps('b'))), str) large = b'x' * (100 * 1024 * 1024) msgpack_loads(msgpack_dumps(large)) @unittest.skipUnless(ismacos, 'FSEvents only present on OS X') def test_fsevents(self): from fsevents import Observer, Stream del Observer, Stream @unittest.skipUnless(iswindows, 'winutil is windows only') def test_winutil(self): import tempfile from calibre import strftime from calibre_extensions import winutil self.assertEqual(winutil.special_folder_path(winutil.CSIDL_APPDATA), winutil.known_folder_path(winutil.FOLDERID_RoamingAppData)) self.assertEqual(winutil.special_folder_path(winutil.CSIDL_LOCAL_APPDATA), winutil.known_folder_path(winutil.FOLDERID_LocalAppData)) self.assertEqual(winutil.special_folder_path(winutil.CSIDL_FONTS), winutil.known_folder_path(winutil.FOLDERID_Fonts)) self.assertEqual(winutil.special_folder_path(winutil.CSIDL_PROFILE), winutil.known_folder_path(winutil.FOLDERID_Profile)) def au(x, name): self.assertTrue( isinstance(x, str), f'{name}() did not return a unicode string, instead returning: {x!r}') for x in 'username temp_path locale_name'.split(): au(getattr(winutil, x)(), x) d = winutil.localeconv() au(d['thousands_sep'], 'localeconv') au(d['decimal_point'], 'localeconv') for k, v in iteritems(d): au(v, k) os.environ['XXXTEST'] = 'YYY' self.assertEqual(os.getenv('XXXTEST'), 'YYY') del os.environ['XXXTEST'] self.assertIsNone(os.getenv('XXXTEST')) for k in os.environ: v = os.getenv(k) if v is not None: au(v, 'getenv-' + k) t = time.localtime() fmt = '%Y%a%b%e%H%M' for fmt in (fmt, fmt.encode('ascii')): x = strftime(fmt, t) au(x, 'strftime') tdir = tempfile.mkdtemp(dir=winutil.temp_path()) path = os.path.join(tdir, 'test-create-file.txt') h = winutil.create_file( path, winutil.GENERIC_READ | winutil.GENERIC_WRITE, 0, winutil.OPEN_ALWAYS, winutil.FILE_ATTRIBUTE_NORMAL) self.assertRaises(OSError, winutil.delete_file, path) del h winutil.delete_file(path) self.assertRaises(OSError, winutil.delete_file, path) self.assertRaises(OSError, winutil.create_file, os.path.join(path, 'cannot'), winutil.GENERIC_READ, 0, winutil.OPEN_ALWAYS, winutil.FILE_ATTRIBUTE_NORMAL) self.assertTrue(winutil.supports_hardlinks(os.path.abspath(os.getcwd())[0] + ':\\')) sz = 23 data = os.urandom(sz) open(path, 'wb').write(data) h = winutil.Handle(0, winutil.ModuleHandle, 'moo') r = repr(h) h2 = winutil.Handle(h.detach(), winutil.ModuleHandle, 'moo') self.assertEqual(r, repr(h2)) h2.close() h = winutil.create_file( path, winutil.GENERIC_READ | winutil.GENERIC_WRITE, 0, winutil.OPEN_ALWAYS, winutil.FILE_ATTRIBUTE_NORMAL) self.assertEqual(winutil.get_file_size(h), sz) self.assertRaises(OSError, winutil.set_file_pointer, h, 23, 23) self.assertEqual(winutil.read_file(h), data) self.assertEqual(winutil.read_file(h), b'') winutil.set_file_pointer(h, 3) self.assertEqual(winutil.read_file(h), data[3:]) self.assertEqual(winutil.nlinks(path), 1) npath = path + '.2' winutil.create_hard_link(npath, path) h.close() self.assertEqual(open(npath, 'rb').read(), data) self.assertEqual(winutil.nlinks(path), 2) winutil.delete_file(path) self.assertEqual(winutil.nlinks(npath), 1) winutil.set_file_attributes(npath, winutil.FILE_ATTRIBUTE_READONLY) self.assertRaises(OSError, winutil.delete_file, npath) winutil.set_file_attributes(npath, winutil.FILE_ATTRIBUTE_NORMAL) winutil.delete_file(npath) self.assertGreater(min(winutil.get_disk_free_space(None)), 0) open(path, 'wb').close() open(npath, 'wb').close() winutil.move_file(path, npath, winutil.MOVEFILE_WRITE_THROUGH | winutil.MOVEFILE_REPLACE_EXISTING) self.assertFalse(os.path.exists(path)) os.remove(npath) dpath = tempfile.mkdtemp(dir=os.path.dirname(path)) dh = winutil.create_file( dpath, winutil.FILE_LIST_DIRECTORY, winutil.FILE_SHARE_READ, winutil.OPEN_EXISTING, winutil.FILE_FLAG_BACKUP_SEMANTICS, ) from threading import Event, Thread started = Event() events = [] def read_changes(): buffer = b'0' * 8192 started.set() events.extend(winutil.read_directory_changes( dh, buffer, True, winutil.FILE_NOTIFY_CHANGE_FILE_NAME | winutil.FILE_NOTIFY_CHANGE_DIR_NAME | winutil.FILE_NOTIFY_CHANGE_ATTRIBUTES | winutil.FILE_NOTIFY_CHANGE_SIZE | winutil.FILE_NOTIFY_CHANGE_LAST_WRITE | winutil.FILE_NOTIFY_CHANGE_SECURITY )) t = Thread(target=read_changes, daemon=True) t.start() started.wait(1) t.join(0.1) testp = os.path.join(dpath, 'test') open(testp, 'w').close() t.join(4) self.assertTrue(events) for actions, path in events: self.assertEqual(os.path.join(dpath, path), testp) dh.close() os.remove(testp) os.rmdir(dpath) del h shutil.rmtree(tdir) m = winutil.create_mutex("test-mutex", False) self.assertRaises(OSError, winutil.create_mutex, 'test-mutex', False) m.close() self.assertEqual(winutil.parse_cmdline('"c:\\test exe.exe" "some arg" 2'), ('c:\\test exe.exe', 'some arg', '2')) def test_ffmpeg(self): from calibre_extensions.ffmpeg import resample_raw_audio_16bit data = os.urandom(22050 * 2) resample_raw_audio_16bit(data, 22050, 44100) def test_sqlite(self): import sqlite3 conn = sqlite3.connect(':memory:') from calibre.library.sqlite import load_c_extensions self.assertTrue(load_c_extensions(conn, True), 'Failed to load sqlite extension') def test_apsw(self): import apsw conn = apsw.Connection(':memory:') conn.close() @unittest.skipIf('SKIP_QT_BUILD_TEST' in os.environ, 'Skipping Qt build test as it causes crashes in the macOS VM') def test_qt(self): if is_sanitized: raise unittest.SkipTest('Skipping Qt build test as sanitizer is enabled') from qt.core import QApplication, QFontDatabase, QImageReader, QLoggingCategory, QNetworkAccessManager, QSslSocket, QTimer QLoggingCategory.setFilterRules('''qt.webenginecontext.debug=true''') if hasattr(os, 'geteuid') and os.geteuid() == 0: # likely a container build, webengine cannot run as root with sandbox os.environ['QTWEBENGINE_CHROMIUM_FLAGS'] = '--no-sandbox' from qt.webengine import QWebEnginePage from calibre.utils.img import image_from_data, image_to_data, test # Ensure that images can be read before QApplication is constructed. # Note that this requires QCoreApplication.libraryPaths() to return the # path to the Qt plugins which it always does in the frozen build, # because Qt is patched to know the layout of the calibre application # package. On non-frozen builds, it should just work because the # hard-coded paths of the Qt installation should work. If they do not, # then it is a distro problem. fmts = set(map(lambda x: x.data().decode('utf-8'), QImageReader.supportedImageFormats())) # no2to3 testf = {'jpg', 'png', 'svg', 'ico', 'gif', 'webp'} self.assertEqual(testf.intersection(fmts), testf, "Qt doesn't seem to be able to load some of its image plugins. Available plugins: %s" % fmts) data = P('images/blank.png', allow_user_override=False, data=True) img = image_from_data(data) image_from_data(P('catalog/mastheadImage.gif', allow_user_override=False, data=True)) for fmt in 'png bmp jpeg'.split(): d = image_to_data(img, fmt=fmt) image_from_data(d) # Run the imaging tests test() from calibre.gui2 import destroy_app, ensure_app from calibre.utils.webengine import setup_profile display_env_var = os.environ.pop('DISPLAY', None) try: ensure_app() self.assertGreaterEqual(len(QFontDatabase.families()), 5, 'The QPA headless plugin is not able to locate enough system fonts via fontconfig') if 'SKIP_SPEECH_TESTS' not in os.environ: from qt.core import QMediaDevices, QTextToSpeech available_tts_engines = tuple(x for x in QTextToSpeech.availableEngines() if x != 'mock') self.assertTrue(available_tts_engines) QMediaDevices.audioOutputs() from calibre.ebooks.oeb.transforms.rasterize import rasterize_svg img = rasterize_svg(as_qimage=True) self.assertFalse(img.isNull()) self.assertGreater(img.width(), 8) from calibre.ebooks.covers import create_cover create_cover('xxx', ['yyy']) na = QNetworkAccessManager() self.assertTrue(hasattr(na, 'sslErrors'), 'Qt not compiled with openssl') self.assertTrue(QSslSocket.availableBackends(), 'Qt tls plugins missings') p = QWebEnginePage() setup_profile(p.profile()) def callback(result): callback.result = result if hasattr(print_callback, 'result'): QApplication.instance().quit() def print_callback(result): print_callback.result = result if hasattr(callback, 'result'): QApplication.instance().quit() def do_webengine_test(title): nonlocal p p.runJavaScript('1 + 1', callback) p.printToPdf(print_callback) def render_process_crashed(status, exit_code): print('Qt WebEngine Render process crashed with status:', status, 'and exit code:', exit_code) QApplication.instance().quit() p.titleChanged.connect(do_webengine_test) p.renderProcessTerminated.connect(render_process_crashed) p.runJavaScript(f'document.title = "test-run-{os.getpid()}";') timeout = 10 QTimer.singleShot(timeout * 1000, lambda: QApplication.instance().quit()) QApplication.instance().exec() self.assertTrue(hasattr(callback, 'result'), f'Qt WebEngine failed to run in {timeout} seconds') self.assertEqual(callback.result, 2, 'Simple JS computation failed') self.assertTrue(hasattr(print_callback, 'result'), f'Qt WebEngine failed to print in {timeout} seconds') self.assertIn(b'%PDF-1.4', bytes(print_callback.result), 'Print to PDF failed') del p del na destroy_app() del QWebEnginePage finally: if display_env_var is not None: os.environ['DISPLAY'] = display_env_var def test_imaging(self): from PIL import Image try: import _imaging import _imagingft import _imagingmath _imaging, _imagingmath, _imagingft except ImportError: from PIL import _imaging, _imagingft, _imagingmath _imaging, _imagingmath, _imagingft from io import StringIO from PIL import features out = StringIO() features.pilinfo(out=out, supported_formats=False) out = out.getvalue() for line in '''\ --- PIL CORE support ok --- FREETYPE2 support ok --- WEBP support ok --- WEBP Transparency support ok --- WEBPMUX support ok --- WEBP Animation support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok '''.splitlines(): self.assertIn(line.strip(), out) with Image.open(I('lt.png', allow_user_override=False)) as i: self.assertGreaterEqual(i.size, (20, 20)) with Image.open(P('catalog/DefaultCover.jpg', allow_user_override=False)) as i: self.assertGreaterEqual(i.size, (20, 20)) @unittest.skipUnless(iswindows and not is_ci, 'File dialog helper only used on windows (non-continuous-integration)') def test_file_dialog_helper(self): from calibre.gui2.win_file_dialogs import test test() def test_unrar(self): from calibre.utils.unrar import test_basic test_basic() def test_7z(self): from calibre.utils.seven_zip import test_basic test_basic() @unittest.skipUnless(iswindows, 'WPD is windows only') def test_wpd(self): from calibre_extensions import wpd try: wpd.init('calibre', 1, 1, 1) except wpd.NoWPD: pass else: wpd.uninit() def test_tinycss_tokenizer(self): from tinycss.tokenizer import c_tokenize_flat self.assertIsNotNone(c_tokenize_flat, 'tinycss C tokenizer not loaded') @unittest.skipUnless(getattr(sys, 'frozen', False), 'Only makes sense to test executables in frozen builds') def test_executables(self): from calibre.ebooks.pdf.pdftohtml import PDFTOHTML, PDFTOTEXT from calibre.utils.ipc.launch import Worker w = Worker({}) self.assertTrue(os.path.exists(w.executable), 'calibre-parallel (%s) does not exist' % w.executable) self.assertTrue(os.path.exists(w.gui_executable), 'calibre-parallel-gui (%s) does not exist' % w.gui_executable) self.assertTrue(os.path.exists(PDFTOHTML), 'pdftohtml (%s) does not exist' % PDFTOHTML) self.assertTrue(os.path.exists(PDFTOTEXT), 'pdftotext (%s) does not exist' % PDFTOTEXT) if iswindows: from calibre.devices.usbms.device import eject_exe self.assertTrue(os.path.exists(eject_exe()), 'calibre-eject.exe (%s) does not exist' % eject_exe()) def test_netifaces(self): import netifaces self.assertGreaterEqual(len(netifaces.interfaces()), 1, 'netifaces could find no network interfaces') def test_psutil(self): import psutil psutil.Process(os.getpid()) def test_podofo(self): from calibre.utils.podofo import test_podofo as dotest dotest() @unittest.skipIf(iswindows, 'readline not available on windows') def test_terminal(self): import readline del readline def test_html2text(self): import html2text del html2text def test_markdown(self): from calibre.ebooks.conversion.plugins.txt_input import MD_EXTENSIONS from calibre.ebooks.txt.processor import create_markdown_object create_markdown_object(sorted(MD_EXTENSIONS)) from calibre.library.comments import sanitize_comments_html sanitize_comments_html(b'''<script>moo</script>xxx<img src="http://moo.com/x.jpg">''') def test_feedparser(self): # sgmllib is needed for feedparser parsing malformed feeds # on python3 you can get it by taking it from python2 stdlib and # running 2to3 on it import sgmllib from calibre.web.feeds.feedparser import parse sgmllib, parse def test_openssl(self): import ssl ssl.PROTOCOL_TLSv1_2 if ismacos: cafile = ssl.get_default_verify_paths().cafile if not cafile or not cafile.endswith('/mozilla-ca-certs.pem') or not os.access(cafile, os.R_OK): raise AssertionError('Mozilla CA certs not loaded') # On Fedora create_default_context() succeeds in the main thread but # not in other threads, because upstream OpenSSL cannot read whatever # shit Fedora puts in /etc/ssl, so this check makes sure our bundled # OpenSSL is built with ssl dir that is not /etc/ssl from threading import Thread certs_loaded = False def check_ssl_loading_certs(): nonlocal certs_loaded ssl.create_default_context() certs_loaded = True t = Thread(target=check_ssl_loading_certs) t.start() t.join() if not certs_loaded: raise AssertionError('Failed to load SSL certificates') def test_multiprocessing(): from multiprocessing import get_all_start_methods, get_context for stype in get_all_start_methods(): if stype == 'fork': continue ctx = get_context(stype) q = ctx.Queue() arg = 'hello' p = ctx.Process(target=q.put, args=(arg,)) p.start() try: x = q.get(timeout=2) except Exception: raise SystemExit(f'Failed to get response from worker process with spawn_type: {stype}') if x != arg: raise SystemExit(f'{x!r} != {arg!r} with spawn_type: {stype}') p.join() def find_tests(only_build=False): ans = unittest.defaultTestLoader.loadTestsFromTestCase(BuildTest) if only_build: return ans from calibre.utils.icu_test import find_tests ans.addTests(find_tests()) from tinycss.tests.main import find_tests ans.addTests(find_tests()) from calibre.spell.dictionary import find_tests ans.addTests(find_tests()) from calibre.db.tests.fts import find_tests ans.addTests(find_tests()) return ans def test(): from calibre.utils.run_tests import run_cli run_cli(find_tests()) if __name__ == '__main__': test()
24,084
Python
.py
517
37.046422
153
0.637811
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,571
prints.py
kovidgoyal_calibre/src/calibre/prints.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import io import sys import time from polyglot.builtins import as_bytes, as_unicode def is_binary(stream): mode = getattr(stream, 'mode', None) if mode: return 'b' in mode return not isinstance(stream, io.TextIOBase) def prints(*a, **kw): ' Print either unicode or bytes to either binary or text mode streams ' stream = kw.get('file', sys.stdout) if stream is None: return sep, end = kw.get('sep'), kw.get('end') if sep is None: sep = ' ' if end is None: end = '\n' if is_binary(stream): encoding = getattr(stream, 'encoding', None) or 'utf-8' a = (as_bytes(x, encoding=encoding) for x in a) sep = as_bytes(sep) end = as_bytes(end) else: a = (as_unicode(x, errors='replace') for x in a) sep = as_unicode(sep) end = as_unicode(end) for i, x in enumerate(a): if sep and i != 0: stream.write(sep) stream.write(x) if end: stream.write(end) if kw.get('flush'): try: stream.flush() except Exception: pass def debug_print(*args, **kw): ''' Prints debug information to the console if debugging is enabled. This function prints a message prefixed with a timestamp showing the elapsed time since the first call to this function. The message is printed only if debugging is enabled. Parameters: *args : tuple Variable length argument list to be printed. **kw : dict Arbitrary keyword arguments to be passed to the `print` function. Attributes: base_time : float The timestamp of the first call to this function. Stored as an attribute of the function. Behavior: - On the first call, initializes `base_time` to the current time using `time.monotonic()`. - If `is_debugging()` returns True, prints the elapsed time since `base_time` along with the provided arguments. ''' from calibre.constants import is_debugging # Get the base_time attribute, initializing it on the first call base_time = getattr(debug_print, 'base_time', None) if base_time is None: # Set base_time to the current monotonic time if it hasn't been set debug_print.base_time = base_time = time.monotonic() # Check if debugging is enabled if is_debugging(): # Print the elapsed time and the provided arguments if debugging is enabled prints('DEBUG: %6.1f' % (time.monotonic() - base_time), *args, **kw)
2,618
Python
.py
68
32.132353
116
0.652345
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,572
constants.py
kovidgoyal_calibre/src/calibre/constants.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import codecs import collections import collections.abc import locale import os import sys from functools import lru_cache from polyglot.builtins import environ_item, hasenv __appname__ = 'calibre' numeric_version = (7, 20, 100) __version__ = '.'.join(map(str, numeric_version)) git_version = None __author__ = "Kovid Goyal <kovid@kovidgoyal.net>" ''' Various run time constants. ''' _plat = sys.platform.lower() iswindows = 'win32' in _plat or 'win64' in _plat ismacos = isosx = 'darwin' in _plat isnewosx = ismacos and getattr(sys, 'new_app_bundle', False) isfreebsd = 'freebsd' in _plat isnetbsd = 'netbsd' in _plat isdragonflybsd = 'dragonfly' in _plat isbsd = isfreebsd or isnetbsd or isdragonflybsd ishaiku = 'haiku1' in _plat islinux = not (iswindows or ismacos or isbsd or ishaiku) isfrozen = hasattr(sys, 'frozen') isunix = ismacos or islinux or ishaiku isportable = hasenv('CALIBRE_PORTABLE_BUILD') ispy3 = sys.version_info.major > 2 isxp = isoldvista = False if iswindows: wver = sys.getwindowsversion() isxp = wver.major < 6 isoldvista = wver.build < 6002 is64bit = True isworker = hasenv('CALIBRE_WORKER') or hasenv('CALIBRE_SIMPLE_WORKER') if isworker: os.environ.pop(environ_item('CALIBRE_FORCE_ANSI'), None) FAKE_PROTOCOL, FAKE_HOST = 'clbr', 'internal.invalid' SPECIAL_TITLE_FOR_WEBENGINE_COMMS = '__webengine_messages_pending__' VIEWER_APP_UID = 'com.calibre-ebook.viewer' EDITOR_APP_UID = 'com.calibre-ebook.edit-book' MAIN_APP_UID = 'com.calibre-ebook.main-gui' STORE_DIALOG_APP_UID = 'com.calibre-ebook.store-dialog' TOC_DIALOG_APP_UID = 'com.calibre-ebook.toc-editor' try: preferred_encoding = locale.getpreferredencoding() codecs.lookup(preferred_encoding) except: preferred_encoding = 'utf-8' dark_link_color = '#6cb4ee' builtin_colors_light = { 'yellow': '#ffeb6b', 'green': '#c0ed72', 'blue': '#add8ff', 'red': '#ffb0ca', 'purple': '#d9b2ff', } builtin_colors_dark = { 'yellow': '#906e00', 'green': '#306f50', 'blue': '#265589', 'red': '#a23e5a', 'purple': '#505088', } builtin_decorations = { 'wavy': {'text-decoration-style': 'wavy', 'text-decoration-color': 'red', 'text-decoration-line': 'underline'}, 'strikeout': {'text-decoration-line': 'line-through', 'text-decoration-color': 'red'}, } _osx_ver = None def get_osx_version(): global _osx_ver if _osx_ver is None: import platform from collections import namedtuple OSX = namedtuple('OSX', 'major minor tertiary') try: ver = platform.mac_ver()[0].split('.') if len(ver) == 2: ver.append(0) _osx_ver = OSX(*map(int, ver)) # no2to3 except Exception: _osx_ver = OSX(0, 0, 0) return _osx_ver filesystem_encoding = sys.getfilesystemencoding() if filesystem_encoding is None: filesystem_encoding = 'utf-8' else: try: if codecs.lookup(filesystem_encoding).name == 'ascii': filesystem_encoding = 'utf-8' # On linux, unicode arguments to os file functions are coerced to an ascii # bytestring if sys.getfilesystemencoding() == 'ascii', which is # just plain dumb. This is fixed by the icu.py module which, when # imported changes ascii to utf-8 except Exception: filesystem_encoding = 'utf-8' DEBUG = hasenv('CALIBRE_DEBUG') def debug(val=True): global DEBUG DEBUG = bool(val) def is_debugging(): return DEBUG def _get_cache_dir(): import errno confcache = os.path.join(config_dir, 'caches') try: os.makedirs(confcache) except OSError as err: if err.errno != errno.EEXIST: raise if isportable: return confcache ccd = os.getenv('CALIBRE_CACHE_DIRECTORY') if ccd is not None: ans = os.path.abspath(ccd) try: os.makedirs(ans) return ans except OSError as err: if err.errno == errno.EEXIST: return ans if iswindows: try: candidate = os.path.join(winutil.special_folder_path(winutil.CSIDL_LOCAL_APPDATA), '%s-cache'%__appname__) except ValueError: return confcache elif ismacos: candidate = os.path.join(os.path.expanduser('~/Library/Caches'), __appname__) else: candidate = os.getenv('XDG_CACHE_HOME', '~/.cache') candidate = os.path.join(os.path.expanduser(candidate), __appname__) if isinstance(candidate, bytes): try: candidate = candidate.decode(filesystem_encoding) except ValueError: candidate = confcache try: os.makedirs(candidate) except OSError as err: if err.errno != errno.EEXIST: candidate = confcache return candidate def cache_dir(): ans = getattr(cache_dir, 'ans', None) if ans is None: ans = cache_dir.ans = os.path.realpath(_get_cache_dir()) return ans # plugins {{{ plugins_loc = sys.extensions_location system_plugins_loc = getattr(sys, 'system_plugins_location', None) from importlib import import_module from importlib.machinery import EXTENSION_SUFFIXES, ExtensionFileLoader, ModuleSpec from importlib.util import find_spec class DeVendorLoader: def __init__(self, aliased_name): self.aliased_module = import_module(aliased_name) try: self.path = self.aliased_module.__loader__.path except Exception: self.path = aliased_name def create_module(self, spec): return self.aliased_module def exec_module(self, module): return module def __repr__(self): return repr(self.path) class DeVendor: def find_spec(self, fullname, path=None, target=None): if fullname == 'calibre.web.feeds.feedparser': return find_spec('feedparser') if fullname.startswith('calibre.ebooks.markdown'): return ModuleSpec(fullname, DeVendorLoader(fullname[len('calibre.ebooks.'):])) if fullname.startswith('PyQt5'): # this is present for third party plugin compat if fullname == 'PyQt5': return ModuleSpec(fullname, DeVendorLoader('qt')) return ModuleSpec(fullname, DeVendorLoader('qt.webengine' if 'QWebEngine' in fullname else 'qt.core')) if fullname.startswith('Cryptodome'): # this is needed for py7zr which uses pycryptodomex instead of # pycryptodome for some reason return ModuleSpec(fullname, DeVendorLoader(fullname.replace('dome', '', 1))) class ExtensionsPackageLoader: def __init__(self, calibre_extensions): self.calibre_extensions = calibre_extensions def is_package(self, fullname=None): return True def get_resource_reader(self, fullname=None): return self def get_source(self, fullname=None): return '' def contents(self): return iter(self.calibre_extensions) def create_module(self, spec): pass def exec_module(self, spec): pass class ExtensionsImporter: def __init__(self): extensions = ( 'pictureflow', 'lzx', 'msdes', 'podofo', 'cPalmdoc', 'progress_indicator', 'rcc_backend', 'icu', 'speedup', 'html_as_json', 'fast_css_transform', 'fast_html_entities', 'unicode_names', 'html_syntax_highlighter', 'hyphen', 'ffmpeg', 'freetype', 'imageops', 'hunspell', '_patiencediff_c', 'bzzdec', 'matcher', 'tokenizer', 'certgen', 'sqlite_extension', 'uchardet', ) if iswindows: extra = ('winutil', 'wpd', 'winfonts',) elif ismacos: extra = ('usbobserver', 'cocoa', 'libusb', 'libmtp') elif isfreebsd or ishaiku or islinux: extra = ('libusb', 'libmtp') else: extra = () self.calibre_extensions = frozenset(extensions + extra) def find_spec(self, fullname, path=None, target=None): if not fullname.startswith('calibre_extensions'): return parts = fullname.split('.') if parts[0] != 'calibre_extensions': return if len(parts) > 2: return is_package = len(parts) == 1 extension_name = None if is_package else parts[1] path = os.path.join(plugins_loc, '__init__.py') if extension_name: if extension_name not in self.calibre_extensions: return for suffix in EXTENSION_SUFFIXES: path = os.path.join(plugins_loc, extension_name + suffix) if os.path.exists(path): break else: return return ModuleSpec(fullname, ExtensionFileLoader(fullname, path), is_package=is_package, origin=path) return ModuleSpec(fullname, ExtensionsPackageLoader(self.calibre_extensions), is_package=is_package, origin=path) sys.meta_path.insert(0, DeVendor()) sys.meta_path.append(ExtensionsImporter()) if iswindows: from calibre_extensions import winutil class Plugins(collections.abc.Mapping): def __iter__(self): from importlib.resources import contents return contents('calibre_extensions') def __len__(self): from importlib.resources import contents ans = 0 for x in contents('calibre_extensions'): ans += 1 return ans def __contains__(self, name): from importlib.resources import contents for x in contents('calibre_extensions'): if x == name: return True return False def __getitem__(self, name): from importlib import import_module try: return import_module('calibre_extensions.' + name), '' except ModuleNotFoundError: raise KeyError('No plugin named %r'%name) except Exception as err: return None, str(err) def load_apsw_extension(self, conn, name): conn.enableloadextension(True) try: ext = 'pyd' if iswindows else 'so' path = os.path.join(plugins_loc, f'{name}.{ext}') conn.loadextension(path, f'calibre_{name}_init') finally: conn.enableloadextension(False) def load_sqlite3_extension(self, conn, name): conn.enable_load_extension(True) try: ext = 'pyd' if iswindows else 'so' path = os.path.join(plugins_loc, f'{name}.{ext}') conn.load_extension(path) finally: conn.enable_load_extension(False) plugins = None if plugins is None: plugins = Plugins() # }}} # config_dir {{{ CONFIG_DIR_MODE = 0o700 cconfd = os.getenv('CALIBRE_CONFIG_DIRECTORY') if cconfd is not None: config_dir = os.path.abspath(cconfd) elif iswindows: try: config_dir = winutil.special_folder_path(winutil.CSIDL_APPDATA) except ValueError: config_dir = None if not config_dir or not os.access(config_dir, os.W_OK|os.X_OK): config_dir = os.path.expanduser('~') config_dir = os.path.join(config_dir, 'calibre') elif ismacos: config_dir = os.path.expanduser('~/Library/Preferences/calibre') else: bdir = os.path.abspath(os.path.expanduser(os.getenv('XDG_CONFIG_HOME', '~/.config'))) config_dir = os.path.join(bdir, 'calibre') try: os.makedirs(config_dir, mode=CONFIG_DIR_MODE) except: pass if not os.path.exists(config_dir) or \ not os.access(config_dir, os.W_OK) or not \ os.access(config_dir, os.X_OK): print('No write access to', config_dir, 'using a temporary dir instead') import atexit import tempfile config_dir = tempfile.mkdtemp(prefix='calibre-config-') def cleanup_cdir(): try: import shutil shutil.rmtree(config_dir) except: pass atexit.register(cleanup_cdir) # }}} is_running_from_develop = False if getattr(sys, 'frozen', False): try: from bypy_importer import running_in_develop_mode except ImportError: pass else: is_running_from_develop = running_in_develop_mode() in_develop_mode = os.getenv('CALIBRE_ENABLE_DEVELOP_MODE') == '1' if iswindows: # Needed to get Qt to use the correct cache dir, relies on a patched Qt os.environ['CALIBRE_QT_CACHE_LOCATION'] = cache_dir() def get_version(): '''Return version string for display to user ''' if git_version is not None: v = git_version else: v = __version__ if numeric_version[-1] == 0: v = v[:-2] if is_running_from_develop: v += '*' return v def get_appname_for_display(): ans = __appname__ if isportable: ans = _('{} Portable').format(ans) return ans def get_portable_base(): 'Return path to the directory that contains calibre-portable.exe or None' if isportable: return os.path.dirname(os.path.dirname(os.getenv('CALIBRE_PORTABLE_BUILD'))) def get_windows_username(): ''' Return the user name of the currently logged in user as a unicode string. Note that usernames on windows are case insensitive, the case of the value returned depends on what the user typed into the login box at login time. ''' return winutil.username() def get_windows_temp_path(): return winutil.temp_path() def get_windows_user_locale_name(): return winutil.locale_name() def get_windows_number_formats(): ans = getattr(get_windows_number_formats, 'ans', None) if ans is None: d = winutil.localeconv() thousands_sep, decimal_point = d['thousands_sep'], d['decimal_point'] ans = get_windows_number_formats.ans = thousands_sep, decimal_point return ans def trash_name(): return _('Trash') if ismacos else _('Recycle Bin') @lru_cache(maxsize=2) def get_umask(): mask = os.umask(0o22) os.umask(mask) return mask # call this at startup as it changes process global state, which doesn't work # with multi-threading. It's absurd there is no way to safely read the current # umask of a process. get_umask() @lru_cache(maxsize=2) def bundled_binaries_dir() -> str: if ismacos and hasattr(sys, 'frameworks_dir'): base = os.path.join(os.path.dirname(sys.frameworks_dir), 'utils.app', 'Contents', 'MacOS') return base if iswindows and hasattr(sys, 'frozen'): base = sys.extensions_location if hasattr(sys, 'new_app_layout') else os.path.dirname(sys.executable) return base if (islinux or isbsd) and getattr(sys, 'frozen', False): return os.path.join(sys.executables_location, 'bin') return '' @lru_cache(2) def piper_cmdline() -> tuple[str, ...]: ext = '.exe' if iswindows else '' if bbd := bundled_binaries_dir(): if ismacos: return (os.path.join(sys.frameworks_dir, 'piper', 'piper'),) return (os.path.join(bbd, 'piper', 'piper' + ext),) if pd := os.environ.get('PIPER_TTS_DIR'): return (os.path.join(pd, 'piper' + ext),) import shutil exe = shutil.which('piper-tts') if exe: return (exe,) return ()
15,639
Python
.py
433
28.919169
121
0.631997
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,573
startup.py
kovidgoyal_calibre/src/calibre/startup.py
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' ''' Perform various initialization tasks. ''' import locale import os import sys # Default translation is NOOP from polyglot.builtins import builtins builtins.__dict__['_'] = lambda s: s # For strings which belong in the translation tables, but which shouldn't be # immediately translated to the environment language builtins.__dict__['__'] = lambda s: s # For backwards compat with some third party plugins builtins.__dict__['dynamic_property'] = lambda func: func(None) from calibre.constants import DEBUG, isfreebsd, islinux, ismacos, iswindows def get_debug_executable(headless=False): exe_name = 'calibre-debug' + ('.exe' if iswindows else '') if hasattr(sys, 'frameworks_dir'): base = os.path.dirname(sys.frameworks_dir) if headless: from calibre.utils.ipc.launch import Worker class W(Worker): exe_name = 'calibre-debug' return [W().executable] return [os.path.join(base, 'MacOS', exe_name)] if getattr(sys, 'run_local', None): return [sys.run_local, exe_name] nearby = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), exe_name) if getattr(sys, 'frozen', False): return [nearby] exloc = getattr(sys, 'executables_location', None) if exloc: ans = os.path.join(exloc, exe_name) if os.path.exists(ans): return [ans] if os.path.exists(nearby): return [nearby] return [exe_name] def connect_lambda(bound_signal, self, func, **kw): import weakref r = weakref.ref(self) del self num_args = func.__code__.co_argcount - 1 if num_args < 0: raise TypeError('lambda must take at least one argument') def slot(*args): ctx = r() if ctx is not None: if len(args) != num_args: args = args[:num_args] func(ctx, *args) bound_signal.connect(slot, **kw) def initialize_calibre(): if hasattr(initialize_calibre, 'initialized'): return initialize_calibre.initialized = True # Ensure that all temp files/dirs are created under a calibre tmp dir from calibre.ptempfile import base_dir try: base_dir() except OSError: pass # Ignore this error during startup, so we can show a better error message to the user later. # # Ensure that the max number of open files is at least 1024 if iswindows: # See https://msdn.microsoft.com/en-us/library/6e3b887c.aspx from calibre_extensions import winutil winutil.setmaxstdio(max(1024, winutil.getmaxstdio())) else: import resource soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) if soft < 1024: try: resource.setrlimit(resource.RLIMIT_NOFILE, (min(1024, hard), hard)) except Exception: if DEBUG: import traceback traceback.print_exc() # # Fix multiprocessing from multiprocessing import spawn, util def get_command_line(**kwds): prog = 'from multiprocessing.spawn import spawn_main; spawn_main(%s)' prog %= ', '.join('%s=%r' % item for item in kwds.items()) return get_debug_executable() + ['--fix-multiprocessing', '--', prog] spawn.get_command_line = get_command_line orig_spawn_passfds = util.spawnv_passfds def wrapped_orig_spawn_fds(args, passfds): # as of python 3.11 util.spawnv_passfds expects bytes args if sys.version_info >= (3, 11): args = [x.encode('utf-8') if isinstance(x, str) else x for x in args] return orig_spawn_passfds(args[0], args, passfds) def spawnv_passfds(path, args, passfds): try: idx = args.index('-c') except ValueError: return wrapped_orig_spawn_fds(args, passfds) patched_args = get_debug_executable() + ['--fix-multiprocessing', '--'] + args[idx + 1:] return wrapped_orig_spawn_fds(patched_args, passfds) util.spawnv_passfds = spawnv_passfds # # Setup resources import calibre.utils.resources as resources resources # # Setup translations from calibre.utils.localization import getlangcode_from_envvars, set_translators set_translators() # # Initialize locale # Import string as we do not want locale specific # string.whitespace/printable, on windows especially, this causes problems. # Before the delay load optimizations, string was loaded before this point # anyway, so we preserve the old behavior explicitly. import string string try: locale.setlocale(locale.LC_ALL, '') # set the locale to the user's default locale except Exception: try: dl = getlangcode_from_envvars() if dl: locale.setlocale(locale.LC_ALL, dl) except Exception: pass builtins.__dict__['lopen'] = open # legacy compatibility from calibre.utils.icu import lower as icu_lower from calibre.utils.icu import title_case from calibre.utils.icu import upper as icu_upper builtins.__dict__['icu_lower'] = icu_lower builtins.__dict__['icu_upper'] = icu_upper builtins.__dict__['icu_title'] = title_case builtins.__dict__['connect_lambda'] = connect_lambda if islinux or ismacos or isfreebsd: # Name all threads at the OS level created using the threading module, see # http://bugs.python.org/issue15500 import threading from calibre_extensions import speedup orig_start = threading.Thread.start def new_start(self): orig_start(self) try: name = self.name if not name or name.startswith('Thread-'): name = self.__class__.__name__ if name == 'Thread': name = self.name if name: if isinstance(name, str): name = name.encode('ascii', 'replace').decode('ascii') speedup.set_thread_name(name[:15]) except Exception: pass # Don't care about failure to set name threading.Thread.start = new_start
6,371
Python
.py
157
32.477707
106
0.633673
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,574
__init__.py
kovidgoyal_calibre/src/calibre/__init__.py
''' E-book management software''' __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import re import sys import time import warnings from functools import lru_cache, partial from math import floor from polyglot.builtins import codepoint_to_chr, hasenv, native_string_type if not hasenv('CALIBRE_SHOW_DEPRECATION_WARNINGS'): warnings.simplefilter('ignore', DeprecationWarning) try: os.getcwd() except OSError: os.chdir(os.path.expanduser('~')) from calibre.constants import ( __appname__, __author__, __version__, config_dir, filesystem_encoding, isbsd, isfrozen, islinux, ismacos, iswindows, plugins, preferred_encoding, ) from calibre.startup import initialize_calibre initialize_calibre() from calibre.prints import prints from calibre.utils.icu import safe_chr from calibre.utils.resources import get_path as P if False: # Prevent pyflakes from complaining __appname__, islinux, __version__ isfrozen, __author__, isbsd, config_dir, plugins _mt_inited = False def _init_mimetypes(): global _mt_inited import mimetypes mimetypes.init([P('mime.types')]) _mt_inited = True @lru_cache(4096) def guess_type(*args, **kwargs): import mimetypes if not _mt_inited: _init_mimetypes() return mimetypes.guess_type(*args, **kwargs) def guess_all_extensions(*args, **kwargs): import mimetypes if not _mt_inited: _init_mimetypes() return mimetypes.guess_all_extensions(*args, **kwargs) def guess_extension(*args, **kwargs): import mimetypes if not _mt_inited: _init_mimetypes() ext = mimetypes.guess_extension(*args, **kwargs) if not ext and args and args[0] == 'application/x-palmreader': ext = '.pdb' return ext def get_types_map(): import mimetypes if not _mt_inited: _init_mimetypes() return mimetypes.types_map def to_unicode(raw, encoding='utf-8', errors='strict'): if isinstance(raw, str): return raw return raw.decode(encoding, errors) def patheq(p1, p2): p = os.path def d(x): return p.normcase(p.normpath(p.realpath(p.normpath(x)))) if not p1 or not p2: return False return d(p1) == d(p2) def unicode_path(path, abs=False): if isinstance(path, bytes): path = path.decode(filesystem_encoding) if abs: path = os.path.abspath(path) return path def osx_version(): if ismacos: import platform src = platform.mac_ver()[0] m = re.match(r'(\d+)\.(\d+)\.(\d+)', src) if m: return int(m.group(1)), int(m.group(2)), int(m.group(3)) def confirm_config_name(name): return name + '_again' _filename_sanitize_unicode = frozenset(('\\', '|', '?', '*', '<', # no2to3 '"', ':', '>', '+', '/') + tuple(map(codepoint_to_chr, range(32)))) # no2to3 def sanitize_file_name(name, substitute='_'): ''' Sanitize the filename `name`. All invalid characters are replaced by `substitute`. The set of invalid characters is the union of the invalid characters in Windows, macOS and Linux. Also removes leading and trailing whitespace. **WARNING:** This function also replaces path separators, so only pass file names and not full paths to it. ''' if isbytestring(name): name = name.decode(filesystem_encoding, 'replace') if isbytestring(substitute): substitute = substitute.decode(filesystem_encoding, 'replace') chars = (substitute if c in _filename_sanitize_unicode else c for c in name) one = ''.join(chars) one = re.sub(r'\s', ' ', one).strip() bname, ext = os.path.splitext(one) one = re.sub(r'^\.+$', '_', bname) one = one.replace('..', substitute) one += ext # Windows doesn't like path components that end with a period or space if one and one[-1] in ('.', ' '): one = one[:-1]+'_' # Names starting with a period are hidden on Unix if one.startswith('.'): one = '_' + one[1:] return one sanitize_file_name2 = sanitize_file_name_unicode = sanitize_file_name class CommandLineError(Exception): pass def setup_cli_handlers(logger, level): import logging if hasenv('CALIBRE_WORKER') and logger.handlers: return logger.setLevel(level) if level == logging.WARNING: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) handler.setLevel(logging.WARNING) elif level == logging.INFO: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter()) handler.setLevel(logging.INFO) elif level == logging.DEBUG: handler = logging.StreamHandler(sys.stderr) handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('[%(levelname)s] %(filename)s:%(lineno)s: %(message)s')) logger.addHandler(handler) def load_library(name, cdll): if iswindows: return cdll.LoadLibrary(name) if ismacos: name += '.dylib' if hasattr(sys, 'frameworks_dir'): return cdll.LoadLibrary(os.path.join(getattr(sys, 'frameworks_dir'), name)) return cdll.LoadLibrary(name) return cdll.LoadLibrary(name+'.so') def extract(path, dir): extractor = None # First use the file header to identify its type with open(path, 'rb') as f: id_ = f.read(3) if id_ == b'Rar': from calibre.utils.unrar import extract as rarextract extractor = rarextract elif id_.startswith(b'PK'): from calibre.libunzip import extract as zipextract extractor = zipextract elif id_.startswith(b'7z'): from calibre.utils.seven_zip import extract as seven_extract extractor = seven_extract if extractor is None: # Fallback to file extension ext = os.path.splitext(path)[1][1:].lower() if ext in ('zip', 'cbz', 'epub', 'oebzip'): from calibre.libunzip import extract as zipextract extractor = zipextract elif ext in ('cbr', 'rar'): from calibre.utils.unrar import extract as rarextract extractor = rarextract elif ext in ('cb7', '7z'): from calibre.utils.seven_zip import extract as seven_extract extractor = seven_extract if extractor is None: raise Exception('Unknown archive type') extractor(path, dir) def get_proxies(debug=True): from polyglot.urllib import getproxies proxies = getproxies() for key, proxy in list(proxies.items()): if not proxy or '..' in proxy or key == 'auto': del proxies[key] continue if proxy.startswith(key+'://'): proxy = proxy[len(key)+3:] if key == 'https' and proxy.startswith('http://'): proxy = proxy[7:] if proxy.endswith('/'): proxy = proxy[:-1] if len(proxy) > 4: proxies[key] = proxy else: prints('Removing invalid', key, 'proxy:', proxy) del proxies[key] if proxies and debug: prints('Using proxies:', proxies) return proxies def get_parsed_proxy(typ='http', debug=True): proxies = get_proxies(debug) proxy = proxies.get(typ, None) if proxy: pattern = re.compile(( '(?:ptype://)?' '(?:(?P<user>\\w+):(?P<pass>.*)@)?' '(?P<host>[\\w\\-\\.]+)' '(?::(?P<port>\\d+))?').replace('ptype', typ) ) match = pattern.match(proxies[typ]) if match: try: ans = { 'host' : match.group('host'), 'port' : match.group('port'), 'user' : match.group('user'), 'pass' : match.group('pass') } if ans['port']: ans['port'] = int(ans['port']) except: if debug: import traceback traceback.print_exc() else: if debug: prints('Using http proxy', str(ans)) return ans def get_proxy_info(proxy_scheme, proxy_string): ''' Parse all proxy information from a proxy string (as returned by get_proxies). The returned dict will have members set to None when the info is not available in the string. If an exception occurs parsing the string this method returns None. ''' from polyglot.urllib import urlparse try: proxy_url = '%s://%s'%(proxy_scheme, proxy_string) urlinfo = urlparse(proxy_url) ans = { 'scheme': urlinfo.scheme, 'hostname': urlinfo.hostname, 'port': urlinfo.port, 'username': urlinfo.username, 'password': urlinfo.password, } except Exception: return None return ans def is_mobile_ua(ua): return 'Mobile/' in ua or 'Mobile ' in ua def random_user_agent(choose=None, allow_ie=True): from calibre.utils.random_ua import choose_randomly_by_popularity, common_user_agents ua_list = common_user_agents() ua_list = tuple(x for x in ua_list if not is_mobile_ua(x)) if not allow_ie: ua_list = tuple(x for x in ua_list if 'Trident/' not in x) if choose is not None: return ua_list[choose] return choose_randomly_by_popularity(ua_list) def browser(honor_time=True, max_time=2, user_agent=None, verify_ssl_certificates=True, handle_refresh=True, **kw): ''' Create a mechanize browser for web scraping. The browser handles cookies, refresh requests and ignores robots.txt. Also uses proxy if available. :param honor_time: If True honors pause time in refresh requests :param max_time: Maximum time in seconds to wait during a refresh request :param verify_ssl_certificates: If false SSL certificates errors are ignored ''' from calibre.utils.browser import Browser opener = Browser(verify_ssl=verify_ssl_certificates) opener.set_handle_refresh(handle_refresh, max_time=max_time, honor_time=honor_time) opener.set_handle_robots(False) if user_agent is None: user_agent = random_user_agent(0, allow_ie=False) elif user_agent == 'common_words/based': from calibre.utils.random_ua import common_english_word_ua user_agent = common_english_word_ua() opener.addheaders = [('User-agent', user_agent)] proxies = get_proxies() to_add = {} http_proxy = proxies.get('http', None) if http_proxy: to_add['http'] = http_proxy https_proxy = proxies.get('https', None) if https_proxy: to_add['https'] = https_proxy if to_add: opener.set_proxies(to_add) return opener def fit_image(width, height, pwidth, pheight): ''' Fit image in box of width pwidth and height pheight. @param width: Width of image @param height: Height of image @param pwidth: Width of box @param pheight: Height of box @return: scaled, new_width, new_height. scaled is True iff new_width and/or new_height is different from width or height. ''' if height < 1 or width < 1: return False, int(width), int(height) scaled = height > pheight or width > pwidth if height > pheight: corrf = pheight / float(height) width, height = floor(corrf*width), pheight if width > pwidth: corrf = pwidth / float(width) width, height = pwidth, floor(corrf*height) if height > pheight: corrf = pheight / float(height) width, height = floor(corrf*width), pheight return scaled, int(width), int(height) class CurrentDir: def __init__(self, path): self.path = path self.cwd = None def __enter__(self, *args): self.cwd = os.getcwd() os.chdir(self.path) return self.cwd def __exit__(self, *args): try: os.chdir(self.cwd) except OSError: # The previous CWD no longer exists pass _ncpus = None def detect_ncpus(): global _ncpus if _ncpus is None: _ncpus = max(1, os.cpu_count() or 1) return _ncpus relpath = os.path.relpath def walk(dir): ''' A nice interface to os.walk ''' for record in os.walk(dir): for f in record[-1]: yield os.path.join(record[0], f) def strftime(fmt, t=None): ''' A version of strftime that returns unicode strings and tries to handle dates before 1900 ''' if not fmt: return '' if t is None: t = time.localtime() if hasattr(t, 'timetuple'): t = t.timetuple() early_year = t[0] < 1900 if early_year: replacement = 1900 if t[0]%4 == 0 else 1901 fmt = fmt.replace('%Y', '_early year hack##') t = list(t) orig_year = t[0] t[0] = replacement t = time.struct_time(t) ans = None if isinstance(fmt, bytes): fmt = fmt.decode('mbcs' if iswindows else 'utf-8', 'replace') ans = time.strftime(fmt, t) if early_year: ans = ans.replace('_early year hack##', str(orig_year)) return ans def my_unichr(num): try: return safe_chr(num) except (ValueError, OverflowError): return '?' XML_ENTITIES = { '"' : '&quot;', "'" : '&apos;', '<' : '&lt;', '>' : '&gt;', '&' : '&amp;' } def entity_to_unicode(match, exceptions=(), encoding=None, result_exceptions={}): ''' :param match: A match object such that '&'+match.group(1)';' is the entity. :param exceptions: A list of entities to not convert (Each entry is the name of the entity, e.g. 'apos' or '#1234)' :param encoding: The encoding to use to decode numeric entities between 128 and 256. If None, the Unicode UCS encoding is used. A common encoding is cp1252. :param result_exceptions: A mapping of characters to entities. If the result is in result_exceptions, result_exception[result] is returned instead. Convenient way to specify exception for things like < or > that can be specified by various actual entities. ''' from calibre.ebooks.html_entities import entity_to_unicode_in_python try: from calibre_extensions.fast_html_entities import replace_all_entities except ImportError: # Running from source without updated binaries return entity_to_unicode_in_python(match, exceptions, encoding, result_exceptions) if not encoding and not exceptions and (not result_exceptions or result_exceptions is XML_ENTITIES): return replace_all_entities(match.group(), result_exceptions is XML_ENTITIES) return entity_to_unicode_in_python(match, exceptions, encoding, result_exceptions) xml_entity_to_unicode = partial(entity_to_unicode, result_exceptions=XML_ENTITIES) @lru_cache(2) def entity_regex(): return re.compile(r'&(\S+?);') def replace_entities(raw, encoding=None): if encoding is None: try: from calibre_extensions.fast_html_entities import replace_all_entities replace_all_entities(raw) except ImportError: # Running from source without updated binaries pass return entity_regex().sub(partial(entity_to_unicode, encoding=encoding), raw) def xml_replace_entities(raw, encoding=None): if encoding is None: try: from calibre_extensions.fast_html_entities import replace_all_entities replace_all_entities(raw, True) except ImportError: # Running from source without updated binaries pass return entity_regex().sub(partial(xml_entity_to_unicode, encoding=encoding), raw) def prepare_string_for_xml(raw, attribute=False): raw = replace_entities(raw) raw = raw.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;') if attribute: raw = raw.replace('"', '&quot;').replace("'", '&apos;') return raw def isbytestring(obj): return isinstance(obj, bytes) def force_unicode(obj, enc=preferred_encoding): if isbytestring(obj): try: obj = obj.decode(enc) except Exception: try: obj = obj.decode(filesystem_encoding if enc == preferred_encoding else preferred_encoding) except Exception: try: obj = obj.decode('utf-8') except Exception: obj = repr(obj) if isbytestring(obj): obj = obj.decode('utf-8') return obj def as_unicode(obj, enc=preferred_encoding): if not isbytestring(obj): try: obj = str(obj) except Exception: try: obj = native_string_type(obj) except Exception: obj = repr(obj) return force_unicode(obj, enc=enc) def url_slash_cleaner(url): ''' Removes redundant /'s from url's. ''' return re.sub(r'(?<!:)/{2,}', '/', url) def human_readable(size, sep=' '): """ Convert a size in bytes into a human readable form """ divisor, suffix = 1, "B" for i, candidate in enumerate(('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB')): if size < (1 << ((i + 1) * 10)): divisor, suffix = (1 << (i * 10)), candidate break size = str(float(size)/divisor) if size.find(".") > -1: size = size[:size.find(".")+2] if size.endswith('.0'): size = size[:-2] return size + sep + suffix def ipython(user_ns=None): from calibre.utils.ipython import ipython ipython(user_ns=user_ns) def fsync(fileobj): fileobj.flush() os.fsync(fileobj.fileno()) if islinux and getattr(fileobj, 'name', None): # On Linux kernels after 5.1.9 and 4.19.50 using fsync without any # following activity causes Kindles to eject. Instead of fixing this in # the obvious way, which is to have the kernel send some harmless # filesystem activity after the FSYNC, the kernel developers seem to # think the correct solution is to disable FSYNC using a mount flag # which users will have to turn on manually. So instead we create some # harmless filesystem activity, and who cares about performance. # See https://bugs.launchpad.net/calibre/+bug/1834641 # and https://bugzilla.kernel.org/show_bug.cgi?id=203973 # To check for the existence of the bug, simply run: # python -c "p = '/run/media/kovid/Kindle/driveinfo.calibre'; f = open(p, 'r+b'); os.fsync(f.fileno());" # this will cause the Kindle to disconnect. try: os.utime(fileobj.name, None) except Exception: import traceback traceback.print_exc()
18,887
Python
.py
494
31.030364
125
0.629259
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,575
debug.py
kovidgoyal_calibre/src/calibre/debug.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' ''' Embedded console for debugging. ''' import functools import os import sys from calibre import prints from calibre.constants import iswindows from calibre.startup import get_debug_executable from calibre.utils.config import OptionParser from polyglot.builtins import exec_path def run_calibre_debug(*args, **kw): import subprocess creationflags = 0 headless = bool(kw.pop('headless', False)) if iswindows: creationflags = subprocess.CREATE_NO_WINDOW cmd = get_debug_executable(headless=headless) + list(args) kw['creationflags'] = creationflags return subprocess.Popen(cmd, **kw) def option_parser(): parser = OptionParser(usage=_('''\ {0} Various command line interfaces useful for debugging calibre. With no options, this command starts an embedded Python interpreter. You can also run the main calibre GUI, the calibre E-book viewer and the calibre editor in debug mode. It also contains interfaces to various bits of calibre that do not have dedicated command line tools, such as font subsetting, the E-book diff tool and so on. You can also use %prog to run standalone scripts. To do that use it like this: {1} Everything after the -- is passed to the script. You can also use calibre-debug as a shebang in scripts, like this: {2} ''').format(_('%prog [options]'), '%prog -e myscript.py -- --option1 --option2 file1 file2 ...', '#!/usr/bin/env -S calibre-debug -e -- --')) parser.add_option('-c', '--command', help=_('Run Python code.')) parser.add_option('-e', '--exec-file', help=_('Run the Python code in file.')) parser.add_option('-f', '--subset-font', action='store_true', default=False, help=_('Subset the specified font. Use -- after this option to pass option to the font subsetting program.')) parser.add_option('-d', '--debug-device-driver', default=False, action='store_true', help=_('Debug device detection')) parser.add_option('-g', '--gui', default=False, action='store_true', help=_('Run the GUI with debugging enabled. Debug output is ' 'printed to stdout and stderr.')) parser.add_option('--gui-debug', default=None, help=_('Run the GUI with a debug console, logging to the' ' specified path. For internal use only, use the -g' ' option to run the GUI in debug mode')) parser.add_option('--run-without-debug', default=False, action='store_true', help=_('Don\'t run with the DEBUG flag set')) parser.add_option('-w', '--viewer', default=False, action='store_true', help=_('Run the E-book viewer in debug mode')) parser.add_option('--paths', default=False, action='store_true', help=_('Output the paths necessary to setup the calibre environment')) parser.add_option('--add-simple-plugin', default=None, help=_('Add a simple plugin (i.e. a plugin that consists of only a ' '.py file), by specifying the path to the py file containing the ' 'plugin code.')) parser.add_option('-m', '--inspect-mobi', action='store_true', default=False, help=_('Inspect the MOBI file(s) at the specified path(s)')) parser.add_option('-t', '--edit-book', action='store_true', help=_('Launch the calibre "Edit book" tool in debug mode.')) parser.add_option('-x', '--explode-book', default=False, action='store_true', help=_('Explode the book into the specified folder.\nUsage: ' '-x file.epub output_dir\n' 'Exports the book as a collection of HTML ' 'files and metadata, which you can edit using standard HTML ' 'editing tools. Works with EPUB, AZW3, HTMLZ and DOCX files.')) parser.add_option('-i', '--implode-book', default=False, action='store_true', help=_( 'Implode a previously exploded book.\nUsage: -i output_dir file.epub\n' 'Imports the book from the files in output_dir which must have' ' been created by a previous call to --explode-book. Be sure to' ' specify the same file type as was used when exploding.')) parser.add_option('--export-all-calibre-data', default=False, action='store_true', help=_('Export all calibre data (books/settings/plugins). Normally, you will' ' be asked for the export folder and the libraries to export. You can also specify them' ' as command line arguments to skip the questions.' ' Use absolute paths for the export folder and libraries.' ' The special keyword "all" can be used to export all libraries. Examples:\n\n' ' calibre-debug --export-all-calibre-data # for interactive use\n' ' calibre-debug --export-all-calibre-data /path/to/empty/export/folder /path/to/library/folder1 /path/to/library2\n' ' calibre-debug --export-all-calibre-data /export/folder all # export all known libraries' )) parser.add_option('--import-calibre-data', default=False, action='store_true', help=_('Import previously exported calibre data')) parser.add_option('-s', '--shutdown-running-calibre', default=False, action='store_true', help=_('Cause a running calibre instance, if any, to be' ' shutdown. Note that if there are running jobs, they ' 'will be silently aborted, so use with care.')) parser.add_option('--test-build', help=_('Test binary modules in build'), action='store_true', default=False) parser.add_option('-r', '--run-plugin', help=_( 'Run a plugin that provides a command line interface. For example:\n' 'calibre-debug -r "Plugin name" -- file1 --option1\n' 'Everything after the -- will be passed to the plugin as arguments.')) parser.add_option('-t', '--run-test', help=_( 'Run the named test(s). Use the special value "all" to run all tests.' ' If the test name starts with a period it is assumed to be a module name.' ' If the test name starts with @ it is assumed to be a category name.' )) parser.add_option('--diff', action='store_true', default=False, help=_( 'Run the calibre diff tool. For example:\n' 'calibre-debug --diff file1 file2')) parser.add_option('--default-programs', default=None, choices=['register', 'unregister'], help=_('(Un)register calibre from Windows Default Programs.') + ' --default-programs=(register|unregister)') parser.add_option('--fix-multiprocessing', default=False, action='store_true', help=_('For internal use')) return parser def debug_device_driver(): from calibre.devices import debug debug(ioreg_to_tmp=True, buf=sys.stdout) if iswindows: # no2to3 input('Press Enter to continue...') # no2to3 def add_simple_plugin(path_to_plugin): import shutil import tempfile import zipfile tdir = tempfile.mkdtemp() open(os.path.join(tdir, 'custom_plugin.py'), 'wb').write(open(path_to_plugin, 'rb').read()) odir = os.getcwd() os.chdir(tdir) zf = zipfile.ZipFile('plugin.zip', 'w') zf.write('custom_plugin.py') zf.close() from calibre.customize.ui import main main(['calibre-customize', '-a', 'plugin.zip']) os.chdir(odir) shutil.rmtree(tdir) def print_basic_debug_info(out=None): if out is None: out = sys.stdout out = functools.partial(prints, file=out) import platform from calibre.constants import __appname__, get_version, isfrozen, ismacos, isportable from calibre.utils.localization import set_translators out(__appname__, get_version(), 'Portable' if isportable else '', 'embedded-python:', isfrozen) out(platform.platform(), platform.system(), platform.architecture()) out(platform.system_alias(platform.system(), platform.release(), platform.version())) out('Python', platform.python_version()) try: if iswindows: out('Windows:', platform.win32_ver()) elif ismacos: out('OSX:', platform.mac_ver()) else: out('Linux:', platform.linux_distribution()) except: pass out('Interface language:', str(set_translators.lang)) out('EXE path:', sys.executable) from calibre.customize.ui import has_external_plugins, initialized_plugins if has_external_plugins(): from calibre.customize import PluginInstallationType names = (f'{p.name} {p.version}' for p in initialized_plugins() if getattr(p, 'installation_type', None) is not PluginInstallationType.BUILTIN) out('Successfully initialized third party plugins:', ' && '.join(names)) def run_debug_gui(logpath): import time time.sleep(3) # Give previous GUI time to shutdown fully and release locks from calibre.constants import __appname__ prints(__appname__, _('Debug log')) print_basic_debug_info() from calibre.gui_launch import calibre calibre(['__CALIBRE_GUI_DEBUG__', logpath]) def load_user_plugins(): # Load all user defined plugins so the script can import from the # calibre_plugins namespace import calibre.customize.ui as dummy return dummy def run_script(path, args): load_user_plugins() sys.argv = [path] + args ef = os.path.abspath(path) if '/src/calibre/' not in ef.replace(os.pathsep, '/'): base = os.path.dirname(ef) sys.path.insert(0, base) g = globals() g['__name__'] = '__main__' g['__file__'] = ef exec_path(ef, g) def inspect_mobi(path): from calibre.ebooks.mobi.debug.main import inspect_mobi prints('Inspecting:', path) inspect_mobi(path) print() def main(args=sys.argv): from calibre.constants import debug opts, args = option_parser().parse_args(args) if opts.fix_multiprocessing: sys.argv = [sys.argv[0], '--multiprocessing-fork'] exec(args[-1]) return if not opts.run_without_debug: debug() if opts.gui: from calibre.gui_launch import calibre calibre(['calibre'] + args[1:]) elif opts.gui_debug is not None: run_debug_gui(opts.gui_debug) elif opts.viewer: from calibre.gui_launch import ebook_viewer ebook_viewer(['ebook-viewer'] + args[1:]) elif opts.command: sys.argv = args exec(opts.command) elif opts.debug_device_driver: debug_device_driver() elif opts.add_simple_plugin is not None: add_simple_plugin(opts.add_simple_plugin) elif opts.paths: prints('CALIBRE_RESOURCES_PATH='+sys.resources_location) prints('CALIBRE_EXTENSIONS_PATH='+sys.extensions_location) prints('CALIBRE_PYTHON_PATH='+os.pathsep.join(sys.path)) elif opts.inspect_mobi: for path in args[1:]: inspect_mobi(path) elif opts.edit_book: from calibre.gui_launch import ebook_edit ebook_edit(['ebook-edit'] + args[1:]) elif opts.explode_book or opts.implode_book: from calibre.ebooks.tweak import explode, implode try: a1, a2 = args[1:] except Exception: raise SystemExit('Must provide exactly two arguments') f = explode if opts.explode_book else implode f(a1, a2) elif opts.test_build: from calibre.test_build import test, test_multiprocessing test_multiprocessing() test() elif opts.shutdown_running_calibre: from calibre.gui2.main import shutdown_other shutdown_other() elif opts.subset_font: from calibre.utils.fonts.sfnt.subset import main main(['subset-font'] + args[1:]) elif opts.exec_file: if opts.exec_file == '--': run_script(args[1], args[2:]) else: run_script(opts.exec_file, args[1:]) elif opts.run_plugin: from calibre.customize.ui import find_plugin plugin = find_plugin(opts.run_plugin) if plugin is None: prints(_('No plugin named %s found')%opts.run_plugin) raise SystemExit(1) plugin.cli_main([plugin.name] + args[1:]) elif opts.run_test: debug(False) from calibre.utils.run_tests import run_test run_test(opts.run_test) elif opts.diff: from calibre.gui2.tweak_book.diff.main import main main(['calibre-diff'] + args[1:]) elif opts.default_programs: if not iswindows: raise SystemExit('Can only be run on Microsoft Windows') if opts.default_programs == 'register': from calibre.utils.winreg.default_programs import register as func else: from calibre.utils.winreg.default_programs import unregister as func print('Running', func.__name__, '...') func() elif opts.export_all_calibre_data: args = args[1:] from calibre.utils.exim import run_exporter run_exporter(args=args, check_known_libraries=False) elif opts.import_calibre_data: from calibre.utils.exim import run_importer run_importer() elif len(args) >= 2 and args[1].rpartition('.')[-1] in {'py', 'recipe'}: run_script(args[1], args[2:]) elif len(args) >= 2 and args[1].rpartition('.')[-1] in {'mobi', 'azw', 'azw3', 'docx', 'odt'}: for path in args[1:]: ext = path.rpartition('.')[-1] if ext in {'docx', 'odt'}: from calibre.ebooks.docx.dump import dump dump(path) elif ext in {'mobi', 'azw', 'azw3'}: inspect_mobi(path) else: print('Cannot dump unknown filetype: %s' % path) elif len(args) >= 2 and os.path.exists(os.path.join(args[1], '__main__.py')): sys.path.insert(0, args[1]) run_script(os.path.join(args[1], '__main__.py'), args[2:]) else: load_user_plugins() from calibre import ipython ipython() return 0 if __name__ == '__main__': sys.exit(main())
14,209
Python
.py
301
39.48505
141
0.642661
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,576
build_forms.py
kovidgoyal_calibre/src/calibre/build_forms.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> import importlib import os def form_to_compiled_form(form): return form.rpartition('.')[0]+'_ui.py' def find_forms(srcdir): base = os.path.join(srcdir, 'calibre', 'gui2') forms = [] for root, _, files in os.walk(base): for name in files: if name.endswith('.ui'): forms.append(os.path.abspath(os.path.join(root, name))) return forms def ensure_icons_built(resource_dir, force_compile, info): icons = os.path.join(resource_dir, 'icons.rcc') images_dir = os.path.join(resource_dir, 'images') if os.path.exists(icons) and not force_compile: limit = os.stat(icons).st_mtime for x in os.scandir(images_dir): if x.name.endswith('.png'): st = x.stat(follow_symlinks=False) if st.st_mtime >= limit: break else: return info('Building icons.rcc') from calibre.utils.rcc import compile_icon_dir_as_themes compile_icon_dir_as_themes(images_dir, icons) def build_forms(srcdir, info=None, summary=False, check_for_migration=False, check_icons=True): import re from qt.core import QT_VERSION_STR qt_major = QT_VERSION_STR.split('.')[0] m = importlib.import_module(f'PyQt{qt_major}.uic') from polyglot.io import PolyglotStringIO forms = find_forms(srcdir) if info is None: info = print num = 0 transdef_pat = re.compile(r'^\s+_translate\s+=\s+QtCore.QCoreApplication.translate$', flags=re.M) transpat = re.compile(r'_translate\s*\(.+?,\s+"(.+?)(?<!\\)"\)', re.DOTALL) # Ensure that people running from source have all their forms rebuilt for # the qt5 migration force_compile = os.environ.get('CALIBRE_FORCE_BUILD_UI_FORMS', '') in ('1', 'yes', 'true') if check_for_migration: from calibre.gui2 import gprefs force_compile |= not gprefs.get(f'migrated_forms_to_qt{qt_major}', False) icon_constructor_pat = re.compile(r'\s*\S+\s+=\s+QtGui.QIcon\(\)') icon_pixmap_adder_pat = re.compile(r'''(\S+?)\.addPixmap\(.+?(['"]):/images/([^'"]+)\2.+''') def icon_pixmap_sub(match): ans = match.group(1) + ' = QtGui.QIcon.ic(' + match.group(2) + match.group(3) + match.group(2) + ')' return ans for form in forms: compiled_form = form_to_compiled_form(form) if force_compile or not os.path.exists(compiled_form) or os.stat(form).st_mtime > os.stat(compiled_form).st_mtime: if not summary: info('\tCompiling form', form) buf = PolyglotStringIO() m.compileUi(form, buf) dat = buf.getvalue() dat = dat.replace('import images_rc', '') dat = transdef_pat.sub('', dat) dat = transpat.sub(r'_("\1")', dat) dat = dat.replace('_("MMM yyyy")', '"MMM yyyy"') dat = dat.replace('_("d MMM yyyy")', '"d MMM yyyy"') dat = icon_constructor_pat.sub('', dat) dat = icon_pixmap_adder_pat.sub(icon_pixmap_sub, dat) if not isinstance(dat, bytes): dat = dat.encode('utf-8') open(compiled_form, 'wb').write(dat) num += 1 if num: info('Compiled %d forms' % num) if check_icons: resource_dir = os.path.join(os.path.dirname(srcdir), 'resources') ensure_icons_built(resource_dir, force_compile, info) if check_for_migration and force_compile: gprefs.set(f'migrated_forms_to_qt{qt_major}', True)
3,603
Python
.py
78
37.897436
122
0.608039
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,577
users.py
kovidgoyal_calibre/src/calibre/srv/users.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import json import os import re from functools import lru_cache from threading import RLock import apsw from calibre import as_unicode from calibre.constants import config_dir from calibre.utils.config import from_json, to_json from calibre.utils.localization import _ from polyglot.builtins import iteritems def as_json(data): return json.dumps(data, ensure_ascii=False, default=to_json) def load_json(raw): try: return json.loads(raw, object_hook=from_json) except Exception: return {} @lru_cache(maxsize=1024) def parse_restriction(raw): r = load_json(raw) if not isinstance(r, dict): r = {} lr = r.get('library_restrictions', {}) if not isinstance(lr, dict): lr = {} r['allowed_library_names'] = frozenset(map(lambda x: x.lower(), r.get('allowed_library_names', ()))) r['blocked_library_names'] = frozenset(map(lambda x: x.lower(), r.get('blocked_library_names', ()))) r['library_restrictions'] = {k.lower(): v or '' for k, v in iteritems(lr)} return r def serialize_restriction(r): ans = {} for x in 'allowed_library_names blocked_library_names'.split(): v = r.get(x) if v: ans[x] = list(v) ans['library_restrictions'] = {l.lower(): v or '' for l, v in iteritems(r.get('library_restrictions', {}))} return json.dumps(ans) def validate_username(username): if re.sub(r'[-a-zA-Z_0-9 ]', '', username): return _('For maximum compatibility you should use only the letters A-Z,' ' the numbers 0-9, spaces, underscores and hyphens in the username') def validate_password(pw): if not pw: return _('Empty passwords are not allowed') try: pw = pw.encode('ascii', 'strict') except ValueError: return _('The password must contain only ASCII (English) characters and symbols') def create_user_data(pw, readonly=False, restriction=None): return { 'pw':pw, 'restriction':parse_restriction(restriction or '{}').copy(), 'readonly': readonly } def connect(path, exc_class=ValueError): try: return apsw.Connection(path) except apsw.CantOpenError as e: pdir = os.path.dirname(path) if os.path.isdir(pdir): raise exc_class(f'Failed to open userdb database at {path} with error: {as_unicode(e)}') try: os.makedirs(pdir) except OSError as e: raise exc_class(f'Failed to make directory for userdb database at {pdir} with error: {as_unicode(e)}') try: return apsw.Connection(path) except apsw.CantOpenError as e: raise exc_class(f'Failed to open userdb database at {path} with error: {as_unicode(e)}') class UserManager: lock = RLock() @property def conn(self): with self.lock: if self._conn is None: self._conn = connect(self.path) with self._conn: c = self._conn.cursor() uv = next(c.execute('PRAGMA user_version'))[0] if uv == 0: # We have to store the unhashed password, since the digest # auth scheme requires it. (Technically, one can store # a MD5 hash of the username+realm+password, but it has to be # without salt so it is trivially brute-forceable, anyway) # timestamp stores the ISO 8601 creation timestamp in UTC. c.execute(''' CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, pw TEXT NOT NULL, timestamp TEXT DEFAULT CURRENT_TIMESTAMP, session_data TEXT NOT NULL DEFAULT "{}", restriction TEXT NOT NULL DEFAULT "{}", readonly TEXT NOT NULL DEFAULT "n", misc_data TEXT NOT NULL DEFAULT "{}", UNIQUE(name) ); PRAGMA user_version=1; ''') c.close() return self._conn def __init__(self, path=None): self.path = os.path.join(config_dir, 'server-users.sqlite') if path is None else path self._conn = None def get_session_data(self, username): with self.lock: for data, in self.conn.cursor().execute( 'SELECT session_data FROM users WHERE name=?', (username,)): return load_json(data) return {} def set_session_data(self, username, data): with self.lock: conn = self.conn c = conn.cursor() data = as_json(data) if isinstance(data, bytes): data = data.decode('utf-8') c.execute('UPDATE users SET session_data=? WHERE name=?', (data, username)) def get(self, username): ' Get password for user, or None if user does not exist ' with self.lock: for pw, in self.conn.cursor().execute( 'SELECT pw FROM users WHERE name=?', (username,)): return pw def has_user(self, username): return self.get(username) is not None def validate_username(self, username): if self.has_user(username): return _('The username %s already exists') % username return validate_username(username) def validate_password(self, pw): return validate_password(pw) def add_user(self, username, pw, restriction=None, readonly=False): with self.lock: msg = self.validate_username(username) or self.validate_password(pw) if msg is not None: raise ValueError(msg) restriction = restriction or {} self.conn.cursor().execute( 'INSERT INTO users (name, pw, restriction, readonly) VALUES (?, ?, ?, ?)', (username, pw, serialize_restriction(restriction), ('y' if readonly else 'n'))) def remove_user(self, username): with self.lock: self.conn.cursor().execute('DELETE FROM users WHERE name=?', (username,)) return self.conn.changes() > 0 @property def all_user_names(self): with self.lock: return {x for x, in self.conn.cursor().execute( 'SELECT name FROM users')} @property def user_data(self): with self.lock: ans = {} for name, pw, restriction, readonly in self.conn.cursor().execute('SELECT name,pw,restriction,readonly FROM users'): ans[name] = create_user_data(pw, readonly.lower() == 'y', restriction) return ans @user_data.setter def user_data(self, users): with self.lock, self.conn: c = self.conn.cursor() remove = self.all_user_names - set(users) if remove: c.executemany('DELETE FROM users WHERE name=?', [(n,) for n in remove]) for name, data in iteritems(users): res = serialize_restriction(data['restriction']) r = 'y' if data['readonly'] else 'n' c.execute('UPDATE users SET pw=?, restriction=?, readonly=? WHERE name=?', (data['pw'], res, r, name)) if self.conn.changes() > 0: continue c.execute('INSERT INTO USERS (name, pw, restriction, readonly) VALUES (?, ?, ?, ?)', (name, data['pw'], res, r)) self.refresh() def refresh(self): pass # legacy compat def is_readonly(self, username): with self.lock: for readonly, in self.conn.cursor().execute( 'SELECT readonly FROM users WHERE name=?', (username,)): return readonly == 'y' return False def set_readonly(self, username, value): with self.lock: self.conn.cursor().execute( 'UPDATE users SET readonly=? WHERE name=?', ('y' if value else 'n', username)) def change_password(self, username, pw): with self.lock: msg = self.validate_password(pw) if msg is not None: raise ValueError(msg) self.conn.cursor().execute( 'UPDATE users SET pw=? WHERE name=?', (pw, username)) def restrictions(self, username): with self.lock: for restriction, in self.conn.cursor().execute( 'SELECT restriction FROM users WHERE name=?', (username,)): return parse_restriction(restriction).copy() def allowed_library_names(self, username, all_library_names): ' Get allowed library names for specified user from set of all library names ' r = self.restrictions(username) if r is None: return set() inc = r['allowed_library_names'] exc = r['blocked_library_names'] def check(n): n = n.lower() return (not inc or n in inc) and n not in exc return {n for n in all_library_names if check(n)} def update_user_restrictions(self, username, restrictions): if not isinstance(restrictions, dict): raise TypeError('restrictions must be a dict') with self.lock: self.conn.cursor().execute( 'UPDATE users SET restriction=? WHERE name=?', (serialize_restriction(restrictions), username)) def library_restriction(self, username, library_path): r = self.restrictions(username) if r is None: return '' library_name = os.path.basename(library_path).lower() return r['library_restrictions'].get(library_name) or ''
9,968
Python
.py
222
33.630631
128
0.578351
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,578
http_response.py
kovidgoyal_calibre/src/calibre/srv/http_response.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import errno import hashlib import os import struct import time import uuid from collections import namedtuple from functools import wraps from io import DEFAULT_BUFFER_SIZE, BytesIO from itertools import chain, repeat from operator import itemgetter from calibre import force_unicode, guess_type from calibre.constants import __version__ from calibre.srv.errors import HTTPSimpleResponse from calibre.srv.http_request import HTTPRequest, read_headers from calibre.srv.loop import WRITE from calibre.srv.utils import HTTP1, HTTP11, Cookie, MultiDict, get_translator_for_lang, http_date, socket_errors_socket_closed, sort_q_values from calibre.utils.monotonic import monotonic from calibre.utils.speedups import ReadOnlyFileBuffer from polyglot import http_client, reprlib from polyglot.builtins import error_message, iteritems, itervalues, reraise, string_or_bytes Range = namedtuple('Range', 'start stop size') MULTIPART_SEPARATOR = uuid.uuid4().hex if isinstance(MULTIPART_SEPARATOR, bytes): MULTIPART_SEPARATOR = MULTIPART_SEPARATOR.decode('ascii') COMPRESSIBLE_TYPES = {'application/json', 'application/javascript', 'application/xml', 'application/oebps-package+xml'} import zlib from itertools import zip_longest def file_metadata(fileobj): try: fd = fileobj.fileno() return os.fstat(fd) except Exception: pass def header_list_to_file(buf): # {{{ buf.append('') return ReadOnlyFileBuffer(b''.join((x + '\r\n').encode('ascii') for x in buf)) # }}} def parse_multipart_byterange(buf, content_type): # {{{ sep = (content_type.rsplit('=', 1)[-1]).encode('utf-8') ans = [] def parse_part(): line = buf.readline() if not line: raise ValueError('Premature end of message') if not line.startswith(b'--' + sep): raise ValueError('Malformed start of multipart message: %s' % reprlib.repr(line)) if line.endswith(b'--'): return None headers = read_headers(buf.readline) cr = headers.get('Content-Range') if not cr: raise ValueError('Missing Content-Range header in sub-part') if not cr.startswith('bytes '): raise ValueError('Malformed Content-Range header in sub-part, no prefix') try: start, stop = map(lambda x: int(x.strip()), cr.partition(' ')[-1].partition('/')[0].partition('-')[::2]) except Exception: raise ValueError('Malformed Content-Range header in sub-part, failed to parse byte range') content_length = stop - start + 1 ret = buf.read(content_length) if len(ret) != content_length: raise ValueError('Malformed sub-part, length of body not equal to length specified in Content-Range') buf.readline() return (start, ret) while True: data = parse_part() if data is None: break ans.append(data) return ans # }}} def parse_if_none_match(val): # {{{ return {x.strip() for x in val.split(',')} # }}} def acceptable_encoding(val, allowed=frozenset({'gzip'})): # {{{ for x in sort_q_values(val): x = x.lower() if x in allowed: return x # }}} def preferred_lang(val, get_translator_for_lang): # {{{ for x in sort_q_values(val): x = x.lower() found, lang, translator = get_translator_for_lang(x) if found: return x return 'en' # }}} def get_ranges(headervalue, content_length): # {{{ ''' Return a list of ranges from the Range header. If this function returns an empty list, it indicates no valid range was found. ''' if not headervalue: return None result = [] try: bytesunit, byteranges = headervalue.split("=", 1) except Exception: return None if bytesunit.strip() != 'bytes': return None for brange in byteranges.split(","): start, stop = (x.strip() for x in brange.split("-", 1)) if start: if not stop: stop = content_length - 1 try: start, stop = int(start), int(stop) except Exception: continue if start >= content_length: continue if stop < start: continue stop = min(stop, content_length - 1) result.append(Range(start, stop, stop - start + 1)) elif stop: # Negative subscript (last N bytes) try: stop = int(stop) except Exception: continue if stop > content_length: result.append(Range(0, content_length-1, content_length)) else: result.append(Range(content_length - stop, content_length - 1, stop)) return result # }}} # gzip transfer encoding {{{ def gzip_prefix(): # See http://www.gzip.org/zlib/rfc-gzip.html return b''.join(( b'\x1f\x8b', # ID1 and ID2: gzip marker b'\x08', # CM: compression method b'\x00', # FLG: none set # MTIME: 4 bytes, set to zero so as not to leak timezone information b'\0\0\0\0', b'\x02', # XFL: max compression, slowest algo b'\xff', # OS: unknown )) def compress_readable_output(src_file, compress_level=6): crc = zlib.crc32(b"") size = 0 zobj = zlib.compressobj(compress_level, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, zlib.Z_DEFAULT_STRATEGY) prefix_written = False while True: data = src_file.read(DEFAULT_BUFFER_SIZE) if not data: break size += len(data) crc = zlib.crc32(data, crc) data = zobj.compress(data) if not prefix_written: prefix_written = True data = gzip_prefix() + data yield data yield zobj.flush() + struct.pack(b"<L", crc & 0xffffffff) + struct.pack(b"<L", size) # }}} def get_range_parts(ranges, content_type, content_length): # {{{ def part(r): ans = ['--%s' % MULTIPART_SEPARATOR, 'Content-Range: bytes %d-%d/%d' % (r.start, r.stop, content_length)] if content_type: ans.append('Content-Type: %s' % content_type) ans.append('') return ('\r\n'.join(ans)).encode('ascii') return list(map(part, ranges)) + [('--%s--' % MULTIPART_SEPARATOR).encode('ascii')] # }}} class ETaggedFile: # {{{ def __init__(self, output, etag): self.output, self.etag = output, etag def fileno(self): return self.output.fileno() # }}} class RequestData: # {{{ cookies = {} username = None def __init__(self, method, path, query, inheaders, request_body_file, outheaders, response_protocol, static_cache, opts, remote_addr, remote_port, is_trusted_ip, translator_cache, tdir, forwarded_for, request_original_uri=None): (self.method, self.path, self.query, self.inheaders, self.request_body_file, self.outheaders, self.response_protocol, self.static_cache, self.translator_cache) = ( method, path, query, inheaders, request_body_file, outheaders, response_protocol, static_cache, translator_cache ) self.remote_addr, self.remote_port, self.is_trusted_ip = remote_addr, remote_port, is_trusted_ip self.forwarded_for = forwarded_for self.request_original_uri = request_original_uri self.opts = opts self.status_code = http_client.OK self.outcookie = Cookie() self.lang_code = self.gettext_func = self.ngettext_func = None self.set_translator(self.get_preferred_language()) self.tdir = tdir def generate_static_output(self, name, generator, content_type='text/html; charset=UTF-8'): ans = self.static_cache.get(name) if ans is None: ans = self.static_cache[name] = StaticOutput(generator()) ct = self.outheaders.get('Content-Type') if not ct: self.outheaders.set('Content-Type', content_type, replace_all=True) return ans def filesystem_file_with_custom_etag(self, output, *etag_parts): etag = hashlib.sha1() for i in etag_parts: etag.update(str(i).encode('utf-8')) return ETaggedFile(output, etag.hexdigest()) def filesystem_file_with_constant_etag(self, output, etag_as_hexencoded_string): return ETaggedFile(output, etag_as_hexencoded_string) def etagged_dynamic_response(self, etag, func, content_type='text/html; charset=UTF-8'): ' A response that is generated only if the etag does not match ' ct = self.outheaders.get('Content-Type') if not ct: self.outheaders.set('Content-Type', content_type, replace_all=True) if not etag.endswith('"'): etag = '"%s"' % etag return ETaggedDynamicOutput(func, etag) def read(self, size=-1): return self.request_body_file.read(size) def peek(self, size=-1): pos = self.request_body_file.tell() try: return self.read(size) finally: self.request_body_file.seek(pos) def get_translator(self, bcp_47_code): return get_translator_for_lang(self.translator_cache, bcp_47_code) def get_preferred_language(self): return preferred_lang(self.inheaders.get('Accept-Language'), self.get_translator) def _(self, text): return self.gettext_func(text) def ngettext(self, singular, plural, n): return self.ngettext_func(singular, plural, n) def set_translator(self, lang_code): if lang_code != self.lang_code: found, lang, t = self.get_translator(lang_code) self.lang_code = lang self.gettext_func = t.gettext self.ngettext_func = t.ngettext # }}} class ReadableOutput: def __init__(self, output, etag=None, content_length=None): self.src_file = output if content_length is None: self.src_file.seek(0, os.SEEK_END) self.content_length = self.src_file.tell() else: self.content_length = content_length self.etag = etag self.accept_ranges = True self.use_sendfile = False self.src_file.seek(0) def filesystem_file_output(output, outheaders, stat_result): etag = getattr(output, 'etag', None) if etag is None: oname = output.name or '' if not isinstance(oname, string_or_bytes): oname = str(oname) etag = hashlib.sha1((str(stat_result.st_mtime) + force_unicode(oname)).encode('utf-8')).hexdigest() else: output = output.output etag = '"%s"' % etag self = ReadableOutput(output, etag=etag, content_length=stat_result.st_size) self.name = output.name self.use_sendfile = True return self def dynamic_output(output, outheaders, etag=None): if isinstance(output, bytes): data = output else: data = output.encode('utf-8') ct = outheaders.get('Content-Type') if not ct: outheaders.set('Content-Type', 'text/plain; charset=UTF-8', replace_all=True) ans = ReadableOutput(ReadOnlyFileBuffer(data), etag=etag) ans.accept_ranges = False return ans class ETaggedDynamicOutput: def __init__(self, func, etag): self.func, self.etag = func, etag def __call__(self): return self.func() class GeneratedOutput: def __init__(self, output, etag=None): self.output = output self.content_length = None self.etag = etag self.accept_ranges = False class StaticOutput: def __init__(self, data): if isinstance(data, str): data = data.encode('utf-8') self.data = data self.etag = '"%s"' % hashlib.sha1(data).hexdigest() self.content_length = len(data) class HTTPConnection(HTTPRequest): use_sendfile = False def write(self, buf, end=None): pos = buf.tell() if end is None: buf.seek(0, os.SEEK_END) end = buf.tell() buf.seek(pos) limit = end - pos if limit <= 0: return True if self.use_sendfile and not isinstance(buf, (BytesIO, ReadOnlyFileBuffer)): limit = min(limit, 2 ** 30) try: sent = os.sendfile(self.socket.fileno(), buf.fileno(), pos, limit) except OSError as e: if e.errno in socket_errors_socket_closed: self.ready = self.use_sendfile = False return False if e.errno in (errno.EAGAIN, errno.EINTR): return False raise finally: self.last_activity = monotonic() if sent == 0: # Something bad happened, was the file modified on disk by # another process? self.use_sendfile = self.ready = False raise OSError('sendfile() failed to write any bytes to the socket') else: data = buf.read(min(limit, self.send_bufsize)) sent = self.send(data) buf.seek(pos + sent) return buf.tell() >= end def simple_response(self, status_code, msg='', close_after_response=True, extra_headers=None): if self.response_protocol is HTTP1: # HTTP/1.0 has no 413/414/303 codes status_code = { http_client.REQUEST_ENTITY_TOO_LARGE:http_client.BAD_REQUEST, http_client.REQUEST_URI_TOO_LONG:http_client.BAD_REQUEST, http_client.SEE_OTHER:http_client.FOUND }.get(status_code, status_code) self.close_after_response = close_after_response msg = msg.encode('utf-8') ct = 'http' if self.method == 'TRACE' else 'plain' buf = [ '%s %d %s' % (self.response_protocol, status_code, http_client.responses[status_code]), "Content-Length: %s" % len(msg), "Content-Type: text/%s; charset=UTF-8" % ct, "Date: " + http_date(), ] if self.close_after_response and self.response_protocol is HTTP11: buf.append("Connection: close") if extra_headers is not None: for h, v in iteritems(extra_headers): buf.append(f'{h}: {v}') buf.append('') buf = [(x + '\r\n').encode('ascii') for x in buf] if self.method != 'HEAD': buf.append(msg) response_data = b''.join(buf) self.log_access(status_code=status_code, response_size=len(response_data)) self.response_ready(ReadOnlyFileBuffer(response_data)) def prepare_response(self, inheaders, request_body_file): if self.method == 'TRACE': msg = force_unicode(self.request_line, 'utf-8') + '\n' + inheaders.pretty() return self.simple_response(http_client.OK, msg, close_after_response=False) request_body_file.seek(0) outheaders = MultiDict() data = RequestData( self.method, self.path, self.query, inheaders, request_body_file, outheaders, self.response_protocol, self.static_cache, self.opts, self.remote_addr, self.remote_port, self.is_trusted_ip, self.translator_cache, self.tdir, self.forwarded_for, self.request_original_uri ) self.queue_job(self.run_request_handler, data) def run_request_handler(self, data): result = self.request_handler(data) return data, result def send_range_not_satisfiable(self, content_length): buf = [ '%s %d %s' % ( self.response_protocol, http_client.REQUESTED_RANGE_NOT_SATISFIABLE, http_client.responses[http_client.REQUESTED_RANGE_NOT_SATISFIABLE]), "Date: " + http_date(), "Content-Range: bytes */%d" % content_length, ] response_data = header_list_to_file(buf) self.log_access(status_code=http_client.REQUESTED_RANGE_NOT_SATISFIABLE, response_size=response_data.sz) self.response_ready(response_data) def send_not_modified(self, etag=None): buf = [ '%s %d %s' % (self.response_protocol, http_client.NOT_MODIFIED, http_client.responses[http_client.NOT_MODIFIED]), "Content-Length: 0", "Date: " + http_date(), ] if etag is not None: buf.append('ETag: ' + etag) response_data = header_list_to_file(buf) self.log_access(status_code=http_client.NOT_MODIFIED, response_size=response_data.sz) self.response_ready(response_data) def report_busy(self): self.simple_response(http_client.SERVICE_UNAVAILABLE) def job_done(self, ok, result): if not ok: etype, e, tb = result if isinstance(e, HTTPSimpleResponse): eh = {} if e.location: eh['Location'] = e.location if e.authenticate: eh['WWW-Authenticate'] = e.authenticate if e.log: self.log.warn(e.log) return self.simple_response(e.http_code, msg=error_message(e) or '', close_after_response=e.close_connection, extra_headers=eh) reraise(etype, e, tb) data, output = result output = self.finalize_output(output, data, self.method is HTTP1) if output is None: return outheaders = data.outheaders outheaders.set('Date', http_date(), replace_all=True) outheaders.set('Server', 'calibre %s' % __version__, replace_all=True) keep_alive = not self.close_after_response and self.opts.timeout > 0 if keep_alive: outheaders.set('Keep-Alive', 'timeout=%d' % int(self.opts.timeout)) if 'Connection' not in outheaders: if self.response_protocol is HTTP11: if self.close_after_response: outheaders.set('Connection', 'close') else: if not self.close_after_response: outheaders.set('Connection', 'Keep-Alive') ct = outheaders.get('Content-Type', '') if ct.startswith('text/') and 'charset=' not in ct: outheaders.set('Content-Type', ct + '; charset=UTF-8', replace_all=True) buf = [HTTP11 + (' %d ' % data.status_code) + http_client.responses[data.status_code]] for header, value in sorted(iteritems(outheaders), key=itemgetter(0)): buf.append(f'{header}: {value}') for morsel in itervalues(data.outcookie): morsel['version'] = '1' x = morsel.output() if isinstance(x, bytes): x = x.decode('ascii') buf.append(x) buf.append('') response_data = ReadOnlyFileBuffer(b''.join((x + '\r\n').encode('ascii') for x in buf)) if self.access_log is not None: sz = outheaders.get('Content-Length') if sz is not None: sz = int(sz) + response_data.sz self.log_access(status_code=data.status_code, response_size=sz, username=data.username) self.response_ready(response_data, output=output) def log_access(self, status_code, response_size=None, username=None): if self.access_log is None: return if not self.opts.log_not_found and status_code == http_client.NOT_FOUND: return ff = self.forwarded_for if ff: ff = '[%s] ' % ff try: ts = time.strftime('%d/%b/%Y:%H:%M:%S %z') except Exception: ts = 'strftime() failed' line = '{} port-{} {}{} {} "{}" {} {}'.format( self.remote_addr, self.remote_port, ff or '', username or '-', ts, force_unicode(self.request_line or '', 'utf-8'), status_code, ('-' if response_size is None else response_size)) self.access_log(line) def response_ready(self, header_file, output=None): self.response_started = True self.optimize_for_sending_packet() self.use_sendfile = False self.set_state(WRITE, self.write_response_headers, header_file, output) def write_response_headers(self, buf, output, event): if self.write(buf): self.write_response_body(output) def write_response_body(self, output): if output is None or self.method == 'HEAD': self.reset_state() return if isinstance(output, ReadableOutput): self.use_sendfile = output.use_sendfile and self.opts.use_sendfile and hasattr(os, 'sendfile') and self.ssl_context is None # sendfile() does not work with SSL sockets since encryption has to # be done in userspace if output.ranges is not None: if isinstance(output.ranges, Range): r = output.ranges output.src_file.seek(r.start) self.set_state(WRITE, self.write_buf, output.src_file, end=r.stop + 1) else: self.set_state(WRITE, self.write_ranges, output.src_file, output.ranges, first=True) else: self.set_state(WRITE, self.write_buf, output.src_file) elif isinstance(output, GeneratedOutput): self.set_state(WRITE, self.write_iter, chain(output.output, repeat(None, 1))) else: raise TypeError('Unknown output type: %r' % output) def write_buf(self, buf, event, end=None): if self.write(buf, end=end): self.reset_state() def write_ranges(self, buf, ranges, event, first=False): r, range_part = next(ranges) if r is None: # EOF range part self.set_state(WRITE, self.write_buf, ReadOnlyFileBuffer(b'\r\n' + range_part)) else: buf.seek(r.start) self.set_state(WRITE, self.write_range_part, ReadOnlyFileBuffer((b'' if first else b'\r\n') + range_part + b'\r\n'), buf, r.stop + 1, ranges) def write_range_part(self, part_buf, buf, end, ranges, event): if self.write(part_buf): self.set_state(WRITE, self.write_range, buf, end, ranges) def write_range(self, buf, end, ranges, event): if self.write(buf, end=end): self.set_state(WRITE, self.write_ranges, buf, ranges) def write_iter(self, output, event): chunk = next(output) if chunk is None: self.set_state(WRITE, self.write_chunk, ReadOnlyFileBuffer(b'0\r\n\r\n'), output, last=True) else: if chunk: if not isinstance(chunk, bytes): chunk = chunk.encode('utf-8') chunk = ('%X\r\n' % len(chunk)).encode('ascii') + chunk + b'\r\n' self.set_state(WRITE, self.write_chunk, ReadOnlyFileBuffer(chunk), output) else: # Empty chunk, ignore it self.write_iter(output, event) def write_chunk(self, buf, output, event, last=False): if self.write(buf): if last: self.reset_state() else: self.set_state(WRITE, self.write_iter, output) def reset_state(self): ready = not self.close_after_response self.end_send_optimization() self.connection_ready() self.ready = ready def report_unhandled_exception(self, e, formatted_traceback): self.simple_response(http_client.INTERNAL_SERVER_ERROR) def finalize_output(self, output, request, is_http1): none_match = parse_if_none_match(request.inheaders.get('If-None-Match', '')) if isinstance(output, ETaggedDynamicOutput): matched = '*' in none_match or (output.etag and output.etag in none_match) if matched: if self.method in ('GET', 'HEAD'): self.send_not_modified(output.etag) else: self.simple_response(http_client.PRECONDITION_FAILED) return opts = self.opts outheaders = request.outheaders stat_result = file_metadata(output) if stat_result is not None: output = filesystem_file_output(output, outheaders, stat_result) if 'Content-Type' not in outheaders: output_name = output.name if not isinstance(output_name, string_or_bytes): output_name = str(output_name) mt = guess_type(output_name)[0] if mt: if mt in {'text/plain', 'text/html', 'application/javascript', 'text/css'}: mt += '; charset=UTF-8' outheaders['Content-Type'] = mt else: outheaders['Content-Type'] = 'application/octet-stream' elif isinstance(output, string_or_bytes): output = dynamic_output(output, outheaders) elif hasattr(output, 'read'): output = ReadableOutput(output) elif isinstance(output, StaticOutput): output = ReadableOutput(ReadOnlyFileBuffer(output.data), etag=output.etag, content_length=output.content_length) elif isinstance(output, ETaggedDynamicOutput): output = dynamic_output(output(), outheaders, etag=output.etag) else: output = GeneratedOutput(output) ct = outheaders.get('Content-Type', '').partition(';')[0] compressible = (not ct or ct.startswith('text/') or ct.startswith('image/svg') or ct.partition(';')[0] in COMPRESSIBLE_TYPES) compressible = (compressible and request.status_code == http_client.OK and (opts.compress_min_size > -1 and output.content_length >= opts.compress_min_size) and acceptable_encoding(request.inheaders.get('Accept-Encoding', '')) and not is_http1) accept_ranges = (not compressible and output.accept_ranges is not None and request.status_code == http_client.OK and not is_http1) ranges = get_ranges(request.inheaders.get('Range'), output.content_length) if output.accept_ranges and self.method in ('GET', 'HEAD') else None if_range = (request.inheaders.get('If-Range') or '').strip() if if_range and if_range != output.etag: ranges = None if ranges is not None and not ranges: return self.send_range_not_satisfiable(output.content_length) for header in ('Accept-Ranges', 'Content-Encoding', 'Transfer-Encoding', 'ETag', 'Content-Length'): outheaders.pop(header, all=True) matched = '*' in none_match or (output.etag and output.etag in none_match) if matched: if self.method in ('GET', 'HEAD'): self.send_not_modified(output.etag) else: self.simple_response(http_client.PRECONDITION_FAILED) return output.ranges = None if output.etag and self.method in ('GET', 'HEAD'): outheaders.set('ETag', output.etag, replace_all=True) if accept_ranges: outheaders.set('Accept-Ranges', 'bytes', replace_all=True) if compressible and not ranges: outheaders.set('Content-Encoding', 'gzip', replace_all=True) if getattr(output, 'content_length', None): outheaders.set('Calibre-Uncompressed-Length', '%d' % output.content_length) output = GeneratedOutput(compress_readable_output(output.src_file), etag=output.etag) if output.content_length is not None and not compressible and not ranges: outheaders.set('Content-Length', '%d' % output.content_length, replace_all=True) if compressible or output.content_length is None: outheaders.set('Transfer-Encoding', 'chunked', replace_all=True) if ranges: if len(ranges) == 1: r = ranges[0] outheaders.set('Content-Length', '%d' % r.size, replace_all=True) outheaders.set('Content-Range', 'bytes %d-%d/%d' % (r.start, r.stop, output.content_length), replace_all=True) output.ranges = r else: range_parts = get_range_parts(ranges, outheaders.get('Content-Type'), output.content_length) size = sum(map(len, range_parts)) + sum(r.size + 4 for r in ranges) outheaders.set('Content-Length', '%d' % size, replace_all=True) outheaders.set('Content-Type', 'multipart/byteranges; boundary=' + MULTIPART_SEPARATOR, replace_all=True) output.ranges = zip_longest(ranges, range_parts) request.status_code = http_client.PARTIAL_CONTENT return output def create_http_handler(handler=None, websocket_handler=None): from calibre.srv.web_socket import WebSocketConnection static_cache = {} translator_cache = {} if handler is None: def dummy_http_handler(data): return 'Hello' handler = dummy_http_handler @wraps(handler) def wrapper(*args, **kwargs): ans = WebSocketConnection(*args, **kwargs) ans.request_handler = handler ans.websocket_handler = websocket_handler ans.static_cache = static_cache ans.translator_cache = translator_cache return ans return wrapper
29,658
Python
.py
647
35.721793
153
0.604263
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,579
content.py
kovidgoyal_calibre/src/calibre/srv/content.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import base64 import errno import os import re from contextlib import suppress from functools import partial from io import BytesIO from json import load as load_json_file from threading import Lock from calibre import fit_image, guess_type, sanitize_file_name from calibre.constants import config_dir, iswindows from calibre.db.constants import RESOURCE_URL_SCHEME from calibre.db.errors import NoSuchFormat from calibre.ebooks.covers import cprefs, generate_cover, override_prefs, scale_cover, set_use_roman from calibre.ebooks.metadata import authors_to_string from calibre.ebooks.metadata.meta import set_metadata from calibre.ebooks.metadata.opf2 import metadata_to_opf from calibre.library.save_to_disk import find_plugboard from calibre.srv.errors import BookNotFound, HTTPBadRequest, HTTPNotFound from calibre.srv.routes import endpoint, json from calibre.srv.utils import get_db, get_use_roman, http_date from calibre.utils.config_base import tweaks from calibre.utils.date import timestampfromdt from calibre.utils.filenames import ascii_filename, atomic_rename, make_long_path_useable from calibre.utils.img import image_from_data, scale_image from calibre.utils.localization import _ from calibre.utils.resources import get_image_path as I from calibre.utils.resources import get_path as P from calibre.utils.shared_file import share_open from polyglot.binary import as_hex_unicode from polyglot.urllib import quote plugboard_content_server_value = 'content_server' plugboard_content_server_formats = ['epub', 'mobi', 'azw3'] update_metadata_in_fmts = frozenset(plugboard_content_server_formats) lock = Lock() # Get book formats/cover as a cached filesystem file {{{ rename_counter = 0 def reset_caches(): pass def open_for_write(fname): try: return share_open(fname, 'w+b') except OSError: try: os.makedirs(os.path.dirname(fname)) except OSError: pass return share_open(fname, 'w+b') def create_file_copy(ctx, rd, prefix, library_id, book_id, ext, mtime, copy_func, extra_etag_data=''): ''' We cannot copy files directly from the library folder to the output socket, as this can potentially lock the library for an extended period. So instead we copy out the data from the library folder into a temp folder. We make sure to only do this copy once, using the previous copy, if there have been no changes to the data for the file since the last copy. ''' global rename_counter # Avoid too many items in a single directory for performance base = os.path.join(rd.tdir, 'fcache', (('%x' % book_id)[-3:])) if iswindows: base = '\\\\?\\' + os.path.abspath(base) # Ensure fname is not too long for windows' API bname = f'{prefix}-{library_id}-{book_id:x}.{ext}' if '\\' in bname or '/' in bname: raise ValueError('File components must not contain path separators') fname = os.path.join(base, bname) used_cache = 'no' def safe_mtime(): with suppress(OSError): return os.path.getmtime(fname) mt = mtime if isinstance(mtime, (int, float)) else timestampfromdt(mtime) with lock: previous_mtime = safe_mtime() if previous_mtime is None or previous_mtime < mt: if previous_mtime is not None: # File exists and may be open, so we cannot change its # contents, as that would lead to corrupted downloads in any # clients that are currently downloading the file. if iswindows: # On windows in order to re-use bname, we have to rename it # before deleting it rename_counter += 1 dname = os.path.join(base, '_%x' % rename_counter) atomic_rename(fname, dname) os.remove(dname) else: os.remove(fname) ans = open_for_write(fname) copy_func(ans) ans.seek(0) else: try: ans = share_open(fname, 'rb') used_cache = 'yes' except OSError as err: if err.errno != errno.ENOENT: raise ans = open_for_write(fname) copy_func(ans) ans.seek(0) if ctx.testing: rd.outheaders['Used-Cache'] = used_cache rd.outheaders['Tempfile'] = as_hex_unicode(fname) return rd.filesystem_file_with_custom_etag(ans, prefix, library_id, book_id, mt, extra_etag_data) def write_generated_cover(db, book_id, width, height, destf): mi = db.get_metadata(book_id) set_use_roman(get_use_roman()) if height is None: prefs = cprefs else: ratio = height / float(cprefs['cover_height']) prefs = override_prefs(cprefs) scale_cover(prefs, ratio) cdata = generate_cover(mi, prefs=prefs) destf.write(cdata) def generated_cover(ctx, rd, library_id, db, book_id, width=None, height=None): prefix = 'generated-cover' if height is not None: prefix += f'-{width}x{height}' mtime = timestampfromdt(db.field_for('last_modified', book_id)) return create_file_copy(ctx, rd, prefix, library_id, book_id, 'jpg', mtime, partial(write_generated_cover, db, book_id, width, height)) def cover(ctx, rd, library_id, db, book_id, width=None, height=None): mtime = db.cover_last_modified(book_id) if mtime is None: return generated_cover(ctx, rd, library_id, db, book_id, width, height) prefix = 'cover' if width is None and height is None: def copy_func(dest): db.copy_cover_to(book_id, dest) else: prefix += f'-{width}x{height}' def copy_func(dest): buf = BytesIO() db.copy_cover_to(book_id, buf) quality = min(99, max(50, tweaks['content_server_thumbnail_compression_quality'])) data = scale_image(buf.getvalue(), width=width, height=height, compression_quality=quality)[-1] dest.write(data) return create_file_copy(ctx, rd, prefix, library_id, book_id, 'jpg', mtime, copy_func) def fname_for_content_disposition(fname, as_encoded_unicode=False): if as_encoded_unicode: # See https://tools.ietf.org/html/rfc6266 fname = sanitize_file_name(fname).encode('utf-8') fname = str(quote(fname)) else: fname = ascii_filename(fname).replace('"', '_') return fname def book_filename(rd, book_id, mi, fmt, as_encoded_unicode=False): au = authors_to_string(mi.authors or [_('Unknown')]) title = mi.title or _('Unknown') ext = (fmt or '').lower() fname = f'{title[:30]} - {au[:30]}_{book_id}.{ext}' fname = fname_for_content_disposition(fname, as_encoded_unicode) if ext == 'kepub' and 'Kobo Touch' in rd.inheaders.get('User-Agent', ''): fname = fname.replace('!', '_') fname += '.epub' return fname def book_fmt(ctx, rd, library_id, db, book_id, fmt): mdata = db.format_metadata(book_id, fmt) if not mdata: raise NoSuchFormat() mtime = mdata['mtime'] update_metadata = fmt in update_metadata_in_fmts extra_etag_data = '' if update_metadata: mi = db.get_metadata(book_id) mtime = max(mtime, mi.last_modified) # Get any plugboards for the Content server plugboards = db.pref('plugboards') if plugboards: cpb = find_plugboard(plugboard_content_server_value, fmt, plugboards) if cpb: # Transform the metadata via the plugboard newmi = mi.deepcopy_metadata() newmi.template_to_attribute(mi, cpb) mi = newmi extra_etag_data = repr(cpb) else: mi = db.get_proxy_metadata(book_id) def copy_func(dest): db.copy_format_to(book_id, fmt, dest) if update_metadata: if not mi.cover_data or not mi.cover_data[-1]: cdata = db.cover(book_id) if cdata: mi.cover_data = ('jpeg', cdata) set_metadata(dest, mi, fmt) dest.seek(0) cd = rd.query.get('content_disposition', 'attachment') rd.outheaders['Content-Disposition'] = '''{}; filename="{}"; filename*=utf-8''{}'''.format( cd, book_filename(rd, book_id, mi, fmt), book_filename(rd, book_id, mi, fmt, as_encoded_unicode=True)) return create_file_copy(ctx, rd, 'fmt', library_id, book_id, fmt, mtime, copy_func, extra_etag_data=extra_etag_data) # }}} @endpoint('/static/{+what}', auth_required=False, cache_control=24) def static(ctx, rd, what): if not what: raise HTTPNotFound() base = P('content-server', allow_user_override=False) path = os.path.abspath(os.path.join(base, *what.split('/'))) if not path.startswith(base) or ':' in what: raise HTTPNotFound('Naughty, naughty!') path = os.path.relpath(path, base).replace(os.sep, '/') path = P('content-server/' + path) try: return share_open(path, 'rb') except OSError: raise HTTPNotFound() @endpoint('/favicon.png', auth_required=False, cache_control=24) def favicon(ctx, rd): return share_open(I('lt.png'), 'rb') @endpoint('/apple-touch-icon.png', auth_required=False, cache_control=24) def apple_touch_icon(ctx, rd): return share_open(I('apple-touch-icon.png'), 'rb') @endpoint('/icon/{+which}', auth_required=False, cache_control=24) def icon(ctx, rd, which): sz = rd.query.get('sz') if sz != 'full': try: sz = int(rd.query.get('sz', 48)) except Exception: sz = 48 if which in {'', '_'}: raise HTTPNotFound() if which.startswith('_'): base = os.path.join(config_dir, 'tb_icons') path = os.path.abspath(os.path.join(base, *which[1:].split('/'))) if not path.startswith(base) or ':' in which: raise HTTPNotFound('Naughty, naughty!') else: base = P('images', allow_user_override=False) path = os.path.abspath(os.path.join(base, *which.split('/'))) if not path.startswith(base) or ':' in which: raise HTTPNotFound('Naughty, naughty!') path = os.path.relpath(path, base).replace(os.sep, '/') path = P('images/' + path) if sz == 'full': try: return share_open(path, 'rb') except OSError: raise HTTPNotFound() with lock: cached = os.path.join(rd.tdir, 'icons', '%d-%s.png' % (sz, which)) try: return share_open(cached, 'rb') except OSError: pass try: src = share_open(path, 'rb') except OSError: raise HTTPNotFound() with src: idata = src.read() img = image_from_data(idata) scaled, width, height = fit_image(img.width(), img.height(), sz, sz) if scaled: idata = scale_image(img, width, height, as_png=True)[-1] ans = open_for_write(cached) ans.write(idata) ans.seek(0) return ans @endpoint('/reader-background/{encoded_fname}', android_workaround=True) def reader_background(ctx, rd, encoded_fname): base = os.path.abspath(os.path.normapth(os.path.join(config_dir, 'viewer', 'background-images'))) fname = bytes.fromhex(encoded_fname) q = os.path.abspath(os.path.normpath(os.path.join(base, fname))) if not q.startswith(base): raise HTTPNotFound(f'Reader background {encoded_fname} not found') try: return share_open(make_long_path_useable(q), 'rb') except FileNotFoundError: raise HTTPNotFound(f'Reader background {encoded_fname} not found') @endpoint('/reader-profiles/get-all', postprocess=json) def get_all_reader_profiles(ctx, rd): from calibre.gui2.viewer.config import load_viewer_profiles which = 'user:' if rd.username: which += rd.username return load_viewer_profiles(which) @endpoint('/reader-profiles/save', methods={'POST'}, postprocess=json) def save_reader_profile(ctx, rd): try: data = load_json_file(rd.request_body_file) name, profile = data['name'], data['profile'] if not isinstance(profile, dict) and profile is not None: raise TypeError(f'profile must be a dict not {type(profile)}') except Exception as err: raise HTTPBadRequest(f'Invalid query: {err}') from calibre.gui2.viewer.config import save_viewer_profile which = 'user:' if rd.username: which += rd.username save_viewer_profile(name, profile, which) return True @endpoint('/get/{what}/{book_id}/{library_id=None}', android_workaround=True) def get(ctx, rd, what, book_id, library_id): book_id, rest = book_id.partition('_')[::2] try: book_id = int(book_id) except Exception: raise HTTPNotFound('Book with id %r does not exist' % book_id) db = get_db(ctx, rd, library_id) if db is None: raise HTTPNotFound('Library %r not found' % library_id) with db.safe_read_lock: if not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) library_id = db.server_library_id # in case library_id was None if what == 'thumb': sz = rd.query.get('sz') w, h = 60, 80 if sz is None: if rest: try: w, h = map(int, rest.split('_')) except Exception: pass elif sz == 'full': w = h = None elif 'x' in sz: try: w, h = map(int, sz.partition('x')[::2]) except Exception: pass else: try: w = h = int(sz) except Exception: pass return cover(ctx, rd, library_id, db, book_id, width=w, height=h) elif what == 'cover': return cover(ctx, rd, library_id, db, book_id) elif what == 'opf': mi = db.get_metadata(book_id, get_cover=False) rd.outheaders['Content-Type'] = 'application/oebps-package+xml; charset=UTF-8' rd.outheaders['Last-Modified'] = http_date(timestampfromdt(mi.last_modified)) return metadata_to_opf(mi) elif what == 'json': from calibre.srv.ajax import book_to_json data, last_modified = book_to_json(ctx, rd, db, book_id) rd.outheaders['Last-Modified'] = http_date(timestampfromdt(last_modified)) return json(ctx, rd, get, data) else: try: return book_fmt(ctx, rd, library_id, db, book_id, what.lower()) except NoSuchFormat: raise HTTPNotFound(f'No {what.lower()} format for the book {book_id!r}') def resource_hash_to_url(ctx, scheme, digest, library_id): kw = {'scheme': scheme, 'digest': digest} if library_id: kw['library_id'] = library_id return ctx.url_for('/get-note-resource', **kw) def _get_note(ctx, rd, db, field, item_id, library_id): note_data = db.notes_data_for(field, item_id) if not note_data: if db.get_item_name(field, item_id): return '' raise HTTPNotFound(f'Item {field!r}:{item_id!r} not found') note_data.pop('searchable_text', None) resources = note_data.pop('resource_hashes', None) if resources: import re html = note_data['doc'] def r(x): scheme, digest = x.split(':', 1) return f'{scheme}/{digest}' pat = re.compile(rf'{RESOURCE_URL_SCHEME}://({{}})'.format('|'.join(map(r, resources)))) def sub(m): s, d = m.group(1).split('/', 1) return resource_hash_to_url(ctx, s, d, library_id) note_data['doc'] = pat.sub(sub, html) rd.outheaders['Last-Modified'] = http_date(note_data['mtime']) return note_data['doc'] @endpoint('/get-note/{field}/{item_id}/{library_id=None}', types={'item_id': int}) def get_note(ctx, rd, field, item_id, library_id): ''' Get the note as text/html for the specified field and item id. ''' db = get_db(ctx, rd, library_id) if db is None: raise HTTPNotFound(f'Library {library_id} not found') html = _get_note(ctx, rd, db, field, item_id, library_id) rd.outheaders['Content-Type'] = 'text/html; charset=UTF-8' return html @endpoint('/get-note-from-item-val/{field}/{item}/{library_id=None}', postprocess=json) def get_note_from_val(ctx, rd, field, item, library_id): db = get_db(ctx, rd, library_id) if db is None: raise HTTPNotFound(f'Library {library_id} not found') item_id = db.get_item_id(field, item) if not item_id: raise HTTPNotFound(f'Item {field!r}:{item!r} not found') html = _get_note(ctx, rd, db, field, item_id, library_id) return {'item_id': item_id, 'html': html} @endpoint('/get-note-resource/{scheme}/{digest}/{library_id=None}') def get_note_resource(ctx, rd, scheme, digest, library_id): ''' Get the data for a resource in a field note, such as an image. ''' db = get_db(ctx, rd, library_id) if db is None: raise HTTPNotFound(f'Library {library_id} not found') d = db.get_notes_resource(f'{scheme}:{digest}') if not d: raise HTTPNotFound(f'Notes resource {scheme}:{digest} not found') name = d['name'] rd.outheaders['Content-Type'] = guess_type(name)[0] or 'application/octet-stream' rd.outheaders['Content-Disposition'] = '''inline; filename="{}"; filename*=utf-8''{}'''.format( fname_for_content_disposition(name), fname_for_content_disposition(name, as_encoded_unicode=True)) rd.outheaders['Last-Modified'] = http_date(d['mtime']) return d['data'] @endpoint('/set-note/{field}/{item_id}/{library_id=None}', needs_db_write=True, methods={'POST'}, types={'item_id': int}) def set_note(ctx, rd, field, item_id, library_id): ''' Set the note for a field as HTML + text + resources. ''' db = get_db(ctx, rd, library_id) if db is None: raise HTTPNotFound(f'Library {library_id} not found') try: data = load_json_file(rd.request_body_file) if not isinstance(data, dict): raise Exception('note data must be a dict') html, searchable_text, images = data['html'], data['searchable_text'], data['images'] except Exception as err: raise HTTPBadRequest(f'Invalid query: {err}') srv_replacements = {} db_replacements = {} resources = [] res_pat = re.compile(r'get-note-resource/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)') for key, img in images.items(): try: is_new_image = img['data'].startswith('data:') if is_new_image: d = img['data'].encode('ascii') idx = d.index(b',') d = memoryview(d)[idx:] img_data = base64.standard_b64decode(d) fname = img['filename'] else: m = res_pat.search(img['data']) scheme, digest = m.group(1), m.group(2) resources.append(f'{scheme}:{digest}') except Exception as err: raise HTTPBadRequest(f'Invalid query: {err}') if is_new_image: chash = db.add_notes_resource(img_data, fname) scheme, digest = chash.split(':', 1) resources.append(chash) srv_replacements[key] = resource_hash_to_url(ctx, scheme, digest, library_id) db_replacements[key] = f'{RESOURCE_URL_SCHEME}://{scheme}/{digest}' db_html = srv_html = html if db_replacements: db_html = re.sub('|'.join(map(re.escape, db_replacements)), lambda m: db_replacements[m.group()], html) if srv_replacements: srv_html = re.sub('|'.join(map(re.escape, srv_replacements)), lambda m: srv_replacements[m.group()], html) db.set_notes_for(field, item_id, db_html, searchable_text, resources) rd.outheaders['Content-Type'] = 'text/html; charset=UTF-8' return srv_html
20,233
Python
.py
457
36.133479
139
0.620048
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,580
errors.py
kovidgoyal_calibre/src/calibre/srv/errors.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import http.client as http_client class JobQueueFull(Exception): pass class RouteError(ValueError): pass class HTTPSimpleResponse(Exception): def __init__(self, http_code, http_message='', close_connection=False, location=None, authenticate=None, log=None): Exception.__init__(self, http_message) self.http_code = http_code self.close_connection = close_connection self.location = location self.authenticate = authenticate self.log = log class HTTPRedirect(HTTPSimpleResponse): def __init__(self, location, http_code=http_client.MOVED_PERMANENTLY, http_message='', close_connection=False): HTTPSimpleResponse.__init__(self, http_code, http_message, close_connection, location) class HTTPNotFound(HTTPSimpleResponse): def __init__(self, http_message='', close_connection=False): HTTPSimpleResponse.__init__(self, http_client.NOT_FOUND, http_message, close_connection) class HTTPAuthRequired(HTTPSimpleResponse): def __init__(self, payload, log=None): HTTPSimpleResponse.__init__(self, http_client.UNAUTHORIZED, authenticate=payload, log=log) class HTTPBadRequest(HTTPSimpleResponse): def __init__(self, message, close_connection=False): HTTPSimpleResponse.__init__(self, http_client.BAD_REQUEST, message, close_connection) class HTTPFailedDependency(HTTPSimpleResponse): def __init__(self, message, close_connection=False): HTTPSimpleResponse.__init__(self, http_client.FAILED_DEPENDENCY, message, close_connection) class HTTPPreconditionRequired(HTTPSimpleResponse): def __init__(self, message, close_connection=False): HTTPSimpleResponse.__init__(self, http_client.PRECONDITION_REQUIRED, message, close_connection) class HTTPUnprocessableEntity(HTTPSimpleResponse): def __init__(self, message, close_connection=False): HTTPSimpleResponse.__init__(self, http_client.UNPROCESSABLE_ENTITY, message, close_connection) class HTTPForbidden(HTTPSimpleResponse): def __init__(self, http_message='', close_connection=True, log=None): HTTPSimpleResponse.__init__(self, http_client.FORBIDDEN, http_message, close_connection, log=log) class HTTPInternalServerError(HTTPSimpleResponse): def __init__(self, http_message='', close_connection=True, log=None): HTTPSimpleResponse.__init__(self, http_client.INTERNAL_SERVER_ERROR, http_message, close_connection, log=log) class BookNotFound(HTTPNotFound): def __init__(self, book_id, db): HTTPNotFound.__init__(self, f'No book with id: {book_id} in library: {db.server_library_id}')
2,743
Python
.py
46
53.847826
119
0.738427
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,581
opts.py
kovidgoyal_calibre/src/calibre/srv/opts.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import errno import numbers import os from collections import OrderedDict, namedtuple from functools import partial from itertools import zip_longest from operator import attrgetter from calibre.constants import config_dir from calibre.utils.localization import _ from calibre.utils.lock import ExclusiveFile from polyglot.builtins import itervalues Option = namedtuple('Option', 'name default longdoc shortdoc choices') class Choices(frozenset): def __new__(cls, *args): self = super().__new__(cls, args) self.default = args[0] return self raw_options = ( _('Path to the SSL certificate file'), 'ssl_certfile', None, None, _('Path to the SSL private key file'), 'ssl_keyfile', None, None, _('Time (in seconds) after which an idle connection is closed'), 'timeout', 120.0, None, _('Time (in seconds) to wait for a response from the server when making queries'), 'ajax_timeout', 60.0, None, _('Total time in seconds to wait for clean shutdown'), 'shutdown_timeout', 5.0, None, _('Socket pre-allocation, for example, with systemd socket activation'), 'allow_socket_preallocation', True, None, _('Max. size of single HTTP header (in KB)'), 'max_header_line_size', 8.0, None, _('Max. allowed size for files uploaded to the server (in MB)'), 'max_request_body_size', 500.0, None, _('Minimum size for which responses use data compression (in bytes)'), 'compress_min_size', 1024, None, _('Number of worker threads used to process requests'), 'worker_count', 10, None, _('Maximum number of worker processes'), 'max_jobs', 0, _('Worker processes are launched as needed and used for large jobs such as preparing' ' a book for viewing, adding books, converting, etc. Normally, the max.' ' number of such processes is based on the number of CPU cores. You can' ' control it by this setting.'), _('Maximum time for worker processes'), 'max_job_time', 60, _('Maximum amount of time worker processes are allowed to run (in minutes). Set' ' to zero for no limit.'), _('The port on which to listen for connections'), 'port', 8080, None, _('A prefix to prepend to all URLs'), 'url_prefix', None, _('Useful if you wish to run this server behind a reverse proxy. For example use, /calibre as the URL prefix.'), _('Number of books to show in a single page'), 'num_per_page', 50, _('The number of books to show in a single page in the browser.'), _('Advertise OPDS feeds via BonJour'), 'use_bonjour', True, _('Advertise the OPDS feeds via the BonJour service, so that OPDS based' ' reading apps can detect and connect to the server automatically.'), _('Maximum number of books in OPDS feeds'), 'max_opds_items', 30, _('The maximum number of books that the server will return in a single' ' OPDS acquisition feed.'), _('Maximum number of ungrouped items in OPDS feeds'), 'max_opds_ungrouped_items', 100, _('Group items in categories such as author/tags by first letter when' ' there are more than this number of items. Set to zero to disable.'), _('The interface on which to listen for connections'), 'listen_on', None, _('The default is to listen on all available IPv6 and IPv4 interfaces. You can change this to, for' ' example, "127.0.0.1" to only listen for IPv4 connections from the local machine, or' ' to "0.0.0.0" to listen to all incoming IPv4 connections.'), _('Fallback to auto-detected interface'), 'fallback_to_detected_interface', True, _('If for some reason the server is unable to bind to the interface specified in' ' the listen_on option, then it will try to detect an interface that connects' ' to the outside world and bind to that.'), _('Zero copy file transfers for increased performance'), 'use_sendfile', True, _('This will use zero-copy in-kernel transfers when sending files over the network,' ' increasing performance. However, it can cause corrupted file transfers on some' ' broken filesystems. If you experience corrupted file transfers, turn it off.'), _('Max. log file size (in MB)'), 'max_log_size', 20, _('The maximum size of log files, generated by the server. When the log becomes larger' ' than this size, it is automatically rotated. Set to zero to disable log rotation.'), _('Log HTTP 404 (Not Found) requests'), 'log_not_found', True, _('Normally, the server logs all HTTP requests for resources that are not found.' ' This can generate a lot of log spam, if your server is targeted by bots.' ' Use this option to turn it off.'), _('Password based authentication to access the server'), 'auth', False, _('Normally, the server is unrestricted, allowing anyone to access it. You can' ' restrict access to predefined users with this option.'), _('Allow un-authenticated local connections to make changes'), 'local_write', False, _('Normally, if you do not turn on authentication, the server operates in' ' read-only mode, so as to not allow anonymous users to make changes to your' ' calibre libraries. This option allows anybody connecting from the same' ' computer as the server is running on to make changes. This is useful' ' if you want to run the server without authentication but still' ' use calibredb to make changes to your calibre libraries. Note that' ' turning on this option means any program running on the computer' ' can make changes to your calibre libraries.'), _('Allow un-authenticated connections from specific IP addresses to make changes'), 'trusted_ips', None, _('Normally, if you do not turn on authentication, the server operates in' ' read-only mode, so as to not allow anonymous users to make changes to your' ' calibre libraries. This option allows anybody connecting from the specified' ' IP addresses to make changes. Must be a comma separated list of address or network specifications.' ' This is useful if you want to run the server without authentication but still' ' use calibredb to make changes to your calibre libraries. Note that' ' turning on this option means anyone connecting from the specified IP addresses' ' can make changes to your calibre libraries.'), _('Path to user database'), 'userdb', None, _('Path to a file in which to store the user and password information. Normally a' ' file in the calibre configuration folder is used.'), _('Choose the type of authentication used'), 'auth_mode', Choices('auto', 'basic', 'digest'), _('Set the HTTP authentication mode used by the server. Set to "basic" if you are' ' putting this server behind an SSL proxy. Otherwise, leave it as "auto", which' ' will use "basic" if SSL is configured otherwise it will use "digest".'), _('Ban IP addresses that have repeated login failures'), 'ban_for', 0, _('Temporarily bans access for IP addresses that have repeated login failures for the' ' specified number of minutes. Useful to prevent attempts at guessing passwords. If' ' set to zero, no banning is done.'), _('Number of login failures for ban'), 'ban_after', 5, _('The number of login failures after which an IP address is banned'), _('Ignored user-defined metadata fields'), 'ignored_fields', None, _('Comma separated list of user-defined metadata fields that will not be displayed' ' by the Content server in the /opds and /mobile views. For example: {}').format( 'my_rating,my_tags'), _('Restrict displayed user-defined fields'), 'displayed_fields', None, _('Comma separated list of user-defined metadata fields that will be displayed' ' by the Content server in the /opds and /mobile views. If you specify this' ' option, any fields not in this list will not be displayed. For example: {}').format( 'my_rating,my_tags'), _('Choose the default book list mode'), 'book_list_mode', Choices('cover_grid', 'details_list', 'custom_list'), _('Set the default book list mode that will be used for new users. Individual users' ' can override the default in their own settings. The default is to use a cover grid.'), ) assert len(raw_options) % 4 == 0 options = [] def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) for shortdoc, name, default, doc in grouper(4, raw_options): choices = None if isinstance(default, Choices): choices = sorted(default) default = default.default options.append(Option(name, default, doc, shortdoc, choices)) options = OrderedDict([(o.name, o) for o in sorted(options, key=attrgetter('name'))]) del raw_options class Options: __slots__ = tuple(name for name in options) def __init__(self, **kwargs): for opt in itervalues(options): setattr(self, opt.name, kwargs.get(opt.name, opt.default)) def opt_to_cli_help(opt): ans = opt.shortdoc if not ans.endswith('.'): ans += '.' if opt.longdoc: ans += '\n\t' + opt.longdoc return ans def bool_callback(option, opt_str, value, parser, *args, **kwargs): setattr(parser.values, option.dest, opt_str.startswith('--enable-')) def boolean_option(add_option, opt): name = opt.name.replace('_', '-') help = opt_to_cli_help(opt) help += '\n' + (_('By default, this option is enabled.') if opt.default else _('By default, this option is disabled.')) add_option('--enable-' + name, '--disable-' + name, action='callback', callback=bool_callback, help=help) def opts_to_parser(usage): from calibre.utils.config import OptionParser parser = OptionParser(usage) for opt in itervalues(options): add_option = partial(parser.add_option, dest=opt.name, help=opt_to_cli_help(opt), default=opt.default) if opt.default is True or opt.default is False: boolean_option(add_option, opt) elif opt.choices: name = '--' + opt.name.replace('_', '-') add_option(name, choices=opt.choices) else: name = '--' + opt.name.replace('_', '-') otype = 'string' if isinstance(opt.default, numbers.Number): otype = type(opt.default).__name__ add_option(name, type=otype) return parser DEFAULT_CONFIG = os.path.join(config_dir, 'server-config.txt') def parse_config_file(path=DEFAULT_CONFIG): try: with ExclusiveFile(path) as f: raw = f.read().decode('utf-8') except OSError as err: if err.errno != errno.ENOENT: raise raw = '' ans = {} for line in raw.splitlines(): line = line.strip() if line.startswith('#'): continue key, rest = line.partition(' ')[::2] opt = options.get(key) if opt is None: continue val = rest if isinstance(opt.default, bool): val = val.lower() in ('true', 'yes', 'y') elif isinstance(opt.default, numbers.Number): try: val = type(opt.default)(rest) except Exception: raise ValueError(f'The value for {key}: {rest} is not a valid number') elif opt.choices: if rest not in opt.choices: raise ValueError(f'The value for {key}: {rest} is not valid') ans[key] = val return Options(**ans) def write_config_file(opts, path=DEFAULT_CONFIG): changed = {name:getattr(opts, name) for name in options if getattr(opts, name) != options[name].default} lines = [] for name in sorted(changed): o = options[name] lines.append('# ' + o.shortdoc) if o.longdoc: lines.append('# ' + o.longdoc) lines.append(f'{name} {changed[name]}') raw = '\n'.join(lines).encode('utf-8') with ExclusiveFile(path) as f: f.truncate() f.write(raw) def server_config(refresh=False): if refresh or not hasattr(server_config, 'ans'): server_config.ans = parse_config_file() return server_config.ans def change_settings(**kwds): new_opts = {} opts = server_config() for name in options: if name in kwds: new_opts[name] = kwds[name] else: new_opts[name] = getattr(opts, name) new_opts = server_config.ans = Options(**new_opts) write_config_file(new_opts)
12,784
Python
.py
268
41.496269
123
0.667256
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,582
bonjour.py
kovidgoyal_calibre/src/calibre/srv/bonjour.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' from threading import Event class BonJour: # {{{ def __init__(self, name='Books in calibre', service_type='_calibre._tcp', path='/opds', add_hostname=True, wait_for_stop=True): self.service_name = name self.wait_for_stop = wait_for_stop self.service_type = service_type self.add_hostname = add_hostname self.path = path self.shutdown = Event() self.stop = self.shutdown.set self.started = Event() self.stopped = Event() self.services = [] def start(self, loop): from calibre.utils.mdns import publish, unpublish, verify_ip_address ip_address, port = loop.bound_address[:2] prefix = loop.opts.url_prefix or '' mdns_services = ( (self.service_name, self.service_type, port, {'path':prefix + self.path}), ) if self.shutdown.is_set(): return self.services = [] for s in mdns_services: si = publish(*s, add_hostname=self.add_hostname, use_ip_address=verify_ip_address(ip_address) or None) self.services.append(si) loop.log(f'OPDS feeds advertised via BonJour at: {", ".join(si.parsed_addresses())} port: {port}') self.advertised_port = port self.started.set() self.shutdown.wait() for s in mdns_services: unpublish(*s, add_hostname=self.add_hostname, wait_for_stop=self.wait_for_stop) self.stopped.set() # }}}
1,586
Python
.py
37
34.486486
131
0.614286
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,583
pool.py
kovidgoyal_calibre/src/calibre/srv/pool.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import sys from threading import Thread from calibre.utils.monotonic import monotonic from polyglot.queue import Full, Queue class Worker(Thread): daemon = True def __init__(self, log, notify_server, num, request_queue, result_queue): self.request_queue, self.result_queue = request_queue, result_queue self.notify_server = notify_server self.log = log self.working = False Thread.__init__(self, name='ServerWorker%d' % num) def run(self): while True: x = self.request_queue.get() if x is None: break job_id, func = x self.working = True try: result = func() except Exception: self.handle_error(job_id) # must be a separate function to avoid reference cycles with sys.exc_info() else: self.result_queue.put((job_id, True, result)) finally: self.working = False try: self.notify_server() except Exception: self.log.exception('ServerWorker failed to notify server on job completion') def handle_error(self, job_id): self.result_queue.put((job_id, False, sys.exc_info())) class ThreadPool: def __init__(self, log, notify_server, count=10, queue_size=1000): self.request_queue, self.result_queue = Queue(queue_size), Queue(queue_size) self.workers = [Worker(log, notify_server, i, self.request_queue, self.result_queue) for i in range(count)] def start(self): for w in self.workers: w.start() def put_nowait(self, job_id, func): self.request_queue.put_nowait((job_id, func)) def get_nowait(self): return self.result_queue.get_nowait() def stop(self, wait_till): for w in self.workers: try: self.request_queue.put_nowait(None) except Full: break for w in self.workers: now = monotonic() if now >= wait_till: break w.join(wait_till - now) self.workers = [w for w in self.workers if w.is_alive()] @property def busy(self): return sum(int(w.working) for w in self.workers) @property def idle(self): return sum(int(not w.working) for w in self.workers) class PluginPool: def __init__(self, loop, plugins): self.workers = [] self.loop = loop for plugin in plugins: w = Thread(target=self.run_plugin, args=(plugin,), name=self.plugin_name(plugin)) w.daemon = True w.plugin = plugin self.workers.append(w) def plugin_name(self, plugin): return plugin.__class__.__name__ def run_plugin(self, plugin): try: plugin.start(self.loop) except Exception: self.loop.log.exception('Failed to start plugin:', self.plugin_name(plugin)) def start(self): for w in self.workers: w.start() def stop(self, wait_till): for w in self.workers: if w.is_alive(): try: w.plugin.stop() except Exception: self.loop.log.exception('Failed to stop plugin:', self.plugin_name(w.plugin)) for w in self.workers: left = wait_till - monotonic() if left > 0: w.join(left) else: break self.workers = [w for w in self.workers if w.is_alive()]
3,705
Python
.py
98
27.602041
118
0.573304
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,584
opds.py
kovidgoyal_calibre/src/calibre/srv/opds.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import hashlib from collections import OrderedDict, namedtuple from functools import partial from html5_parser import parse from lxml import etree from lxml.builder import ElementMaker from calibre import force_unicode, guess_type from calibre import prepare_string_for_xml as xml from calibre.constants import __appname__ from calibre.db.view import sanitize_sort_field_name from calibre.ebooks.metadata import authors_to_string, fmt_sidx, rating_to_stars from calibre.library.comments import comments_to_html from calibre.srv.errors import HTTPInternalServerError, HTTPNotFound from calibre.srv.http_request import parse_uri from calibre.srv.routes import endpoint from calibre.srv.utils import Offsets, get_library_data, http_date from calibre.utils.config import prefs from calibre.utils.date import as_utc, is_date_undefined, timestampfromdt from calibre.utils.icu import sort_key from calibre.utils.localization import _, ngettext from calibre.utils.search_query_parser import ParseException from calibre.utils.xml_parse import safe_xml_fromstring from polyglot.binary import as_hex_unicode, from_hex_unicode from polyglot.builtins import as_bytes, iteritems from polyglot.urllib import unquote_plus, urlencode def atom(ctx, rd, endpoint, output): rd.outheaders.set('Content-Type', 'application/atom+xml; charset=UTF-8', replace_all=True) rd.outheaders.set('Calibre-Instance-Id', force_unicode(prefs['installation_uuid'], 'utf-8'), replace_all=True) if isinstance(output, bytes): ans = output # Assume output is already UTF-8 XML elif isinstance(output, str): ans = output.encode('utf-8') else: ans = etree.tostring(output, encoding='utf-8', xml_declaration=True, pretty_print=True) return ans def format_tag_string(tags, sep, joinval=', '): if tags: tlist = tags if sep is None else [t.strip() for t in tags.split(sep)] else: tlist = [] tlist.sort(key=sort_key) return joinval.join(tlist) if tlist else '' # Vocabulary for building OPDS feeds {{{ DC_NS = 'http://purl.org/dc/terms/' E = ElementMaker(namespace='http://www.w3.org/2005/Atom', nsmap={ None : 'http://www.w3.org/2005/Atom', 'dc' : DC_NS, 'opds' : 'http://opds-spec.org/2010/catalog', }) FEED = E.feed TITLE = E.title ID = E.id ICON = E.icon def UPDATED(dt, *args, **kwargs): return E.updated(as_utc(dt).strftime('%Y-%m-%dT%H:%M:%S+00:00'), *args, **kwargs) LINK = partial(E.link, type='application/atom+xml') NAVLINK = partial(E.link, type='application/atom+xml;type=feed;profile=opds-catalog') def SEARCH_LINK(url_for, *args, **kwargs): kwargs['rel'] = 'search' kwargs['title'] = 'Search' kwargs['href'] = url_for('/opds/search', query='XXX').replace('XXX', '{searchTerms}') return LINK(*args, **kwargs) def AUTHOR(name, uri=None): args = [E.name(name)] if uri is not None: args.append(E.uri(uri)) return E.author(*args) SUBTITLE = E.subtitle def NAVCATALOG_ENTRY(url_for, updated, title, description, query): href = url_for('/opds/navcatalog', which=as_hex_unicode(query)) id_ = 'calibre-navcatalog:' + hashlib.sha1(as_bytes(href)).hexdigest() return E.entry( TITLE(title), ID(id_), UPDATED(updated), E.content(description, type='text'), NAVLINK(href=href) ) START_LINK = partial(NAVLINK, rel='start') UP_LINK = partial(NAVLINK, rel='up') FIRST_LINK = partial(NAVLINK, rel='first') LAST_LINK = partial(NAVLINK, rel='last') NEXT_LINK = partial(NAVLINK, rel='next', title='Next') PREVIOUS_LINK = partial(NAVLINK, rel='previous') def html_to_lxml(raw): raw = '<div>%s</div>'%raw root = parse(raw, keep_doctype=False, namespace_elements=False, maybe_xhtml=False, sanitize_names=True) root = next(root.iterdescendants('div')) root.set('xmlns', "http://www.w3.org/1999/xhtml") raw = etree.tostring(root, encoding='unicode') try: return safe_xml_fromstring(raw, recover=False) except: for x in root.iterdescendants(): remove = [] for attr in x.attrib: if ':' in attr: remove.append(attr) for a in remove: del x.attrib[a] raw = etree.tostring(root, encoding='unicode') try: return safe_xml_fromstring(raw, recover=False) except: from calibre.ebooks.oeb.parse_utils import _html4_parse return _html4_parse(raw) def CATALOG_ENTRY(item, item_kind, request_context, updated, catalog_name, ignore_count=False, add_kind=False): id_ = 'calibre:category:'+item.name iid = 'N' + item.name if item.id is not None: iid = 'I' + str(item.id) iid += ':'+item_kind href = request_context.url_for('/opds/category', category=as_hex_unicode(catalog_name), which=as_hex_unicode(iid)) link = NAVLINK(href=href) if ignore_count: count = '' else: count = ngettext('one book', '{} books', item.count).format(item.count) if item.use_sort_as_name: name = item.sort else: name = item.name return E.entry( TITLE(name + ('' if not add_kind else ' (%s)'%item_kind)), ID(id_), UPDATED(updated), E.content(count, type='text'), link ) def CATALOG_GROUP_ENTRY(item, category, request_context, updated): id_ = 'calibre:category-group:'+category+':'+item.text iid = item.text link = NAVLINK(href=request_context.url_for('/opds/categorygroup', category=as_hex_unicode(category), which=as_hex_unicode(iid))) return E.entry( TITLE(item.text), ID(id_), UPDATED(updated), E.content(ngettext('one item', '{} items', item.count).format(item.count), type='text'), link ) def ACQUISITION_ENTRY(book_id, updated, request_context): field_metadata = request_context.db.field_metadata mi = request_context.db.get_metadata(book_id) extra = [] if (mi.rating or 0) > 0: rating = rating_to_stars(mi.rating) extra.append(_('RATING: %s<br />')%rating) if mi.tags: extra.append(_('TAGS: %s<br />')%xml(format_tag_string(mi.tags, None))) if mi.series: extra.append(_('SERIES: %(series)s [%(sidx)s]<br />')% dict(series=xml(mi.series), sidx=fmt_sidx(float(mi.series_index)))) for key in filter(request_context.ctx.is_field_displayable, field_metadata.ignorable_field_keys()): name, val = mi.format_field(key) if val: fm = field_metadata[key] datatype = fm['datatype'] if datatype == 'text' and fm['is_multiple']: extra.append('%s: %s<br />'% (xml(name), xml(format_tag_string(val, fm['is_multiple']['ui_to_list'], joinval=fm['is_multiple']['list_to_ui'])))) elif datatype == 'comments' or (fm['datatype'] == 'composite' and fm['display'].get('contains_html', False)): extra.append('%s: %s<br />'%(xml(name), comments_to_html(str(val)))) else: extra.append('%s: %s<br />'%(xml(name), xml(str(val)))) if mi.comments: comments = comments_to_html(mi.comments) extra.append(comments) if extra: extra = html_to_lxml('\n'.join(extra)) ans = E.entry(TITLE(mi.title), E.author(E.name(authors_to_string(mi.authors))), ID('urn:uuid:' + mi.uuid), UPDATED(mi.last_modified), E.published(mi.timestamp.isoformat())) if mi.pubdate and not is_date_undefined(mi.pubdate): ans.append(ans.makeelement('{%s}date' % DC_NS)) ans[-1].text = mi.pubdate.isoformat() if len(extra): ans.append(E.content(extra, type='xhtml')) get = partial(request_context.ctx.url_for, '/get', book_id=book_id, library_id=request_context.library_id) if mi.formats: fm = mi.format_metadata for fmt in mi.formats: fmt = fmt.lower() mt = guess_type('a.'+fmt)[0] if mt: link = E.link(type=mt, href=get(what=fmt), rel="http://opds-spec.org/acquisition") ffm = fm.get(fmt.upper()) if ffm: link.set('length', str(ffm['size'])) link.set('mtime', ffm['mtime'].isoformat()) ans.append(link) ans.append(E.link(type='image/jpeg', href=get(what='cover'), rel="http://opds-spec.org/cover")) ans.append(E.link(type='image/jpeg', href=get(what='thumb'), rel="http://opds-spec.org/thumbnail")) ans.append(E.link(type='image/jpeg', href=get(what='cover'), rel="http://opds-spec.org/image")) ans.append(E.link(type='image/jpeg', href=get(what='thumb'), rel="http://opds-spec.org/image/thumbnail")) return ans # }}} default_feed_title = __appname__ + ' ' + _('Library') class Feed: # {{{ def __init__(self, id_, updated, request_context, subtitle=None, title=None, up_link=None, first_link=None, last_link=None, next_link=None, previous_link=None): self.base_href = request_context.url_for('/opds') self.root = \ FEED( TITLE(title or default_feed_title), AUTHOR(__appname__, uri='https://calibre-ebook.com'), ID(id_), ICON(request_context.ctx.url_for('/favicon.png')), UPDATED(updated), SEARCH_LINK(request_context.url_for), START_LINK(href=request_context.url_for('/opds')) ) if up_link: self.root.append(UP_LINK(href=up_link)) if first_link: self.root.append(FIRST_LINK(href=first_link)) if last_link: self.root.append(LAST_LINK(href=last_link)) if next_link: self.root.append(NEXT_LINK(href=next_link)) if previous_link: self.root.append(PREVIOUS_LINK(href=previous_link)) if subtitle: self.root.insert(1, SUBTITLE(subtitle)) # }}} class TopLevel(Feed): # {{{ def __init__(self, updated, # datetime object in UTC categories, request_context, id_='urn:calibre:main', subtitle=_('Books in your library') ): Feed.__init__(self, id_, updated, request_context, subtitle=subtitle) subc = partial(NAVCATALOG_ENTRY, request_context.url_for, updated) subcatalogs = [subc(_('By ')+title, _('Books sorted by ') + desc, q) for title, desc, q in categories] for x in subcatalogs: self.root.append(x) for library_id, library_name in sorted(iteritems(request_context.library_map), key=lambda item: sort_key(item[1])): id_ = 'calibre-library:' + library_id self.root.append(E.entry( TITLE(_('Library:') + ' ' + library_name), ID(id_), UPDATED(updated), E.content(_('Change calibre library to:') + ' ' + library_name, type='text'), NAVLINK(href=request_context.url_for('/opds', library_id=library_id)) )) # }}} class NavFeed(Feed): def __init__(self, id_, updated, request_context, offsets, page_url, up_url, title=None): kwargs = {'up_link': up_url} kwargs['first_link'] = page_url kwargs['last_link'] = page_url+'&offset=%d'%offsets.last_offset if offsets.offset > 0: kwargs['previous_link'] = \ page_url+'&offset=%d'%offsets.previous_offset if offsets.next_offset > -1: kwargs['next_link'] = \ page_url+'&offset=%d'%offsets.next_offset if title: kwargs['title'] = title Feed.__init__(self, id_, updated, request_context, **kwargs) class AcquisitionFeed(NavFeed): def __init__(self, id_, updated, request_context, items, offsets, page_url, up_url, title=None): NavFeed.__init__(self, id_, updated, request_context, offsets, page_url, up_url, title=title) for book_id in items: self.root.append(ACQUISITION_ENTRY(book_id, updated, request_context)) class CategoryFeed(NavFeed): def __init__(self, items, which, id_, updated, request_context, offsets, page_url, up_url, title=None): NavFeed.__init__(self, id_, updated, request_context, offsets, page_url, up_url, title=title) ignore_count = False if which == 'search': ignore_count = True for item in items: self.root.append(CATALOG_ENTRY( item, item.category, request_context, updated, which, ignore_count=ignore_count, add_kind=which != item.category)) class CategoryGroupFeed(NavFeed): def __init__(self, items, which, id_, updated, request_context, offsets, page_url, up_url, title=None): NavFeed.__init__(self, id_, updated, request_context, offsets, page_url, up_url, title=title) for item in items: self.root.append(CATALOG_GROUP_ENTRY(item, which, request_context, updated)) class RequestContext: def __init__(self, ctx, rd): self.db, self.library_id, self.library_map, self.default_library = get_library_data(ctx, rd) self.ctx, self.rd = ctx, rd def url_for(self, path, **kwargs): lid = kwargs.pop('library_id', self.library_id) ans = self.ctx.url_for(path, **kwargs) q = {'library_id':lid} ans += '?' + urlencode(q) return ans def allowed_book_ids(self): return self.ctx.allowed_book_ids(self.rd, self.db) @property def outheaders(self): return self.rd.outheaders @property def opts(self): return self.ctx.opts def last_modified(self): return self.db.last_modified() def get_categories(self, report_parse_errors=False): return self.ctx.get_categories(self.rd, self.db, report_parse_errors=report_parse_errors) def search(self, query): return self.ctx.search(self.rd, self.db, query) def get_acquisition_feed(rc, ids, offset, page_url, up_url, id_, sort_by='title', ascending=True, feed_title=None): if not ids: raise HTTPNotFound('No books found') with rc.db.safe_read_lock: sort_by = sanitize_sort_field_name(rc.db.field_metadata, sort_by) items = rc.db.multisort([(sort_by, ascending)], ids) max_items = rc.opts.max_opds_items offsets = Offsets(offset, max_items, len(items)) items = items[offsets.offset:offsets.offset+max_items] lm = rc.last_modified() rc.outheaders['Last-Modified'] = http_date(timestampfromdt(lm)) return AcquisitionFeed(id_, lm, rc, items, offsets, page_url, up_url, title=feed_title).root def get_all_books(rc, which, page_url, up_url, offset=0): try: offset = int(offset) except Exception: raise HTTPNotFound('Not found') if which not in ('title', 'newest'): raise HTTPNotFound('Not found') sort = 'timestamp' if which == 'newest' else 'title' ascending = which == 'title' feed_title = {'newest':_('Newest'), 'title': _('Title')}.get(which, which) feed_title = default_feed_title + ' :: ' + _('By %s') % feed_title ids = rc.allowed_book_ids() return get_acquisition_feed(rc, ids, offset, page_url, up_url, id_='calibre-all:'+sort, sort_by=sort, ascending=ascending, feed_title=feed_title) def get_navcatalog(request_context, which, page_url, up_url, offset=0): categories = request_context.get_categories() if which not in categories: raise HTTPNotFound('Category %r not found'%which) items = categories[which] updated = request_context.last_modified() category_meta = request_context.db.field_metadata meta = category_meta.get(which, {}) category_name = meta.get('name', which) feed_title = default_feed_title + ' :: ' + _('By %s') % category_name id_ = 'calibre-category-feed:'+which MAX_ITEMS = request_context.opts.max_opds_ungrouped_items if MAX_ITEMS > 0 and len(items) <= MAX_ITEMS: max_items = request_context.opts.max_opds_items offsets = Offsets(offset, max_items, len(items)) items = list(items)[offsets.offset:offsets.offset+max_items] ans = CategoryFeed(items, which, id_, updated, request_context, offsets, page_url, up_url, title=feed_title) else: Group = namedtuple('Group', 'text count') starts = set() for x in items: val = getattr(x, 'sort', x.name) if not val: val = 'A' starts.add(val[0].upper()) category_groups = OrderedDict() for x in sorted(starts, key=sort_key): category_groups[x] = len([y for y in items if getattr(y, 'sort', y.name).upper().startswith(x)]) items = [Group(x, y) for x, y in category_groups.items()] max_items = request_context.opts.max_opds_items offsets = Offsets(offset, max_items, len(items)) items = items[offsets.offset:offsets.offset+max_items] ans = CategoryGroupFeed(items, which, id_, updated, request_context, offsets, page_url, up_url, title=feed_title) request_context.outheaders['Last-Modified'] = http_date(timestampfromdt(updated)) return ans.root @endpoint('/opds', postprocess=atom) def opds(ctx, rd): rc = RequestContext(ctx, rd) db = rc.db try: categories = rc.get_categories(report_parse_errors=True) except ParseException as p: raise HTTPInternalServerError(p.msg) category_meta = db.field_metadata cats = [ (_('Newest'), _('Date'), 'Onewest'), (_('Title'), _('Title'), 'Otitle'), ] def getter(x): try: return category_meta[x]['name'].lower() except KeyError: return x fm = rc.db.field_metadata for category in sorted(categories, key=lambda x: sort_key(getter(x))): if fm.is_ignorable_field(category) and not rc.ctx.is_field_displayable(category): continue if len(categories[category]) == 0: continue if category in ('formats', 'identifiers'): continue meta = category_meta.get(category, None) if meta is None: continue cats.append((meta['name'], meta['name'], 'N'+category)) last_modified = db.last_modified() rd.outheaders['Last-Modified'] = http_date(timestampfromdt(last_modified)) return TopLevel(last_modified, cats, rc).root @endpoint('/opds/navcatalog/{which}', postprocess=atom) def opds_navcatalog(ctx, rd, which): try: offset = int(rd.query.get('offset', 0)) except Exception: raise HTTPNotFound('Not found') rc = RequestContext(ctx, rd) page_url = rc.url_for('/opds/navcatalog', which=which) up_url = rc.url_for('/opds') which = from_hex_unicode(which) type_ = which[0] which = which[1:] if type_ == 'O': return get_all_books(rc, which, page_url, up_url, offset=offset) elif type_ == 'N': return get_navcatalog(rc, which, page_url, up_url, offset=offset) raise HTTPNotFound('Not found') @endpoint('/opds/category/{category}/{which}', postprocess=atom) def opds_category(ctx, rd, category, which): try: offset = int(rd.query.get('offset', 0)) except Exception: raise HTTPNotFound('Not found') if not which or not category: raise HTTPNotFound('Not found') rc = RequestContext(ctx, rd) page_url = rc.url_for('/opds/category', which=which, category=category) up_url = rc.url_for('/opds/navcatalog', which=category) which, category = from_hex_unicode(which), from_hex_unicode(category) type_ = which[0] which = which[1:] if type_ == 'I': try: p = which.rindex(':') category = which[p+1:] which = which[:p] # This line will toss an exception for composite columns which = int(which[:p]) except Exception: # Might be a composite column, where we have the lookup key if not (category in rc.db.field_metadata and rc.db.field_metadata[category]['datatype'] == 'composite'): raise HTTPNotFound('Tag %r not found'%which) categories = rc.get_categories() if category not in categories: raise HTTPNotFound('Category %r not found'%which) if category == 'search': try: ids = rc.search('search:"%s"'%which) except Exception: raise HTTPNotFound('Search: %r not understood'%which) return get_acquisition_feed(rc, ids, offset, page_url, up_url, 'calibre-search:'+which) if type_ != 'I': raise HTTPNotFound('Non id categories not supported') q = category if q == 'news': q = 'tags' ids = rc.db.get_books_for_category(q, which) & rc.allowed_book_ids() sort_by = 'series' if category == 'series' else 'title' return get_acquisition_feed(rc, ids, offset, page_url, up_url, 'calibre-category:'+category+':'+str(which), sort_by=sort_by) @endpoint('/opds/categorygroup/{category}/{which}', postprocess=atom) def opds_categorygroup(ctx, rd, category, which): try: offset = int(rd.query.get('offset', 0)) except Exception: raise HTTPNotFound('Not found') if not which or not category: raise HTTPNotFound('Not found') rc = RequestContext(ctx, rd) categories = rc.get_categories() page_url = rc.url_for('/opds/categorygroup', category=category, which=which) category = from_hex_unicode(category) if category not in categories: raise HTTPNotFound('Category %r not found'%which) category_meta = rc.db.field_metadata meta = category_meta.get(category, {}) category_name = meta.get('name', which) which = from_hex_unicode(which) feed_title = default_feed_title + ' :: ' + (_('By {0} :: {1}').format(category_name, which)) owhich = as_hex_unicode('N'+category) up_url = rc.url_for('/opds/navcatalog', which=owhich) items = categories[category] def belongs(x, which): return getattr(x, 'sort', x.name).lower().startswith(which.lower()) items = [x for x in items if belongs(x, which)] if not items: raise HTTPNotFound('No items in group %r:%r'%(category, which)) updated = rc.last_modified() id_ = 'calibre-category-group-feed:'+category+':'+which max_items = rc.opts.max_opds_items offsets = Offsets(offset, max_items, len(items)) items = list(items)[offsets.offset:offsets.offset+max_items] rc.outheaders['Last-Modified'] = http_date(timestampfromdt(updated)) return CategoryFeed(items, category, id_, updated, rc, offsets, page_url, up_url, title=feed_title).root @endpoint('/opds/search/{query=""}', postprocess=atom) def opds_search(ctx, rd, query): try: offset = int(rd.query.get('offset', 0)) except Exception: raise HTTPNotFound('Not found') rc = RequestContext(ctx, rd) if query: path = parse_uri(rd.request_original_uri, parse_query=False, unquote_func=unquote_plus)[1] query = path[-1] if isinstance(query, bytes): query = query.decode('utf-8') try: ids = rc.search(query) except Exception: raise HTTPNotFound('Search: %r not understood'%query) page_url = rc.url_for('/opds/search', query=query) return get_acquisition_feed(rc, ids, offset, page_url, rc.url_for('/opds'), 'calibre-search:'+query)
24,031
Python
.py
529
37.245747
137
0.622959
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,585
http_request.py
kovidgoyal_calibre/src/calibre/srv/http_request.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import re from io import DEFAULT_BUFFER_SIZE, BytesIO from calibre import as_unicode, force_unicode from calibre.ptempfile import SpooledTemporaryFile from calibre.srv.errors import HTTPSimpleResponse from calibre.srv.loop import READ, WRITE, Connection from calibre.srv.utils import HTTP1, HTTP11, Accumulator, MultiDict from polyglot import http_client, reprlib from polyglot.builtins import error_message from polyglot.urllib import unquote protocol_map = {(1, 0):HTTP1, (1, 1):HTTP11} quoted_slash = re.compile(br'%2[fF]') HTTP_METHODS = {'HEAD', 'GET', 'PUT', 'POST', 'TRACE', 'DELETE', 'OPTIONS'} # Parse URI {{{ def parse_request_uri(uri): """Parse a Request-URI into (scheme, authority, path). Note that Request-URI's must be one of:: Request-URI = "*" | absoluteURI | abs_path | authority Therefore, a Request-URI which starts with a double forward-slash cannot be a "net_path":: net_path = "//" authority [ abs_path ] Instead, it must be interpreted as an "abs_path" with an empty first path segment:: abs_path = "/" path_segments path_segments = segment *( "/" segment ) segment = *pchar *( ";" param ) param = *pchar """ if uri == b'*': return None, None, uri i = uri.find(b'://') if i > 0 and b'?' not in uri[:i]: # An absoluteURI. # If there's a scheme (and it must be http or https), then: # http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query # ]] scheme, remainder = uri[:i].lower(), uri[i + 3:] authority, path = remainder.partition(b'/')[::2] path = b'/' + path return scheme, authority, path if uri.startswith(b'/'): # An abs_path. return None, None, uri else: # An authority. return None, uri, None def parse_uri(uri, parse_query=True, unquote_func=unquote): scheme, authority, path = parse_request_uri(uri) if path is None: raise HTTPSimpleResponse(http_client.BAD_REQUEST, "No path component") if b'#' in path: raise HTTPSimpleResponse(http_client.BAD_REQUEST, "Illegal #fragment in Request-URI.") if scheme: try: scheme = scheme.decode('ascii') except ValueError: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'Un-decodeable scheme') path, qs = path.partition(b'?')[::2] if parse_query: try: query = MultiDict.create_from_query_string(qs) except Exception: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'Unparseable query string') else: query = None try: path = '%2F'.join(unquote_func(x).decode('utf-8') for x in quoted_slash.split(path)) except ValueError as e: raise HTTPSimpleResponse(http_client.BAD_REQUEST, as_unicode(e)) path = tuple(filter(None, (x.replace('%2F', '/') for x in path.split('/')))) return scheme, path, query # }}} # HTTP Header parsing {{{ comma_separated_headers = { 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Accept-Ranges', 'Allow', 'Cache-Control', 'Connection', 'Content-Encoding', 'Content-Language', 'Expect', 'If-Match', 'If-None-Match', 'Pragma', 'Proxy-Authenticate', 'TE', 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Vary', 'Via', 'Warning', } decoded_headers = { 'Transfer-Encoding', 'Keep-Alive', 'Expect', 'WWW-Authenticate', 'Authorization', 'Sec-WebSocket-Key', 'Sec-WebSocket-Version', 'Sec-WebSocket-Protocol', } | comma_separated_headers uppercase_headers = {'WWW', 'TE'} def normalize_header_name(name): parts = [x.capitalize() for x in name.split('-')] q = parts[0].upper() if q in uppercase_headers: parts[0] = q if len(parts) == 3 and parts[1] == 'Websocket': parts[1] = 'WebSocket' return '-'.join(parts) class HTTPHeaderParser: ''' Parse HTTP headers. Use this class by repeatedly calling the created object with a single line at a time and checking the finished attribute. Can raise ValueError for malformed headers, in which case you should probably return BAD_REQUEST. Headers which are repeated are folded together using a comma if their specification so dictates. ''' __slots__ = ('hdict', 'lines', 'finished') def __init__(self): self.hdict = MultiDict() self.lines = [] self.finished = False def push(self, *lines): for line in lines: self(line) def __call__(self, line): 'Process a single line' def safe_decode(hname, value): try: return value.decode('utf-8') except UnicodeDecodeError: if hname in decoded_headers: raise return value def commit(): if not self.lines: return line = b' '.join(self.lines) del self.lines[:] k, v = line.partition(b':')[::2] key = normalize_header_name(k.strip().decode('ascii')) val = safe_decode(key, v.strip()) if not key or not val: raise ValueError('Malformed header line: %s' % reprlib.repr(line)) if key in comma_separated_headers: existing = self.hdict.pop(key) if existing is not None: val = existing + ', ' + val self.hdict[key] = val if self.finished: raise ValueError('Header block already terminated') if line == b'\r\n': # Normal end of headers commit() self.finished = True return if line and line[0] in b' \t': # It's a continuation line. if not self.lines: raise ValueError('Orphaned continuation line') self.lines.append(line.lstrip()) else: commit() self.lines.append(line) def read_headers(readline): p = HTTPHeaderParser() while not p.finished: p(readline()) return p.hdict # }}} class HTTPRequest(Connection): request_handler = None static_cache = None translator_cache = None def __init__(self, *args, **kwargs): Connection.__init__(self, *args, **kwargs) self.max_header_line_size = int(1024 * self.opts.max_header_line_size) self.max_request_body_size = int(1024 * 1024 * self.opts.max_request_body_size) self.forwarded_for = None self.request_original_uri = None def read(self, buf, endpos): size = endpos - buf.tell() if size > 0: data = self.recv(size) if data: buf.write(data) return len(data) >= size else: return False else: return True def readline(self, buf): line = self.read_buffer.readline() buf.append(line) if buf.total_length > self.max_header_line_size: self.simple_response(self.header_line_too_long_error_code) return if line.endswith(b'\n'): line = buf.getvalue() if not line.endswith(b'\r\n'): self.simple_response(http_client.BAD_REQUEST, 'HTTP requires CRLF line terminators') return return line if not line: # read buffer is empty, fill it self.fill_read_buffer() def connection_ready(self): 'Become ready to read an HTTP request' self.method = self.request_line = None self.response_protocol = self.request_protocol = HTTP1 self.forwarded_for = None self.path = self.query = None self.close_after_response = False self.header_line_too_long_error_code = http_client.REQUEST_URI_TOO_LONG self.response_started = False self.set_state(READ, self.parse_request_line, Accumulator(), first=True) def parse_request_line(self, buf, event, first=False): # {{{ line = self.readline(buf) if line is None: return self.request_line = line.rstrip() if line == b'\r\n': # Ignore a single leading empty line, as per RFC 2616 sec 4.1 if first: return self.set_state(READ, self.parse_request_line, Accumulator()) return self.simple_response(http_client.BAD_REQUEST, 'Multiple leading empty lines not allowed') try: method, uri, req_protocol = line.strip().split(b' ', 2) req_protocol = req_protocol.decode('ascii') rp = int(req_protocol[5]), int(req_protocol[7]) self.method = method.decode('ascii').upper() except Exception: return self.simple_response(http_client.BAD_REQUEST, "Malformed Request-Line") if self.method not in HTTP_METHODS: return self.simple_response(http_client.BAD_REQUEST, "Unknown HTTP method") try: self.request_protocol = protocol_map[rp] except KeyError: return self.simple_response(http_client.HTTP_VERSION_NOT_SUPPORTED) self.response_protocol = protocol_map[min((1, 1), rp)] self.request_original_uri = uri try: self.scheme, self.path, self.query = parse_uri(uri) except HTTPSimpleResponse as e: return self.simple_response(e.http_code, error_message(e), close_after_response=False) self.header_line_too_long_error_code = http_client.REQUEST_ENTITY_TOO_LARGE self.set_state(READ, self.parse_header_line, HTTPHeaderParser(), Accumulator()) # }}} @property def state_description(self): return 'State: {} Client: {}:{} Request: {}'.format( getattr(self.handle_event, '__name__', None), self.remote_addr, self.remote_port, force_unicode(getattr(self, 'request_line', 'WebSocketConnection'), 'utf-8')) def parse_header_line(self, parser, buf, event): line = self.readline(buf) if line is None: return try: parser(line) except ValueError: self.simple_response(http_client.BAD_REQUEST, 'Failed to parse header line') return if parser.finished: self.finalize_headers(parser.hdict) def finalize_headers(self, inheaders): request_content_length = int(inheaders.get('Content-Length', 0)) if request_content_length > self.max_request_body_size: return self.simple_response(http_client.REQUEST_ENTITY_TOO_LARGE, "The entity sent with the request exceeds the maximum " "allowed bytes (%d)." % self.max_request_body_size) # Persistent connection support if self.response_protocol is HTTP11: # Both server and client are HTTP/1.1 if inheaders.get("Connection", "") == "close": self.close_after_response = True else: # Either the server or client (or both) are HTTP/1.0 if inheaders.get("Connection", "") != "Keep-Alive": self.close_after_response = True # Transfer-Encoding support te = () if self.response_protocol is HTTP11: rte = inheaders.get("Transfer-Encoding") if rte: te = [x.strip().lower() for x in rte.split(",") if x.strip()] chunked_read = False if te: for enc in te: if enc == "chunked": chunked_read = True else: # Note that, even if we see "chunked", we must reject # if there is an extension we don't recognize. return self.simple_response(http_client.NOT_IMPLEMENTED, "Unknown transfer encoding: %r" % enc) if inheaders.get("Expect", '').lower() == "100-continue": buf = BytesIO((HTTP11 + " 100 Continue\r\n\r\n").encode('ascii')) return self.set_state(WRITE, self.write_continue, buf, inheaders, request_content_length, chunked_read) self.forwarded_for = inheaders.get('X-Forwarded-For') self.read_request_body(inheaders, request_content_length, chunked_read) def write_continue(self, buf, inheaders, request_content_length, chunked_read, event): if self.write(buf): self.read_request_body(inheaders, request_content_length, chunked_read) def read_request_body(self, inheaders, request_content_length, chunked_read): buf = SpooledTemporaryFile(prefix='rq-body-', max_size=DEFAULT_BUFFER_SIZE, dir=self.tdir) if chunked_read: self.set_state(READ, self.read_chunk_length, inheaders, Accumulator(), buf, [0]) else: if request_content_length > 0: self.set_state(READ, self.sized_read, inheaders, buf, request_content_length) else: self.prepare_response(inheaders, BytesIO()) def sized_read(self, inheaders, buf, request_content_length, event): if self.read(buf, request_content_length): self.prepare_response(inheaders, buf) def read_chunk_length(self, inheaders, line_buf, buf, bytes_read, event): line = self.readline(line_buf) if line is None: return bytes_read[0] += len(line) try: chunk_size = int(line.strip(), 16) except Exception: return self.simple_response(http_client.BAD_REQUEST, '%s is not a valid chunk size' % reprlib.repr(line.strip())) if bytes_read[0] + chunk_size + 2 > self.max_request_body_size: return self.simple_response(http_client.REQUEST_ENTITY_TOO_LARGE, 'Chunked request is larger than %d bytes' % self.max_request_body_size) if chunk_size == 0: self.set_state(READ, self.read_chunk_separator, inheaders, Accumulator(), buf, bytes_read, last=True) else: self.set_state(READ, self.read_chunk, inheaders, buf, chunk_size, buf.tell() + chunk_size, bytes_read) def read_chunk(self, inheaders, buf, chunk_size, end, bytes_read, event): if not self.read(buf, end): return bytes_read[0] += chunk_size self.set_state(READ, self.read_chunk_separator, inheaders, Accumulator(), buf, bytes_read) def read_chunk_separator(self, inheaders, line_buf, buf, bytes_read, event, last=False): line = self.readline(line_buf) if line is None: return if line != b'\r\n': return self.simple_response(http_client.BAD_REQUEST, 'Chunk does not have trailing CRLF') bytes_read[0] += len(line) if bytes_read[0] > self.max_request_body_size: return self.simple_response(http_client.REQUEST_ENTITY_TOO_LARGE, 'Chunked request is larger than %d bytes' % self.max_request_body_size) if last: self.prepare_response(inheaders, buf) else: self.set_state(READ, self.read_chunk_length, inheaders, Accumulator(), buf, bytes_read) def handle_timeout(self): if not hasattr(self, 'response_protocol') or self.response_started: # Either connection is not ready or a response has already bee # started return False self.simple_response(http_client.REQUEST_TIMEOUT) return True def write(self, buf, end=None): raise NotImplementedError() def simple_response(self, status_code, msg='', close_after_response=True): raise NotImplementedError() def prepare_response(self, inheaders, request_body_file): raise NotImplementedError()
15,867
Python
.py
350
35.745714
125
0.610669
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,586
cdb.py
kovidgoyal_calibre/src/calibre/srv/cdb.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> import os import shutil import time from functools import partial from io import BytesIO from calibre import as_unicode, sanitize_file_name from calibre.db.cli import module_for_cmd from calibre.ebooks.metadata.meta import get_metadata from calibre.srv.changes import books_added, books_deleted, metadata from calibre.srv.errors import HTTPBadRequest, HTTPForbidden, HTTPNotFound from calibre.srv.metadata import book_as_json from calibre.srv.routes import endpoint, json, msgpack_or_json from calibre.srv.utils import get_db, get_library_data from calibre.utils.imghdr import what from calibre.utils.localization import canonicalize_lang, reverse_lang_map_for_ui from calibre.utils.serialize import MSGPACK_MIME, json_loads, msgpack_loads from calibre.utils.speedups import ReadOnlyFileBuffer from polyglot.binary import from_base64_bytes from polyglot.builtins import iteritems receive_data_methods = {'GET', 'POST'} @endpoint('/cdb/cmd/{which}/{version=0}', postprocess=msgpack_or_json, methods=receive_data_methods, cache_control='no-cache') def cdb_run(ctx, rd, which, version): try: m = module_for_cmd(which) except ImportError: raise HTTPNotFound(f'No module named: {which}') if not getattr(m, 'readonly', False): ctx.check_for_write_access(rd) if getattr(m, 'version', 0) != int(version): raise HTTPNotFound(('The module {} is not available in version: {}.' 'Make sure the version of calibre used for the' ' server and calibredb match').format(which, version)) db = get_library_data(ctx, rd, strict_library_id=True)[0] if ctx.restriction_for(rd, db): raise HTTPForbidden('Cannot use the command-line db interface with a user who has per library restrictions') raw = rd.read() ct = rd.inheaders.get('Content-Type', all=True) ct = {x.lower().partition(';')[0] for x in ct} try: if MSGPACK_MIME in ct: args = msgpack_loads(raw) elif 'application/json' in ct: args = json_loads(raw) else: raise HTTPBadRequest('Only JSON or msgpack requests are supported') except Exception: raise HTTPBadRequest('args are not valid encoded data') if getattr(m, 'needs_srv_ctx', False): args = [ctx] + list(args) try: result = m.implementation(db, partial(ctx.notify_changes, db.backend.library_path), *args) except Exception as err: tb = '' if not getattr(err, 'suppress_traceback', False): import traceback tb = traceback.format_exc() return {'err': as_unicode(err), 'tb': tb} return {'result': result} @endpoint('/cdb/add-book/{job_id}/{add_duplicates}/{filename}/{library_id=None}', needs_db_write=True, postprocess=json, methods=receive_data_methods, cache_control='no-cache') def cdb_add_book(ctx, rd, job_id, add_duplicates, filename, library_id): ''' Add a file as a new book. The file contents must be in the body of the request. The response will also have the title/authors/languages read from the metadata of the file/filename. It will contain a `book_id` field specifying the id of the newly added book, or if add_duplicates is not specified and a duplicate was found, no book_id will be present, instead there will be a `duplicates` field specifying the title and authors for all duplicate matches. It will also return the value of `job_id` as the `id` field and `filename` as the `filename` field. ''' db = get_db(ctx, rd, library_id) if ctx.restriction_for(rd, db): raise HTTPForbidden('Cannot use the add book interface with a user who has per library restrictions') if not filename: raise HTTPBadRequest('An empty filename is not allowed') sfilename = sanitize_file_name(filename) fmt = os.path.splitext(sfilename)[1] fmt = fmt[1:] if fmt else None if not fmt: raise HTTPBadRequest('An filename with no extension is not allowed') if isinstance(rd.request_body_file, BytesIO): raise HTTPBadRequest('A request body containing the file data must be specified') add_duplicates = add_duplicates in ('y', '1') path = os.path.join(rd.tdir, sfilename) rd.request_body_file.seek(0) with open(path, 'wb') as f: shutil.copyfileobj(rd.request_body_file, f) from calibre.ebooks.metadata.worker import run_import_plugins path = run_import_plugins((path,), time.monotonic_ns(), rd.tdir)[0] with open(path, 'rb') as f: mi = get_metadata(f, stream_type=os.path.splitext(path)[1][1:], use_libprs_metadata=True) f.seek(0) nfmt = os.path.splitext(path)[1] fmt = nfmt[1:] if nfmt else fmt ids, duplicates = db.add_books([(mi, {fmt: f})], add_duplicates=add_duplicates) ans = {'title': mi.title, 'authors': mi.authors, 'languages': mi.languages, 'filename': filename, 'id': job_id} if ids: ans['book_id'] = ids[0] ctx.notify_changes(db.backend.library_path, books_added(ids)) else: ans['duplicates'] = [{'title': m.title, 'authors': m.authors} for m, _ in duplicates] return ans @endpoint('/cdb/delete-books/{book_ids}/{library_id=None}', needs_db_write=True, postprocess=json, methods=receive_data_methods, cache_control='no-cache') def cdb_delete_book(ctx, rd, book_ids, library_id): db = get_db(ctx, rd, library_id) if ctx.restriction_for(rd, db): raise HTTPForbidden('Cannot use the delete book interface with a user who has per library restrictions') try: ids = {int(x) for x in book_ids.split(',')} except Exception: raise HTTPBadRequest(f'invalid book_ids: {book_ids}') db.remove_books(ids) ctx.notify_changes(db.backend.library_path, books_deleted(ids)) return {} @endpoint('/cdb/set-cover/{book_id}/{library_id=None}', types={'book_id': int}, needs_db_write=True, postprocess=json, methods=receive_data_methods, cache_control='no-cache') def cdb_set_cover(ctx, rd, book_id, library_id): db = get_db(ctx, rd, library_id) if ctx.restriction_for(rd, db): raise HTTPForbidden('Cannot use the add book interface with a user who has per library restrictions') rd.request_body_file.seek(0) dirtied = db.set_cover({book_id: rd.request_body_file}) ctx.notify_changes(db.backend.library_path, metadata(dirtied)) return tuple(dirtied) def load_payload_data(rd): raw = rd.read() ct = rd.inheaders.get('Content-Type', all=True) ct = {x.lower().partition(';')[0] for x in ct} try: if MSGPACK_MIME in ct: return msgpack_loads(raw) elif 'application/json' in ct: return json_loads(raw) else: raise HTTPBadRequest('Only JSON or msgpack requests are supported') except Exception: raise HTTPBadRequest('Invalid encoded data') @endpoint('/cdb/set-fields/{book_id}/{library_id=None}', types={'book_id': int}, needs_db_write=True, postprocess=msgpack_or_json, methods=receive_data_methods, cache_control='no-cache') def cdb_set_fields(ctx, rd, book_id, library_id): db = get_db(ctx, rd, library_id) if ctx.restriction_for(rd, db): raise HTTPForbidden('Cannot use the set fields interface with a user who has per library restrictions') data = load_payload_data(rd) try: changes, loaded_book_ids = data['changes'], frozenset(map(int, data.get('loaded_book_ids', ()))) all_dirtied = bool(data.get('all_dirtied')) if not isinstance(changes, dict): raise TypeError('changes must be a dict') except Exception: raise HTTPBadRequest( '''Data must be of the form {'changes': {'title': 'New Title', ...}, 'loaded_book_ids':[book_id1, book_id2, ...]'}''') dirtied = set() cdata = changes.pop('cover', False) if cdata is not False: if cdata is not None: try: cdata = from_base64_bytes(cdata.split(',', 1)[-1]) except Exception: raise HTTPBadRequest('Cover data is not valid base64 encoded data') try: fmt = what(None, cdata) except Exception: fmt = None if fmt not in ('jpeg', 'png'): raise HTTPBadRequest('Cover data must be either JPEG or PNG') dirtied |= db.set_cover({book_id: cdata}) added_formats = changes.pop('added_formats', False) if added_formats: for data in added_formats: try: fmt = data['ext'].upper() except Exception: raise HTTPBadRequest('Format has no extension') if fmt: try: fmt_data = from_base64_bytes(data['data_url'].split(',', 1)[-1]) except Exception: raise HTTPBadRequest('Format data is not valid base64 encoded data') if db.add_format(book_id, fmt, ReadOnlyFileBuffer(fmt_data)): dirtied.add(book_id) removed_formats = changes.pop('removed_formats', False) if removed_formats: db.remove_formats({book_id: list(removed_formats)}) dirtied.add(book_id) for field, value in iteritems(changes): if field == 'languages' and value: rmap = reverse_lang_map_for_ui() def to_lang_code(x): return rmap.get(x, canonicalize_lang(x)) value = list(filter(None, map(to_lang_code, value))) dirtied |= db.set_field(field, {book_id: value}) ctx.notify_changes(db.backend.library_path, metadata(dirtied)) all_ids = dirtied if all_dirtied else (dirtied & loaded_book_ids) all_ids |= {book_id} return {bid: book_as_json(db, bid) for bid in all_ids} @endpoint('/cdb/copy-to-library/{target_library_id}/{library_id=None}', needs_db_write=True, postprocess=msgpack_or_json, methods=receive_data_methods, cache_control='no-cache') def cdb_copy_to_library(ctx, rd, target_library_id, library_id): db_src = get_db(ctx, rd, library_id) db_dest = get_db(ctx, rd, target_library_id) if ctx.restriction_for(rd, db_src) or ctx.restriction_for(rd, db_dest): raise HTTPForbidden('Cannot use the copy to library interface with a user who has per library restrictions') data = load_payload_data(rd) try: book_ids = {int(x) for x in data['book_ids']} move_books = bool(data.get('move', False)) preserve_date = bool(data.get('preserve_date', True)) duplicate_action = data.get('duplicate_action') or 'add' automerge_action = data.get('automerge_action') or 'overwrite' except Exception: raise HTTPBadRequest('Invalid encoded data, must be of the form: {book_ids: [id1, id2, ..]}') if duplicate_action not in ('add', 'add_formats_to_existing', 'ignore'): raise HTTPBadRequest('duplicate_action must be one of: add, add_formats_to_existing, ignore') if automerge_action not in ('overwrite', 'ignore', 'new record'): raise HTTPBadRequest('automerge_action must be one of: overwrite, ignore, new record') response = {} identical_books_data = None if duplicate_action != 'add': identical_books_data = db_dest.data_for_find_identical_books() to_remove = set() from calibre.db.copy_to_library import copy_one_book for book_id in book_ids: try: rdata = copy_one_book( book_id, db_src, db_dest, duplicate_action=duplicate_action, automerge_action=automerge_action, preserve_uuid=move_books, preserve_date=preserve_date, identical_books_data=identical_books_data) if move_books: to_remove.add(book_id) response[book_id] = {'ok': True, 'payload': rdata} except Exception: import traceback response[book_id] = {'ok': False, 'payload': traceback.format_exc()} if to_remove: db_src.remove_books(to_remove, permanent=True) return response
12,155
Python
.py
240
43.029167
126
0.66036
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,587
code.py
kovidgoyal_calibre/src/calibre/srv/code.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import hashlib import random import shutil import sys import zipfile from json import load as load_json_file from json import loads as json_loads from threading import Lock from calibre import as_unicode from calibre.constants import in_develop_mode from calibre.customize.ui import available_input_formats from calibre.db.view import sanitize_sort_field_name from calibre.srv.ajax import search_result from calibre.srv.errors import BookNotFound, HTTPBadRequest, HTTPForbidden, HTTPNotFound, HTTPRedirect from calibre.srv.last_read import last_read_cache from calibre.srv.metadata import book_as_json, categories_as_json, categories_settings, icon_map from calibre.srv.routes import endpoint, json from calibre.srv.utils import get_library_data, get_use_roman from calibre.utils.config import prefs, tweaks from calibre.utils.icu import numeric_sort_key, sort_key from calibre.utils.localization import _, get_lang, lang_code_for_user_manual, lang_map_for_ui, localize_website_link from calibre.utils.resources import get_path as P from calibre.utils.search_query_parser import ParseException from calibre.utils.serialize import json_dumps from polyglot.builtins import iteritems, itervalues POSTABLE = frozenset({'GET', 'POST', 'HEAD'}) @endpoint('', auth_required=True) # auth_required=True needed for Chrome: https://bugs.launchpad.net/calibre/+bug/1982060 def index(ctx, rd): if rd.opts.url_prefix and rd.request_original_uri: # We need a trailing slash for relative URLs to resolve correctly, for # example the link to the mobile page in index.html from urllib.parse import urlparse, urlunparse p = urlparse(rd.request_original_uri) if not p.path.endswith(b'/'): p = p._replace(path=p.path + b'/') raise HTTPRedirect(urlunparse(p).decode('utf-8')) ans_file = open(P('content-server/index-generated.html'), 'rb') if not in_develop_mode: return ans_file return ans_file.read().replace(b'__IN_DEVELOP_MODE__', b'1') @endpoint('/robots.txt', auth_required=False) def robots(ctx, rd): return b'User-agent: *\nDisallow: /' @endpoint('/ajax-setup', auth_required=False, cache_control='no-cache', postprocess=json) def ajax_setup(ctx, rd): auto_reload_port = getattr(rd.opts, 'auto_reload_port', 0) return { 'auto_reload_port': max(0, auto_reload_port), 'allow_console_print': bool(getattr(rd.opts, 'allow_console_print', False)), 'ajax_timeout': rd.opts.ajax_timeout, } print_lock = Lock() @endpoint('/console-print', methods=('POST', )) def console_print(ctx, rd): if not getattr(rd.opts, 'allow_console_print', False): raise HTTPForbidden('console printing is not allowed') with print_lock: print(rd.remote_addr, end=' ') stdout = getattr(sys.stdout, 'buffer', sys.stdout) shutil.copyfileobj(rd.request_body_file, stdout) stdout.flush() return '' def get_basic_query_data(ctx, rd): db, library_id, library_map, default_library = get_library_data(ctx, rd) skeys = db.field_metadata.sortable_field_keys() sorts, orders = [], [] for x in rd.query.get('sort', '').split(','): if x: s, o = x.rpartition('.')[::2] if o and not s: s, o = o, '' if o not in ('asc', 'desc'): o = 'asc' if s.startswith('_'): s = '#' + s[1:] s = sanitize_sort_field_name(db.field_metadata, s) if s in skeys: sorts.append(s), orders.append(o) if not sorts: sorts, orders = ['timestamp'], ['desc'] return library_id, db, sorts, orders, rd.query.get('vl') or '' def get_translations_data(): with zipfile.ZipFile( P('content-server/locales.zip', allow_user_override=False), 'r' ) as zf: names = set(zf.namelist()) lang = get_lang() if lang not in names: xlang = lang.split('_')[0].lower() if xlang in names: lang = xlang if lang in names: return zf.open(lang, 'r').read() def get_translations(): if not hasattr(get_translations, 'cached'): get_translations.cached = False data = get_translations_data() if data: get_translations.cached = json_loads(data) return get_translations.cached def custom_list_template(): ans = getattr(custom_list_template, 'ans', None) if ans is None: ans = { 'thumbnail': True, 'thumbnail_height': 140, 'height': 'auto', 'comments_fields': ['comments'], 'lines': [ _('<b>{title}</b> by {authors}'), _('{series_index} of <i>{series}</i>') + '|||{rating}', '{tags}', _('Date: {timestamp}') + '|||' + _('Published: {pubdate}') + '|||' + _('Publisher: {publisher}'), '', ] } custom_list_template.ans = ans return ans def book_exists(x, ctx, rd): try: db = ctx.get_library(rd, x['library_id']) if db is None: raise Exception('') except Exception: return False return bool(db.new_api.has_format(x['book_id'], x['format'])) def basic_interface_data(ctx, rd): ans = { 'username': rd.username, 'output_format': prefs['output_format'].upper(), 'input_formats': {x.upper(): True for x in available_input_formats()}, 'gui_pubdate_display_format': tweaks['gui_pubdate_display_format'], 'gui_timestamp_display_format': tweaks['gui_timestamp_display_format'], 'gui_last_modified_display_format': tweaks['gui_last_modified_display_format'], 'completion_mode': tweaks['completion_mode'], 'use_roman_numerals_for_series_number': get_use_roman(), 'translations': get_translations(), 'icon_map': icon_map(), 'icon_path': ctx.url_for('/icon', which=''), 'custom_list_template': getattr(ctx, 'custom_list_template', None) or custom_list_template(), 'search_the_net_urls': getattr(ctx, 'search_the_net_urls', None) or [], 'num_per_page': rd.opts.num_per_page, 'default_book_list_mode': rd.opts.book_list_mode, 'donate_link': localize_website_link('https://calibre-ebook.com/donate'), 'lang_code_for_user_manual': lang_code_for_user_manual(), } ans['library_map'], ans['default_library_id'] = ctx.library_info(rd) if ans['username']: ans['recently_read_by_user'] = tuple( x for x in last_read_cache().get_recently_read(ans['username']) if x['library_id'] in ans['library_map'] and book_exists(x, ctx, rd)) return ans @endpoint('/interface-data/update/{translations_hash=None}', postprocess=json) def update_interface_data(ctx, rd, translations_hash): ''' Return the interface data needed for the server UI ''' ans = basic_interface_data(ctx, rd) t = ans['translations'] if t and (t.get('hash') or translations_hash) and t.get('hash') == translations_hash: del ans['translations'] return ans def get_field_list(db): fieldlist = list(db.pref('book_display_fields', ())) names = frozenset(x[0] for x in fieldlist) available = frozenset(db.field_metadata.displayable_field_keys()) for field in available: if field not in names: fieldlist.append((field, True)) return [f for f, d in fieldlist if d and f in available] def get_library_init_data(ctx, rd, db, num, sorts, orders, vl): ans = {} with db.safe_read_lock: try: ans['search_result'] = search_result( ctx, rd, db, rd.query.get('search', ''), num, 0, ','.join(sorts), ','.join(orders), vl ) except ParseException: ans['search_result'] = search_result( ctx, rd, db, '', num, 0, ','.join(sorts), ','.join(orders), vl ) sf = db.field_metadata.ui_sortable_field_keys() sf.pop('ondevice', None) ans['sortable_fields'] = sorted( ((sanitize_sort_field_name(db.field_metadata, k), v) for k, v in iteritems(sf)), key=lambda field_name: sort_key(field_name[1]) ) ans['field_metadata'] = db.field_metadata.all_metadata() ans['virtual_libraries'] = db._pref('virtual_libraries', {}) ans['bools_are_tristate'] = db._pref('bools_are_tristate', True) ans['book_display_fields'] = get_field_list(db) ans['fts_enabled'] = db.is_fts_enabled() ans['book_details_vertical_categories'] = db._pref('book_details_vertical_categories', ()) ans['fields_that_support_notes'] = tuple(db._field_supports_notes()) mdata = ans['metadata'] = {} try: extra_books = { int(x) for x in rd.query.get('extra_books', '').split(',') } except Exception: extra_books = () for coll in (ans['search_result']['book_ids'], extra_books): for book_id in coll: if book_id not in mdata: data = book_as_json(db, book_id) if data is not None: mdata[book_id] = data return ans @endpoint('/interface-data/books-init', postprocess=json) def books(ctx, rd): ''' Get data to create list of books Optional: ?num=50&sort=timestamp.desc&library_id=<default library> &search=''&extra_books=''&vl='' ''' ans = {} try: num = int(rd.query.get('num', rd.opts.num_per_page)) except Exception: raise HTTPNotFound('Invalid number of books: %r' % rd.query.get('num')) library_id, db, sorts, orders, vl = get_basic_query_data(ctx, rd) ans = get_library_init_data(ctx, rd, db, num, sorts, orders, vl) ans['library_id'] = library_id return ans @endpoint('/interface-data/init', postprocess=json) def interface_data(ctx, rd): ''' Return the data needed to create the server UI as well as a list of books. Optional: ?num=50&sort=timestamp.desc&library_id=<default library> &search=''&extra_books=''&vl='' ''' ans = basic_interface_data(ctx, rd) ud = {} if rd.username: # Override session data with stored values for the authenticated user, # if any ud = ctx.user_manager.get_session_data(rd.username) lid = ud.get('library_id') if lid and lid in ans['library_map']: rd.query.set('library_id', lid) usort = ud.get('sort') if usort: rd.query.set('sort', usort) ans['library_id'], db, sorts, orders, vl = get_basic_query_data(ctx, rd) ans['user_session_data'] = ud try: num = int(rd.query.get('num', rd.opts.num_per_page)) except Exception: raise HTTPNotFound('Invalid number of books: %r' % rd.query.get('num')) ans.update(get_library_init_data(ctx, rd, db, num, sorts, orders, vl)) return ans @endpoint('/interface-data/newly-added', postprocess=json) def newly_added(ctx, rd): ''' Get newly added books. Optional: ?num=3&library_id=<default library> ''' db, library_id = get_library_data(ctx, rd)[:2] count = int(rd.query.get('num', 3)) nbids = ctx.newest_book_ids(rd, db, count=count) with db.safe_read_lock: titles = db._all_field_for('title', nbids) authors = db._all_field_for('authors', nbids) return {'library_id': library_id, 'books': nbids, 'titles': titles, 'authors': authors} @endpoint('/interface-data/more-books', postprocess=json, methods=POSTABLE) def more_books(ctx, rd): ''' Get more results from the specified search-query, which must be specified as JSON in the request body. Optional: ?num=50&library_id=<default library> ''' db, library_id = get_library_data(ctx, rd)[:2] try: num = int(rd.query.get('num', rd.opts.num_per_page)) except Exception: raise HTTPNotFound('Invalid number of books: %r' % rd.query.get('num')) try: search_query = load_json_file(rd.request_body_file) query, offset, sorts, orders, vl = search_query['query'], search_query[ 'offset' ], search_query['sort'], search_query['sort_order'], search_query['vl'] except KeyError as err: raise HTTPBadRequest('Search query missing key: %s' % as_unicode(err)) except Exception as err: raise HTTPBadRequest('Invalid query: %s' % as_unicode(err)) ans = {} with db.safe_read_lock: ans['search_result'] = search_result( ctx, rd, db, query, num, offset, sorts, orders, vl ) mdata = ans['metadata'] = {} for book_id in ans['search_result']['book_ids']: data = book_as_json(db, book_id) if data is not None: mdata[book_id] = data return ans @endpoint('/interface-data/set-session-data', postprocess=json, methods=POSTABLE) def set_session_data(ctx, rd): ''' Store session data persistently so that it is propagated automatically to new logged in clients ''' if rd.username: try: new_data = load_json_file(rd.request_body_file) if not isinstance(new_data, dict): raise Exception('session data must be a dict') except Exception as err: raise HTTPBadRequest('Invalid data: %s' % as_unicode(err)) ud = ctx.user_manager.get_session_data(rd.username) ud.update(new_data) ctx.user_manager.set_session_data(rd.username, ud) @endpoint('/interface-data/get-books', postprocess=json) def get_books(ctx, rd): ''' Get books for the specified query Optional: ?library_id=<default library>&num=50&sort=timestamp.desc&search=''&vl='' ''' library_id, db, sorts, orders, vl = get_basic_query_data(ctx, rd) try: num = int(rd.query.get('num', rd.opts.num_per_page)) except Exception: raise HTTPNotFound('Invalid number of books: %r' % rd.query.get('num')) searchq = rd.query.get('search', '') db = get_library_data(ctx, rd)[0] ans = {} mdata = ans['metadata'] = {} with db.safe_read_lock: try: ans['search_result'] = search_result( ctx, rd, db, searchq, num, 0, ','.join(sorts), ','.join(orders), vl ) except ParseException as err: # This must not be translated as it is used by the front end to # detect invalid search expressions raise HTTPBadRequest('Invalid search expression: %s' % as_unicode(err)) for book_id in ans['search_result']['book_ids']: data = book_as_json(db, book_id) if data is not None: mdata[book_id] = data return ans @endpoint('/interface-data/book-metadata/{book_id=0}', postprocess=json) def book_metadata(ctx, rd, book_id): ''' Get metadata for the specified book. If no book_id is specified, return metadata for a random book. Optional: ?library_id=<default library>&vl=<virtual library> ''' library_id, db, sorts, orders, vl = get_basic_query_data(ctx, rd) if not book_id: all_ids = ctx.allowed_book_ids(rd, db) book_id = random.choice(tuple(all_ids)) elif not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) data = book_as_json(db, book_id) if data is None: raise BookNotFound(book_id, db) data['id'] = book_id # needed for random book view (when book_id=0) return data @endpoint('/interface-data/tag-browser') def tag_browser(ctx, rd): ''' Get the Tag Browser serialized as JSON Optional: ?library_id=<default library>&sort_tags_by=name&partition_method=first letter &collapse_at=25&dont_collapse=&hide_empty_categories=&vl='' ''' db, library_id = get_library_data(ctx, rd)[:2] opts = categories_settings(rd.query, db, gst_container=tuple) vl = rd.query.get('vl') or '' etag = json_dumps([db.last_modified().isoformat(), rd.username, library_id, vl, list(opts)]) etag = hashlib.sha1(etag).hexdigest() def generate(): return json(ctx, rd, tag_browser, categories_as_json(ctx, rd, db, opts, vl)) return rd.etagged_dynamic_response(etag, generate) def all_lang_names(): ans = getattr(all_lang_names, 'ans', None) if ans is None: ans = all_lang_names.ans = tuple(sorted(itervalues(lang_map_for_ui()), key=numeric_sort_key)) return ans @endpoint('/interface-data/field-names/{field}', postprocess=json) def field_names(ctx, rd, field): ''' Get a list of all names for the specified field Optional: ?library_id=<default library> ''' if field == 'languages': ans = all_lang_names() else: db, library_id = get_library_data(ctx, rd)[:2] try: ans = tuple(sorted(db.all_field_names(field), key=numeric_sort_key)) except ValueError: raise HTTPNotFound(f'{field} is not a one-one or many-one field') return ans @endpoint('/interface-data/field-id-map/{field}', postprocess=json) def field_id_map(ctx, rd, field): ''' Get a map of all ids:names for the specified field Optional: ?library_id=<default library> ''' db, library_id = get_library_data(ctx, rd)[:2] try: return db.get_id_map(field) except ValueError: raise HTTPNotFound(f'{field} is not a one-one or many-one field')
17,651
Python
.py
410
35.617073
122
0.625116
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,588
last_read.py
kovidgoyal_calibre/src/calibre/srv/last_read.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net> import os from contextlib import suppress from threading import Lock from time import time_ns import apsw from calibre.constants import cache_dir creation_sql = ''' CREATE TABLE IF NOT EXISTS last_read_positions ( id INTEGER PRIMARY KEY AUTOINCREMENT, library_id TEXT NOT NULL, book INTEGER NOT NULL, format TEXT NOT NULL COLLATE NOCASE, user TEXT NOT NULL, cfi TEXT NOT NULL, epoch INTEGER NOT NULL, pos_frac REAL NOT NULL DEFAULT 0, tooltip TEXT NOT NULL, UNIQUE(user, library_id, book, format) ); CREATE INDEX IF NOT EXISTS users_id ON last_read_positions (user); ''' lock = Lock() class LastReadCache: def __init__(self, path='', limit=5): self.limit = limit self.conn = apsw.Connection(path or os.path.join(cache_dir(), 'srv-last-read.sqlite')) self.execute(creation_sql) def get(self, *args, **kw): ans = self.conn.cursor().execute(*args) if kw.get('all', True): return ans.fetchall() with suppress(StopIteration, IndexError): return next(ans)[0] def execute(self, sql, bindings=None): cursor = self.conn.cursor() return cursor.execute(sql, bindings) def add_last_read_position(self, library_id, book_id, fmt, user, cfi, pos_frac, tooltip): with lock, self.conn: if not cfi: self.execute( 'DELETE FROM last_read_positions WHERE library_id=? AND book=? AND format=? AND user=?', (library_id, book_id, fmt, user)) else: epoch = time_ns() self.execute( 'INSERT OR REPLACE INTO last_read_positions(library_id,book,format,user,cfi,epoch,pos_frac,tooltip) VALUES (?,?,?,?,?,?,?,?)', (library_id, book_id, fmt, user, cfi, epoch, pos_frac, tooltip)) items = tuple(self.get('SELECT id FROM last_read_positions WHERE user=? ORDER BY id DESC', (user,), all=True)) if len(items) > self.limit: self.execute('DELETE FROM last_read_positions WHERE user=? AND id <= ?', (user, items[self.limit][0])) return epoch def get_recently_read(self, user): with lock: ans = [] for library_id, book, fmt, cfi, epoch, pos_frac, tooltip in self.execute( 'SELECT library_id,book,format,cfi,epoch,pos_frac,tooltip FROM last_read_positions WHERE user=? ORDER BY epoch DESC', (user,) ): ans.append({ 'library_id': library_id, 'book_id': book, 'format': fmt, 'cfi': cfi, 'epoch':epoch, 'pos_frac':pos_frac, 'tooltip': tooltip, }) return ans path_cache = {} def last_read_cache(path=''): with lock: ans = path_cache.get(path) if ans is None: ans = path_cache[path] = LastReadCache(path) return ans
3,033
Python
.py
70
34.214286
146
0.605361
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,589
library_broker.py
kovidgoyal_calibre/src/calibre/srv/library_broker.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> import os from collections import OrderedDict, defaultdict from threading import RLock as Lock from calibre import filesystem_encoding from calibre.db.cache import Cache from calibre.db.legacy import LibraryDatabase, create_backend, set_global_state from calibre.utils.filenames import samefile as _samefile from calibre.utils.monotonic import monotonic from polyglot.builtins import iteritems, itervalues def gui_on_db_event(event_type, library_id, event_data): from calibre.gui2.ui import get_gui gui = get_gui() if gui is not None: gui.library_broker.on_db_event(event_type, library_id, event_data) def canonicalize_path(p): if isinstance(p, bytes): p = p.decode(filesystem_encoding) p = os.path.abspath(p).replace(os.sep, '/').rstrip('/') return os.path.normcase(p) def samefile(a, b): a, b = canonicalize_path(a), canonicalize_path(b) if a == b: return True return _samefile(a, b) def basename(path): while path and path[-1] in ('/' + os.sep): path = path[:-1] ans = os.path.basename(path) if not ans: # Can happen for a path like D:\ on windows if len(path) == 2 and path[1] == ':': ans = path[0] return ans or 'Library' def init_library(library_path, is_default_library): db = Cache( create_backend( library_path, load_user_formatter_functions=is_default_library)) db.init() return db def make_library_id_unique(library_id, existing): bname = library_id c = 0 while library_id in existing: c += 1 library_id = bname + ('%d' % c) return library_id def library_id_from_path(path, existing=frozenset()): library_id = basename(path).replace(' ', '_') return make_library_id_unique(library_id, existing) def correct_case_of_last_path_component(original_path): original_path = os.path.abspath(original_path) prefix, basename = os.path.split(original_path) q = basename.lower() try: equals = tuple(x for x in os.listdir(prefix) if x.lower() == q) except OSError: equals = () if len(equals) > 1: if basename not in equals: basename = equals[0] elif equals: basename = equals[0] return os.path.join(prefix, basename) def db_matches(db, library_id, library_path): db = db.new_api if getattr(db, 'server_library_id', object()) == library_id: return True dbpath = db.dbpath return samefile(dbpath, os.path.join(library_path, os.path.basename(dbpath))) class LibraryBroker: def __init__(self, libraries): self.lock = Lock() self.lmap = OrderedDict() self.library_name_map = {} self.original_path_map = {} seen = set() for original_path in libraries: path = canonicalize_path(original_path) if path in seen: continue is_samefile = False for s in seen: if samefile(s, path): is_samefile = True break seen.add(path) if is_samefile or not LibraryDatabase.exists_at(path): continue corrected_path = correct_case_of_last_path_component(original_path) library_id = library_id_from_path(corrected_path, self.lmap) self.lmap[library_id] = path self.library_name_map[library_id] = basename(corrected_path) self.original_path_map[path] = original_path self.loaded_dbs = {} self.category_caches, self.search_caches, self.tag_browser_caches = ( defaultdict(OrderedDict), defaultdict(OrderedDict), defaultdict(OrderedDict)) def get(self, library_id=None): with self: library_id = library_id or self.default_library if library_id in self.loaded_dbs: return self.loaded_dbs[library_id] path = self.lmap.get(library_id) if path is None: return try: self.loaded_dbs[library_id] = ans = self.init_library( path, library_id == self.default_library) ans.new_api.server_library_id = library_id except Exception: self.loaded_dbs[library_id] = None raise return ans def init_library(self, library_path, is_default_library): library_path = self.original_path_map.get(library_path, library_path) return init_library(library_path, is_default_library) def close(self): with self: for db in itervalues(self.loaded_dbs): getattr(db, 'close', lambda: None)() self.lmap, self.loaded_dbs = OrderedDict(), {} @property def default_library(self): return next(iter(self.lmap)) @property def library_map(self): with self: return self.library_name_map.copy() def allowed_libraries(self, filter_func): with self: allowed_names = filter_func( basename(l) for l in itervalues(self.lmap)) return OrderedDict(((lid, self.library_map[lid]) for lid, path in iteritems(self.lmap) if basename(path) in allowed_names)) def path_for_library_id(self, library_id): with self: lpath = self.lmap.get(library_id) if lpath is None: q = library_id.lower() for k, v in self.lmap.items(): if k.lower() == q: lpath = v break else: return return self.original_path_map.get(lpath) def __enter__(self): self.lock.acquire() def __exit__(self, *a): self.lock.release() EXPIRED_AGE = 300 # seconds def load_gui_libraries(gprefs=None): if gprefs is None: from calibre.utils.config import JSONConfig gprefs = JSONConfig('gui') stats = gprefs.get('library_usage_stats', {}) return sorted(stats, key=stats.get, reverse=True) def path_for_db(db): return db.new_api.backend.library_path class GuiLibraryBroker(LibraryBroker): def __init__(self, db): from calibre.gui2 import gprefs self.last_used_times = defaultdict(lambda: -EXPIRED_AGE) self.gui_library_id = None self.listening_for_db_events = False LibraryBroker.__init__(self, load_gui_libraries(gprefs)) self.gui_library_changed(db) def init_library(self, library_path, is_default_library): library_path = self.original_path_map.get(library_path, library_path) db = LibraryDatabase(library_path, is_second_db=True) if self.listening_for_db_events: db.new_api.add_listener(gui_on_db_event) return db def get(self, library_id=None): try: return getattr(LibraryBroker.get(self, library_id), 'new_api', None) finally: self.last_used_times[library_id or self.default_library] = monotonic() def start_listening_for_db_events(self): with self: self.listening_for_db_events = True for db in self.loaded_dbs.values(): db.new_api.add_listener(gui_on_db_event) def on_db_event(self, event_type, library_id, event_data): from calibre.gui2.ui import get_gui gui = get_gui() if gui is not None: with self: db = self.loaded_dbs.get(library_id) if db is not None: gui.event_in_db.emit(db, event_type, event_data) def get_library(self, original_library_path): library_path = canonicalize_path(original_library_path) with self: for library_id, path in iteritems(self.lmap): if samefile(library_path, path): db = self.loaded_dbs.get(library_id) if db is None: db = self.loaded_dbs[library_id] = self.init_library( path, False) db.new_api.server_library_id = library_id return db # A new library if library_path not in self.original_path_map: self.original_path_map[library_path] = original_library_path db = self.init_library(library_path, False) corrected_path = correct_case_of_last_path_component(original_library_path) library_id = library_id_from_path(corrected_path, self.lmap) db.new_api.server_library_id = library_id self.lmap[library_id] = library_path self.library_name_map[library_id] = basename(corrected_path) self.loaded_dbs[library_id] = db return db def prepare_for_gui_library_change(self, newloc): # Must be called with lock held for library_id, path in iteritems(self.lmap): db = self.loaded_dbs.get(library_id) if db is not None and samefile(newloc, path): if library_id == self.gui_library_id: # Have to reload db self.loaded_dbs.pop(library_id, None) return set_global_state(db) return db def gui_library_changed(self, db, olddb=None): # Must be called with lock held original_path = path_for_db(db) newloc = canonicalize_path(original_path) for library_id, path in iteritems(self.lmap): if samefile(newloc, path): self.loaded_dbs[library_id] = db self.gui_library_id = library_id break else: # A new library corrected_path = correct_case_of_last_path_component(original_path) library_id = self.gui_library_id = library_id_from_path(corrected_path, self.lmap) self.lmap[library_id] = newloc self.library_name_map[library_id] = basename(corrected_path) self.original_path_map[newloc] = original_path self.loaded_dbs[library_id] = db db.new_api.server_library_id = library_id if self.listening_for_db_events: db.new_api.add_listener(gui_on_db_event) if olddb is not None and samefile(path_for_db(olddb), path_for_db(db)): # This happens after a restore database, for example olddb.close(), olddb.break_cycles() self._prune_loaded_dbs() def is_gui_library(self, library_path): with self: if self.gui_library_id and self.gui_library_id in self.lmap: return samefile(library_path, self.lmap[self.gui_library_id]) return False def _prune_loaded_dbs(self): now = monotonic() for library_id in tuple(self.loaded_dbs): if library_id != self.gui_library_id and now - self.last_used_times[ library_id] > EXPIRED_AGE: db = self.loaded_dbs.pop(library_id, None) if db is not None: db.close() db.break_cycles() def prune_loaded_dbs(self): with self: self._prune_loaded_dbs() def unload_library(self, library_path): with self: path = canonicalize_path(library_path) for library_id, q in iteritems(self.lmap): if samefile(path, q): break else: return db = self.loaded_dbs.pop(library_id, None) if db is not None: db.close() db.break_cycles() def remove_library(self, path): with self: path = canonicalize_path(path) for library_id, q in iteritems(self.lmap): if samefile(path, q): break else: return self.lmap.pop(library_id, None), self.library_name_map.pop( library_id, None), self.original_path_map.pop(path, None) db = self.loaded_dbs.pop(library_id, None) if db is not None: db.close() db.break_cycles()
12,345
Python
.py
294
31.214286
94
0.591731
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,590
books.py
kovidgoyal_calibre/src/calibre/srv/books.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import errno import json as jsonlib import os import tempfile import time from functools import partial from hashlib import sha1 from threading import Lock, RLock from calibre.constants import cache_dir, iswindows from calibre.customize.ui import plugin_for_input_format from calibre.ebooks.metadata import authors_to_string from calibre.srv.errors import BookNotFound, HTTPNotFound from calibre.srv.last_read import last_read_cache from calibre.srv.metadata import book_as_json from calibre.srv.render_book import RENDER_VERSION from calibre.srv.routes import endpoint, json from calibre.srv.utils import get_db, get_library_data from calibre.utils.filenames import rmtree from calibre.utils.localization import _ from calibre.utils.resources import get_path as P from calibre.utils.serialize import json_dumps from polyglot.builtins import as_unicode, itervalues cache_lock = RLock() queued_jobs = {} failed_jobs = {} def abspath(x): x = os.path.abspath(x) if iswindows and not x.startswith('\\\\?\\'): x = '\\\\?\\' + os.path.abspath(x) return x _books_cache_dir = None def books_cache_dir(): global _books_cache_dir if _books_cache_dir: return _books_cache_dir base = abspath(os.path.join(cache_dir(), 'srvb')) for d in 'sf': try: os.makedirs(os.path.join(base, d)) except OSError as e: if e.errno != errno.EEXIST: raise _books_cache_dir = base return base def book_hash(library_uuid, book_id, fmt, size, mtime): raw = json_dumps((library_uuid, book_id, fmt.upper(), size, mtime, RENDER_VERSION)) return as_unicode(sha1(raw).hexdigest()) staging_cleaned = False def safe_remove(x, is_file=None): if is_file is None: is_file = os.path.isfile(x) try: os.remove(x) if is_file else rmtree(x, ignore_errors=True) except OSError: pass def queue_job(ctx, copy_format_to, bhash, fmt, book_id, size, mtime): global staging_cleaned tdir = os.path.join(books_cache_dir(), 's') if not staging_cleaned: staging_cleaned = True for x in os.listdir(tdir): safe_remove(os.path.join(tdir, x)) fd, pathtoebook = tempfile.mkstemp(prefix='', suffix=('.' + fmt.lower()), dir=tdir) with os.fdopen(fd, 'wb') as f: copy_format_to(f) tdir = tempfile.mkdtemp('', '', tdir) job_id = ctx.start_job(f'Render book {book_id} ({fmt})', 'calibre.srv.render_book', 'render', args=( pathtoebook, tdir, {'size':size, 'mtime':mtime, 'hash':bhash}), job_done_callback=job_done, job_data=(bhash, pathtoebook, tdir)) queued_jobs[bhash] = job_id return job_id last_final_clean_time = 0 def clean_final(interval=24 * 60 * 60): global last_final_clean_time now = time.time() if now - last_final_clean_time < interval: return last_final_clean_time = now fdir = os.path.join(books_cache_dir(), 'f') for x in os.listdir(fdir): try: tm = os.path.getmtime(os.path.join(fdir, x, 'calibre-book-manifest.json')) except OSError: continue if now - tm >= interval: # This book has not been accessed for a long time, delete it safe_remove(x) def job_done(job): with cache_lock: bhash, pathtoebook, tdir = job.data queued_jobs.pop(bhash, None) safe_remove(pathtoebook) if job.failed: failed_jobs[bhash] = (job.was_aborted, job.traceback) safe_remove(tdir, False) else: try: clean_final() dest = os.path.join(books_cache_dir(), 'f', bhash) safe_remove(dest, False) os.rename(tdir, dest) except Exception: import traceback failed_jobs[bhash] = (False, traceback.format_exc()) @endpoint('/book-manifest/{book_id}/{fmt}', postprocess=json, types={'book_id':int}) def book_manifest(ctx, rd, book_id, fmt): db, library_id = get_library_data(ctx, rd)[:2] force_reload = rd.query.get('force_reload') == '1' if plugin_for_input_format(fmt) is None: raise HTTPNotFound('The format %s cannot be viewed' % fmt.upper()) if not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) with db.safe_read_lock: fm = db.format_metadata(book_id, fmt, allow_cache=False) if not fm: raise HTTPNotFound(f'No {fmt} format for the book (id:{book_id}) in the library: {library_id}') size, mtime = map(int, (fm['size'], time.mktime(fm['mtime'].utctimetuple())*10)) bhash = book_hash(db.library_id, book_id, fmt, size, mtime) with cache_lock: mpath = abspath(os.path.join(books_cache_dir(), 'f', bhash, 'calibre-book-manifest.json')) if force_reload: safe_remove(mpath, True) try: os.utime(mpath, None) with open(mpath, 'rb') as f: ans = jsonlib.load(f) ans['metadata'] = book_as_json(db, book_id) user = rd.username or None ans['last_read_positions'] = db.get_last_read_positions(book_id, fmt, user) if user else [] ans['annotations_map'] = db.annotations_map_for_book(book_id, fmt, user_type='web', user=user or '*') return ans except OSError as e: if e.errno != errno.ENOENT: raise x = failed_jobs.pop(bhash, None) if x is not None: return {'aborted':x[0], 'traceback':x[1], 'job_status':'finished'} job_id = queued_jobs.get(bhash) if job_id is None: job_id = queue_job(ctx, partial(db.copy_format_to, book_id, fmt), bhash, fmt, book_id, size, mtime) status, result, tb, aborted = ctx.job_status(job_id) return {'aborted': aborted, 'traceback':tb, 'job_status':status, 'job_id':job_id} @endpoint('/book-file/{book_id}/{fmt}/{size}/{mtime}/{+name}', types={'book_id':int, 'size':int, 'mtime':int}) def book_file(ctx, rd, book_id, fmt, size, mtime, name): db, library_id = get_library_data(ctx, rd)[:2] if not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) bhash = book_hash(db.library_id, book_id, fmt, size, mtime) base = abspath(os.path.join(books_cache_dir(), 'f')) mpath = abspath(os.path.join(base, bhash, name)) if not mpath.startswith(base): raise HTTPNotFound(f'No book file with hash: {bhash} and name: {name}') try: return rd.filesystem_file_with_custom_etag(open(mpath, 'rb'), bhash, name) except OSError as e: if e.errno != errno.ENOENT: raise raise HTTPNotFound(f'No book file with hash: {bhash} and name: {name}') @endpoint('/book-get-last-read-position/{library_id}/{+which}', postprocess=json) def get_last_read_position(ctx, rd, library_id, which): ''' Get last read position data for the specified books, where which is of the form: book_id1-fmt1_book_id2-fmt2,... ''' db = get_db(ctx, rd, library_id) user = rd.username or None if not user: raise HTTPNotFound('login required for sync') ans = {} allowed_book_ids = ctx.allowed_book_ids(rd, db) for item in which.split('_'): book_id, fmt = item.partition('-')[::2] try: book_id = int(book_id) except Exception: continue if book_id not in allowed_book_ids: continue key = f'{book_id}:{fmt}' ans[key] = db.get_last_read_positions(book_id, fmt, user) return ans @endpoint('/book-set-last-read-position/{library_id}/{book_id}/{+fmt}', types={'book_id': int}, methods=('POST',)) def set_last_read_position(ctx, rd, library_id, book_id, fmt): db = get_db(ctx, rd, library_id) user = rd.username or None if not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) try: data = jsonlib.load(rd.request_body_file) device, cfi, pos_frac = data['device'], data['cfi'], data['pos_frac'] except Exception: raise HTTPNotFound('Invalid data') cfi = cfi or None db.set_last_read_position( book_id, fmt, user=user, device=device, cfi=cfi, pos_frac=pos_frac) if user: with db.safe_read_lock: tt = db._field_for('title', book_id) tt += ' ' + _('by') + ' ' + authors_to_string(db._field_for('authors', book_id)) last_read_cache().add_last_read_position(library_id, book_id, fmt, user, cfi, pos_frac, tt) rd.outheaders['Content-type'] = 'text/plain' return b'' @endpoint('/book-get-annotations/{library_id}/{+which}', postprocess=json) def get_annotations(ctx, rd, library_id, which): ''' Get annotations and last read position data for the specified books, where which is of the form: book_id1-fmt1_book_id2-fmt2,... ''' db = get_db(ctx, rd, library_id) user = rd.username or '*' ans = {} allowed_book_ids = ctx.allowed_book_ids(rd, db) for item in which.split('_'): book_id, fmt = item.partition('-')[::2] try: book_id = int(book_id) except Exception: continue if book_id not in allowed_book_ids: continue key = f'{book_id}:{fmt}' ans[key] = { 'last_read_positions': db.get_last_read_positions(book_id, fmt, user), 'annotations_map': db.annotations_map_for_book(book_id, fmt, user_type='web', user=user) if user else {} } return ans @endpoint('/book-update-annotations/{library_id}/{book_id}/{+fmt}', types={'book_id': int}, methods=('POST',)) def update_annotations(ctx, rd, library_id, book_id, fmt): db = get_db(ctx, rd, library_id) user = rd.username or '*' if not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) try: amap = jsonlib.load(rd.request_body_file) except Exception: raise HTTPNotFound('Invalid data') alist = [] for val in itervalues(amap): if val: alist.extend(val) db.merge_annotations_for_book(book_id, fmt, alist, user_type='web', user=user) return b'' mathjax_lock = Lock() mathjax_manifest = None def manifest_as_json(): return P('mathjax/manifest.json', data=True, allow_user_override=False) def get_mathjax_manifest(): global mathjax_manifest with mathjax_lock: if mathjax_manifest is None: mathjax_manifest = jsonlib.loads(manifest_as_json()) return mathjax_manifest @endpoint('/mathjax/{+which=""}', auth_required=False) def mathjax(ctx, rd, which): manifest = get_mathjax_manifest() if not which: return rd.etagged_dynamic_response(manifest['etag'], manifest_as_json, content_type='application/json; charset=UTF-8') if which not in manifest['files']: raise HTTPNotFound('No MathJax file named: %s' % which) path = os.path.abspath(P('mathjax/' + which, allow_user_override=False)) if not path.startswith(P('mathjax', allow_user_override=False)): raise HTTPNotFound('No MathJax file named: %s' % which) return rd.filesystem_file_with_constant_etag(open(path, 'rb'), manifest['etag'])
11,358
Python
.py
265
35.656604
126
0.629921
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,591
convert.py
kovidgoyal_calibre/src/calibre/srv/convert.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> import os import shutil import tempfile from threading import Lock from calibre.customize.ui import input_profiles, output_profiles, run_plugins_on_postconvert from calibre.db.errors import NoSuchBook from calibre.srv.changes import formats_added from calibre.srv.errors import BookNotFound, HTTPNotFound from calibre.srv.routes import endpoint, json from calibre.srv.utils import get_library_data from calibre.utils.localization import _ from calibre.utils.monotonic import monotonic from calibre.utils.shared_file import share_open from polyglot.builtins import iteritems receive_data_methods = {'GET', 'POST'} conversion_jobs = {} cache_lock = Lock() class JobStatus: def __init__(self, job_id, book_id, tdir, library_id, pathtoebook, conversion_data): self.job_id = job_id self.log = self.traceback = '' self.book_id = book_id self.output_path = os.path.join( tdir, 'output.' + conversion_data['output_fmt'].lower()) self.tdir = tdir self.library_id, self.pathtoebook = library_id, pathtoebook self.conversion_data = conversion_data self.running = self.ok = True self.last_check_at = monotonic() self.was_aborted = False def cleanup(self): safe_delete_tree(self.tdir) self.log = self.traceback = '' @property def current_status(self): try: with share_open(os.path.join(self.tdir, 'status'), 'rb') as f: lines = f.read().decode('utf-8').splitlines() except Exception: lines = () for line in reversed(lines): if line.endswith('|||'): p, msg = line.partition(':')[::2] percent = float(p) msg = msg[:-3] return percent, msg return 0, '' def expire_old_jobs(): now = monotonic() with cache_lock: remove = [job_id for job_id, job_status in iteritems(conversion_jobs) if now - job_status.last_check_at >= 360] for job_id in remove: job_status = conversion_jobs.pop(job_id) job_status.cleanup() def safe_delete_file(path): try: os.remove(path) except OSError: pass def safe_delete_tree(path): try: shutil.rmtree(path, ignore_errors=True) except OSError: pass def job_done(job): with cache_lock: try: job_status = conversion_jobs[job.job_id] except KeyError: return job_status.running = False if job.failed: job_status.ok = False job_status.log = job.read_log() job_status.was_aborted = job.was_aborted job_status.traceback = job.traceback safe_delete_file(job_status.pathtoebook) def convert_book(path_to_ebook, opf_path, cover_path, output_fmt, recs): from calibre.customize.conversion import OptionRecommendation from calibre.ebooks.conversion.plumber import Plumber from calibre.utils.logging import Log recs.append(('verbose', 2, OptionRecommendation.HIGH)) recs.append(('read_metadata_from_opf', opf_path, OptionRecommendation.HIGH)) if cover_path: recs.append(('cover', cover_path, OptionRecommendation.HIGH)) log = Log() os.chdir(os.path.dirname(path_to_ebook)) status_file = share_open('status', 'wb') def notification(percent, msg=''): status_file.write(f'{percent}:{msg}|||\n'.encode()) status_file.flush() output_path = os.path.abspath('output.' + output_fmt.lower()) plumber = Plumber(path_to_ebook, output_path, log, report_progress=notification, override_input_metadata=True) plumber.merge_ui_recommendations(recs) plumber.run() def queue_job(ctx, rd, library_id, db, fmt, book_id, conversion_data): from calibre.customize.conversion import OptionRecommendation from calibre.ebooks.conversion.config import GuiRecommendations, save_specifics from calibre.ebooks.metadata.opf2 import metadata_to_opf tdir = tempfile.mkdtemp(dir=rd.tdir) with tempfile.NamedTemporaryFile(prefix='', suffix=('.' + fmt.lower()), dir=tdir, delete=False) as src_file: db.copy_format_to(book_id, fmt, src_file) with tempfile.NamedTemporaryFile(prefix='', suffix='.jpeg', dir=tdir, delete=False) as cover_file: cover_copied = db.copy_cover_to(book_id, cover_file) cover_path = cover_file.name if cover_copied else None mi = db.get_metadata(book_id) mi.application_id = mi.uuid raw = metadata_to_opf(mi) with tempfile.NamedTemporaryFile(prefix='', suffix='.opf', dir=tdir, delete=False) as opf_file: opf_file.write(raw) recs = GuiRecommendations() recs.update(conversion_data['options']) recs['gui_preferred_input_format'] = conversion_data['input_fmt'].lower() save_specifics(db, book_id, recs) recs = [(k, v, OptionRecommendation.HIGH) for k, v in iteritems(recs)] job_id = ctx.start_job( f'Convert book {book_id} ({fmt})', 'calibre.srv.convert', 'convert_book', args=( src_file.name, opf_file.name, cover_path, conversion_data['output_fmt'], recs), job_done_callback=job_done ) expire_old_jobs() with cache_lock: conversion_jobs[job_id] = JobStatus( job_id, book_id, tdir, library_id, src_file.name, conversion_data) return job_id @endpoint('/conversion/start/{book_id}', postprocess=json, needs_db_write=True, types={'book_id': int}, methods=receive_data_methods) def start_conversion(ctx, rd, book_id): db, library_id = get_library_data(ctx, rd)[:2] if not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) data = json.loads(rd.request_body_file.read()) input_fmt = data['input_fmt'] job_id = queue_job(ctx, rd, library_id, db, input_fmt, book_id, data) return job_id @endpoint('/conversion/status/{job_id}', postprocess=json, needs_db_write=True, types={'job_id': int}, methods=receive_data_methods) def conversion_status(ctx, rd, job_id): with cache_lock: job_status = conversion_jobs.get(job_id) if job_status is None: raise HTTPNotFound(f'No job with id: {job_id}') job_status.last_check_at = monotonic() if job_status.running: percent, msg = job_status.current_status if rd.query.get('abort_job'): ctx.abort_job(job_id) return {'running': True, 'percent': percent, 'msg': msg} del conversion_jobs[job_id] try: ans = {'running': False, 'ok': job_status.ok, 'was_aborted': job_status.was_aborted, 'traceback': job_status.traceback, 'log': job_status.log} if job_status.ok: db, library_id = get_library_data(ctx, rd)[:2] if library_id != job_status.library_id: raise HTTPNotFound('job library_id does not match') fmt = job_status.output_path.rpartition('.')[-1] try: db.add_format(job_status.book_id, fmt, job_status.output_path) except NoSuchBook: raise HTTPNotFound( f'book_id {job_status.book_id} not found in library') run_plugins_on_postconvert(db, job_status.book_id, fmt) formats_added({job_status.book_id: (fmt,)}) ans['size'] = os.path.getsize(job_status.output_path) ans['fmt'] = fmt return ans finally: job_status.cleanup() def get_conversion_options(input_fmt, output_fmt, book_id, db): from calibre.customize.conversion import OptionRecommendation from calibre.ebooks.conversion.config import OPTIONS, load_defaults, load_specifics, options_for_input_fmt, options_for_output_fmt from calibre.ebooks.conversion.plumber import create_dummy_plumber plumber = create_dummy_plumber(input_fmt, output_fmt) specifics = load_specifics(db, book_id) ans = {'options': {}, 'disabled': set(), 'defaults': {}, 'help': {}} ans['input_plugin_name'] = plumber.input_plugin.commit_name ans['output_plugin_name'] = plumber.output_plugin.commit_name ans['input_ui_data'] = plumber.input_plugin.ui_data ans['output_ui_data'] = plumber.output_plugin.ui_data def merge_group(group_name, option_names): if not group_name or group_name in ('debug', 'metadata'): return defs = load_defaults(group_name) defs.merge_recommendations( plumber.get_option_by_name, OptionRecommendation.LOW, option_names) specifics.merge_recommendations( plumber.get_option_by_name, OptionRecommendation.HIGH, option_names, only_existing=True) defaults = defs.as_dict()['options'] for k in defs: if k in specifics: defs[k] = specifics[k] defs = defs.as_dict() ans['options'].update(defs['options']) ans['disabled'] |= set(defs['disabled']) ans['defaults'].update(defaults) ans['help'] = plumber.get_all_help() for group_name, option_names in iteritems(OPTIONS['pipe']): merge_group(group_name, option_names) group_name, option_names = options_for_input_fmt(input_fmt) merge_group(group_name, option_names) group_name, option_names = options_for_output_fmt(output_fmt) merge_group(group_name, option_names) ans['disabled'] = tuple(ans['disabled']) return ans def profiles(): ans = getattr(profiles, 'ans', None) if ans is None: def desc(profile): w, h = profile.screen_size if w >= 10000: ss = _('unlimited') else: ss = _('%(width)d x %(height)d pixels') % dict(width=w, height=h) ss = _('Screen size: %s') % ss return {'name': profile.name, 'description': (f'{profile.description} [{ss}]')} ans = profiles.ans = {} ans['input'] = {p.short_name: desc(p) for p in input_profiles()} ans['output'] = {p.short_name: desc(p) for p in output_profiles()} return ans @endpoint('/conversion/book-data/{book_id}', postprocess=json, types={'book_id': int}) def conversion_data(ctx, rd, book_id): from calibre.ebooks.conversion.config import NoSupportedInputFormats, get_input_format_for_book, get_sorted_output_formats db = get_library_data(ctx, rd)[0] if not ctx.has_id(rd, db, book_id): raise BookNotFound(book_id, db) try: input_format, input_formats = get_input_format_for_book(db, book_id) except NoSupportedInputFormats: input_formats = [] else: if rd.query.get('input_fmt') and rd.query.get('input_fmt').lower() in input_formats: input_format = rd.query.get('input_fmt').lower() if input_format in input_formats: input_formats.remove(input_format) input_formats.insert(0, input_format) input_fmt = input_formats[0] if input_formats else 'epub' output_formats = get_sorted_output_formats(rd.query.get('output_fmt')) ans = { 'input_formats': [x.upper() for x in input_formats], 'output_formats': output_formats, 'profiles': profiles(), 'conversion_options': get_conversion_options(input_fmt, output_formats[0], book_id, db), 'title': db.field_for('title', book_id), 'authors': db.field_for('authors', book_id), 'book_id': book_id } return ans
11,530
Python
.py
252
37.876984
134
0.645724
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,592
legacy.py
kovidgoyal_calibre/src/calibre/srv/legacy.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from functools import partial from lxml.html import tostring from lxml.html.builder import E as E_ from calibre import strftime from calibre.constants import __appname__ from calibre.db.view import sanitize_sort_field_name from calibre.ebooks.metadata import authors_to_string from calibre.srv.content import book_filename, get from calibre.srv.errors import HTTPBadRequest, HTTPRedirect from calibre.srv.routes import endpoint from calibre.srv.utils import get_library_data, http_date from calibre.utils.cleantext import clean_xml_chars from calibre.utils.date import dt_as_local, is_date_undefined, timestampfromdt from calibre.utils.localization import _ from polyglot.builtins import as_bytes, iteritems, string_or_bytes from polyglot.urllib import urlencode # /mobile {{{ def clean(x): if isinstance(x, string_or_bytes): x = clean_xml_chars(x) return x def E(tag, *children, **attribs): children = list(map(clean, children)) attribs = {k.rstrip('_').replace('_', '-'):clean(v) for k, v in iteritems(attribs)} return getattr(E_, tag)(*children, **attribs) for tag in 'HTML HEAD TITLE LINK DIV IMG BODY OPTION SELECT INPUT FORM SPAN TABLE TR TD A HR META'.split(): setattr(E, tag, partial(E, tag)) tag = tag.lower() setattr(E, tag, partial(E, tag)) def html(ctx, rd, endpoint, output): rd.outheaders.set('Content-Type', 'text/html; charset=UTF-8', replace_all=True) if isinstance(output, bytes): ans = output # Assume output is already UTF-8 encoded html else: ans = tostring(output, include_meta_content_type=True, pretty_print=True, encoding='utf-8', doctype='<!DOCTYPE html>', with_tail=False) if not isinstance(ans, bytes): ans = ans.encode('utf-8') return ans def build_search_box(num, search, sort, order, ctx, field_metadata, library_id): # {{{ div = E.div(id='search_box') form = E.form(_('Show '), method='get', action=ctx.url_for('/mobile')) form.set('accept-charset', 'UTF-8') div.append(form) num_select = E.select(name='num') for option in (5, 10, 25, 100): kwargs = {'value':str(option)} if option == num: kwargs['SELECTED'] = 'SELECTED' num_select.append(E.option(str(option), **kwargs)) num_select.tail = ' books matching ' form.append(num_select) searchf = E.input(name='search', id='s', value=search if search else '') searchf.tail = _(' sorted by ') form.append(searchf) sort_select = E.select(name='sort') for option in ('date','author','title','rating','size','tags','series'): q = sanitize_sort_field_name(field_metadata, option) kwargs = {'value':option} if q == sanitize_sort_field_name(field_metadata, sort): kwargs['SELECTED'] = 'SELECTED' sort_select.append(E.option(option, **kwargs)) form.append(sort_select) order_select = E.select(name='order') for option in ('ascending','descending'): kwargs = {'value':option} if option == order: kwargs['SELECTED'] = 'SELECTED' order_select.append(E.option(option, **kwargs)) form.append(order_select) if library_id: form.append(E.input(name='library_id', type='hidden', value=library_id)) form.append(E.input(id='go', type='submit', value=_('Search'))) return div # }}} def build_navigation(start, num, total, url_base): # {{{ end = min((start+num-1), total) tagline = E.span('Books %d to %d of %d'%(start, end, total), style='display: block; text-align: center;') left_buttons = E.td(class_='button', style='text-align:left') right_buttons = E.td(class_='button', style='text-align:right') if start > 1: for t,s in [('First', 1), ('Previous', max(start-num,1))]: left_buttons.append(E.a(t, href='%s&start=%d'%(url_base, s))) if total > start + num: for t,s in [('Next', start+num), ('Last', total-num+1)]: right_buttons.append(E.a(t, href='%s&start=%d'%(url_base, s))) buttons = E.table( E.tr(left_buttons, right_buttons), class_='buttons') return E.div(tagline, buttons, class_='navigation') # }}} def build_choose_library(ctx, library_map): select = E.select(name='library_id') for library_id, library_name in iteritems(library_map): select.append(E.option(library_name, value=library_id)) return E.div( E.form( _('Change library to: '), select, ' ', E.input(type='submit', value=_('Change library')), method='GET', action=ctx.url_for('/mobile'), accept_charset='UTF-8' ), id='choose_library') def build_index(rd, books, num, search, sort, order, start, total, url_base, field_metadata, ctx, library_map, library_id): # {{{ logo = E.div(E.img(src=ctx.url_for('/static', what='calibre.png'), alt=__appname__), id='logo') search_box = build_search_box(num, search, sort, order, ctx, field_metadata, library_id) navigation = build_navigation(start, num, total, url_base) navigation2 = build_navigation(start, num, total, url_base) if library_map: choose_library = build_choose_library(ctx, library_map) books_table = E.table(id='listing') body = E.body( logo, search_box, navigation, E.hr(class_='spacer'), books_table, E.hr(class_='spacer'), navigation2 ) for book in books: thumbnail = E.td( E.img(type='image/jpeg', border='0', src=ctx.url_for('/get', what='thumb', book_id=book.id, library_id=library_id), class_='thumbnail') ) data = E.td() for fmt in book.formats or (): if not fmt or fmt.lower().startswith('original_'): continue s = E.span( E.a( fmt.lower(), href=ctx.url_for('/legacy/get', what=fmt, book_id=book.id, library_id=library_id, filename=book_filename(rd, book.id, book, fmt)) ), class_='button') s.tail = '' data.append(s) div = E.div(class_='data-container') data.append(div) series = ('[%s - %s]'%(book.series, book.series_index)) if book.series else '' tags = ('Tags=[%s]'%', '.join(book.tags)) if book.tags else '' ctext = '' for key in filter(ctx.is_field_displayable, field_metadata.ignorable_field_keys()): fm = field_metadata[key] if fm['datatype'] == 'comments': continue name, val = book.format_field(key) if val: ctext += '%s=[%s] '%(name, val) first = E.span('{} {} by {}'.format(book.title, series, authors_to_string(book.authors)), class_='first-line') div.append(first) ds = '' if is_date_undefined(book.timestamp) else strftime('%d %b, %Y', t=dt_as_local(book.timestamp).timetuple()) second = E.span(f'{ds} {tags} {ctext}', class_='second-line') div.append(second) books_table.append(E.tr(thumbnail, data)) if library_map: body.append(choose_library) body.append(E.div( E.a(_('Switch to the full interface (non-mobile interface)'), href=ctx.url_for(None), style="text-decoration: none; color: blue", title=_('The full interface gives you many more features, ' 'but it may not work well on a small screen')), style="text-align:center") ) return E.html( E.head( E.title(__appname__ + ' Library'), E.link(rel='icon', href=ctx.url_for('/favicon.png'), type='image/png'), E.link(rel='stylesheet', type='text/css', href=ctx.url_for('/static', what='mobile.css')), E.link(rel='apple-touch-icon', href=ctx.url_for("/static", what='calibre.png')), E.meta(name="robots", content="noindex") ), # End head body ) # End html # }}} @endpoint('/mobile', postprocess=html) def mobile(ctx, rd): db, library_id, library_map, default_library = get_library_data(ctx, rd) try: start = max(1, int(rd.query.get('start', 1))) except ValueError: raise HTTPBadRequest('start is not an integer') try: num = max(0, int(rd.query.get('num', 25))) except ValueError: raise HTTPBadRequest('num is not an integer') search = rd.query.get('search') or '' with db.safe_read_lock: book_ids = ctx.search(rd, db, search) total = len(book_ids) ascending = rd.query.get('order', '').lower().strip() == 'ascending' sort_by = sanitize_sort_field_name(db.field_metadata, rd.query.get('sort') or 'date') try: book_ids = db.multisort([(sort_by, ascending)], book_ids) except Exception: sort_by = 'date' book_ids = db.multisort([(sort_by, ascending)], book_ids) books = [db.get_metadata(book_id) for book_id in book_ids[(start-1):(start-1)+num]] rd.outheaders['Last-Modified'] = http_date(timestampfromdt(db.last_modified())) order = 'ascending' if ascending else 'descending' q = {b'search':search.encode('utf-8'), b'order':order.encode('ascii'), b'sort':sort_by.encode('utf-8'), b'num':as_bytes(num), 'library_id':library_id} url_base = ctx.url_for('/mobile') + '?' + urlencode(q) lm = {k:v for k, v in iteritems(library_map) if k != library_id} return build_index(rd, books, num, search, sort_by, order, start, total, url_base, db.field_metadata, ctx, lm, library_id) # }}} @endpoint('/browse/{+rest=""}') def browse(ctx, rd, rest): if rest.startswith('book/'): try: book_id = int(rest[5:]) except Exception: raise HTTPRedirect(ctx.url_for(None)) # implementation of https://bugs.launchpad.net/calibre/+bug/1698411 # redirect old server book URLs to new URLs redirect = ctx.url_for(None) + f'#book_id={book_id}&amp;panel=book_details' from lxml import etree as ET return html(ctx, rd, endpoint, E.html(E.head( ET.XML('<meta http-equiv="refresh" content="0;url=' + redirect + '"/>'), ET.XML('<script language="javascript">' + 'window.location.href = "' + redirect + '"' + '</script>' )))) else: raise HTTPRedirect(ctx.url_for(None)) @endpoint('/stanza/{+rest=""}') def stanza(ctx, rd, rest): raise HTTPRedirect(ctx.url_for('/opds')) @endpoint('/legacy/get/{what}/{book_id}/{library_id}/{+filename=""}', android_workaround=True) def legacy_get(ctx, rd, what, book_id, library_id, filename): # See https://www.mobileread.com/forums/showthread.php?p=3531644 for why # this is needed for Kobo browsers ua = rd.inheaders.get('User-Agent', '') is_old_kindle = 'Kindle/3' in ua ans = get(ctx, rd, what, book_id, library_id) if is_old_kindle: # Content-Disposition causes downloads to fail when the filename has non-ascii chars in it # https://www.mobileread.com/forums/showthread.php?t=364015 rd.outheaders.pop('Content-Disposition', '') return ans
11,384
Python
.py
242
39.107438
154
0.613054
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,593
auth.py
kovidgoyal_calibre/src/calibre/srv/auth.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import os import random import struct from collections import OrderedDict from hashlib import md5, sha256 from itertools import permutations from threading import Lock from calibre.srv.errors import HTTPAuthRequired, HTTPForbidden, HTTPSimpleResponse from calibre.srv.http_request import parse_uri from calibre.srv.utils import encode_path, parse_http_dict from calibre.utils.monotonic import monotonic from polyglot import http_client from polyglot.binary import as_hex_unicode, from_base64_unicode, from_hex_bytes MAX_AGE_SECONDS = 3600 nonce_counter, nonce_counter_lock = 0, Lock() class BanList: def __init__(self, ban_time_in_minutes=0, max_failures_before_ban=5): self.interval = max(0, ban_time_in_minutes) * 60 self.max_failures_before_ban = max(0, max_failures_before_ban) if not self.interval or not self.max_failures_before_ban: self.is_banned = lambda *a: False self.failed = lambda *a: None else: self.items = OrderedDict() self.lock = Lock() def is_banned(self, key): with self.lock: x = self.items.get(key) if x is None: return False previous_fail, fail_count = x if fail_count < self.max_failures_before_ban: return False return monotonic() - previous_fail < self.interval def failed(self, key): with self.lock: x = self.items.pop(key, None) fail_count = 0 if x is None else x[1] now = monotonic() self.items[key] = now, fail_count + 1 remove = [] for old in reversed(self.items): previous_fail = self.items[old][0] if now - previous_fail > self.interval: remove.append(old) else: break for r in remove: self.items.pop(r, None) def as_bytestring(x): if not isinstance(x, bytes): x = x.encode('utf-8') return x def as_unicodestring(x): if isinstance(x, bytes): x = x.decode('utf-8') return x def md5_hex(s): return as_unicodestring(md5(as_bytestring(s)).hexdigest()) def sha256_hex(s): return as_unicodestring(sha256(as_bytestring(s)).hexdigest()) def base64_decode(s): return from_base64_unicode(s) def synthesize_nonce(key_order, realm, secret, timestamp=None): ''' Create a nonce. Can be used for either digest or cookie based auth. The nonce is of the form timestamp:hash with hash being a hash of the timestamp, server secret and realm. This allows the timestamp to be validated and stale nonce's to be rejected. ''' if timestamp is None: global nonce_counter with nonce_counter_lock: nonce_counter = (nonce_counter + 1) % 65535 # The resolution of monotonic() on windows is very low (10s of # milliseconds) so to ensure nonce values are not re-used, we have a # global counter timestamp = as_hex_unicode(struct.pack(b'!dH', float(monotonic()), nonce_counter)) h = sha256_hex(key_order.format(timestamp, realm, secret)) nonce = ':'.join((timestamp, h)) return nonce def validate_nonce(key_order, nonce, realm, secret): timestamp, hashpart = nonce.partition(':')[::2] s_nonce = synthesize_nonce(key_order, realm, secret, timestamp) return s_nonce == nonce def is_nonce_stale(nonce, max_age_seconds=MAX_AGE_SECONDS): try: timestamp = struct.unpack(b'!dH', from_hex_bytes(as_bytestring(nonce.partition(':')[0])))[0] return timestamp + max_age_seconds < monotonic() except Exception: pass return True class DigestAuth: # {{{ valid_algorithms = {'MD5', 'MD5-SESS'} valid_qops = {'auth', 'auth-int'} def __init__(self, header_val): data = parse_http_dict(header_val) self.realm = data.get('realm') self.username = data.get('username') self.nonce = data.get('nonce') self.uri = data.get('uri') self.method = data.get('method') self.response = data.get('response') self.algorithm = data.get('algorithm', 'MD5').upper() self.cnonce = data.get('cnonce') self.opaque = data.get('opaque') self.qop = data.get('qop', '').lower() self.nonce_count = data.get('nc') if self.algorithm not in self.valid_algorithms: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'Unsupported digest algorithm') if not (self.username and self.realm and self.nonce and self.uri and self.response): raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'Digest algorithm required fields missing') if self.qop: if self.qop not in self.valid_qops: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'Unsupported digest qop') if not (self.cnonce and self.nonce_count): raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'qop present, but cnonce and nonce_count absent') else: if self.cnonce or self.nonce_count: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'qop missing') def H(self, val): return md5_hex(val) def H_A2(self, data): """Returns the H(A2) string. See :rfc:`2617` section 3.2.2.3.""" # RFC 2617 3.2.2.3 # If the "qop" directive's value is "auth" or is unspecified, # then A2 is: # A2 = method ":" digest-uri-value # # If the "qop" value is "auth-int", then A2 is: # A2 = method ":" digest-uri-value ":" H(entity-body) if self.qop == "auth-int": a2 = f"{data.method}:{self.uri}:{self.H(data.peek())}" else: a2 = f'{data.method}:{self.uri}' return self.H(a2) def request_digest(self, pw, data): ha1 = self.H(':'.join((self.username, self.realm, pw))) ha2 = self.H_A2(data) # Request-Digest -- RFC 2617 3.2.2.1 if self.qop: req = "{}:{}:{}:{}:{}".format( self.nonce, self.nonce_count, self.cnonce, self.qop, ha2) else: req = f"{self.nonce}:{ha2}" # RFC 2617 3.2.2.2 # # If the "algorithm" directive's value is "MD5" or is unspecified, # then A1 is: # A1 = unq(username-value) ":" unq(realm-value) ":" passwd # # If the "algorithm" directive's value is "MD5-sess", then A1 is # calculated only once - on the first request by the client following # receipt of a WWW-Authenticate challenge from the server. # A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd ) # ":" unq(nonce-value) ":" unq(cnonce-value) if self.algorithm == 'MD5-SESS': ha1 = self.H(f'{ha1}:{self.nonce}:{self.cnonce}') return self.H(f'{ha1}:{req}') def validate_request(self, pw, data, log=None): # We should also be checking for replay attacks by using nonce_count, # however, various HTTP clients, most prominently Firefox dont # implement nonce-counts correctly, so we cannot do the check. # https://bugzil.la/114451 path = parse_uri(self.uri.encode('utf-8'))[1] if path != data.path: if log is not None: log.warn('Authorization URI mismatch: {} != {} from client: {}'.format( data.path, path, data.remote_addr)) raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'The uri in the Request Line and the Authorization header do not match') return self.response is not None and data.path == path and self.request_digest(pw, data) == self.response # }}} class AuthController: ''' Implement Basic/Digest authentication for the Content server. Android browsers cannot handle HTTP AUTH when downloading files, as the download is handed off to a separate process. So we use a cookie based authentication scheme for some endpoints (/get) to allow downloads to work on android. Apparently, cookies are passed to the download process. The cookie expires after MAX_AGE_SECONDS. The android browser appears to send a GET request to the server and only if that request succeeds is the download handed off to the download process. We could reduce MAX_AGE_SECONDS, but we leave it high as the download process might have downloads queued and therefore not start the download immediately. Note that this makes the server vulnerable to session-hijacking (i.e. some one can sniff the traffic and create their own requests to /get with the appropriate cookie, for an hour). The fix is to use https, but since this is usually run as a private server, that cannot be done. If you care about this vulnerability, run the server behind a reverse proxy that uses HTTPS. Also, note that digest auth is itself vulnerable to partial session hijacking, since we have to ignore repeated nc values, because Firefox does not implement the digest auth spec properly (it sends out of order nc values). ''' ANDROID_COOKIE = 'android_workaround' def __init__(self, user_credentials=None, prefer_basic_auth=False, realm='calibre', max_age_seconds=MAX_AGE_SECONDS, log=None, ban_time_in_minutes=0, ban_after=5): self.user_credentials, self.prefer_basic_auth = user_credentials, prefer_basic_auth self.ban_list = BanList(ban_time_in_minutes=ban_time_in_minutes, max_failures_before_ban=ban_after) self.log = log self.secret = as_hex_unicode(os.urandom(random.randint(20, 30))) self.max_age_seconds = max_age_seconds self.key_order = '{%d}:{%d}:{%d}' % random.choice(tuple(permutations((0,1,2)))) self.realm = realm if '"' in realm: raise ValueError('Double-quotes are not allowed in the authentication realm') def check(self, un, pw): return pw and self.user_credentials.get(un) == pw def __call__(self, data, endpoint): path = encode_path(*data.path) http_auth_needed = not (endpoint.android_workaround and self.validate_android_cookie(path, data.cookies.get(self.ANDROID_COOKIE))) if http_auth_needed: self.do_http_auth(data, endpoint) if endpoint.android_workaround: data.outcookie[self.ANDROID_COOKIE] = synthesize_nonce(self.key_order, path, self.secret) data.outcookie[self.ANDROID_COOKIE]['path'] = path def validate_android_cookie(self, path, cookie): return cookie and validate_nonce(self.key_order, cookie, path, self.secret) and not is_nonce_stale(cookie, self.max_age_seconds) def do_http_auth(self, data, endpoint): ban_key = data.remote_addr, data.forwarded_for if self.ban_list.is_banned(ban_key): raise HTTPForbidden('Too many login attempts', log='Too many login attempts from: %s' % (ban_key if data.forwarded_for else data.remote_addr)) auth = data.inheaders.get('Authorization') nonce_is_stale = False log_msg = None data.username = None if auth: scheme, rest = auth.partition(' ')[::2] scheme = scheme.lower() if scheme == 'digest': da = DigestAuth(rest.strip()) if validate_nonce(self.key_order, da.nonce, self.realm, self.secret): pw = self.user_credentials.get(da.username) if pw and da.validate_request(pw, data, self.log): nonce_is_stale = is_nonce_stale(da.nonce, self.max_age_seconds) if not nonce_is_stale: data.username = da.username return log_msg = 'Failed login attempt from: %s' % data.remote_addr self.ban_list.failed(ban_key) elif self.prefer_basic_auth and scheme == 'basic': try: un, pw = base64_decode(rest.strip()).partition(':')[::2] except ValueError: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'The username or password contained non-UTF8 encoded characters') if not un or not pw: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'The username or password was empty') if self.check(un, pw): data.username = un return log_msg = 'Failed login attempt from: %s' % data.remote_addr self.ban_list.failed(ban_key) else: raise HTTPSimpleResponse(http_client.BAD_REQUEST, 'Unsupported authentication method') if self.prefer_basic_auth: raise HTTPAuthRequired('Basic realm="%s"' % self.realm, log=log_msg) s = 'Digest realm="{}", nonce="{}", algorithm="MD5", qop="auth"'.format( self.realm, synthesize_nonce(self.key_order, self.realm, self.secret)) if nonce_is_stale: s += ', stale="true"' raise HTTPAuthRequired(s, log=log_msg)
13,282
Python
.py
266
40.454887
154
0.629021
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,594
utils.py
kovidgoyal_calibre/src/calibre/srv/utils.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import errno import os import socket from email.utils import formatdate from operator import itemgetter from calibre import prints from calibre.constants import iswindows from calibre.srv.errors import HTTPNotFound from calibre.utils.localization import get_translator from calibre.utils.logging import ThreadSafeLog from calibre.utils.shared_file import share_open from calibre.utils.socket_inheritance import set_socket_inherit from polyglot import reprlib from polyglot.binary import as_hex_unicode as encode_name from polyglot.binary import from_hex_unicode as decode_name from polyglot.builtins import as_unicode, iteritems from polyglot.http_cookie import SimpleCookie from polyglot.urllib import parse_qs from polyglot.urllib import quote as urlquote HTTP1 = 'HTTP/1.0' HTTP11 = 'HTTP/1.1' DESIRED_SEND_BUFFER_SIZE = 16 * 1024 # windows 7 uses an 8KB sndbuf encode_name, decode_name def http_date(timeval=None): return str(formatdate(timeval=timeval, usegmt=True)) class MultiDict(dict): # {{{ def __setitem__(self, key, val): vals = dict.get(self, key, []) vals.append(val) dict.__setitem__(self, key, vals) def __getitem__(self, key): return dict.__getitem__(self, key)[-1] @staticmethod def create_from_query_string(qs): ans = MultiDict() qs = as_unicode(qs) for k, v in iteritems(parse_qs(qs, keep_blank_values=True)): dict.__setitem__(ans, as_unicode(k), [as_unicode(x) for x in v]) return ans def update_from_listdict(self, ld): for key, values in iteritems(ld): for val in values: self[key] = val def items(self, duplicates=True): f = dict.items for k, v in f(self): if duplicates: for x in v: yield k, x else: yield k, v[-1] iteritems = items def values(self, duplicates=True): f = dict.values for v in f(self): if duplicates: yield from v else: yield v[-1] itervalues = values def set(self, key, val, replace_all=False): if replace_all: dict.__setitem__(self, key, [val]) else: self[key] = val def get(self, key, default=None, all=False): if all: try: return dict.__getitem__(self, key) except KeyError: return [] try: return self.__getitem__(key) except KeyError: return default def pop(self, key, default=None, all=False): ans = dict.pop(self, key, default) if ans is default: return [] if all else default return ans if all else ans[-1] def __repr__(self): return '{' + ', '.join(f'{reprlib.repr(k)}: {reprlib.repr(v)}' for k, v in iteritems(self)) + '}' __str__ = __unicode__ = __repr__ def pretty(self, leading_whitespace=''): return leading_whitespace + ('\n' + leading_whitespace).join( f'{k}: {(repr(v) if isinstance(v, bytes) else v)}' for k, v in sorted(self.items(), key=itemgetter(0))) # }}} def error_codes(*errnames): ''' Return error numbers for error names, ignoring non-existent names ''' ans = {getattr(errno, x, None) for x in errnames} ans.discard(None) return ans socket_errors_eintr = error_codes("EINTR", "WSAEINTR") socket_errors_socket_closed = error_codes( # errors indicating a disconnected connection "EPIPE", "EBADF", "WSAEBADF", "ENOTSOCK", "WSAENOTSOCK", "ENOTCONN", "WSAENOTCONN", "ESHUTDOWN", "WSAESHUTDOWN", "ETIMEDOUT", "WSAETIMEDOUT", "ECONNREFUSED", "WSAECONNREFUSED", "ECONNRESET", "WSAECONNRESET", "ECONNABORTED", "WSAECONNABORTED", "ENETRESET", "WSAENETRESET", "EHOSTDOWN", "EHOSTUNREACH", ) socket_errors_nonblocking = error_codes( 'EAGAIN', 'EWOULDBLOCK', 'WSAEWOULDBLOCK') def start_cork(sock): if hasattr(socket, 'TCP_CORK'): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1) def stop_cork(sock): if hasattr(socket, 'TCP_CORK'): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 0) def create_sock_pair(): '''Create socket pair. ''' client_sock, srv_sock = socket.socketpair() set_socket_inherit(client_sock, False), set_socket_inherit(srv_sock, False) return client_sock, srv_sock def parse_http_list(header_val): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Neither commas nor quotes count if they are escaped. Only double-quotes count, not single-quotes. """ if isinstance(header_val, bytes): slash, dquote, comma = b'\\",' empty = b'' else: slash, dquote, comma = '\\",' empty = '' part = empty escape = quote = False for cur in header_val: if escape: part += cur escape = False continue if quote: if cur == slash: escape = True continue elif cur == dquote: quote = False part += cur continue if cur == comma: yield part.strip() part = empty continue if cur == dquote: quote = True part += cur if part: yield part.strip() def parse_http_dict(header_val): 'Parse an HTTP comma separated header with items of the form a=1, b="xxx" into a dictionary' if not header_val: return {} ans = {} sep, dquote = b'="' if isinstance(header_val, bytes) else '="' for item in parse_http_list(header_val): k, v = item.partition(sep)[::2] if k: if v.startswith(dquote) and v.endswith(dquote): v = v[1:-1] ans[k] = v return ans def sort_q_values(header_val): 'Get sorted items from an HTTP header of type: a;q=0.5, b;q=0.7...' if not header_val: return [] def item(x): e, r = x.partition(';')[::2] p, v = r.partition('=')[::2] q = 1.0 if p == 'q' and v: try: q = max(0.0, min(1.0, float(v.strip()))) except Exception: pass return e.strip(), q return tuple(map(itemgetter(0), sorted(map(item, parse_http_list(header_val)), key=itemgetter(1), reverse=True))) def eintr_retry_call(func, *args, **kwargs): while True: try: return func(*args, **kwargs) except OSError as e: if getattr(e, 'errno', None) in socket_errors_eintr: continue raise def get_translator_for_lang(cache, bcp_47_code): try: return cache[bcp_47_code] except KeyError: pass cache[bcp_47_code] = ans = get_translator(bcp_47_code) return ans def encode_path(*components): 'Encode the path specified as a list of path components using URL encoding' return '/' + '/'.join(urlquote(x.encode('utf-8'), '') for x in components) class Cookie(SimpleCookie): def _BaseCookie__set(self, key, real_value, coded_value): return SimpleCookie._BaseCookie__set(self, key, real_value, coded_value) def custom_fields_to_display(db): return frozenset(db.field_metadata.ignorable_field_keys()) # Logging {{{ class ServerLog(ThreadSafeLog): exception_traceback_level = ThreadSafeLog.WARN class RotatingStream: def __init__(self, filename, max_size=None, history=5): self.filename, self.history, self.max_size = filename, history, max_size if iswindows: self.filename = '\\\\?\\' + os.path.abspath(self.filename) self.set_output() def set_output(self): if iswindows: self.stream = share_open(self.filename, 'a', newline='') else: # see https://bugs.python.org/issue27805 self.stream = open(os.open(self.filename, os.O_WRONLY|os.O_APPEND|os.O_CREAT|os.O_CLOEXEC), 'w') try: self.stream.tell() except OSError: # Happens if filename is /dev/stdout for example self.max_size = None def flush(self): self.stream.flush() def prints(self, level, *args, **kwargs): kwargs['file'] = self.stream prints(*args, **kwargs) self.rollover() def rename(self, src, dest): try: if iswindows: from calibre_extensions import winutil winutil.move_file(src, dest) else: os.rename(src, dest) except OSError as e: if e.errno != errno.ENOENT: # the source of the rename does not exist raise def rollover(self): if not self.max_size or self.stream.tell() <= self.max_size: return self.stream.close() for i in range(self.history - 1, 0, -1): src, dest = '%s.%d' % (self.filename, i), '%s.%d' % (self.filename, i+1) self.rename(src, dest) self.rename(self.filename, '%s.%d' % (self.filename, 1)) self.set_output() def clear(self): if self.filename in ('/dev/stdout', '/dev/stderr'): return self.stream.close() failed = {} try: os.remove(self.filename) except OSError as e: failed[self.filename] = e import glob for f in glob.glob(self.filename + '.*'): try: os.remove(f) except OSError as e: failed[f] = e self.set_output() return failed class RotatingLog(ServerLog): def __init__(self, filename, max_size=None, history=5): ServerLog.__init__(self) self.outputs = [RotatingStream(filename, max_size, history)] def flush(self): for o in self.outputs: o.flush() # }}} class HandleInterrupt: # {{{ # On windows socket functions like accept(), recv(), send() are not # interrupted by a Ctrl-C in the console. So to make Ctrl-C work we have to # use this special context manager. See the echo server example at the # bottom of srv/loop.py for how to use it. def __init__(self, action): if not iswindows: return # Interrupts work fine on POSIX self.action = action from ctypes import WINFUNCTYPE, windll from ctypes.wintypes import BOOL, DWORD kernel32 = windll.LoadLibrary('kernel32') # <http://msdn.microsoft.com/en-us/library/ms686016.aspx> PHANDLER_ROUTINE = WINFUNCTYPE(BOOL, DWORD) self.SetConsoleCtrlHandler = kernel32.SetConsoleCtrlHandler self.SetConsoleCtrlHandler.argtypes = (PHANDLER_ROUTINE, BOOL) self.SetConsoleCtrlHandler.restype = BOOL @PHANDLER_ROUTINE def handle(event): if event == 0: # CTRL_C_EVENT if self.action is not None: self.action() self.action = None return 1 return 0 self.handle = handle def __enter__(self): if iswindows: if self.SetConsoleCtrlHandler(self.handle, 1) == 0: import ctypes raise ctypes.WinError() def __exit__(self, *args): if iswindows: if self.SetConsoleCtrlHandler(self.handle, 0) == 0: import ctypes raise ctypes.WinError() # }}} class Accumulator: # {{{ 'Optimized replacement for BytesIO when the usage pattern is many writes followed by a single getvalue()' def __init__(self): self._buf = [] self.total_length = 0 def append(self, b): self._buf.append(b) self.total_length += len(b) def getvalue(self): ans = b''.join(self._buf) self._buf = [] self.total_length = 0 return ans # }}} def get_db(ctx, rd, library_id): db = ctx.get_library(rd, library_id) if db is None: raise HTTPNotFound('Library %r not found' % library_id) return db def get_library_data(ctx, rd, strict_library_id=False): library_id = rd.query.get('library_id') library_map, default_library = ctx.library_info(rd) if library_id not in library_map: if strict_library_id and library_id: raise HTTPNotFound(f'No library with id: {library_id}') library_id = default_library db = get_db(ctx, rd, library_id) return db, library_id, library_map, default_library class Offsets: 'Calculate offsets for a paginated view' def __init__(self, offset, delta, total): if offset < 0: offset = 0 if offset >= total: raise HTTPNotFound('Invalid offset: %r'%offset) last_allowed_index = total - 1 last_current_index = offset + delta - 1 self.slice_upper_bound = offset+delta self.offset = offset self.next_offset = last_current_index + 1 if self.next_offset > last_allowed_index: self.next_offset = -1 self.previous_offset = self.offset - delta if self.previous_offset < 0: self.previous_offset = 0 self.last_offset = last_allowed_index - delta if self.last_offset < 0: self.last_offset = 0 _use_roman = None def get_use_roman(): global _use_roman if _use_roman is None: from calibre.gui2 import config _use_roman = config['use_roman_numerals_for_series_number'] return _use_roman
13,857
Python
.py
373
28.941019
117
0.604766
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,595
metadata.py
kovidgoyal_calibre/src/calibre/srv/metadata.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import os from collections import namedtuple from copy import copy from datetime import datetime, time from functools import partial from threading import Lock from calibre.constants import config_dir from calibre.db.categories import Tag, category_display_order from calibre.ebooks.metadata.sources.identify import urls_from_identifiers from calibre.library.comments import comments_to_html, markdown from calibre.library.field_metadata import category_icon_map from calibre.utils.config import tweaks from calibre.utils.date import UNDEFINED_DATE, isoformat, local_tz from calibre.utils.file_type_icons import EXT_MAP from calibre.utils.formatter import EvalFormatter from calibre.utils.icu import collation_order_for_partitioning from calibre.utils.icu import upper as icu_upper from calibre.utils.localization import _, calibre_langcode_to_name from polyglot.builtins import iteritems, itervalues from polyglot.urllib import quote IGNORED_FIELDS = frozenset('cover ondevice path marked au_map'.split()) def encode_datetime(dateval): if dateval is None: return "None" if not isinstance(dateval, datetime): dateval = datetime.combine(dateval, time()) if hasattr(dateval, 'tzinfo') and dateval.tzinfo is None: dateval = dateval.replace(tzinfo=local_tz) if dateval <= UNDEFINED_DATE: return None return isoformat(dateval) empty_val = ((), '', {}) passthrough_comment_types = {'long-text', 'short-text'} def add_field(field, db, book_id, ans, field_metadata): datatype = field_metadata.get('datatype') if datatype is not None: val = db._field_for(field, book_id) if val is not None and val not in empty_val: if datatype == 'datetime': val = encode_datetime(val) if val is None: return elif datatype == 'comments' or field == 'comments': ctype = field_metadata.get('display', {}).get('interpret_as', 'html') if ctype == 'markdown': ans[field + '#markdown#'] = val val = markdown(val) elif ctype not in passthrough_comment_types: val = comments_to_html(val) elif datatype == 'composite' and field_metadata['display'].get('contains_html'): val = comments_to_html(val) ans[field] = val def book_as_json(db, book_id): db = db.new_api with db.safe_read_lock: fmts = db._formats(book_id, verify_formats=False) ans = [] fm = {} for fmt in fmts: m = db.format_metadata(book_id, fmt) if m and m.get('size', 0) > 0: ans.append(fmt) fm[fmt] = m['size'] ans = {'formats': ans, 'format_sizes': fm} if not ans['formats'] and not db.has_id(book_id): return None fm = db.field_metadata for field in fm.all_field_keys(): if field not in IGNORED_FIELDS: add_field(field, db, book_id, ans, fm[field]) ids = ans.get('identifiers') if ids: ans['urls_from_identifiers'] = urls_from_identifiers(ids) langs = ans.get('languages') if langs: ans['lang_names'] = {l:calibre_langcode_to_name(l) for l in langs} link_maps = db.get_all_link_maps_for_book(book_id) if link_maps: ans['link_maps'] = link_maps x = db.items_with_notes_in_book(book_id) if x: ans['items_with_notes'] = {field: {v: k for k, v in items.items()} for field, items in x.items()} return ans _include_fields = frozenset(Tag.__slots__) - frozenset({ 'state', 'is_editable', 'is_searchable', 'original_name', 'use_sort_as_name', 'is_hierarchical' }) def category_as_json(items, category, display_name, count, tooltip=None, parent=None, is_editable=True, is_gst=False, is_hierarchical=False, is_searchable=True, is_user_category=False, is_first_letter=False): ans = {'category': category, 'name': display_name, 'is_category':True, 'count':count} if tooltip: ans['tooltip'] = tooltip if parent: ans['parent'] = parent if is_editable: ans['is_editable'] = True if is_gst: ans['is_gst'] = True if is_hierarchical: ans['is_hierarchical'] = is_hierarchical if is_searchable: ans['is_searchable'] = True if is_user_category: ans['is_user_category'] = True if is_first_letter: ans['is_first_letter'] = True item_id = 'c' + str(len(items)) items[item_id] = ans return item_id def category_item_as_json(x, clear_rating=False): ans = {} for k in _include_fields: val = getattr(x, k) if val is not None: if k == 'original_categories': val = tuple(val) ans[k] = val.copy() if isinstance(val, set) else val s = ans.get('sort') if x.use_sort_as_name: ans['name'] = s if x.original_name != ans['name']: ans['original_name'] = x.original_name if x.use_sort_as_name or not s or s == ans['name']: ans.pop('sort', None) if clear_rating: del ans['avg_rating'] return ans CategoriesSettings = namedtuple( 'CategoriesSettings', 'dont_collapse collapse_model collapse_at sort_by' ' template using_hierarchy grouped_search_terms hidden_categories hide_empty_categories') class GroupedSearchTerms: __slots__ = ('keys', 'vals', 'hash') def __init__(self, src): self.keys = frozenset(src) self.hash = hash(self.keys) # We dont need to store values since this is used as part of a key for # a cache and if the values have changed the cache will be invalidated # for other reasons anyway (last_modified() will have changed on the # db) def __contains__(self, val): return val in self.keys def __hash__(self): return self.hash def __eq__(self, other): try: return self.keys == other.keys except AttributeError: return False _icon_map = None _icon_map_lock = Lock() def icon_map(): global _icon_map with _icon_map_lock: if _icon_map is None: from calibre.gui2 import gprefs _icon_map = category_icon_map.copy() custom_icons = gprefs.get('tags_browser_category_icons', {}) for k, v in iteritems(custom_icons): if os.access(os.path.join(config_dir, 'tb_icons', v), os.R_OK): _icon_map[k] = '_' + quote(v) _icon_map['file_type_icons'] = { k:'mimetypes/%s.png' % v for k, v in iteritems(EXT_MAP) } return _icon_map def categories_settings(query, db, gst_container=GroupedSearchTerms): dont_collapse = frozenset(query.get('dont_collapse', '').split(',')) partition_method = query.get('partition_method', 'first letter') if partition_method not in {'first letter', 'disable', 'partition'}: partition_method = 'first letter' try: collapse_at = max(0, int(float(query.get('collapse_at', 25)))) except Exception: collapse_at = 25 sort_by = query.get('sort_tags_by', 'name') if sort_by not in {'name', 'popularity', 'rating'}: sort_by = 'name' collapse_model = partition_method if collapse_at else 'disable' template = None if collapse_model != 'disable': if sort_by != 'name': collapse_model = 'partition' template = tweaks['categories_collapsed_%s_template' % sort_by] using_hierarchy = frozenset(db.pref('categories_using_hierarchy', [])) hidden_categories = frozenset(db.pref('tag_browser_hidden_categories', set())) return CategoriesSettings( dont_collapse, collapse_model, collapse_at, sort_by, template, using_hierarchy, gst_container(db.pref('grouped_search_terms', {})), hidden_categories, query.get('hide_empty_categories') == 'yes') def create_toplevel_tree(category_data, items, field_metadata, opts, db): # Create the basic tree, containing all top level categories , user # categories and grouped search terms last_category_node, category_node_map, root = None, {}, {'id':None, 'children':[]} node_id_map = {} category_nodes, recount_nodes = [], [] scats = category_display_order(db.pref('tag_browser_category_order', []), list(category_data.keys())) for category in scats: is_user_category = category.startswith('@') is_gst, tooltip = (is_user_category and category[1:] in opts.grouped_search_terms), '' cdata = category_data[category] if is_gst: tooltip = _('The grouped search term name is "{0}"').format(category) elif category != 'news': cust_desc = '' fm = field_metadata[category] if fm['is_custom']: cust_desc = fm['display'].get('description', '') if cust_desc: cust_desc = '\n' + _('Description:') + ' ' + cust_desc tooltip = _('The lookup/search name is "{0}"{1}').format(category, cust_desc) if is_user_category: path_parts = category.split('.') path = '' last_category_node = None current_root = root for i, p in enumerate(path_parts): path += p if path not in category_node_map: last_category_node = category_as_json( items, path, (p[1:] if i == 0 else p), len(cdata), parent=last_category_node, tooltip=tooltip, is_gst=is_gst, is_editable=((not is_gst) and (i == (len(path_parts)-1))), is_hierarchical=False if is_gst else 5, is_user_category=True ) node_id_map[last_category_node] = category_node_map[path] = node = {'id':last_category_node, 'children':[]} category_nodes.append(last_category_node) recount_nodes.append(node) current_root['children'].append(node) current_root = node else: current_root = category_node_map[path] last_category_node = current_root['id'] path += '.' else: last_category_node = category_as_json( items, category, field_metadata[category]['name'], len(cdata), tooltip=tooltip ) category_node_map[category] = node_id_map[last_category_node] = node = {'id':last_category_node, 'children':[]} root['children'].append(node) category_nodes.append(last_category_node) recount_nodes.append(node) return root, node_id_map, category_nodes, recount_nodes def build_first_letter_list(category_items): # Build a list of 'equal' first letters by noticing changes # in ICU's 'ordinal' for the first letter. In this case, the # first letter can actually be more than one letter long. cl_list = [None] * len(category_items) last_ordnum = 0 last_c = ' ' for idx, tag in enumerate(category_items): if not tag.sort: c = ' ' else: c = icu_upper(tag.sort) ordnum, ordlen = collation_order_for_partitioning(c) if last_ordnum != ordnum: last_c = c[0:ordlen] last_ordnum = ordnum cl_list[idx] = last_c return cl_list categories_with_ratings = {'authors', 'series', 'publisher', 'tags'} def get_name_components(name): components = list(filter(None, [t.strip() for t in name.split('.')])) if not components or '.'.join(components) != name: components = [name] return components def collapse_partition(collapse_nodes, items, category_node, idx, tag, opts, top_level_component, cat_len, category_is_hierarchical, category_items, eval_formatter, is_gst, last_idx, node_parent): # Only partition at the top level. This means that we must not do a break # until the outermost component changes. if idx >= last_idx + opts.collapse_at and not tag.original_name.startswith(top_level_component+'.'): last = idx + opts.collapse_at - 1 if cat_len > idx + opts.collapse_at else cat_len - 1 if category_is_hierarchical: ct = copy(category_items[last]) components = get_name_components(ct.original_name) ct.sort = ct.name = components[0] # Do the first node after the last node so that the components # array contains the right values to be used later ct2 = copy(tag) components = get_name_components(ct2.original_name) ct2.sort = ct2.name = components[0] format_data = {'last': ct, 'first':ct2} else: format_data = {'first': tag, 'last': category_items[last]} name = eval_formatter.safe_format(opts.template, format_data, '##TAG_VIEW##', None) if not name.startswith('##TAG_VIEW##'): # Formatter succeeded node_id = category_as_json( items, items[category_node['id']]['category'], name, 0, parent=category_node['id'], is_editable=False, is_gst=is_gst, is_hierarchical=category_is_hierarchical, is_searchable=False) node_parent = {'id':node_id, 'children':[]} collapse_nodes.append(node_parent) category_node['children'].append(node_parent) last_idx = idx # remember where we last partitioned return last_idx, node_parent def collapse_first_letter(collapse_nodes, items, category_node, cl_list, idx, is_gst, category_is_hierarchical, collapse_letter, node_parent): cl = cl_list[idx] if cl != collapse_letter: collapse_letter = cl node_id = category_as_json( items, items[category_node['id']]['category'], collapse_letter, 0, parent=category_node['id'], is_editable=False, is_gst=is_gst, is_hierarchical=category_is_hierarchical, is_first_letter=True) node_parent = {'id':node_id, 'children':[]} category_node['children'].append(node_parent) collapse_nodes.append(node_parent) return collapse_letter, node_parent def process_category_node( category_node, items, category_data, eval_formatter, field_metadata, opts, tag_map, hierarchical_tags, node_to_tag_map, collapse_nodes, intermediate_nodes, hierarchical_items): category = items[category_node['id']]['category'] if category not in category_data: # This can happen for user categories that are hierarchical and missing their parent. return category_items = category_data[category] cat_len = len(category_items) if cat_len <= 0: return collapse_letter = None is_gst = items[category_node['id']].get('is_gst', False) collapse_model = 'disable' if category in opts.dont_collapse else opts.collapse_model fm = field_metadata[category] category_child_map = {} is_user_category = fm['kind'] == 'user' and not is_gst top_level_component = 'z' + category_items[0].original_name last_idx = -opts.collapse_at category_is_hierarchical = ( category in opts.using_hierarchy and opts.sort_by == 'name' and category not in {'authors', 'publisher', 'news', 'formats', 'rating'} ) clear_rating = category not in categories_with_ratings and not fm['is_custom'] and not fm['kind'] == 'user' collapsible = collapse_model != 'disable' and cat_len > opts.collapse_at partitioned = collapse_model == 'partition' cl_list = build_first_letter_list(category_items) if collapsible and collapse_model == 'first letter' else () node_parent = category_node def create_tag_node(tag, parent): # User categories contain references to items in other categories, so # reflect that in the node structure as well. node_data = tag_map.get(id(tag), None) if node_data is None: node_id = 'n%d' % len(tag_map) node_data = items[node_id] = category_item_as_json(tag, clear_rating=clear_rating) tag_map[id(tag)] = (node_id, node_data) node_to_tag_map[node_id] = tag else: node_id, node_data = node_data node = {'id':node_id, 'children':[]} parent['children'].append(node) return node, node_data for idx, tag in enumerate(category_items): if collapsible: if partitioned: last_idx, node_parent = collapse_partition( collapse_nodes, items, category_node, idx, tag, opts, top_level_component, cat_len, category_is_hierarchical, category_items, eval_formatter, is_gst, last_idx, node_parent) else: # by 'first letter' collapse_letter, node_parent = collapse_first_letter( collapse_nodes, items, category_node, cl_list, idx, is_gst, category_is_hierarchical, collapse_letter, node_parent) else: node_parent = category_node tag_is_hierarchical = id(tag) in hierarchical_tags components = get_name_components(tag.original_name) if category_is_hierarchical or tag_is_hierarchical else (tag.original_name,) if not tag_is_hierarchical and ( is_user_category or not category_is_hierarchical or len(components) == 1 or (fm['is_custom'] and fm['display'].get('is_names', False)) ): # A non-hierarchical leaf item in a non-hierarchical category node, item = create_tag_node(tag, node_parent) category_child_map[item['name'], item['category']] = node intermediate_nodes[tag.category, tag.original_name] = node else: orig_node_parent = node_parent for i, component in enumerate(components): if i == 0: child_map = category_child_map else: child_map = {} for sibling in node_parent['children']: item = items[sibling['id']] if not item.get('is_category', False): child_map[item['name'], item['category']] = sibling cm_key = component, tag.category if cm_key in child_map: node_parent = child_map[cm_key] node_id = node_parent['id'] item = items[node_id] item['is_hierarchical'] = 3 if tag.category == 'search' else 5 if tag.id_set is not None: item['id_set'] |= tag.id_set hierarchical_items.add(node_id) hierarchical_tags.add(id(node_to_tag_map[node_parent['id']])) else: if i < len(components) - 1: # Non-leaf node original_name = '.'.join(components[:i+1]) inode = intermediate_nodes.get((tag.category, original_name), None) if inode is None: t = copy(tag) t.original_name, t.count = original_name, 0 t.is_editable, t.is_searchable = False, category == 'search' node_parent, item = create_tag_node(t, node_parent) hierarchical_tags.add(id(t)) intermediate_nodes[tag.category, original_name] = node_parent else: item = items[inode['id']] ch = node_parent['children'] node_parent = {'id':inode['id'], 'children':[]} ch.append(node_parent) else: node_parent, item = create_tag_node(tag, node_parent) if not is_user_category: item['original_name'] = tag.name intermediate_nodes[tag.category, tag.original_name] = node_parent item['name'] = component item['is_hierarchical'] = 3 if tag.category == 'search' else 5 hierarchical_tags.add(id(tag)) child_map[cm_key] = node_parent items[node_parent['id']]['id_set'] |= tag.id_set node_parent = orig_node_parent def iternode_descendants(node): for child in node['children']: yield child yield from iternode_descendants(child) def fillout_tree(root, items, node_id_map, category_nodes, category_data, field_metadata, opts, book_rating_map): eval_formatter = EvalFormatter() tag_map, hierarchical_tags, node_to_tag_map = {}, set(), {} first, later, collapse_nodes, intermediate_nodes, hierarchical_items = [], [], [], {}, set() # User categories have to be processed after normal categories as they can # reference hierarchical nodes that were created only during processing of # normal categories for category_node_id in category_nodes: cnode = items[category_node_id] coll = later if cnode.get('is_user_category', False) else first coll.append(node_id_map[category_node_id]) for coll in (first, later): for cnode in coll: process_category_node( cnode, items, category_data, eval_formatter, field_metadata, opts, tag_map, hierarchical_tags, node_to_tag_map, collapse_nodes, intermediate_nodes, hierarchical_items) # Do not store id_set in the tag items as it is a lot of data, with not # much use. Instead only update the ratings and counts based on id_set for item_id in hierarchical_items: item = items[item_id] total = count = 0 for book_id in item['id_set']: rating = book_rating_map.get(book_id, 0) if rating: total += rating/2.0 count += 1 item['avg_rating'] = float(total)/count if count else 0 for item_id, item in itervalues(tag_map): id_len = len(item.pop('id_set', ())) if id_len: item['count'] = id_len for node in collapse_nodes: item = items[node['id']] item['count'] = sum(1 for _ in iternode_descendants(node)) def render_categories(opts, db, category_data): items = {} with db.safe_read_lock: root, node_id_map, category_nodes, recount_nodes = create_toplevel_tree(category_data, items, db.field_metadata, opts, db) fillout_tree(root, items, node_id_map, category_nodes, category_data, db.field_metadata, opts, db.fields['rating'].book_value_map) for node in recount_nodes: item = items[node['id']] item['count'] = sum(1 for x in iternode_descendants(node) if not items[x['id']].get('is_category', False)) if opts.hidden_categories: # We have to remove hidden categories after all processing is done as # items from a hidden category could be in a user category root['children'] = list(filter((lambda child:items[child['id']]['category'] not in opts.hidden_categories), root['children'])) if opts.hide_empty_categories: root['children'] = list(filter((lambda child:items[child['id']]['count'] > 0), root['children'])) return {'root':root, 'item_map': items} def categories_as_json(ctx, rd, db, opts, vl): return ctx.get_tag_browser(rd, db, opts, partial(render_categories, opts), vl=vl) # Test tag browser {{{ def dump_categories_tree(data): root, items = data['root'], data['item_map'] ans, indent = [], ' ' def dump_node(node, level=0): item = items[node['id']] rating = item.get('avg_rating', None) or 0 if rating: rating = ',rating=%.1f' % rating try: ans.append(indent*level + item['name'] + ' [count={}{}]'.format(item['count'], rating or '')) except KeyError: print(item) raise for child in node['children']: dump_node(child, level+1) if level == 0: ans.append('') [dump_node(c) for c in root['children']] return '\n'.join(ans) def dump_tags_model(m): from qt.core import QModelIndex, Qt ans, indent = [], ' ' def dump_node(index, level=-1): if level > -1: ans.append(indent*level + index.data(Qt.ItemDataRole.UserRole).dump_data()) for i in range(m.rowCount(index)): dump_node(m.index(i, 0, index), level + 1) if level == 0: ans.append('') dump_node(QModelIndex()) return '\n'.join(ans) def test_tag_browser(library_path=None): ' Compare output of server and GUI tag browsers ' from calibre.library import db olddb = db(library_path) db = olddb.new_api opts = categories_settings({}, db) # opts = opts._replace(hidden_categories={'publisher'}) opts = opts._replace(hide_empty_categories=True) category_data = db.get_categories(sort=opts.sort_by, first_letter_sort=opts.collapse_model == 'first letter') data = render_categories(opts, db, category_data) srv_data = dump_categories_tree(data) from calibre.gui2 import Application, gprefs from calibre.gui2.tag_browser.model import TagsModel prefs = { 'tags_browser_category_icons':gprefs['tags_browser_category_icons'], 'tags_browser_collapse_at':opts.collapse_at, 'tags_browser_partition_method': opts.collapse_model, 'tag_browser_dont_collapse': opts.dont_collapse, 'tag_browser_hide_empty_categories': opts.hide_empty_categories, } app = Application([]) m = TagsModel(None, prefs) m.set_database(olddb, opts.hidden_categories) m_data = dump_tags_model(m) if m_data == srv_data: print('No differences found in the two Tag Browser implementations') raise SystemExit(0) from calibre.gui2.tweak_book.diff.main import Diff d = Diff(show_as_window=True) d.string_diff(m_data, srv_data, left_name='GUI', right_name='server') d.exec() del app # }}}
26,357
Python
.py
544
38.455882
142
0.606388
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,596
manage_users_cli.py
kovidgoyal_calibre/src/calibre/srv/manage_users_cli.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> import sys from functools import partial from calibre import prints from calibre.constants import iswindows, preferred_encoding from calibre.utils.config import OptionParser from calibre.utils.localization import _, ngettext from polyglot.builtins import iteritems def create_subcommand_parser(name, usage): usage = f'%prog --manage-users -- {name} ' + usage parser = OptionParser(usage) return parser def add(user_manager, args): p = create_subcommand_parser('add', _('username [password]') + '\n\n' + '''\ Create a new user account with the specified name and password. If the password is not specified on the command line, it will be read from STDIN. ''') p.add_option('--readonly', action='store_true', default=False, help=_('Give this user only read access')) opts, args = p.parse_args(['calibre-server'] + list(args)) if len(args) < 2: p.print_help() raise SystemExit(_('username is required')) username = args[1] if len(args) > 2: pw = args[2] else: pw = sys.stdin.read() user_manager.add_user(username, pw, readonly=opts.readonly) def remove(user_manager, args): p = create_subcommand_parser('remove', _('username') + '\n\n' + '''\ Remove the user account with the specified username. ''') opts, args = p.parse_args(['calibre-server'] + list(args)) if len(args) < 2: p.print_help() raise SystemExit(_('username is required')) username = args[1] user_manager.remove_user(username) def list_users(user_manager, args): p = create_subcommand_parser('list', '\n\n' + '''\ List all usernames. ''') opts, args = p.parse_args(['calibre-server'] + list(args)) for name in user_manager.all_user_names: print(name) def change_readonly(user_manager, args): p = create_subcommand_parser('readonly', _('username set|reset|toggle|show') + '\n\n' + '''\ Restrict the specified user account to prevent it from making changes. \ The value of set makes the account readonly, reset allows it to make \ changes, toggle flips the value and show prints out the current value. \ ''') opts, args = p.parse_args(['calibre-server'] + list(args)) if len(args) < 3: p.print_help() raise SystemExit(_('username and operation are required')) username, op = args[1], args[2] if op == 'toggle': val = not user_manager.is_readonly(username) elif op == 'set': val = True elif op == 'reset': val = False elif op == 'show': print('set' if user_manager.is_readonly(username) else 'reset', end='') return else: raise SystemExit(f'{op} is an unknown operation') user_manager.set_readonly(username, val) def change_libraries(user_manager, args): p = create_subcommand_parser( 'libraries', _('[options] username [library_name ...]') + '\n\n' + '''\ Manage the libraries the specified user account is restricted to. ''') p.add_option('--action', type='choice', choices='allow-all allow block per-library show'.split(), default='show', help=_( 'Specify the action to perform.' '\nA value of "show" shows the current library restrictions for the specified user.' '\nA value of "allow-all" removes all library restrictions.' '\nA value of "allow" allows access to only the specified libraries.' '\nA value of "block" allows access to all, except the specified libraries.' '\nA value of "per-library" sets per library restrictions. In this case the libraries list' ' is interpreted as a list of library name followed by restriction to apply, followed' ' by next library name and so on. Using a restriction of "=" removes any previous restriction' ' on that library.' )) opts, args = p.parse_args(['calibre-server'] + list(args)) if len(args) < 2: p.print_help() raise SystemExit(_('username is required')) username, libraries = args[1], args[2:] r = user_manager.restrictions(username) if r is None: raise SystemExit(f'The user {username} does not exist') if opts.action == 'show': if r['allowed_library_names']: print('Allowed:') for name in r['allowed_library_names']: print('\t' + name) if r['blocked_library_names']: print('Blocked:') for name in r['blocked_library_names']: print('\t' + name) if r['library_restrictions']: print('Per Library:') for name, res in r['library_restrictions'].items(): print('\t' + name) print('\t\t' + res) if not r['allowed_library_names'] and not r['blocked_library_names'] and not r['library_restrictions']: print(f'{username} has no library restrictions') elif opts.action == 'allow-all': user_manager.update_user_restrictions(username, {}) elif opts.action == 'per-library': if not libraries: p.print_help() raise SystemExit('Must specify at least one library and restriction') if len(libraries) % 2 != 0: p.print_help() raise SystemExit('Must specify a restriction for every library') lres = r['library_restrictions'] for i in range(0, len(libraries), 2): name, res = libraries[i:i+2] if res == '=': lres.pop(name, None) else: lres[name] = res user_manager.update_user_restrictions(username, r) else: if not libraries: p.print_help() raise SystemExit('Must specify at least one library name') k = 'blocked_library_names' if opts.action == 'block' else 'allowed_library_names' r.pop('allowed_library_names', None) r.pop('blocked_library_names', None) r[k] = libraries user_manager.update_user_restrictions(username, r) def chpass(user_manager, args): p = create_subcommand_parser('chpass', _('username [password]') + '\n\n' + '''\ Change the password of the new user account with the specified username. If the password is not specified on the command line, it will be read from STDIN. ''') opts, args = p.parse_args(['calibre-server'] + list(args)) if len(args) < 2: p.print_help() raise SystemExit(_('username is required')) username = args[1] if len(args) > 2: pw = args[2] else: pw = sys.stdin.read() user_manager.change_password(username, pw) def main(user_manager, args): q, rest = args[0], args[1:] if q == 'add': return add(user_manager, rest) if q == 'remove': return remove(user_manager, rest) if q == 'chpass': return chpass(user_manager, rest) if q == 'list': return list_users(user_manager, rest) if q == 'readonly': return change_readonly(user_manager, rest) if q == 'libraries': return change_libraries(user_manager, rest) if q != 'help': print(_('Unknown command: {}').format(q), file=sys.stderr) print() print(_('Manage the user accounts for calibre-server. Available commands are:')) print('add, remove, chpass, list') print(_('Use {} for help on individual commands').format('calibre-server --manage-users -- command -h')) raise SystemExit(1) def manage_users_cli(path=None, args=()): from calibre.srv.users import UserManager m = UserManager(path) if args: main(m, args) return enc = getattr(sys.stdin, 'encoding', preferred_encoding) or preferred_encoding def get_input(prompt): prints(prompt, end=' ') ans = input() if isinstance(ans, bytes): ans = ans.decode(enc) if iswindows: # https://bugs.python.org/issue11272 ans = ans.rstrip('\r') return ans def choice( question=_('What do you want to do?'), choices=(), default=None, banner=''): prints(banner) for i, choice in enumerate(choices): prints('%d)' % (i + 1), choice) print() while True: prompt = question + ' [1-%d]:' % len(choices) if default is not None: prompt = question + ' [1-%d %s: %d]' % ( len(choices), _('default'), default + 1) reply = get_input(prompt) if not reply and default is not None: reply = str(default + 1) if not reply: prints(_('No choice selected, exiting...')) raise SystemExit(0) reply = reply.strip() try: num = int(reply) - 1 if not (0 <= num < len(choices)): raise Exception('bad num') return num except Exception: prints(_('%s is not a valid choice, try again') % reply) def get_valid(prompt, invalidq=lambda x: None): while True: ans = get_input(prompt + ':').strip() fail_message = invalidq(ans) if fail_message is None: return ans prints(fail_message) def get_valid_user(): prints(_('Existing user names:')) users = sorted(m.all_user_names) if not users: raise SystemExit(_('There are no users, you must first add an user')) prints(', '.join(users)) def validate(username): if not m.has_user(username): return _('The username %s does not exist') % username return get_valid(_('Enter the username'), validate) def get_pass(username): from getpass import getpass while True: one = getpass( _('Enter the new password for %s: ') % username) if not one: prints(_('Empty passwords are not allowed')) continue two = getpass( _('Re-enter the new password for %s, to verify: ') % username ) if one != two: prints(_('Passwords do not match')) continue msg = m.validate_password(one) if msg is None: return one prints(msg) def add_user(): username = get_valid(_('Enter the username'), m.validate_username) pw = get_pass(username) m.add_user(username, pw) prints(_('User %s added successfully!') % username) def remove_user(): un = get_valid_user() if get_input((_('Are you sure you want to remove the user %s?') % un) + ' [y/n]:') != 'y': raise SystemExit(0) m.remove_user(un) prints(_('User %s successfully removed!') % un) def change_password(username): pw = get_pass(username) m.change_password(username, pw) prints(_('Password for %s successfully changed!') % username) def show_password(username): pw = m.get(username) prints(_('Current password for {0} is: {1}').format(username, pw)) def change_readonly(username): readonly = m.is_readonly(username) if readonly: q = _('Allow {} to make changes (i.e. grant write access)') else: q = _('Prevent {} from making changes (i.e. remove write access)') if get_input(q.format(username) + '? [y/n]:').lower() == 'y': m.set_readonly(username, not readonly) def change_restriction(username): r = m.restrictions(username) if r is None: raise SystemExit(f'The user {username} does not exist') if r['allowed_library_names']: libs = r['allowed_library_names'] prints( ngettext( '{} is currently only allowed to access the library named: {}', '{} is currently only allowed to access the libraries named: {}', len(libs)).format(username, ', '.join(libs))) if r['blocked_library_names']: libs = r['blocked_library_names'] prints( ngettext( '{} is currently not allowed to access the library named: {}', '{} is currently not allowed to access the libraries named: {}', len(libs)).format(username, ', '.join(libs))) if r['library_restrictions']: prints( _('{} has the following additional per-library restrictions:') .format(username)) for k, v in iteritems(r['library_restrictions']): prints(k + ':', v) else: prints(_('{} has no additional per-library restrictions').format(username)) c = choice( choices=[ _('Allow access to all libraries'), _('Allow access to only specified libraries'), _('Allow access to all, except specified libraries'), _('Change per-library restrictions'), _('Cancel')]) if c == 0: m.update_user_restrictions(username, {}) elif c == 3: while True: library = get_input(_('Enter the name of the library:')) if not library: break prints( _( 'Enter a search expression, access will be granted only to books matching this expression.' ' An empty expression will grant access to all books.')) plr = get_input(_('Search expression:')) if plr: r['library_restrictions'][library] = plr else: r['library_restrictions'].pop(library, None) m.update_user_restrictions(username, r) if get_input(_('Another restriction?') + ' (y/n):') != 'y': break elif c == 4: pass else: names = get_input(_('Enter a comma separated list of library names:')) names = list(filter(None, [x.strip() for x in names.split(',')])) w = 'allowed_library_names' if c == 1 else 'blocked_library_names' t = _('Allowing access only to libraries: {}') if c == 1 else _( 'Allowing access to all libraries, except: {}') prints(t.format(', '.join(names))) m.update_user_restrictions(username, {w: names}) def edit_user(username=None): username = username or get_valid_user() c = choice( choices=[ _('Show password for {}').format(username), _('Change password for {}').format(username), _('Change read/write permission for {}').format(username), _('Change the libraries {} is allowed to access').format(username), _('Cancel'), ], banner='\n' + _('{0} has {1} access').format( username, _('readonly') if m.is_readonly(username) else _('read-write'))) print() if c > 3: actions.append(toplevel) return { 0: show_password, 1: change_password, 2: change_readonly, 3: change_restriction}[c](username) actions.append(partial(edit_user, username=username)) def toplevel(): { 0: add_user, 1: edit_user, 2: remove_user, 3: lambda: None}[choice( choices=[ _('Add a new user'), _('Edit an existing user'), _('Remove a user'), _('Cancel')])]() actions = [toplevel] while actions: actions[0]() del actions[0]
15,896
Python
.py
373
32.533512
125
0.569297
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,597
users_api.py
kovidgoyal_calibre/src/calibre/srv/users_api.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> import json from calibre import as_unicode from calibre.srv.errors import HTTPBadRequest, HTTPForbidden from calibre.srv.routes import endpoint from calibre.srv.users import validate_password from calibre.utils.localization import _ @endpoint('/users/change-pw', methods={'POST'}) def change_pw(ctx, rd): user = rd.username or None if user is None: raise HTTPForbidden('Anonymous users are not allowed to change passwords') try: pw = json.loads(rd.request_body_file.read()) oldpw, newpw = pw['oldpw'], pw['newpw'] except Exception: raise HTTPBadRequest('No decodable password found') if oldpw != ctx.user_manager.get(user): raise HTTPBadRequest(_('Existing password is incorrect')) err = validate_password(newpw) if err: raise HTTPBadRequest(err) try: ctx.user_manager.change_password(user, newpw) except Exception as err: raise HTTPBadRequest(as_unicode(err)) ctx.log.warn('Changed password for user', user) return f'password for {user} changed'
1,154
Python
.py
29
34.896552
82
0.721429
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,598
standalone.py
kovidgoyal_calibre/src/calibre/srv/standalone.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import json import os import signal import sys from calibre import as_unicode from calibre.constants import is_running_from_develop, ismacos, iswindows from calibre.db.legacy import LibraryDatabase from calibre.srv.bonjour import BonJour from calibre.srv.handler import Handler from calibre.srv.http_response import create_http_handler from calibre.srv.library_broker import load_gui_libraries from calibre.srv.loop import BadIPSpec, ServerLoop from calibre.srv.manage_users_cli import manage_users_cli from calibre.srv.opts import opts_to_parser from calibre.srv.users import connect from calibre.srv.utils import HandleInterrupt, RotatingLog from calibre.utils.config import prefs from calibre.utils.localization import _, localize_user_manual_link from calibre.utils.lock import singleinstance from calibre_extensions import speedup from polyglot.builtins import error_message def daemonize(): # {{{ try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError as e: raise SystemExit('fork #1 failed: %s' % as_unicode(e)) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError as e: raise SystemExit('fork #2 failed: %s' % as_unicode(e)) # Redirect standard file descriptors. speedup.detach(os.devnull) # }}} class Server: def __init__(self, libraries, opts): log = access_log = None log_size = opts.max_log_size * 1024 * 1024 if opts.log: log = RotatingLog(opts.log, max_size=log_size) if opts.access_log: access_log = RotatingLog(opts.access_log, max_size=log_size) self.handler = Handler(libraries, opts) if opts.custom_list_template: with open(os.path.expanduser(opts.custom_list_template), 'rb') as f: self.handler.router.ctx.custom_list_template = json.load(f) if opts.search_the_net_urls: with open(os.path.expanduser(opts.search_the_net_urls), 'rb') as f: self.handler.router.ctx.search_the_net_urls = json.load(f) plugins = [] if opts.use_bonjour: plugins.append(BonJour(wait_for_stop=max(0, opts.shutdown_timeout - 0.2))) self.loop = ServerLoop( create_http_handler(self.handler.dispatch), opts=opts, log=log, access_log=access_log, plugins=plugins) self.handler.set_log(self.loop.log) self.handler.set_jobs_manager(self.loop.jobs_manager) self.serve_forever = self.loop.serve_forever self.stop = self.loop.stop if is_running_from_develop: from calibre.utils.rapydscript import compile_srv compile_srv() def create_option_parser(): parser = opts_to_parser( '%prog ' + _( '''[options] [path to library folder...] Start the calibre Content server. The calibre Content server exposes your calibre libraries over the internet. You can specify the path to the library folders as arguments to %prog. If you do not specify any paths, all the libraries that the main calibre program knows about will be used. ''')) parser.add_option( '--log', default=None, help=_( 'Path to log file for server log. This log contains server information and errors, not access logs. By default it is written to stdout.' )) parser.add_option( '--access-log', default=None, help=_( 'Path to the access log file. This log contains information' ' about clients connecting to the server and making requests. By' ' default no access logging is done.')) parser.add_option( '--custom-list-template', help=_( 'Path to a JSON file containing a template for the custom book list mode.' ' The easiest way to create such a template file is to go to Preferences->' ' Sharing over the net-> Book list template in calibre, create the' ' template and export it.' )) parser.add_option( '--search-the-net-urls', help=_( 'Path to a JSON file containing URLs for the "Search the internet" feature.' ' The easiest way to create such a file is to go to Preferences->' ' Sharing over the net->Search the internet in calibre, create the' ' URLs and export them.' )) if not iswindows and not ismacos: # Does not work on macOS because if we fork() we cannot connect to Core # Serives which is needed by the QApplication() constructor, which in # turn is needed by ensure_app() parser.add_option( '--daemonize', default=False, action='store_true', help=_('Run process in background as a daemon (Linux only).')) parser.add_option( '--pidfile', default=None, help=_('Write process PID to the specified file')) parser.add_option( '--auto-reload', default=False, action='store_true', help=_( 'Automatically reload server when source code changes. Useful' ' for development. You should also specify a small value for the' ' shutdown timeout.')) parser.add_option( '--manage-users', default=False, action='store_true', help=_( 'Manage the database of users allowed to connect to this server.' ' You can use it in automated mode by adding a --. See {0}' ' for details. See also the {1} option.').format('calibre-server --manage-users -- help', '--userdb')) parser.get_option('--userdb').help = _( 'Path to the user database to use for authentication. The database' ' is a SQLite file. To create it use {0}. You can read more' ' about managing users at: {1}' ).format( '--manage-users', localize_user_manual_link( 'https://manual.calibre-ebook.com/server.html#managing-user-accounts-from-the-command-line-only' )) return parser option_parser = create_option_parser def ensure_single_instance(): if 'CALIBRE_NO_SI_DANGER_DANGER' not in os.environ and not singleinstance('db'): ext = '.exe' if iswindows else '' raise SystemExit( _( 'Another calibre program such as another instance of {} or the main' ' calibre program is running. Having multiple programs that can make' ' changes to a calibre library running at the same time is not supported.' ).format('calibre-server' + ext)) def main(args=sys.argv): opts, args = create_option_parser().parse_args(args) if opts.auto_reload and not opts.manage_users: if getattr(opts, 'daemonize', False): raise SystemExit( 'Cannot specify --auto-reload and --daemonize at the same time') from calibre.srv.auto_reload import NoAutoReload, auto_reload try: from calibre.utils.logging import default_log return auto_reload(default_log, listen_on=opts.listen_on) except NoAutoReload as e: raise SystemExit(error_message(e)) if opts.userdb: opts.userdb = os.path.abspath(os.path.expandvars(os.path.expanduser(opts.userdb))) connect(opts.userdb, exc_class=SystemExit).close() if opts.manage_users: try: manage_users_cli(opts.userdb, args[1:]) except (KeyboardInterrupt, EOFError): raise SystemExit(_('Interrupted by user')) raise SystemExit(0) ensure_single_instance() libraries = args[1:] for lib in libraries: if not lib or not LibraryDatabase.exists_at(lib): raise SystemExit(_('There is no calibre library at: %s') % lib) libraries = libraries or load_gui_libraries() if not libraries: if not prefs['library_path']: raise SystemExit(_('You must specify at least one calibre library')) libraries = [prefs['library_path']] opts.auto_reload_port = int(os.environ.get('CALIBRE_AUTORELOAD_PORT', 0)) opts.allow_console_print = 'CALIBRE_ALLOW_CONSOLE_PRINT' in os.environ if opts.log and os.path.isdir(opts.log): raise SystemExit('The --log option must point to a file, not a directory') if opts.access_log and os.path.isdir(opts.access_log): raise SystemExit('The --access-log option must point to a file, not a directory') try: server = Server(libraries, opts) except BadIPSpec as e: raise SystemExit(f'{e}') if getattr(opts, 'daemonize', False): if not opts.log and not iswindows: raise SystemExit( 'In order to daemonize you must specify a log file, you can use /dev/stdout to log to screen even as a daemon' ) daemonize() if opts.pidfile: with open(opts.pidfile, 'wb') as f: f.write(str(os.getpid()).encode('ascii')) signal.signal(signal.SIGTERM, lambda s, f: server.stop()) if not getattr(opts, 'daemonize', False) and not iswindows: signal.signal(signal.SIGHUP, lambda s, f: server.stop()) # Needed for dynamic cover generation, which uses Qt for drawing from calibre.gui2 import ensure_app, load_builtin_fonts ensure_app(), load_builtin_fonts() with HandleInterrupt(server.stop): server.serve_forever()
9,685
Python
.py
218
36.275229
148
0.64947
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,599
pre_activated.py
kovidgoyal_calibre/src/calibre/srv/pre_activated.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' # Support server pre-activation, such as with systemd's socket activation import errno import socket from calibre.constants import islinux def pre_activated_socket(): return None has_preactivated_support = False if islinux: import ctypes class SOCKADDR_NL(ctypes.Structure): _fields_ = [("nl_family", ctypes.c_ushort), ("nl_pad", ctypes.c_ushort), ("nl_pid", ctypes.c_int), ("nl_groups", ctypes.c_int)] def getsockfamily(fd): addr = SOCKADDR_NL(0, 0, 0, 0) sz = ctypes.c_int(ctypes.sizeof(addr)) if ctypes.CDLL(None, use_errno=True).getsockname(fd, ctypes.pointer(addr), ctypes.pointer(sz)) != 0: raise OSError(errno.errcode[ctypes.get_errno()]) return addr.nl_family try: from ctypes.util import find_library systemd = ctypes.CDLL(find_library('systemd')) systemd.sd_listen_fds except Exception: pass else: del pre_activated_socket has_preactivated_support = True def pre_activated_socket(): # noqa num = systemd.sd_listen_fds(1) # Remove systemd env vars so that child processes do not inherit them if num > 1: raise OSError('Too many file descriptors received from systemd') if num != 1: return None fd = 3 # systemd starts activated sockets at 3 ret = systemd.sd_is_socket(fd, socket.AF_UNSPEC, socket.SOCK_STREAM, -1) if ret == 0: raise OSError('The systemd socket file descriptor is not valid') if ret < 0: raise OSError('Failed to check the systemd socket file descriptor for validity') family = getsockfamily(fd) return socket.fromfd(fd, family, socket.SOCK_STREAM) if __name__ == '__main__': # Run as: # /usr/lib/systemd/systemd-activate -l 8081 calibre-debug pre_activated.py # telnet localhost 8081 s = pre_activated_socket() print(s, s.getsockname())
2,182
Python
.py
52
33.211538
113
0.620804
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)