Update RapydScript and replace type() by jstype()

This commit is contained in:
Kovid Goyal 2016-10-03 11:16:33 +05:30
parent 27376893ca
commit 2be19e90ce
18 changed files with 40 additions and 41 deletions

Binary file not shown.

View File

@ -14,9 +14,8 @@ def string_to_bytes_slow(string):
return String.fromCharCode('0x' + p1) return String.fromCharCode('0x' + p1)
) )
ua = Uint8Array(binstr.length) ua = Uint8Array(binstr.length)
Array.prototype.forEach.call(binstr, def(ch, i): for i, ch in enumerate(binstr):
ua[i] = ch.charCodeAt(0) ua[i] = ch.charCodeAt(0)
)
return ua return ua
def as_hex(array, sep=''): def as_hex(array, sep=''):
@ -46,8 +45,8 @@ def bytes_to_string_slow(bytes, offset):
i += 3 i += 3
return ans.join('') return ans.join('')
string_to_bytes = string_to_bytes_encoder if type(TextEncoder) is 'function' else string_to_bytes_slow string_to_bytes = string_to_bytes_encoder if jstype(TextEncoder) is 'function' else string_to_bytes_slow
bytes_to_string = bytes_to_string_decoder if type(TextDecoder) is 'function' else bytes_to_string_slow bytes_to_string = bytes_to_string_decoder if jstype(TextDecoder) is 'function' else bytes_to_string_slow
def increment_counter(c): def increment_counter(c):
# c must be a Uint8Array of length 16 # c must be a Uint8Array of length 16
@ -269,7 +268,7 @@ def random_bytes_secure(sz):
crypto.getRandomValues(ans) crypto.getRandomValues(ans)
return ans return ans
random_bytes = random_bytes_secure if type(crypto) is not 'undefined' and type(crypto.getRandomValues) is 'function' else random_bytes_insecure random_bytes = random_bytes_secure if jstype(crypto) is not 'undefined' and jstype(crypto.getRandomValues) is 'function' else random_bytes_insecure
if random_bytes is random_bytes_insecure: if random_bytes is random_bytes_insecure:
try: try:
noderandom = require('crypto').randomBytes noderandom = require('crypto').randomBytes
@ -293,7 +292,7 @@ class ModeOfOperation: # {{{
return tag return tag
if not tag: if not tag:
return Uint8Array(0) return Uint8Array(0)
if type(tag) is 'string': if jstype(tag) is 'string':
return string_to_bytes(tag) return string_to_bytes(tag)
raise TypeError('Invalid tag, must be a string or a Uint8Array') raise TypeError('Invalid tag, must be a string or a Uint8Array')
# }}} # }}}

View File

@ -48,11 +48,11 @@ def _makeelement(tag, *args, **kwargs):
ans.addEventListener(attr, val) ans.addEventListener(attr, val)
elif val is True: elif val is True:
ans.setAttribute(vattr, vattr) ans.setAttribute(vattr, vattr)
elif type(val) is 'string': elif jstype(val) is 'string':
ans.setAttribute(vattr, val) ans.setAttribute(vattr, val)
for arg in args: for arg in args:
if type(arg) is 'string': if jstype(arg) is 'string':
arg = this.createTextNode(arg) arg = this.createTextNode(arg)
ans.appendChild(arg) ans.appendChild(arg)
return ans return ans
@ -64,7 +64,7 @@ def maker_for_document(document):
Object.defineProperty(E, tag, {'value':_makeelement.bind(document, tag)}) Object.defineProperty(E, tag, {'value':_makeelement.bind(document, tag)})
return E return E
if type(document) is 'undefined': if jstype(document) is 'undefined':
E = maker_for_document({ E = maker_for_document({
'createTextNode': def(value): return value;, 'createTextNode': def(value): return value;,
'createElement': def(name): 'createElement': def(name):

View File

@ -21,7 +21,7 @@ def base64encode(bytes):
def base64decode(string): def base64decode(string):
# convert the output of base64encode back into an array of bytes (Uint8Array) # convert the output of base64encode back into an array of bytes (Uint8Array)
if type(window) is not 'undefined': if jstype(window) is not 'undefined':
chars = window.atob(string) chars = window.atob(string)
else: else:
chars = new Buffer(string, 'base64').toString('binary') # noqa: undef chars = new Buffer(string, 'base64').toString('binary') # noqa: undef
@ -106,7 +106,7 @@ def utf8_encode_js(string):
ans.push(ch.charCodeAt(0)) ans.push(ch.charCodeAt(0))
return Uint8Array(ans) return Uint8Array(ans)
if type(TextEncoder) is 'function': if jstype(TextEncoder) is 'function':
_u8enc = TextEncoder('utf-8') _u8enc = TextEncoder('utf-8')
utf8_encode = _u8enc.encode.bind(_u8enc) utf8_encode = _u8enc.encode.bind(_u8enc)
_u8enc = undefined _u8enc = undefined

View File

@ -30,10 +30,10 @@
ρσ_seed_state.key[ρσ_seed_state.key_j]) % 256] ρσ_seed_state.key[ρσ_seed_state.key_j]) % 256]
def seed(x=Date().getTime()): def seed(x=Date().getTime()):
if type(x) is 'number': if jstype(x) is 'number':
x = x.toString() x = x.toString()
elif type(x) is not 'string': elif jstype(x) is not 'string':
raise TypeError("unhashable type: '" + type(x) + "'") raise TypeError("unhashable type: '" + jstype(x) + "'")
for i in range(256): for i in range(256):
ρσ_seed_state.key[i] = i ρσ_seed_state.key[i] = i
j = 0 j = 0

