@quran.ws/qvp-react-native 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -4
- package/android/src/main/java/ws/quran/qvp/rn/Codes.kt +34 -0
- package/android/src/main/java/ws/quran/qvp/rn/Marshal.kt +78 -30
- package/android/src/main/java/ws/quran/qvp/rn/QvpModule.kt +104 -50
- package/android/src/main/java/ws/quran/qvp/rn/QvpPageViewManager.kt +1 -0
- package/android/src/main/java/ws/quran/qvp/rn/QvpRnPageView.kt +55 -14
- package/android/src/main/java/ws/quran/qvp/rn/QvpRnWords.kt +26 -0
- package/package.json +1 -1
- package/src/codes.ts +33 -0
- package/src/index.tsx +89 -49
package/README.md
CHANGED
|
@@ -169,9 +169,17 @@ await atlas.pagesOfJuz(30); atlas.searchSurahs('cow' | 'البقرة' | '2'); at
|
|
|
169
169
|
// tag-level equivalents: Qvp.atlasPageOf(id, s, a), Qvp.atlasSearchSurahs(id, text), Qvp.atlasPagesOfJuz(id, n), Qvp.atlasJuzOf(id, s, a), …
|
|
170
170
|
```
|
|
171
171
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
172
|
+
The module runs a call on one of two threads. Its own query thread runs each call that reads only
|
|
173
|
+
what a page fixed when it loaded: `info`, `words`, `word`, `ayahs`, `lines`, `decorations`, `findWord`,
|
|
174
|
+
`targetWords`, `wordForm`, `hasForm`, the metadata calls except `surahHeaders` and `surahHeadersView`,
|
|
175
|
+
`text`, `search`, `citation`, `cropBounds`, `grid`, the engine-wide helpers and the atlas. A long call
|
|
176
|
+
there does not hold up a frame. The view keeps its page open until such a call returns. Every other
|
|
177
|
+
call reads or changes the layout, the view, the styles or the page state, and runs on the UI thread,
|
|
178
|
+
where the view draws. `attachWords` runs on the UI thread after the queries queued before it, and the
|
|
179
|
+
queries queued after it wait for it.
|
|
180
|
+
|
|
181
|
+
`words` builds each word's record once per page: its forms, its label and the names of its paths.
|
|
182
|
+
A later call sends the same records again, and `attachWords` drops them.
|
|
175
183
|
|
|
176
184
|
## Layout of this package
|
|
177
185
|
|
|
@@ -185,15 +193,18 @@ android/src/main/java/ws/quran/qvp/rn/
|
|
|
185
193
|
QvpRnBytes.kt the bytes a URI names (asset, file, path, base64)
|
|
186
194
|
QvpModule.kt ReactContextBaseJavaModule: page queries by react tag, engine helpers, atlas, ornament sets
|
|
187
195
|
Marshal.kt JS shapes ↔ Kotlin types (targets, selectors, styles, records)
|
|
196
|
+
QvpRnWords.kt each word's record, built once per page
|
|
197
|
+
Codes.kt QVP_TARGET_* and QVP_SELECTOR_* by name (scripts/gen-rn-enums.py writes it)
|
|
188
198
|
QvpPackage.kt
|
|
189
199
|
src/index.tsx typed API: <QvpPageView/>, <QvpPassageView/>, useQvp(), Qvp, QvpAtlas, QvpOrnaments, Sel, T, constants
|
|
200
|
+
src/codes.ts the same codes for T and Sel (scripts/gen-rn-enums.py writes it)
|
|
190
201
|
```
|
|
191
202
|
|
|
192
203
|
## iOS — TODO
|
|
193
204
|
|
|
194
205
|
Not implemented (no macOS in the build environment). The iOS side mirrors the Android module over the
|
|
195
206
|
same `qvp.h`: a Swift `QvpPage`/`QvpAtlas` over `libqvp_ffi.a` (build with
|
|
196
|
-
`cargo build -p qvp-ffi --
|
|
207
|
+
`cargo build -p qvp-ffi --profile dist --target aarch64-apple-ios[-sim]`), a `UIView` renderer with the
|
|
197
208
|
same draw order (highlight bands → cached base ink → styled ink → mask boxes, `tick(now)` per
|
|
198
209
|
`CADisplayLink` frame), an `RCTViewManager` exposing the props above with the same reconciliation, and
|
|
199
210
|
an `RCTBridgeModule` with the same method names. `src/index.tsx` needs no changes.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Generated by scripts/gen-rn-enums.py from crates/qvp-ffi/include/qvp.h. Do not edit.
|
|
2
|
+
package ws.quran.qvp.rn
|
|
3
|
+
|
|
4
|
+
/** The QVP_TARGET_* and QVP_SELECTOR_* codes, and each code by its JavaScript name. */
|
|
5
|
+
object Codes {
|
|
6
|
+
const val TARGET_PAGE = 0
|
|
7
|
+
const val TARGET_WORD = 1
|
|
8
|
+
const val TARGET_WORDS = 2
|
|
9
|
+
const val TARGET_AYAH = 3
|
|
10
|
+
const val TARGET_AYAH_RANGE = 4
|
|
11
|
+
const val TARGET_LINE = 5
|
|
12
|
+
const val TARGET_SURAH = 6
|
|
13
|
+
const val TARGET_RANGE = 7
|
|
14
|
+
/** QVP_TARGET_*: the kind of a target, by name. */
|
|
15
|
+
val TARGETS: Map<String, Int> = mapOf("page" to TARGET_PAGE, "word" to TARGET_WORD, "words" to TARGET_WORDS, "ayah" to TARGET_AYAH, "ayahRange" to TARGET_AYAH_RANGE, "line" to TARGET_LINE, "surah" to TARGET_SURAH, "range" to TARGET_RANGE)
|
|
16
|
+
const val SELECTOR_PAGE = 0
|
|
17
|
+
const val SELECTOR_PATH = 1
|
|
18
|
+
const val SELECTOR_WORD_PATH = 2
|
|
19
|
+
const val SELECTOR_WORD_MARK = 3
|
|
20
|
+
const val SELECTOR_WORD_MARK_NAMED = 4
|
|
21
|
+
const val SELECTOR_WORD_BODY = 5
|
|
22
|
+
const val SELECTOR_WORD_MARKS = 6
|
|
23
|
+
const val SELECTOR_WORD = 7
|
|
24
|
+
const val SELECTOR_AYAH = 8
|
|
25
|
+
const val SELECTOR_LINE = 9
|
|
26
|
+
const val SELECTOR_MARK = 10
|
|
27
|
+
const val SELECTOR_CATEGORY = 11
|
|
28
|
+
const val SELECTOR_FAMILY = 12
|
|
29
|
+
const val SELECTOR_KIND = 13
|
|
30
|
+
const val SELECTOR_DECORATION = 14
|
|
31
|
+
const val SELECTOR_DECORATION_INDEX = 15
|
|
32
|
+
/** QVP_SELECTOR_*: the kind of a selector, by name. */
|
|
33
|
+
val SELECTORS: Map<String, Int> = mapOf("page" to SELECTOR_PAGE, "path" to SELECTOR_PATH, "wordPath" to SELECTOR_WORD_PATH, "wordMark" to SELECTOR_WORD_MARK, "wordMarkNamed" to SELECTOR_WORD_MARK_NAMED, "wordBody" to SELECTOR_WORD_BODY, "wordMarks" to SELECTOR_WORD_MARKS, "word" to SELECTOR_WORD, "ayah" to SELECTOR_AYAH, "line" to SELECTOR_LINE, "mark" to SELECTOR_MARK, "category" to SELECTOR_CATEGORY, "family" to SELECTOR_FAMILY, "kind" to SELECTOR_KIND, "decoration" to SELECTOR_DECORATION, "decorationIndex" to SELECTOR_DECORATION_INDEX)
|
|
34
|
+
}
|
|
@@ -13,8 +13,8 @@ import ws.quran.qvp.Target
|
|
|
13
13
|
* styling decisions live here — every call goes to [QvpPage] / [QvpAtlas], which go to the engine.
|
|
14
14
|
*
|
|
15
15
|
* Targets from JS: "page" | "2:255" | "2:255:3" | "2:255-257" | "line:7" | "surah:2" | word index |
|
|
16
|
-
* [word indices] | {target, a, b, c, words} (target = QVP_TARGET_* or its name).
|
|
17
|
-
* Selectors from JS: {selector, a, b, c} (selector = QVP_SELECTOR_* or its name). Colours: '#rgb' | '#rrggbb' | '#rrggbbaa'.
|
|
16
|
+
* [word indices] | {target, a, b, c, words} (target = QVP_TARGET_* or its name in [Codes]).
|
|
17
|
+
* Selectors from JS: {selector, a, b, c} (selector = QVP_SELECTOR_* or its name in [Codes]). Colours: '#rgb' | '#rrggbb' | '#rrggbbaa'.
|
|
18
18
|
*/
|
|
19
19
|
object Marshal {
|
|
20
20
|
// ── colours ──
|
|
@@ -36,11 +36,10 @@ object Marshal {
|
|
|
36
36
|
else -> IntArray(0)
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
private
|
|
41
|
-
private fun kindOf(v: Any?, names: List<String>): Int = when (v) {
|
|
39
|
+
/** A code given as a number, or by its name in [names] (or as a numeral); -1 when neither. */
|
|
40
|
+
private fun codeOf(v: Any?, names: Map<String, Int>): Int = when (v) {
|
|
42
41
|
is Number -> v.toInt()
|
|
43
|
-
is String -> names
|
|
42
|
+
is String -> names[v] ?: v.toIntOrNull() ?: -1
|
|
44
43
|
else -> -1
|
|
45
44
|
}
|
|
46
45
|
|
|
@@ -53,9 +52,15 @@ object Marshal {
|
|
|
53
52
|
is IntArray -> Target.words(v)
|
|
54
53
|
is Map<*, *> -> {
|
|
55
54
|
val a = num(v["a"]) ?: 0; val b = num(v["b"]) ?: 0; val c = num(v["c"]) ?: 0
|
|
56
|
-
when (
|
|
57
|
-
|
|
58
|
-
|
|
55
|
+
when (codeOf(v["target"], Codes.TARGETS)) {
|
|
56
|
+
Codes.TARGET_PAGE -> Target.page()
|
|
57
|
+
Codes.TARGET_WORD -> Target.word(a)
|
|
58
|
+
Codes.TARGET_WORDS -> Target.words(ints(v["words"] ?: v["a"]))
|
|
59
|
+
Codes.TARGET_AYAH -> Target.ayah(a, b)
|
|
60
|
+
Codes.TARGET_AYAH_RANGE -> Target.ayahRange(a, b, c)
|
|
61
|
+
Codes.TARGET_LINE -> Target.line(a)
|
|
62
|
+
Codes.TARGET_SURAH -> Target.surah(a)
|
|
63
|
+
Codes.TARGET_RANGE -> Target.range(a, b)
|
|
59
64
|
else -> Target.words(IntArray(0))
|
|
60
65
|
}
|
|
61
66
|
}
|
|
@@ -66,34 +71,57 @@ object Marshal {
|
|
|
66
71
|
fun selector(v: Any?): Selector? {
|
|
67
72
|
val m = v as? Map<*, *> ?: return null
|
|
68
73
|
val a = num(m["a"]) ?: 0; val b = num(m["b"]) ?: 0; val c = num(m["c"]) ?: 0
|
|
69
|
-
return when (
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
74
|
+
return when (codeOf(m["selector"], Codes.SELECTORS)) {
|
|
75
|
+
Codes.SELECTOR_PAGE -> Selector.page()
|
|
76
|
+
Codes.SELECTOR_PATH -> Selector.path(a)
|
|
77
|
+
Codes.SELECTOR_WORD_PATH -> Selector.wordPath(a, b)
|
|
78
|
+
Codes.SELECTOR_WORD_MARK -> Selector.wordMark(a, b)
|
|
79
|
+
Codes.SELECTOR_WORD_MARK_NAMED -> Selector.wordMarkNamed(a, (m["mark"] as? String) ?: QvpEngine.markName(b), c)
|
|
80
|
+
Codes.SELECTOR_WORD_BODY -> Selector.wordBody(a)
|
|
81
|
+
Codes.SELECTOR_WORD_MARKS -> Selector.wordMarks(a)
|
|
82
|
+
Codes.SELECTOR_WORD -> Selector.word(a)
|
|
83
|
+
Codes.SELECTOR_AYAH -> Selector.ayah(a, b)
|
|
84
|
+
Codes.SELECTOR_LINE -> Selector.line(a)
|
|
85
|
+
Codes.SELECTOR_MARK -> (m["mark"] as? String)?.let { Selector.mark(it) } ?: Selector.mark(a)
|
|
86
|
+
Codes.SELECTOR_CATEGORY -> Selector.category(a)
|
|
87
|
+
Codes.SELECTOR_FAMILY -> Selector.family(a)
|
|
88
|
+
Codes.SELECTOR_KIND -> Selector.kind(a)
|
|
89
|
+
Codes.SELECTOR_DECORATION -> Selector.decoration(a)
|
|
90
|
+
Codes.SELECTOR_DECORATION_INDEX -> Selector.decorationIndex(a)
|
|
75
91
|
else -> null
|
|
76
92
|
}
|
|
77
93
|
}
|
|
78
94
|
|
|
95
|
+
/** The constant of [entries] that [v] names, in any of its spellings: the constant's own
|
|
96
|
+
* (RASM_IMLAI), snake case (rasm_imlai) or the camelCase of the TypeScript types (rasmImlai). */
|
|
97
|
+
private fun <E : Enum<E>> named(entries: List<E>, v: String): E? {
|
|
98
|
+
val key = v.replace("_", "")
|
|
99
|
+
return entries.firstOrNull { it.name.replace("_", "").equals(key, ignoreCase = true) }
|
|
100
|
+
}
|
|
101
|
+
/** A constant's name as the TypeScript types spell it: RASM_IMLAI is rasmImlai. */
|
|
102
|
+
fun jsName(e: Enum<*>): String {
|
|
103
|
+
val parts = e.name.lowercase().split('_')
|
|
104
|
+
return parts[0] + parts.drop(1).joinToString("") { it.replaceFirstChar(Char::uppercaseChar) }
|
|
105
|
+
}
|
|
106
|
+
|
|
79
107
|
fun form(v: Any?, d: Form = Form.RASM_UTHMANI): Form = when (v) {
|
|
80
108
|
is Number -> Form.entries.getOrElse(v.toInt()) { d }
|
|
81
|
-
is String -> Form.entries
|
|
109
|
+
is String -> named(Form.entries, v) ?: d
|
|
82
110
|
else -> d
|
|
83
111
|
}
|
|
84
112
|
fun searchMode(v: Any?): SearchMode = when (v) {
|
|
85
113
|
is Number -> SearchMode.entries.getOrElse(v.toInt()) { SearchMode.INCLUDES }
|
|
86
|
-
is String -> SearchMode.entries
|
|
114
|
+
is String -> named(SearchMode.entries, v) ?: SearchMode.INCLUDES
|
|
87
115
|
else -> SearchMode.INCLUDES
|
|
88
116
|
}
|
|
89
117
|
fun maskMode(v: Any?): MaskMode = when (v) {
|
|
90
118
|
is Number -> MaskMode.entries.getOrElse(v.toInt()) { MaskMode.HIDE }
|
|
91
|
-
is String -> MaskMode.entries
|
|
119
|
+
is String -> named(MaskMode.entries, v) ?: MaskMode.HIDE
|
|
92
120
|
else -> MaskMode.HIDE
|
|
93
121
|
}
|
|
94
122
|
fun division(v: Any?): Division = when (v) {
|
|
95
123
|
is Number -> Division.entries.getOrElse(v.toInt()) { Division.JUZ }
|
|
96
|
-
is String -> Division.entries
|
|
124
|
+
is String -> named(Division.entries, v) ?: Division.JUZ
|
|
97
125
|
else -> Division.JUZ
|
|
98
126
|
}
|
|
99
127
|
|
|
@@ -101,8 +129,8 @@ object Marshal {
|
|
|
101
129
|
fun highlightStyle(v: Any?): QvpHighlightStyle {
|
|
102
130
|
val m = v as? Map<*, *> ?: return QvpHighlightStyle()
|
|
103
131
|
val d = QvpHighlightStyle()
|
|
104
|
-
val mode = when (val x = m["mode"]) { is Number -> HighlightMode.entries.getOrElse(x.toInt()) { d.mode }; is String -> HighlightMode.entries
|
|
105
|
-
val height = when (val x = m["height"]) { is Number -> BandHeight.entries.getOrElse(x.toInt()) { d.height }; is String -> BandHeight.entries
|
|
132
|
+
val mode = when (val x = m["mode"]) { is Number -> HighlightMode.entries.getOrElse(x.toInt()) { d.mode }; is String -> named(HighlightMode.entries, x) ?: d.mode; else -> d.mode }
|
|
133
|
+
val height = when (val x = m["height"]) { is Number -> BandHeight.entries.getOrElse(x.toInt()) { d.height }; is String -> named(BandHeight.entries, x) ?: d.height; else -> d.height }
|
|
106
134
|
return QvpHighlightStyle(mode = mode, ink = color(m["ink"], d.ink), band = color(m["band"], d.band), height = height, padX = flt(m["padX"], d.padX), padY = flt(m["padY"], d.padY),
|
|
107
135
|
radius = flt(m["radius"], d.radius), seam = flt(m["seam"], d.seam), transitionMs = num(m["ms"] ?: m["transitionMs"]) ?: d.transitionMs, layer = num(m["layer"]) ?: d.layer)
|
|
108
136
|
}
|
|
@@ -158,19 +186,39 @@ object Marshal {
|
|
|
158
186
|
"overflow" to listOf(i.overflow.left, i.overflow.top, i.overflow.right, i.overflow.bottom))
|
|
159
187
|
|
|
160
188
|
// ── Kotlin → JS ──
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
189
|
+
/**
|
|
190
|
+
* The engine's name of every id of the path and decoration tables, read once. A page has
|
|
191
|
+
* hundreds of paths, and each names its kind, mark, category and family: a lookup here is
|
|
192
|
+
* an array read, not four calls into the engine. Ids run 0..255, so the table covers every
|
|
193
|
+
* id a path can hold, and an id the engine does not know gets the engine's own answer.
|
|
194
|
+
*/
|
|
195
|
+
private class Names {
|
|
196
|
+
val kind = Array(256) { QvpEngine.kindName(it) }
|
|
197
|
+
val mark = Array(256) { QvpEngine.markName(it) }
|
|
198
|
+
val category = Array(256) { QvpEngine.categoryName(it) }
|
|
199
|
+
val family = Array(256) { QvpEngine.familyName(it) }
|
|
200
|
+
val decoration = Array(256) { QvpEngine.decorationName(it).ifEmpty { "other" } }
|
|
201
|
+
}
|
|
202
|
+
private val names by lazy { Names() }
|
|
203
|
+
|
|
204
|
+
/** The forms a page has: [Form.RASM_UTHMANI] always, and each other form the words sidecar gave. */
|
|
205
|
+
fun forms(p: QvpPage): List<Form> = Form.entries.filter { it == Form.RASM_UTHMANI || p.hasForm(it) }
|
|
206
|
+
|
|
207
|
+
/** One word and its paths. [forms] is [forms] of the page, read once by the caller. */
|
|
208
|
+
fun word(p: QvpPage, w: QvpWord, forms: List<Form>): Map<String, Any?> {
|
|
209
|
+
val n = names
|
|
210
|
+
val text = LinkedHashMap<String, String>()
|
|
211
|
+
for (f in forms) text[jsName(f)] = p.wordForm(w.index, f)
|
|
164
212
|
val paths = (w.firstPath until w.firstPath + w.nPaths).map { i ->
|
|
165
213
|
val kind = p.pathKind(i); val mark = p.pathMark(i); val cat = p.pathCategory(i); val fam = p.pathFamily(i)
|
|
166
|
-
mapOf("index" to i, "kind" to kind, "kindName" to
|
|
167
|
-
"nthInWord" to p.pathNthInWord(i), "category" to cat, "categoryName" to
|
|
214
|
+
mapOf("index" to i, "kind" to kind, "kindName" to n.kind[kind], "mark" to mark, "markName" to n.mark[mark], "nthMark" to p.pathNthMark(i),
|
|
215
|
+
"nthInWord" to p.pathNthInWord(i), "category" to cat, "categoryName" to n.category[cat], "family" to fam, "familyName" to n.family[fam], "line" to p.pathLine(i))
|
|
168
216
|
}
|
|
169
217
|
return mapOf("index" to w.index, "surah" to w.surah, "ayah" to w.ayah, "word" to w.word, "line" to w.line, "lineIndex" to w.lineIndex, "ayahIndex" to w.ayahIndex,
|
|
170
218
|
"x0" to w.x0, "y0" to w.y0, "x1" to w.x1, "y1" to w.y1, "text" to w.text, "firstPath" to w.firstPath, "nPaths" to w.nPaths,
|
|
171
|
-
"wordKey" to w.wordKey, "ayahKey" to w.ayahKey, "forms" to
|
|
219
|
+
"wordKey" to w.wordKey, "ayahKey" to w.ayahKey, "forms" to text, "label" to p.wordLabel(w.index), "paths" to paths)
|
|
172
220
|
}
|
|
173
|
-
fun decoration(d: QvpDecoration): Map<String, Any?> = mapOf("index" to d.index, "decoration" to d.decoration, "decorationName" to
|
|
221
|
+
fun decoration(d: QvpDecoration): Map<String, Any?> = mapOf("index" to d.index, "decoration" to d.decoration, "decorationName" to names.decoration[d.decoration and 0xff],
|
|
174
222
|
"surah" to d.surah, "ayah" to d.ayah, "line" to d.line, "x0" to d.x0, "y0" to d.y0, "x1" to d.x1, "y1" to d.y1, "text" to d.text, "firstPath" to d.firstPath, "nPaths" to d.nPaths)
|
|
175
223
|
fun hit(p: QvpPage, h: QvpHit): Map<String, Any?> {
|
|
176
224
|
val w = if (h.word >= 0) p.words[h.word] else null
|
|
@@ -200,8 +248,8 @@ object Marshal {
|
|
|
200
248
|
fun atlasRubuAlHizb(r: QvpAtlasRubuAlHizb): Map<String, Any?> = mapOf("rubuAlHizb" to r.rubuAlHizb, "surah" to r.surah, "ayah" to r.ayah, "page" to r.page, "ayahKey" to r.ayahKey)
|
|
201
249
|
fun layout(l: QvpLayout): Map<String, Any?> = mapOf("scale" to l.scale, "offsetX" to l.offsetX, "offsetY" to l.offsetY, "contentW" to l.contentW, "contentH" to l.contentH, "lineSpacing" to l.lineSpacing, "fitScale" to l.fitScale, "fitX" to l.fitX, "fitY" to l.fitY, "lineDy" to l.lineDy.toList(),
|
|
202
250
|
"slots" to l.slotTop.indices.map { listOf(l.slotTop[it], l.slotBottom[it]) })
|
|
203
|
-
fun pageInfo(p: QvpPage): Map<String, Any?> = mapOf("page" to p.pageNo, "width" to p.width, "height" to p.height, "nLines" to p.nLines, "nAyahs" to p.nAyahs, "nWords" to p.nWords, "nPaths" to p.nPaths, "nDecorations" to p.nDecorations,
|
|
204
|
-
"lineSpacing" to p.lineSpacing, "forms" to
|
|
251
|
+
fun pageInfo(p: QvpPage, forms: List<Form>): Map<String, Any?> = mapOf("page" to p.pageNo, "width" to p.width, "height" to p.height, "nLines" to p.nLines, "nAyahs" to p.nAyahs, "nWords" to p.nWords, "nPaths" to p.nPaths, "nDecorations" to p.nDecorations,
|
|
252
|
+
"lineSpacing" to p.lineSpacing, "forms" to forms.map { jsName(it) })
|
|
205
253
|
fun selection(p: QvpPage): Map<String, Any?> {
|
|
206
254
|
val ws = p.selection()
|
|
207
255
|
return mapOf("words" to ws.toList(), "text" to (if (ws.isEmpty()) "" else p.text(Target.words(ws))), "citation" to (if (ws.isEmpty()) "" else p.citation(ws)),
|
|
@@ -3,27 +3,71 @@ package ws.quran.qvp.rn
|
|
|
3
3
|
import com.facebook.react.bridge.*
|
|
4
4
|
import com.facebook.react.module.annotations.ReactModule
|
|
5
5
|
import com.facebook.react.uimanager.UIManagerHelper
|
|
6
|
+
import java.util.concurrent.CountDownLatch
|
|
7
|
+
import java.util.concurrent.ExecutorService
|
|
8
|
+
import java.util.concurrent.Executors
|
|
9
|
+
import java.util.concurrent.RejectedExecutionException
|
|
6
10
|
import ws.quran.qvp.*
|
|
7
11
|
import ws.quran.qvp.Target
|
|
8
12
|
|
|
9
13
|
/**
|
|
10
14
|
* Promise-based queries on the page behind a `<QvpPageView />` (looked up by react tag) plus engine-wide
|
|
11
|
-
* helpers and the atlas.
|
|
12
|
-
*
|
|
15
|
+
* helpers and the atlas. Names follow docs/API.md.
|
|
16
|
+
*
|
|
17
|
+
* Two threads run the calls. The query thread, which this module owns, runs every call that reads
|
|
18
|
+
* only what a page fixed when it loaded: its words, ayahs, lines, text, search, metadata and crop
|
|
19
|
+
* box. It also runs the engine-wide helpers and owns the atlases. A long query on it does not hold
|
|
20
|
+
* up a frame. The view keeps the page open while a query reads it ([QvpRnPageView.read]). Every
|
|
21
|
+
* call that reads or changes the layout, the view, styles, colours, the selection, the mask, the
|
|
22
|
+
* reveal or the dress runs on the UI thread, where the view draws.
|
|
13
23
|
*/
|
|
14
24
|
@ReactModule(name = QvpModule.NAME)
|
|
15
25
|
class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJavaModule(ctx) {
|
|
16
26
|
override fun getName() = NAME
|
|
27
|
+
/** The query thread. The atlases below are touched only on it. */
|
|
28
|
+
private val queries: ExecutorService = Executors.newSingleThreadExecutor { r -> Thread(r, "qvp-rn-query").apply { isDaemon = true } }
|
|
17
29
|
private val atlases = HashMap<Int, QvpAtlas>()
|
|
18
30
|
private val atlasByUri = HashMap<String, Int>()
|
|
19
31
|
private var nextAtlas = 1
|
|
20
32
|
|
|
21
33
|
private fun view(tag: Int): QvpRnPageView? = QvpRegistry.get(tag) ?: runCatching { UIManagerHelper.getUIManagerForReactTag(ctx, tag)?.resolveView(tag) as? QvpRnPageView }.getOrNull()
|
|
22
34
|
// Every @ReactMethod must be `void` for the TurboModule interop layer: these helpers return Unit on purpose.
|
|
23
|
-
private fun
|
|
35
|
+
private fun settle(promise: Promise, block: () -> Any?) {
|
|
36
|
+
try { promise.resolve(Marshal.toJs(block())) } catch (e: Throwable) { promise.reject("qvp", e.message ?: e.toString(), e) }
|
|
37
|
+
}
|
|
38
|
+
private fun ui(promise: Promise, block: () -> Any?) { UiThreadUtil.runOnUiThread { settle(promise, block) } }
|
|
39
|
+
/** Run [task] on the query thread, or reject when the module is gone. */
|
|
40
|
+
private fun queue(promise: Promise, task: () -> Unit) {
|
|
41
|
+
try { queries.execute(task) } catch (e: RejectedExecutionException) { promise.reject("qvp", "QvpModule was invalidated", e) }
|
|
42
|
+
}
|
|
43
|
+
/** An engine-wide call, or an atlas call, on the query thread. */
|
|
44
|
+
private fun off(promise: Promise, block: () -> Any?) = queue(promise) { settle(promise, block) }
|
|
45
|
+
/**
|
|
46
|
+
* A read-only page query on the query thread, with the page held open until it returns. A view
|
|
47
|
+
* the registry does not hold (not attached yet, or detached) is found through the UIManager,
|
|
48
|
+
* which only the UI thread may call, so that query runs there as before.
|
|
49
|
+
*/
|
|
50
|
+
private fun readPage(tag: Int, promise: Promise, block: (QvpRnPageView, QvpPage) -> Any?) = queue(promise) {
|
|
51
|
+
val v = QvpRegistry.get(tag)
|
|
52
|
+
if (v == null) withPage(tag, promise, block)
|
|
53
|
+
else settle(promise) { v.read { p -> block(v, p ?: throw IllegalStateException("QvpPageView $tag has no page loaded")) } }
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A page call on the UI thread that the queries queued before it see done, and that is done
|
|
57
|
+
* before the queries queued after it start: the query thread waits for it. It holds no page
|
|
58
|
+
* open while it waits, so the UI thread never waits for it in turn.
|
|
59
|
+
*/
|
|
60
|
+
private fun inOrder(tag: Int, promise: Promise, block: (QvpRnPageView, QvpPage) -> Any?) = queue(promise) {
|
|
61
|
+
val done = CountDownLatch(1)
|
|
24
62
|
UiThreadUtil.runOnUiThread {
|
|
25
|
-
try {
|
|
63
|
+
try {
|
|
64
|
+
settle(promise) {
|
|
65
|
+
val v = view(tag) ?: throw IllegalStateException("no QvpPageView with tag $tag")
|
|
66
|
+
block(v, v.page ?: throw IllegalStateException("QvpPageView $tag has no page loaded"))
|
|
67
|
+
}
|
|
68
|
+
} finally { done.countDown() }
|
|
26
69
|
}
|
|
70
|
+
try { done.await() } catch (_: InterruptedException) { Thread.currentThread().interrupt() }
|
|
27
71
|
}
|
|
28
72
|
private fun withPage(tag: Int, promise: Promise, block: (QvpRnPageView, QvpPage) -> Any?) {
|
|
29
73
|
ui(promise) {
|
|
@@ -32,60 +76,64 @@ class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJava
|
|
|
32
76
|
block(v, p)
|
|
33
77
|
}
|
|
34
78
|
}
|
|
35
|
-
private fun withAtlas(id: Int, promise: Promise, block: (QvpAtlas) -> Any?)
|
|
79
|
+
private fun withAtlas(id: Int, promise: Promise, block: (QvpAtlas) -> Any?) = off(promise) { block(atlases[id] ?: throw IllegalStateException("no atlas $id")) }
|
|
36
80
|
private fun opt(m: ReadableMap?): Map<String, Any?> = m?.toHashMap() ?: emptyMap()
|
|
37
|
-
|
|
38
|
-
|
|
81
|
+
/** A target argument as plain values. A query reads its arguments this way on the calling
|
|
82
|
+
* thread, before it is queued, since the bridge's argument objects belong to the call. */
|
|
83
|
+
private fun plain(d: Dynamic): Any? = when (d.type) {
|
|
84
|
+
ReadableType.String -> d.asString(); ReadableType.Number -> d.asDouble(); ReadableType.Array -> d.asArray()?.toArrayList(); ReadableType.Map -> d.asMap()?.toHashMap(); else -> null }
|
|
85
|
+
private fun tgt(d: Dynamic, p: QvpPage): Target = Marshal.target(plain(d), p)
|
|
39
86
|
private fun ints(a: ReadableArray?): IntArray = a?.toArrayList()?.mapNotNull { (it as? Number)?.toInt() }?.toIntArray() ?: IntArray(0)
|
|
40
87
|
|
|
41
88
|
// ── page facts ──
|
|
42
|
-
@ReactMethod fun info(tag: Int, promise: Promise) =
|
|
43
|
-
@ReactMethod fun words(tag: Int, promise: Promise) =
|
|
44
|
-
@ReactMethod fun word(tag: Int, index: Int, promise: Promise) =
|
|
45
|
-
@ReactMethod fun ayahs(tag: Int, promise: Promise) =
|
|
46
|
-
@ReactMethod fun lines(tag: Int, promise: Promise) =
|
|
47
|
-
@ReactMethod fun decorations(tag: Int, promise: Promise) =
|
|
48
|
-
@ReactMethod fun findWord(tag: Int, s: Int, a: Int, w: Int, promise: Promise) =
|
|
49
|
-
@ReactMethod fun targetWords(tag: Int, target: Dynamic, promise: Promise) =
|
|
50
|
-
@ReactMethod fun wordForm(tag: Int, index: Int, form: String?, promise: Promise) =
|
|
51
|
-
@ReactMethod fun hasForm(tag: Int, form: String?, promise: Promise) =
|
|
52
|
-
@ReactMethod fun attachWords(tag: Int, json: String, promise: Promise) =
|
|
89
|
+
@ReactMethod fun info(tag: Int, promise: Promise) = readPage(tag, promise) { v, p -> Marshal.pageInfo(p, v.words(p).forms) + mapOf("loadMs" to v.loadMs, "bytes" to v.pageBytes) }
|
|
90
|
+
@ReactMethod fun words(tag: Int, promise: Promise) = readPage(tag, promise) { v, p -> v.words(p).all() }
|
|
91
|
+
@ReactMethod fun word(tag: Int, index: Int, promise: Promise) = readPage(tag, promise) { v, p -> v.words(p).word(index) }
|
|
92
|
+
@ReactMethod fun ayahs(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.ayahs.map { Marshal.ayah(it) } }
|
|
93
|
+
@ReactMethod fun lines(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.lines.map { Marshal.line(it) } }
|
|
94
|
+
@ReactMethod fun decorations(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.decorations.map { Marshal.decoration(it) } }
|
|
95
|
+
@ReactMethod fun findWord(tag: Int, s: Int, a: Int, w: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.findWord(s, a, w) }
|
|
96
|
+
@ReactMethod fun targetWords(tag: Int, target: Dynamic, promise: Promise) { val t = plain(target); readPage(tag, promise) { _, p -> p.targetWords(Marshal.target(t, p)).toList() } }
|
|
97
|
+
@ReactMethod fun wordForm(tag: Int, index: Int, form: String?, promise: Promise) = readPage(tag, promise) { _, p -> p.wordForm(index, Marshal.form(form)) }
|
|
98
|
+
@ReactMethod fun hasForm(tag: Int, form: String?, promise: Promise) = readPage(tag, promise) { _, p -> p.hasForm(Marshal.form(form)) }
|
|
99
|
+
@ReactMethod fun attachWords(tag: Int, json: String, promise: Promise) = inOrder(tag, promise) { v, p -> v.attachWords(p, json) }
|
|
53
100
|
|
|
54
101
|
// ── metadata ──
|
|
55
|
-
@ReactMethod fun surahs(tag: Int, promise: Promise) =
|
|
56
|
-
@ReactMethod fun divisions(tag: Int, promise: Promise) =
|
|
102
|
+
@ReactMethod fun surahs(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.surahs().map { Marshal.surah(it) } }
|
|
103
|
+
@ReactMethod fun divisions(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.divisions().map { Marshal.division(it) } }
|
|
57
104
|
@ReactMethod fun surahHeaders(tag: Int, promise: Promise) = withPage(tag, promise) { _, p -> p.surahHeaders().map { Marshal.surahHeader(it) } }
|
|
58
105
|
@ReactMethod fun surahHeadersView(tag: Int, promise: Promise) = withPage(tag, promise) { _, p -> p.surahHeadersView().map { Marshal.surahHeader(it) } }
|
|
59
|
-
@ReactMethod fun ayahMarks(tag: Int, promise: Promise) =
|
|
60
|
-
@ReactMethod fun rosettes(tag: Int, promise: Promise) =
|
|
61
|
-
@ReactMethod fun sajdahs(tag: Int, promise: Promise) =
|
|
62
|
-
@ReactMethod fun ayahKeys(tag: Int, promise: Promise) =
|
|
63
|
-
@ReactMethod fun ayahWordCount(tag: Int, s: Int, a: Int, promise: Promise) =
|
|
64
|
-
@ReactMethod fun reciteMap(tag: Int, s: Int, a: Int, n: Int, promise: Promise) =
|
|
65
|
-
@ReactMethod fun wordLabel(tag: Int, i: Int, promise: Promise) =
|
|
66
|
-
@ReactMethod fun ayahLabel(tag: Int, i: Int, promise: Promise) =
|
|
106
|
+
@ReactMethod fun ayahMarks(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.ayahMarks().map { Marshal.ayahMark(it) } }
|
|
107
|
+
@ReactMethod fun rosettes(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.rosettes().map { Marshal.rosette(it) } }
|
|
108
|
+
@ReactMethod fun sajdahs(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.sajdahs().map { Marshal.sajdah(it) } }
|
|
109
|
+
@ReactMethod fun ayahKeys(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.ayahKeys().map { mapOf("surah" to it.first, "ayah" to it.second, "ayahKey" to "${it.first}:${it.second}") } }
|
|
110
|
+
@ReactMethod fun ayahWordCount(tag: Int, s: Int, a: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.ayahWordCount(s, a).let { mapOf("count" to it.first, "isComplete" to it.second) } }
|
|
111
|
+
@ReactMethod fun reciteMap(tag: Int, s: Int, a: Int, n: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.reciteMap(s, a, n)?.toList() }
|
|
112
|
+
@ReactMethod fun wordLabel(tag: Int, i: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.wordLabel(i) }
|
|
113
|
+
@ReactMethod fun ayahLabel(tag: Int, i: Int, promise: Promise) = readPage(tag, promise) { _, p -> p.ayahLabel(i) }
|
|
67
114
|
|
|
68
115
|
// ── text & search ──
|
|
69
|
-
@ReactMethod fun text(tag: Int, target: Dynamic, opts: ReadableMap?, promise: Promise) =
|
|
70
|
-
|
|
71
|
-
@ReactMethod fun search(tag: Int, query: String, opts: ReadableMap?, promise: Promise) =
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
@ReactMethod fun
|
|
75
|
-
@ReactMethod fun arabic(op: String, s: String, promise: Promise) = ui(promise) { when (op) { "strip" -> QvpEngine.strip(s); "fold" -> QvpEngine.fold(s); "normalize" -> QvpEngine.normalize(s); "loose", "looseKey" -> QvpEngine.looseKey(s); else -> s } }
|
|
116
|
+
@ReactMethod fun text(tag: Int, target: Dynamic, opts: ReadableMap?, promise: Promise) { val t = plain(target); val o = opt(opts)
|
|
117
|
+
readPage(tag, promise) { _, p -> p.text(Marshal.target(t, p), Marshal.form(o["form"]), (o["wordSep"] as? String) ?: " ", (o["lineSep"] as? String) ?: "\n") } }
|
|
118
|
+
@ReactMethod fun search(tag: Int, query: String, opts: ReadableMap?, promise: Promise) { val o = opt(opts)
|
|
119
|
+
readPage(tag, promise) { _, p -> p.search(query, Marshal.form(o["form"], Form.SEARCH), Marshal.searchMode(o["mode"]), o["normalize"] != false, o["looseMatch"] != false, (o["limit"] as? Number)?.toInt() ?: 0).map { Marshal.match(it) } } }
|
|
120
|
+
@ReactMethod fun citation(tag: Int, words: ReadableArray, promise: Promise) { val ws = ints(words); readPage(tag, promise) { _, p -> p.citation(ws) } }
|
|
121
|
+
@ReactMethod fun arabic(op: String, s: String, promise: Promise) = off(promise) { when (op) { "strip" -> QvpEngine.strip(s); "fold" -> QvpEngine.fold(s); "normalize" -> QvpEngine.normalize(s); "loose", "looseKey" -> QvpEngine.looseKey(s); else -> s } }
|
|
76
122
|
|
|
77
123
|
// ── hit testing / layout (the view already does gestures; these are for scroll-into-view etc.) ──
|
|
78
124
|
private fun hitOptions(o: Map<String, Any?>) = QvpHitOptions((o["maxDistance"] as? Number)?.toFloat() ?: QvpDefaults.TAP_DISTANCE, (o["gapBias"] as? Number)?.toFloat() ?: QvpDefaults.GAP_BIAS, o["preferExact"] != false)
|
|
79
|
-
/** Exact
|
|
125
|
+
/** Exact hit at a point in page units: the outline under the point, else the box of a word or a decoration. */
|
|
80
126
|
@ReactMethod fun hitTestExact(tag: Int, x: Double, y: Double, promise: Promise) = withPage(tag, promise) { _, p -> p.hitTestExact(x.toFloat(), y.toFloat())?.let { Marshal.hit(p, it) } }
|
|
81
127
|
/** Gap-aware hit at a point in page units. */
|
|
82
128
|
@ReactMethod fun hitTest(tag: Int, x: Double, y: Double, opts: ReadableMap?, promise: Promise) = withPage(tag, promise) { _, p -> p.hitTest(x.toFloat(), y.toFloat(), hitOptions(opt(opts)))?.let { Marshal.hit(p, it) } }
|
|
83
|
-
/** Exact
|
|
129
|
+
/** Exact hit at a point in view dp (density and pan/zoom removed here, the layout in the engine). */
|
|
84
130
|
@ReactMethod fun hitTestExactView(tag: Int, x: Double, y: Double, promise: Promise) = withPage(tag, promise) { v, p -> val d = v.resources.displayMetrics.density
|
|
85
|
-
p.
|
|
131
|
+
val (lx, ly) = p.viewToLayout(QvpView(v.inner.viewScale, v.inner.viewOx, v.inner.viewOy), (x * d).toFloat(), (y * d).toFloat())
|
|
132
|
+
p.hitTestExactView(lx, ly)?.let { Marshal.hit(p, it) } }
|
|
86
133
|
@ReactMethod fun hitTestView(tag: Int, x: Double, y: Double, opts: ReadableMap?, promise: Promise) = withPage(tag, promise) { v, p ->
|
|
87
134
|
val o = opt(opts); val d = v.resources.displayMetrics.density
|
|
88
|
-
p.
|
|
135
|
+
val (lx, ly) = p.viewToLayout(QvpView(v.inner.viewScale, v.inner.viewOx, v.inner.viewOy), (x * d).toFloat(), (y * d).toFloat())
|
|
136
|
+
p.hitTestView(lx, ly, hitOptions(o))?.let { Marshal.hit(p, it) } }
|
|
89
137
|
@ReactMethod fun wordBoundsView(tag: Int, i: Int, promise: Promise) = withPage(tag, promise) { v, p -> val d = v.resources.displayMetrics.density
|
|
90
138
|
p.wordBoundsView(i)?.let { b -> mapOf("x0" to (v.inner.viewOx + b[0] * v.inner.viewScale) / d, "y0" to (v.inner.viewOy + b[1] * v.inner.viewScale) / d, "x1" to (v.inner.viewOx + b[2] * v.inner.viewScale) / d, "y1" to (v.inner.viewOy + b[3] * v.inner.viewScale) / d) } }
|
|
91
139
|
@ReactMethod fun currentLayout(tag: Int, promise: Promise) = withPage(tag, promise) { _, p -> p.currentLayout?.let { Marshal.layout(it) } }
|
|
@@ -96,7 +144,7 @@ class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJava
|
|
|
96
144
|
@ReactMethod fun layoutWastedFraction(tag: Int, promise: Promise) = withPage(tag, promise) { v, p -> p.layoutWastedFraction(v.inner.layoutSpec()) }
|
|
97
145
|
/** The page's height at the printed pitch for the spec this view lays out with. */
|
|
98
146
|
@ReactMethod fun layoutPrintedHeight(tag: Int, promise: Promise) = withPage(tag, promise) { v, p -> p.layoutPrintedHeight(v.inner.layoutSpec()) }
|
|
99
|
-
@ReactMethod fun grid(tag: Int, promise: Promise) =
|
|
147
|
+
@ReactMethod fun grid(tag: Int, promise: Promise) = readPage(tag, promise) { _, p -> mapOf("lines" to p.grid.lines, "lineSpacing" to p.grid.lineSpacing) }
|
|
100
148
|
@ReactMethod fun stats(tag: Int, promise: Promise) = ui(promise) { view(tag)?.stats() }
|
|
101
149
|
@ReactMethod fun invalidate(tag: Int, promise: Promise) = ui(promise) { view(tag)?.inner?.invalidate(); null }
|
|
102
150
|
|
|
@@ -120,13 +168,13 @@ class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJava
|
|
|
120
168
|
@ReactMethod fun revealStepOf(tag: Int, i: Int, promise: Promise) = withPage(tag, promise) { _, p -> p.revealStepOf(i).toDouble() }
|
|
121
169
|
|
|
122
170
|
// ── crop ──
|
|
123
|
-
@ReactMethod fun cropBounds(tag: Int, target: Dynamic, opts: ReadableMap?, promise: Promise) =
|
|
124
|
-
|
|
171
|
+
@ReactMethod fun cropBounds(tag: Int, target: Dynamic, opts: ReadableMap?, promise: Promise) { val t = plain(target); val o = opt(opts)
|
|
172
|
+
readPage(tag, promise) { _, p -> p.cropBounds(Marshal.target(t, p), (o["pad"] as? Number)?.toFloat() ?: QvpDefaults.CROP_PAD, o["keepAyahMarks"] != false)?.let { Marshal.cropBounds(it) } } }
|
|
125
173
|
@ReactMethod fun cropSvg(tag: Int, target: Dynamic, opts: ReadableMap?, promise: Promise) = withPage(tag, promise) { _, p ->
|
|
126
174
|
val o = opt(opts); p.cropSvg(tgt(target, p), (o["pad"] as? Number)?.toFloat() ?: QvpDefaults.CROP_PAD, o["keepAyahMarks"] != false, Marshal.color(o["background"], 0)) }
|
|
127
175
|
|
|
128
176
|
// ── atlas ──
|
|
129
|
-
@ReactMethod fun loadAtlas(uri: String, promise: Promise) =
|
|
177
|
+
@ReactMethod fun loadAtlas(uri: String, promise: Promise) = off(promise) {
|
|
130
178
|
atlasByUri[uri] ?: run {
|
|
131
179
|
val bytes = when {
|
|
132
180
|
uri.startsWith("asset://") -> ctx.assets.open(uri.removePrefix("asset://")).use { it.readBytes() }
|
|
@@ -139,7 +187,7 @@ class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJava
|
|
|
139
187
|
val id = nextAtlas++; atlases[id] = QvpAtlas(bytes); atlasByUri[uri] = id; id
|
|
140
188
|
}
|
|
141
189
|
}
|
|
142
|
-
@ReactMethod fun freeAtlas(id: Int, promise: Promise) =
|
|
190
|
+
@ReactMethod fun freeAtlas(id: Int, promise: Promise) = off(promise) { atlases.remove(id)?.close(); atlasByUri.entries.removeAll { it.value == id }; null }
|
|
143
191
|
@ReactMethod fun atlasPageOf(id: Int, s: Int, a: Int, promise: Promise) = withAtlas(id, promise) { it.pageOf(s, a) }
|
|
144
192
|
@ReactMethod fun atlasPageRange(id: Int, page: Int, promise: Promise) = withAtlas(id, promise) { it.pageRange(page)?.let { r -> mapOf("first" to mapOf("surah" to r.first.first, "ayah" to r.first.second), "last" to mapOf("surah" to r.second.first, "ayah" to r.second.second)) } }
|
|
145
193
|
@ReactMethod fun atlasPageCount(id: Int, promise: Promise) = withAtlas(id, promise) { it.pageCount() }
|
|
@@ -186,19 +234,25 @@ class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJava
|
|
|
186
234
|
@ReactMethod fun dressRevision(tag: Int, promise: Promise) = withPage(tag, promise) { _, p -> p.dressRevision() }
|
|
187
235
|
|
|
188
236
|
// ── names ──
|
|
189
|
-
@ReactMethod fun markName(m: Int, promise: Promise) =
|
|
190
|
-
@ReactMethod fun markFromName(s: String, promise: Promise) =
|
|
191
|
-
@ReactMethod fun markCategory(m: Int, promise: Promise) =
|
|
192
|
-
@ReactMethod fun engineName(promise: Promise) =
|
|
237
|
+
@ReactMethod fun markName(m: Int, promise: Promise) = off(promise) { QvpEngine.markName(m) }
|
|
238
|
+
@ReactMethod fun markFromName(s: String, promise: Promise) = off(promise) { QvpEngine.markFromName(s) }
|
|
239
|
+
@ReactMethod fun markCategory(m: Int, promise: Promise) = off(promise) { QvpEngine.markCategory(m) }
|
|
240
|
+
@ReactMethod fun engineName(promise: Promise) = off(promise) { QvpEngine.engineName() }
|
|
193
241
|
/** Every name table, read from the engine; the JavaScript side resolves names with these. */
|
|
194
242
|
override fun getConstants(): Map<String, Any> = mapOf("version" to QvpEngine.version(), "formatVersion" to QvpEngine.formatVersion(),
|
|
195
243
|
"marks" to QvpEngine.names(QvpEngine.Names.MARK), "kinds" to QvpEngine.names(QvpEngine.Names.KIND),
|
|
196
244
|
"families" to QvpEngine.names(QvpEngine.Names.FAMILY), "categories" to QvpEngine.names(QvpEngine.Names.CATEGORY),
|
|
197
245
|
"decorations" to QvpEngine.names(QvpEngine.Names.DECORATION), "divisions" to QvpEngine.names(QvpEngine.Names.DIVISION),
|
|
198
246
|
"places" to QvpEngine.names(QvpEngine.Names.PLACE),
|
|
199
|
-
|
|
247
|
+
// the whole defaults table by camelCase name, as the decimals the header states
|
|
248
|
+
"defaults" to QvpDefaults.decimal)
|
|
200
249
|
|
|
201
|
-
override fun invalidate() {
|
|
250
|
+
override fun invalidate() {
|
|
251
|
+
// The atlases belong to the query thread: free them there, after the queries already queued.
|
|
252
|
+
runCatching { queries.execute { atlases.values.forEach { it.close() }; atlases.clear(); atlasByUri.clear() } }
|
|
253
|
+
queries.shutdown()
|
|
254
|
+
QvpOrnamentSets.clear(); super.invalidate()
|
|
255
|
+
}
|
|
202
256
|
companion object { const val NAME = "QvpModule" }
|
|
203
257
|
}
|
|
204
258
|
|
|
@@ -24,6 +24,7 @@ class QvpPageViewManager : SimpleViewManager<QvpRnPageView>() {
|
|
|
24
24
|
@ReactProp(name = "padBottom", defaultFloat = 0f) fun setPadBottom(v: QvpRnPageView, f: Float) = v.setPadBottomDp(f)
|
|
25
25
|
@ReactProp(name = "padSide", defaultFloat = 0f) fun setPadSide(v: QvpRnPageView, f: Float) = v.setPadSideDp(f)
|
|
26
26
|
@ReactProp(name = "lineSpacing", defaultFloat = 1f) fun setLineSpacing(v: QvpRnPageView, f: Float) = v.setLineSpacingProp(f)
|
|
27
|
+
@ReactProp(name = "reflowBreaks") fun setReflowBreaks(v: QvpRnPageView, s: String?) = v.setReflowBreaksProp(s)
|
|
27
28
|
@ReactProp(name = "fillHeight", defaultBoolean = false) fun setFillHeight(v: QvpRnPageView, b: Boolean) = v.setFillHeightProp(b)
|
|
28
29
|
@ReactProp(name = "surahFrames", defaultBoolean = true) fun setSurahFrames(v: QvpRnPageView, b: Boolean) = v.setSurahFramesProp(b)
|
|
29
30
|
@ReactProp(name = "paperColor") fun setPaperColor(v: QvpRnPageView, s: String?) { v.paperColor = if (s.isNullOrBlank()) 0 else QvpColor.argb(QvpColor.parse(s)); v.invalidate() }
|
|
@@ -5,6 +5,10 @@ import android.util.Log
|
|
|
5
5
|
import com.facebook.react.bridge.Arguments
|
|
6
6
|
import com.facebook.react.uimanager.ThemedReactContext
|
|
7
7
|
import android.widget.FrameLayout
|
|
8
|
+
import java.util.concurrent.ConcurrentHashMap
|
|
9
|
+
import java.util.concurrent.locks.ReentrantReadWriteLock
|
|
10
|
+
import kotlin.concurrent.read
|
|
11
|
+
import kotlin.concurrent.write
|
|
8
12
|
import ws.quran.qvp.*
|
|
9
13
|
import ws.quran.qvp.Target
|
|
10
14
|
|
|
@@ -13,6 +17,11 @@ import ws.quran.qvp.Target
|
|
|
13
17
|
* URI, and reconciles the declarative props (theme / styles / highlights / mask / reveal) against engine
|
|
14
18
|
* handles so JS never sees a handle. Every decision (hit-test, layout, style resolution, bands, masks)
|
|
15
19
|
* is the engine's; this class only marshals and forwards.
|
|
20
|
+
*
|
|
21
|
+
* The module reads the page from its query thread while this view draws on the UI thread (see
|
|
22
|
+
* [read]). Those reads touch only what the page fixed when it loaded, so the two do not meet,
|
|
23
|
+
* except where the page is closed, replaced, or given a words sidecar: each of these holds
|
|
24
|
+
* [lock] for writing, and waits for a query in progress to finish.
|
|
16
25
|
*/
|
|
17
26
|
class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
|
|
18
27
|
private val density = ctx.resources.displayMetrics.density
|
|
@@ -20,7 +29,22 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
|
|
|
20
29
|
val inner = QvpPageView(ctx).also { addView(it, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) }
|
|
21
30
|
var page: QvpPage?
|
|
22
31
|
get() = inner.page
|
|
23
|
-
set(v) { inner.page = v }
|
|
32
|
+
private set(v) { inner.page = v }
|
|
33
|
+
|
|
34
|
+
/** Read by the module's queries, written where the page closes, changes, or takes a sidecar. */
|
|
35
|
+
private val lock = ReentrantReadWriteLock()
|
|
36
|
+
/** Run [block] on the page in view, held open until the block returns: null when no page is loaded.
|
|
37
|
+
* The block must not wait for the UI thread, which can be waiting for this lock. */
|
|
38
|
+
fun <T> read(block: (QvpPage?) -> T): T = lock.read { block(page) }
|
|
39
|
+
/** Attach a words sidecar. Queries in progress finish first, and the word records built
|
|
40
|
+
* before it are dropped, since the forms they hold have changed. */
|
|
41
|
+
fun attachWords(p: QvpPage, json: String): Int = lock.write { p.attachWords(json).also { dropWords() } }
|
|
42
|
+
|
|
43
|
+
private val wordsLock = Any()
|
|
44
|
+
private var words: QvpRnWords? = null
|
|
45
|
+
/** The word records of [p], built on first use and kept until the page changes or takes a sidecar. */
|
|
46
|
+
fun words(p: QvpPage): QvpRnWords = synchronized(wordsLock) { words?.takeIf { it.page === p } ?: QvpRnWords(p).also { words = it } }
|
|
47
|
+
private fun dropWords() = synchronized(wordsLock) { words = null }
|
|
24
48
|
var paperColor: Int get() = inner.paperColor; set(v) { inner.paperColor = v; inner.invalidate() }
|
|
25
49
|
var selectionBand: Int get() = inner.selectionBand; set(v) { inner.selectionBand = v }
|
|
26
50
|
var selectionEnabled: Boolean get() = inner.selectionEnabled; set(v) { inner.selectionEnabled = v }
|
|
@@ -68,7 +92,7 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
|
|
|
68
92
|
var pageBytes = 0; private set
|
|
69
93
|
|
|
70
94
|
init {
|
|
71
|
-
inner.onWordTap = { w, h -> page?.let { p -> emit("onWordTap", mapOf("word" to
|
|
95
|
+
inner.onWordTap = { w, h -> page?.let { p -> emit("onWordTap", mapOf("word" to words(p).word(w.index), "hit" to Marshal.hit(p, h))) } }
|
|
72
96
|
inner.onDecorationTap = { d, h -> page?.let { p -> emit("onDecorationTap", mapOf("decoration" to Marshal.decoration(d), "hit" to Marshal.hit(p, h))) } }
|
|
73
97
|
inner.onEmptyTap = { emit("onEmptyTap", emptyMap()) }
|
|
74
98
|
// The engine says a flick turns the page and by how many, in reading order. Which page
|
|
@@ -81,12 +105,16 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
|
|
|
81
105
|
override fun onAttachedToWindow() { super.onAttachedToWindow(); QvpRegistry.register(this) }
|
|
82
106
|
override fun onDetachedFromWindow() { QvpRegistry.unregister(this); super.onDetachedFromWindow() }
|
|
83
107
|
|
|
84
|
-
fun destroy() { QvpRegistry.unregister(this); page?.close(); page = null; loadedKey = null }
|
|
108
|
+
fun destroy() { QvpRegistry.unregister(this); lock.write { page?.close(); page = null; dropWords() }; loadedKey = null }
|
|
85
109
|
|
|
86
110
|
/** Padding props arrive in dp. */
|
|
87
111
|
fun setPadTopDp(v: Float) { inner.padTop = v * density; layoutDirty = true }
|
|
88
112
|
fun setPadBottomDp(v: Float) { inner.padBottom = v * density; layoutDirty = true }
|
|
89
113
|
fun setPadSideDp(v: Float) { inner.padSide = v * density; layoutDirty = true }
|
|
114
|
+
fun setReflowBreaksProp(v: String?) {
|
|
115
|
+
inner.reflowBreaks = QvpBreaks.entries.find { it.name.equals(v, ignoreCase = true) } ?: QvpBreaks.FITTED
|
|
116
|
+
layoutDirty = true
|
|
117
|
+
}
|
|
90
118
|
fun setLineSpacingProp(v: Float) { inner.lineSpacing = v; layoutDirty = true }
|
|
91
119
|
|
|
92
120
|
// ── the reader's zoom control ──
|
|
@@ -142,15 +170,27 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
|
|
|
142
170
|
if (key == loadedKey) return
|
|
143
171
|
// drop everything bound to the old page: handles die with it
|
|
144
172
|
themeHandle = 0; appliedTheme = null; styleHandles.clear(); highlightHandles.clear(); appliedMask = null; appliedReveal = null; appliedRevealAt = null; appliedInk = null; appliedDress = null; revealStepCount = 0
|
|
145
|
-
|
|
146
|
-
if (key == null) return
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
val p
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
173
|
+
loadedKey = key
|
|
174
|
+
if (key == null) { lock.write { page?.close(); page = null; dropWords() }; return }
|
|
175
|
+
// Load the new page before the swap, so a query sees the old page or the new one and
|
|
176
|
+
// never a view with no page. A load that fails leaves no page, as before.
|
|
177
|
+
val p: QvpPage
|
|
178
|
+
val bytes: ByteArray
|
|
179
|
+
val ms: Double
|
|
180
|
+
try {
|
|
181
|
+
bytes = pageBase64?.let { Base64.decode(it, Base64.DEFAULT) } ?: readUri(pageUri!!)
|
|
182
|
+
val t0 = System.nanoTime()
|
|
183
|
+
p = QvpPage(bytes); p.buildPaths()
|
|
184
|
+
ms = (System.nanoTime() - t0) / 1e6
|
|
185
|
+
// No query sees the page before the swap below, so the sidecar needs no lock.
|
|
186
|
+
wordsUri?.let { runCatching { p.attachWords(readUri(it)) }.onFailure { e -> Log.w("QvpRn", "words sidecar: $e") } }
|
|
187
|
+
} catch (e: Exception) {
|
|
188
|
+
lock.write { page?.close(); page = null; dropWords() }
|
|
189
|
+
throw e
|
|
190
|
+
}
|
|
191
|
+
lock.write { val old = page; page = p; dropWords(); loadMs = ms; pageBytes = bytes.size; old?.close() }
|
|
192
|
+
layoutDirty = true
|
|
193
|
+
emit("onPageLoad", Marshal.pageInfo(p, words(p).forms) + mapOf("loadMs" to loadMs, "bytes" to pageBytes, "uri" to pageUri))
|
|
154
194
|
}
|
|
155
195
|
|
|
156
196
|
private fun applyInk(p: QvpPage) {
|
|
@@ -257,9 +297,10 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
|
|
|
257
297
|
"engineVersion" to QvpEngine.version(), "viewScale" to inner.viewScale, "layout" to page?.currentLayout?.let { Marshal.layout(it) })
|
|
258
298
|
}
|
|
259
299
|
|
|
260
|
-
/** Views by react tag, so the module can find the page behind a `viewTag` without going through the
|
|
300
|
+
/** Views by react tag, so the module can find the page behind a `viewTag` without going through the
|
|
301
|
+
* UIManager. The UI thread registers views and the module's query thread looks them up. */
|
|
261
302
|
object QvpRegistry {
|
|
262
|
-
private val views =
|
|
303
|
+
private val views = ConcurrentHashMap<Int, QvpRnPageView>()
|
|
263
304
|
fun register(v: QvpRnPageView) { if (v.id > 0) views[v.id] = v }
|
|
264
305
|
fun unregister(v: QvpRnPageView) { views.entries.removeAll { it.value === v } }
|
|
265
306
|
fun get(tag: Int): QvpRnPageView? = views[tag]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
package ws.quran.qvp.rn
|
|
2
|
+
|
|
3
|
+
import ws.quran.qvp.Form
|
|
4
|
+
import ws.quran.qvp.QvpPage
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The bridge record of each word of one page, built the first time the word is asked for and
|
|
8
|
+
* kept. A record holds the word's text forms, its label and the names of its paths. The words
|
|
9
|
+
* sidecar is attached once per page, so a record does not change until the next attach, and
|
|
10
|
+
* the view drops this table then. The module's query thread and the UI thread can both call it.
|
|
11
|
+
*/
|
|
12
|
+
class QvpRnWords(val page: QvpPage) {
|
|
13
|
+
/** The forms this page has. Each one is a scan of every word in the engine, so read them once. */
|
|
14
|
+
val forms: List<Form> by lazy { Marshal.forms(page) }
|
|
15
|
+
private val records = arrayOfNulls<Map<String, Any?>>(page.nWords)
|
|
16
|
+
|
|
17
|
+
/** The record of word [index], or null when the page has no such word. */
|
|
18
|
+
@Synchronized
|
|
19
|
+
fun word(index: Int): Map<String, Any?>? {
|
|
20
|
+
val w = page.words.getOrNull(index) ?: return null
|
|
21
|
+
return records[index] ?: Marshal.word(page, w, forms).also { records[index] = it }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Every word's record, in page order. */
|
|
25
|
+
fun all(): List<Map<String, Any?>> = List(page.nWords) { word(it)!! }
|
|
26
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quran.ws/qvp-react-native",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "React Native wrapper for the QVP vector mushaf engine (Android; iOS TODO). Thin marshalling over the Kotlin library, which is JNI over qvp.h.",
|
|
5
5
|
"main": "src/index.tsx",
|
|
6
6
|
"types": "src/index.tsx",
|
package/src/codes.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Generated by scripts/gen-rn-enums.py from crates/qvp-ffi/include/qvp.h. Do not edit.
|
|
2
|
+
|
|
3
|
+
/** QVP_TARGET_*: the kind of a target, by name. */
|
|
4
|
+
export const TARGET = {
|
|
5
|
+
page: 0,
|
|
6
|
+
word: 1,
|
|
7
|
+
words: 2,
|
|
8
|
+
ayah: 3,
|
|
9
|
+
ayahRange: 4,
|
|
10
|
+
line: 5,
|
|
11
|
+
surah: 6,
|
|
12
|
+
range: 7,
|
|
13
|
+
} as const;
|
|
14
|
+
|
|
15
|
+
/** QVP_SELECTOR_*: the kind of a selector, by name. */
|
|
16
|
+
export const SELECTOR = {
|
|
17
|
+
page: 0,
|
|
18
|
+
path: 1,
|
|
19
|
+
wordPath: 2,
|
|
20
|
+
wordMark: 3,
|
|
21
|
+
wordMarkNamed: 4,
|
|
22
|
+
wordBody: 5,
|
|
23
|
+
wordMarks: 6,
|
|
24
|
+
word: 7,
|
|
25
|
+
ayah: 8,
|
|
26
|
+
line: 9,
|
|
27
|
+
mark: 10,
|
|
28
|
+
category: 11,
|
|
29
|
+
family: 12,
|
|
30
|
+
kind: 13,
|
|
31
|
+
decoration: 14,
|
|
32
|
+
decorationIndex: 15,
|
|
33
|
+
} as const;
|
package/src/index.tsx
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
type NativeSyntheticEvent,
|
|
16
16
|
type ViewProps,
|
|
17
17
|
} from 'react-native';
|
|
18
|
+
import { SELECTOR, TARGET } from './codes';
|
|
18
19
|
|
|
19
20
|
// ── constants (mirror qvp.h) ─────────────────────────────────────────────────────────────────
|
|
20
21
|
export const KIND = { BODY: 0, MARK: 1, AYAH_NUMBER: 2, AYAH_MARK_ORNAMENT: 3, HEADER_INK: 4, OTHER: 255 } as const;
|
|
@@ -40,42 +41,44 @@ export function css(c: Color | null | undefined): string | undefined {
|
|
|
40
41
|
/** Colour with a replaced alpha (0..1). */
|
|
41
42
|
export function rgba(c: Color, alpha: number): string {
|
|
42
43
|
const h = css(c)!;
|
|
43
|
-
return h.slice(0, 7) + Math.round(Math.max(0, Math.min(1, alpha)) * 255).toString(16).padStart(2, '0');
|
|
44
|
+
return h.slice(0, 7) + Math.round((Number.isNaN(alpha) ? 0 : Math.max(0, Math.min(1, alpha))) * 255).toString(16).padStart(2, '0');
|
|
44
45
|
}
|
|
45
46
|
|
|
46
47
|
// ── targets and selectors (same shapes as web/qvp.js T / Sel) ────────────────────────────────
|
|
48
|
+
// The codes come from qvp.h through codes.ts, which scripts/gen-rn-enums.py writes; the Android
|
|
49
|
+
// module reads them back with the same table.
|
|
47
50
|
export interface TargetObj { target: number; a?: number; b?: number; c?: number; words?: number[] }
|
|
48
51
|
/** 'page' | '2:255' | '2:255:3' | '2:255-257' | 'line:7' | 'surah:2' | word index | [indices] | T.* */
|
|
49
52
|
export type Target = string | number | number[] | TargetObj;
|
|
50
53
|
export const T = {
|
|
51
|
-
page: (): TargetObj => ({ target:
|
|
52
|
-
word: (i: number): TargetObj => ({ target:
|
|
53
|
-
words: (ws: number[]): TargetObj => ({ target:
|
|
54
|
-
ayah: (s: number, a: number): TargetObj => ({ target:
|
|
55
|
-
ayahRange: (s: number, a: number, b: number): TargetObj => ({ target:
|
|
56
|
-
line: (n: number): TargetObj => ({ target:
|
|
57
|
-
surah: (s: number): TargetObj => ({ target:
|
|
58
|
-
range: (a: number, b: number): TargetObj => ({ target:
|
|
54
|
+
page: (): TargetObj => ({ target: TARGET.page }),
|
|
55
|
+
word: (i: number): TargetObj => ({ target: TARGET.word, a: i }),
|
|
56
|
+
words: (ws: number[]): TargetObj => ({ target: TARGET.words, words: ws }),
|
|
57
|
+
ayah: (s: number, a: number): TargetObj => ({ target: TARGET.ayah, a: s, b: a }),
|
|
58
|
+
ayahRange: (s: number, a: number, b: number): TargetObj => ({ target: TARGET.ayahRange, a: s, b: a, c: b }),
|
|
59
|
+
line: (n: number): TargetObj => ({ target: TARGET.line, a: n }),
|
|
60
|
+
surah: (s: number): TargetObj => ({ target: TARGET.surah, a: s }),
|
|
61
|
+
range: (a: number, b: number): TargetObj => ({ target: TARGET.range, a, b }),
|
|
59
62
|
};
|
|
60
63
|
export interface Selector { selector: number; a?: number; b?: number; c?: number; mark?: string }
|
|
61
64
|
export const Sel = {
|
|
62
|
-
page: (): Selector => ({ selector:
|
|
63
|
-
path: (p: number): Selector => ({ selector:
|
|
64
|
-
wordPath: (w: number, nth: number): Selector => ({ selector:
|
|
65
|
+
page: (): Selector => ({ selector: SELECTOR.page }),
|
|
66
|
+
path: (p: number): Selector => ({ selector: SELECTOR.path, a: p }),
|
|
67
|
+
wordPath: (w: number, nth: number): Selector => ({ selector: SELECTOR.wordPath, a: w, b: nth }),
|
|
65
68
|
/** nth mark of the word (0-based, marks only) */
|
|
66
|
-
wordMark: (w: number, nth: number): Selector => ({ selector:
|
|
67
|
-
wordMarkNamed: (w: number, mark: string, nth = 0): Selector => ({ selector:
|
|
68
|
-
wordBody: (w: number): Selector => ({ selector:
|
|
69
|
-
wordMarks: (w: number): Selector => ({ selector:
|
|
70
|
-
word: (w: number): Selector => ({ selector:
|
|
71
|
-
ayah: (s: number, a: number): Selector => ({ selector:
|
|
72
|
-
line: (n: number): Selector => ({ selector:
|
|
73
|
-
mark: (m: string | number): Selector => ({ selector:
|
|
74
|
-
category: (c: string | number): Selector => ({ selector:
|
|
75
|
-
family: (f: string | number): Selector => ({ selector:
|
|
76
|
-
kind: (k: string | number): Selector => ({ selector:
|
|
77
|
-
decoration: (k: string | number): Selector => ({ selector:
|
|
78
|
-
decorationIndex: (d: number): Selector => ({ selector:
|
|
69
|
+
wordMark: (w: number, nth: number): Selector => ({ selector: SELECTOR.wordMark, a: w, b: nth }),
|
|
70
|
+
wordMarkNamed: (w: number, mark: string, nth = 0): Selector => ({ selector: SELECTOR.wordMarkNamed, a: w, b: markId(mark), c: nth, mark }),
|
|
71
|
+
wordBody: (w: number): Selector => ({ selector: SELECTOR.wordBody, a: w }),
|
|
72
|
+
wordMarks: (w: number): Selector => ({ selector: SELECTOR.wordMarks, a: w }),
|
|
73
|
+
word: (w: number): Selector => ({ selector: SELECTOR.word, a: w }),
|
|
74
|
+
ayah: (s: number, a: number): Selector => ({ selector: SELECTOR.ayah, a: s, b: a }),
|
|
75
|
+
line: (n: number): Selector => ({ selector: SELECTOR.line, a: n }),
|
|
76
|
+
mark: (m: string | number): Selector => ({ selector: SELECTOR.mark, a: markId(m) }),
|
|
77
|
+
category: (c: string | number): Selector => ({ selector: SELECTOR.category, a: named(c, CATEGORY_NAMES) }),
|
|
78
|
+
family: (f: string | number): Selector => ({ selector: SELECTOR.family, a: named(f, FAMILY_NAMES) }),
|
|
79
|
+
kind: (k: string | number): Selector => ({ selector: SELECTOR.kind, a: named(k, KIND_NAMES) }),
|
|
80
|
+
decoration: (k: string | number): Selector => ({ selector: SELECTOR.decoration, a: named(k, DECORATION_NAMES) }),
|
|
81
|
+
decorationIndex: (d: number): Selector => ({ selector: SELECTOR.decorationIndex, a: d }),
|
|
79
82
|
};
|
|
80
83
|
|
|
81
84
|
// ── records ──────────────────────────────────────────────────────────────────────────────────
|
|
@@ -90,7 +93,7 @@ export interface Word {
|
|
|
90
93
|
wordKey: string; ayahKey: string; forms: Partial<Record<Form, string>>; label: string; paths: WordPath[];
|
|
91
94
|
}
|
|
92
95
|
export interface Deco { index: number; decoration: number; decorationName: string; surah: number; ayah: number; line: number; x0: number; y0: number; x1: number; y1: number; text: string; firstPath: number; nPaths: number }
|
|
93
|
-
/** The one hit shape for every hit test; the exact variants report distance 0
|
|
96
|
+
/** The one hit shape for every hit test; the exact variants report distance 0. `isExact` is true only when the point is inside an outline. */
|
|
94
97
|
export interface Hit { word: number; path: number; decoration: number; line: number; distance: number; isExact: boolean; wordKey: string | null; ayahKey: string | null }
|
|
95
98
|
export interface Ayah { index: number; surah: number; ayah: number; fragment: number; fragments: number; flags: number; rubuAlHizb: number; firstWord: number; nWords: number; ayahMarkDecoration: number; bbox: number[] }
|
|
96
99
|
export interface Line { index: number; lineNumber: number; isHeader: boolean; firstWord: number; nWords: number; bbox: number[]; bandY0: number; bandY1: number; centre: number }
|
|
@@ -162,6 +165,8 @@ export interface Dress extends DressSpec { ornaments: QvpOrnaments | number }
|
|
|
162
165
|
|
|
163
166
|
// ── the view ─────────────────────────────────────────────────────────────────────────────────
|
|
164
167
|
/** What a pinch does to the page: the engine owns the policy, this names which one. */
|
|
168
|
+
/** How the words are broken onto rows. */
|
|
169
|
+
export type Breaks = 'greedy' | 'even' | 'fitted' | 'printed';
|
|
165
170
|
export type ZoomMode = 'stepped' | 'continuous' | 'magnify';
|
|
166
171
|
/** Where the reader's zoom control stands: the mode, the step, and the size in force. */
|
|
167
172
|
export interface Zoom { mode: ZoomMode; step: number; zoom: number }
|
|
@@ -177,6 +182,8 @@ export interface QvpPageViewProps extends ViewProps {
|
|
|
177
182
|
lineSpacing?: number; fillHeight?: boolean;
|
|
178
183
|
/** Draw source-native frames around surah names on the printed page. */
|
|
179
184
|
surahFrames?: boolean;
|
|
185
|
+
/** Keep the printed rows or break them again as the reader zooms in. */
|
|
186
|
+
reflowBreaks?: Breaks;
|
|
180
187
|
paperColor?: Color; defaultInk?: Color; selectionBand?: Color;
|
|
181
188
|
selectionEnabled?: boolean; zoomEnabled?: boolean; hitMaxDistance?: number;
|
|
182
189
|
/** What a pinch does to the page. `stepped` reflows onto the page's own zoom steps and is
|
|
@@ -348,24 +355,50 @@ export function QvpPassageView(props: QvpPassageViewProps) {
|
|
|
348
355
|
|
|
349
356
|
// ── the module ───────────────────────────────────────────────────────────────────────────────
|
|
350
357
|
const M = NativeModules.QvpModule as any;
|
|
358
|
+
// Before the first use: reading the constants of a missing module is a TypeError, and this
|
|
359
|
+
// message says what to do instead.
|
|
360
|
+
if (!M) throw new Error('@quran.ws/qvp-react-native: native module QvpModule not linked (Android only for now; see README)');
|
|
351
361
|
|
|
362
|
+
/** The native module's constants: the engine's name tables, and its defaults by camelCase name
|
|
363
|
+
* (`QVP_DEFAULT_*` in qvp.h; colours as unsigned 0xRRGGBBAA). */
|
|
364
|
+
interface NativeConstants { version?: string; formatVersion?: number; marks?: string[]; kinds?: string[]; families?: string[]; categories?: string[]; decorations?: string[]; divisions?: string[]; places?: string[]; defaults?: Record<string, number> }
|
|
352
365
|
// The engine's name tables, read through the native module's constants; no table lives here.
|
|
353
|
-
const NAMES = (M.getConstants?.() ?? {}) as
|
|
366
|
+
const NAMES = (M.getConstants?.() ?? {}) as NativeConstants;
|
|
354
367
|
const KIND_NAMES: string[] = NAMES.kinds ?? [];
|
|
355
368
|
const FAMILY_NAMES: string[] = NAMES.families ?? [];
|
|
356
369
|
const CATEGORY_NAMES: string[] = NAMES.categories ?? [];
|
|
357
370
|
const DECORATION_NAMES: string[] = NAMES.decorations ?? [];
|
|
358
371
|
export const MARKS: string[] = NAMES.marks ?? [];
|
|
359
|
-
/**
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
372
|
+
/** One default from the native module. No fallback: a missing key means the native module
|
|
373
|
+
* predates this package, and the error says so. */
|
|
374
|
+
const nativeDefault = (key: string): number => {
|
|
375
|
+
const v = NAMES.defaults?.[key];
|
|
376
|
+
if (typeof v !== 'number') throw new Error(`@quran.ws/qvp-react-native: native module QvpModule is older than this package (no default ${key}); rebuild the Android app`);
|
|
377
|
+
return v;
|
|
363
378
|
};
|
|
379
|
+
const SNAKE = (camel: string) => camel.replace(/([A-Z])/g, '_$1').toUpperCase();
|
|
380
|
+
/** The engine's defaults (QVP_DEFAULT_* in qvp.h), read from the native module: every one under
|
|
381
|
+
* its header name, and the ones a host reads most with their own doc comments. */
|
|
382
|
+
export const DEFAULTS: Readonly<Record<string, number>> & {
|
|
383
|
+
/** The size a scanned medallion takes when `ayahMarkScale` is 0, in rings. */
|
|
384
|
+
readonly AYAH_MARK_SCALE_SCAN: number;
|
|
385
|
+
/** How far a reflowed row much shorter than its neighbours opens towards them. */
|
|
386
|
+
readonly REFLOW_RELAX: number;
|
|
387
|
+
/** How far a reflowed row's gaps may open, in word gaps. */
|
|
388
|
+
readonly REFLOW_MAX_STRETCH: number;
|
|
389
|
+
/** Side padding of the selection band, page units. */
|
|
390
|
+
readonly SELECTION_PAD_X: number;
|
|
391
|
+
} = Object.freeze({
|
|
392
|
+
...Object.fromEntries(Object.entries(NAMES.defaults ?? {}).map(([k, v]) => [SNAKE(k), v])),
|
|
393
|
+
AYAH_MARK_SCALE_SCAN: nativeDefault('ayahMarkScaleScan'),
|
|
394
|
+
REFLOW_RELAX: nativeDefault('reflowRelax'),
|
|
395
|
+
REFLOW_MAX_STRETCH: nativeDefault('reflowMaxStretch'),
|
|
396
|
+
SELECTION_PAD_X: nativeDefault('selectionPadX'),
|
|
397
|
+
});
|
|
364
398
|
/** A name's id in a table; 255 when the table has no such name. */
|
|
365
399
|
export type NameTable = 'marks' | 'kinds' | 'families' | 'categories' | 'decorations' | 'divisions' | 'places';
|
|
366
400
|
const named = (v: string | number, names: string[]) => { if (typeof v === 'number') return v; const i = names.indexOf(v); return i < 0 ? 255 : i; };
|
|
367
401
|
export function markId(name: string | number): number { return named(name, MARKS); }
|
|
368
|
-
if (!M) throw new Error('@quran.ws/qvp-react-native: native module QvpModule not linked (Android only for now; see README)');
|
|
369
402
|
|
|
370
403
|
export interface SearchOptions { form?: Form; mode?: 'includes' | 'exact' | 'prefix'; normalize?: boolean; looseMatch?: boolean; limit?: number }
|
|
371
404
|
export interface TextOptions { form?: Form; wordSep?: string; lineSep?: string }
|
|
@@ -491,22 +524,26 @@ export const Qvp = {
|
|
|
491
524
|
/** Cross-page lookup (atlas.qva). `const atlas = await QvpAtlas.load('asset://pages/atlas.qva')`. */
|
|
492
525
|
export class QvpAtlas {
|
|
493
526
|
private constructor(public readonly id: number) {}
|
|
527
|
+
private freed = false;
|
|
528
|
+
/** The native id. Throws once the atlas is freed, so every call after `free()` rejects. */
|
|
529
|
+
private get h(): number { if (this.freed) throw new Error('QvpAtlas was freed'); return this.id; }
|
|
494
530
|
static async load(uri: string): Promise<QvpAtlas> { return new QvpAtlas(await Qvp.loadAtlas(uri)); }
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
531
|
+
/** Free the native atlas. A second call does nothing. */
|
|
532
|
+
async free(): Promise<void> { if (this.freed) return; this.freed = true; await Qvp.freeAtlas(this.id); }
|
|
533
|
+
async pageOf(s: number, a: number) { return Qvp.atlasPageOf(this.h, s, a); }
|
|
534
|
+
async pageRange(page: number) { return Qvp.atlasPageRange(this.h, page); }
|
|
535
|
+
async pageCount() { return Qvp.atlasPageCount(this.h); }
|
|
536
|
+
async surah(n: number) { return Qvp.atlasSurah(this.h, n); }
|
|
537
|
+
async surahs() { return Qvp.atlasSurahs(this.h); }
|
|
538
|
+
async pageOfSurah(n: number) { return Qvp.atlasPageOfSurah(this.h, n); }
|
|
539
|
+
async division(division: DivisionKind, n: number) { return Qvp.atlasDivision(this.h, division, n); }
|
|
540
|
+
async juz(n: number) { return Qvp.atlasDivision(this.h, 'juz', n); }
|
|
541
|
+
async hizb(n: number) { return Qvp.atlasDivision(this.h, 'hizb', n); }
|
|
542
|
+
async rubuAlHizb(n: number) { return Qvp.atlasDivision(this.h, 'rubuAlHizb', n); }
|
|
543
|
+
async divisionOf(division: DivisionKind, s: number, a: number) { return Qvp.atlasDivisionOf(this.h, division, s, a); }
|
|
544
|
+
async juzOf(s: number, a: number) { return Qvp.atlasJuzOf(this.h, s, a); }
|
|
545
|
+
async pagesOfJuz(n: number) { return Qvp.atlasPagesOfJuz(this.h, n); }
|
|
546
|
+
async searchSurahs(text: string) { return Qvp.atlasSearchSurahs(this.h, text); }
|
|
510
547
|
}
|
|
511
548
|
|
|
512
549
|
/**
|
|
@@ -518,14 +555,17 @@ export class QvpOrnaments {
|
|
|
518
555
|
/** Every ornament of the set, in the set's order. */
|
|
519
556
|
readonly count: number;
|
|
520
557
|
private constructor(public readonly id: number, public readonly list: Ornament[]) { this.count = list.length; }
|
|
558
|
+
private freed = false;
|
|
521
559
|
/** Load a set from a URI (the same schemes as `pageUri`; `base64:…` for bytes in hand). */
|
|
522
560
|
static async load(uri: string): Promise<QvpOrnaments> {
|
|
523
561
|
const id = await Qvp.loadOrnaments(uri);
|
|
524
562
|
return new QvpOrnaments(id, await Qvp.ornamentList(id));
|
|
525
563
|
}
|
|
526
|
-
|
|
527
|
-
|
|
564
|
+
/** Free the native set. A second call does nothing. `list`, `ofKind` and `styles` stay readable. */
|
|
565
|
+
async free(): Promise<void> { if (this.freed) return; this.freed = true; await Qvp.freeOrnaments(this.id); }
|
|
566
|
+
/** The ornament of `kind` in `style`, or null; the engine looks it up. Rejects once the set is freed. */
|
|
528
567
|
async find(kind: OrnamentKind, style: string): Promise<Ornament | null> {
|
|
568
|
+
if (this.freed) throw new Error('QvpOrnaments was freed');
|
|
529
569
|
const i = await Qvp.ornamentFind(this.id, kind, style);
|
|
530
570
|
return i < 0 ? null : this.list[i] ?? null;
|
|
531
571
|
}
|