View File

@ -74,7 +74,7 @@ def _expand(groups, repl, group_name_map):
return String.fromCharCode(_ASCII_CONTROL_CHARS[q]) return String.fromCharCode(_ASCII_CONTROL_CHARS[q])
if '0' <= q <= '9': if '0' <= q <= '9':
ans = read_digits(Number.MAX_VALUE, _NUM_PAT, 10, Number.MAX_VALUE, q) ans = read_digits(Number.MAX_VALUE, _NUM_PAT, 10, Number.MAX_VALUE, q)
if type(ans) is 'number': if jstype(ans) is 'number':
return groups[ans] or '' return groups[ans] or ''
return '\\' + ans return '\\' + ans
if q is 'g': if q is 'g':
@ -89,17 +89,17 @@ def _expand(groups, repl, group_name_map):
return groups[gn] or '' return groups[gn] or ''
if q is 'x': if q is 'x':
code = read_digits(2, _HEX_PAT, 16, 0x10FFFF) code = read_digits(2, _HEX_PAT, 16, 0x10FFFF)
if type(code) is 'number': if jstype(code) is 'number':
return String.fromCharCode(code) return String.fromCharCode(code)
return '\\x' + code return '\\x' + code
if q is 'u': if q is 'u':
code = read_digits(4, _HEX_PAT, 16, 0x10FFFF) code = read_digits(4, _HEX_PAT, 16, 0x10FFFF)
if type(code) is 'number': if jstype(code) is 'number':
return String.fromCharCode(code) return String.fromCharCode(code)
return '\\u' + code return '\\u' + code
if q is 'U': if q is 'U':
code = read_digits(8, _HEX_PAT, 16, 0x10FFFF) code = read_digits(8, _HEX_PAT, 16, 0x10FFFF)
if type(code) is 'number': if jstype(code) is 'number':
if code <= 0xFFFF: if code <= 0xFFFF:
return String.fromCharCode(code) return String.fromCharCode(code)
code -= 0x10000 code -= 0x10000
@ -265,7 +265,7 @@ class MatchObject:
return ans return ans
def _group_number(self, g): def _group_number(self, g):
if type(g) is 'number': if jstype(g) is 'number':
return g return g
if has_prop(self.re.group_name_map, g): if has_prop(self.re.group_name_map, g):
return self.re.group_name_map[g][-1] return self.re.group_name_map[g][-1]
@ -273,7 +273,7 @@ class MatchObject:
def _group_val(self, q, defval): def _group_val(self, q, defval):
val = undefined val = undefined
if type(q) is 'number' and -1 < q < self._groups.length: if jstype(q) is 'number' and -1 < q < self._groups.length:
val = self._groups[q] val = self._groups[q]
else: else:
if has_prop(self.re.group_name_map, q): if has_prop(self.re.group_name_map, q):
@ -400,7 +400,7 @@ class RegexObject:
def subn(self, repl, string, count=0): def subn(self, repl, string, count=0):
expand = _expand expand = _expand
if type(repl) is 'function': if jstype(repl) is 'function':
expand = def(m, repl, gnm): return '' + repl(MatchObject(self, m, 0, None)) expand = def(m, repl, gnm): return '' + repl(MatchObject(self, m, 0, None))
this._pattern.lastIndex = 0 this._pattern.lastIndex = 0
num = 0 num = 0

View File

@ -223,7 +223,7 @@ class PrefsPanel:
cls = Choices cls = Choices
elif val is True or val is False: elif val is True or val is False:
cls = CheckBox cls = CheckBox
elif type(val) is 'number': elif jstype(val) is 'number':
cls = SpinBox cls = SpinBox
else: else:
cls = LineEdit cls = LineEdit

View File

@ -106,7 +106,7 @@ def test_fd(date, fmt, ans):
def format_date(date=None, fmt='dd MMM yyyy', as_utc=False): def format_date(date=None, fmt='dd MMM yyyy', as_utc=False):
fmt = fmt or 'dd MMM yyyy' fmt = fmt or 'dd MMM yyyy'
ampm = 'ap' in fmt.toLowerCase() ampm = 'ap' in fmt.toLowerCase()
if type(date) is 'string': if jstype(date) is 'string':
date = Date(date) date = Date(date)
date = date or Date() date = date or Date()
if is_date_undefined(date): if is_date_undefined(date):

View File

@ -25,7 +25,7 @@ simple_vendor_prefixes = {
} }
def set_css(elem, **kw): def set_css(elem, **kw):
if type(elem) is 'string': if jstype(elem) is 'string':
elem = document.querySelector(elem) elem = document.querySelector(elem)
s = elem.style s = elem.style
if s: if s:

View File

@ -95,7 +95,7 @@ class CompletionPopup:
self.applied_query = '' self.applied_query = ''
def add_associated_widget(self, widget_or_id): def add_associated_widget(self, widget_or_id):
if type(widget_or_id) is not 'string': if jstype(widget_or_id) is not 'string':
widget_or_id = ensure_id(widget_or_id) widget_or_id = ensure_id(widget_or_id)
self.associated_widget_ids.add(widget_or_id) self.associated_widget_ids.add(widget_or_id)

View File

@ -134,7 +134,7 @@ def encode(doc, node, offset, tail): # {{{
# Handle the offset, if any # Handle the offset, if any
if node.nodeType is Node.ELEMENT_NODE: if node.nodeType is Node.ELEMENT_NODE:
if type(offset) is 'number': if jstype(offset) is 'number':
node = node.childNodes.item(offset) node = node.childNodes.item(offset)
elif Node.TEXT_NODE <= node.nodeType <= Node.ENTITY_NODE: elif Node.TEXT_NODE <= node.nodeType <= Node.ENTITY_NODE:
offset = offset or 0 offset = offset or 0
@ -388,7 +388,7 @@ def point(cfi, doc): # {{{
y = None y = None
range_ = None range_ = None
if type(r.offset) is "number": if jstype(r.offset) is "number":
# Character offset # Character offset
range_ = ndoc.createRange() range_ = ndoc.createRange()
if r.forward: if r.forward:
@ -435,7 +435,7 @@ def scroll_to(cfi, callback, doc): # {{{
if not point_: if not point_:
print("No point found for cfi: " + cfi) print("No point found for cfi: " + cfi)
return return
if type(point_.time) is 'number': if jstype(point_.time) is 'number':
set_current_time(point_.node, point_.time) set_current_time(point_.node, point_.time)
if point_.range is not None: if point_.range is not None:
@ -486,9 +486,9 @@ def scroll_to(cfi, callback, doc): # {{{
fn = def(): fn = def():
r = node.getBoundingClientRect() r = node.getBoundingClientRect()
x, y = viewport_to_document(r.left, r.top, node.ownerDocument) x, y = viewport_to_document(r.left, r.top, node.ownerDocument)
if type(point_.x) is 'number' and node.offsetWidth: if jstype(point_.x) is 'number' and node.offsetWidth:
x += (point_.x*node.offsetWidth)/100 x += (point_.x*node.offsetWidth)/100
if type(point_.y) is 'number' and node.offsetHeight: if jstype(point_.y) is 'number' and node.offsetHeight:
y += (point_.y*node.offsetHeight)/100 y += (point_.y*node.offsetHeight)/100
window.scrollTo(x, y) window.scrollTo(x, y)
if callback: if callback:
@ -526,9 +526,9 @@ def at_point(ox, oy): # {{{
node = p.node node = p.node
r = node.getBoundingClientRect() r = node.getBoundingClientRect()
x, y = viewport_to_document(r.left, r.top, node.ownerDocument) x, y = viewport_to_document(r.left, r.top, node.ownerDocument)
if type(p.x) is 'number' and node.offsetWidth: if jstype(p.x) is 'number' and node.offsetWidth:
x += (p.x*node.offsetWidth)/100 x += (p.x*node.offsetWidth)/100
if type(p.y) is 'number' and node.offsetHeight: if jstype(p.y) is 'number' and node.offsetHeight:
y += (p.y*node.offsetHeight)/100 y += (p.y*node.offsetHeight)/100
if dist(viewport_to_document(ox, oy), v'[x, y]') > 50: if dist(viewport_to_document(ox, oy), v'[x, y]') > 50:

View File

@ -8,7 +8,7 @@ def get_url(mathjax_files, name):
ans = mathjax_files[name] ans = mathjax_files[name]
if not ans: if not ans:
return name return name
if type(ans) is not 'string': if jstype(ans) is not 'string':
ans = mathjax_files[name] = window.URL.createObjectURL(ans) ans = mathjax_files[name] = window.URL.createObjectURL(ans)
return ans return ans

View File

@ -282,7 +282,7 @@ class Overlay:
return document.getElementById('book-overlay') return document.getElementById('book-overlay')
def container_clicked(self, evt): def container_clicked(self, evt):
if self.panels.length and type(self.panels[-1].on_container_click) is 'function': if self.panels.length and jstype(self.panels[-1].on_container_click) is 'function':
self.panels[-1].on_container_click(evt) self.panels[-1].on_container_click(evt)
else: else:
self.hide_current_panel() self.hide_current_panel()

View File

@ -224,7 +224,7 @@ def scroll_to_column(number, animated=False, notify=False, duration=1000):
def scroll_to_xpos(xpos, animated=False, notify=False, duration=1000): def scroll_to_xpos(xpos, animated=False, notify=False, duration=1000):
# Scroll so that the column containing xpos is the left most column in # Scroll so that the column containing xpos is the left most column in
# the viewport # the viewport
if type(xpos) is not 'number': if jstype(xpos) is not 'number':
print(xpos, 'is not a number, cannot scroll to it!') print(xpos, 'is not a number, cannot scroll to it!')
return return
if is_full_screen_layout: if is_full_screen_layout:

View File

@ -34,7 +34,7 @@ def load_resources(db, book, root_name, previous_resources, proceed):
return setTimeout(do_one, 0) return setTimeout(do_one, 0)
if previous_resources[name]: if previous_resources[name]:
ans[name] = data = previous_resources[name] ans[name] = data = previous_resources[name]
if type(data[0]) is 'string': if jstype(data[0]) is 'string':
find_virtualized_resources(data[0]) find_virtualized_resources(data[0])
return setTimeout(do_one, 0) return setTimeout(do_one, 0)
db.get_file(book, name, got_one) db.get_file(book, name, got_one)
@ -44,7 +44,7 @@ def load_resources(db, book, root_name, previous_resources, proceed):
# Enable to have cover image not preserve aspect ratio # Enable to have cover image not preserve aspect ratio
data = data.replace('width: auto', 'width: 100%') data = data.replace('width: auto', 'width: 100%')
ans[name] = v'[data, mimetype]' ans[name] = v'[data, mimetype]'
if type(data) is 'string': if jstype(data) is 'string':
find_virtualized_resources(data) find_virtualized_resources(data)
return setTimeout(do_one, 0) return setTimeout(do_one, 0)
@ -88,7 +88,7 @@ def finalize_resources(book, root_name, resource_data):
# Resolve the non virtualized resources immediately # Resolve the non virtualized resources immediately
for name in resource_data: for name in resource_data:
data, mimetype = resource_data[name] data, mimetype = resource_data[name]
if type(data) is not 'string': if jstype(data) is not 'string':
blob_url_map[name] = window.URL.createObjectURL(data) blob_url_map[name] = window.URL.createObjectURL(data)
for name in blob_url_map: for name in blob_url_map:
v'delete resource_data[name]' v'delete resource_data[name]'

View File

@ -136,7 +136,7 @@ class ReadUI:
self.current_metadata = metadata or {'title':_('Book id #') + book_id} self.current_metadata = metadata or {'title':_('Book id #') + book_id}
get_boss().update_window_title() get_boss().update_window_title()
self.init_ui() self.init_ui()
if type(self.db) is 'string': if jstype(self.db) is 'string':
self.show_error(_('Cannot read book'), self.db) self.show_error(_('Cannot read book'), self.db)
return return
self.db.get_book(book_id, fmt, metadata, self.got_book.bind(self, force_reload)) self.db.get_book(book_id, fmt, metadata, self.got_book.bind(self, force_reload))

View File

@ -242,7 +242,7 @@ class View:
snum = int(snum) snum = int(snum)
except Exception: except Exception:
print('Invalid spine number in CFI:', snum) print('Invalid spine number in CFI:', snum)
if type(snum) == 'number': if jstype(snum) == 'number':
name = book.manifest.spine[(int(snum) // 2) - 1] or name name = book.manifest.spine[(int(snum) // 2) - 1] or name
pos.type, pos.cfi = 'cfi', '/' + rest pos.type, pos.cfi = 'cfi', '/' + rest
self.show_name(name, initial_position=pos) self.show_name(name, initial_position=pos)

View File

@ -66,7 +66,7 @@ class FakeStorage:
return self.data[key] return self.data[key]
def setItem(self, key, value): def setItem(self, key, value):
if type(value) is not 'string': if jstype(value) is not 'string':
value = JSON.stringify(value) value = JSON.stringify(value)
self.data[key] = value self.data[key] = value