@papyrus-sdk/engine-native 0.2.22-beta.9.epub.2 → 0.2.22

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.
Files changed (276) hide show
  1. package/PapyrusNativeEngine.podspec +45 -0
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/cpp/CMakeLists.txt +137 -0
  4. package/android/src/main/cpp/PapyrusComicArchiveJni.cpp +68 -0
  5. package/android/src/main/cpp/PapyrusComicArchiveTest.cpp +55 -0
  6. package/android/src/main/cpp/papyrus_outline_loader_test.cpp +240 -0
  7. package/android/src/main/cpp/papyrus_text_word_test.cpp +72 -0
  8. package/android/src/main/java/com/papyrus/engine/PapyrusComicArchiveNative.java +14 -0
  9. package/android/src/main/java/com/papyrus/engine/PapyrusComicDocumentView.java +491 -0
  10. package/android/src/main/java/com/papyrus/engine/PapyrusComicDocumentViewManager.java +32 -0
  11. package/android/src/main/java/com/papyrus/engine/PapyrusComicPageLayout.java +38 -0
  12. package/android/src/main/java/com/papyrus/engine/PapyrusNativeEngineModule.java +305 -35
  13. package/android/src/main/java/com/papyrus/engine/PapyrusNativeTextModel.java +195 -0
  14. package/android/src/main/java/com/papyrus/engine/PapyrusPackage.java +3 -1
  15. package/android/src/main/java/com/papyrus/engine/PapyrusPdfViewerView.java +195 -5
  16. package/android/src/main/java/com/papyrus/engine/PapyrusPdfViewerViewManager.java +20 -1
  17. package/android/src/main/java/com/papyrus/engine/PapyrusSelectionMenuIcon.java +48 -0
  18. package/android/src/main/java/com/papyrus/engine/PapyrusTextAnnotationModel.java +22 -0
  19. package/android/src/main/java/com/papyrus/engine/PapyrusTextDocumentView.java +661 -0
  20. package/android/src/main/java/com/papyrus/engine/PapyrusTextDocumentViewManager.java +49 -0
  21. package/android/src/main/java/com/papyrus/engine/PapyrusTextStore.java +43 -0
  22. package/dist/index.d.mts +614 -4
  23. package/dist/index.d.ts +614 -4
  24. package/dist/index.js +484 -8
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +477 -7
  27. package/dist/index.mjs.map +1 -1
  28. package/ios/PapyrusComicDocumentView.h +21 -0
  29. package/ios/PapyrusComicDocumentView.m +554 -0
  30. package/ios/PapyrusComicDocumentViewManager.m +23 -0
  31. package/ios/PapyrusEngineStore.h +3 -0
  32. package/ios/PapyrusEngineStore.m +32 -6
  33. package/ios/PapyrusNativeEngine.m +684 -5
  34. package/ios/PapyrusPageRotationRegistry.h +29 -0
  35. package/ios/PapyrusPageRotationRegistry.m +179 -0
  36. package/ios/PapyrusPageView.m +38 -11
  37. package/ios/PapyrusPdfDocumentView.h +55 -0
  38. package/ios/PapyrusPdfDocumentView.m +2370 -0
  39. package/ios/PapyrusPdfDocumentViewManager.m +61 -0
  40. package/ios/PapyrusPdfPageTheme.h +15 -0
  41. package/ios/PapyrusPdfPageTheme.m +218 -0
  42. package/ios/PapyrusSelectionMenu.h +27 -0
  43. package/ios/PapyrusTextAnnotationRange.h +2 -0
  44. package/ios/PapyrusTextAnnotationRange.m +29 -0
  45. package/ios/PapyrusTextDocumentView.h +32 -0
  46. package/ios/PapyrusTextDocumentView.m +518 -0
  47. package/ios/PapyrusTextDocumentViewManager.m +34 -0
  48. package/ios/PapyrusTextStore.h +13 -0
  49. package/ios/PapyrusTextStore.m +73 -0
  50. package/package.json +10 -8
  51. package/react-native.config.js +1 -1
  52. package/third_party_licenses/BLAKE2-NOTICE.txt +11 -0
  53. package/third_party_licenses/libarchive-COPYING +65 -0
  54. package/vendor/libarchive/PapyrusComicArchive.cpp +376 -0
  55. package/vendor/libarchive/PapyrusComicArchive.h +30 -0
  56. package/vendor/libarchive/README.papyrus.md +15 -0
  57. package/vendor/libarchive/android.h +192 -0
  58. package/vendor/libarchive/config/PapyrusArchiveConfig.h +71 -0
  59. package/vendor/libarchive/libarchive/CMakeLists.txt +293 -0
  60. package/vendor/libarchive/libarchive/android_lf.h +36 -0
  61. package/vendor/libarchive/libarchive/archive.h +1266 -0
  62. package/vendor/libarchive/libarchive/archive_acl.c +2025 -0
  63. package/vendor/libarchive/libarchive/archive_acl_private.h +85 -0
  64. package/vendor/libarchive/libarchive/archive_blake2.h +197 -0
  65. package/vendor/libarchive/libarchive/archive_blake2_impl.h +161 -0
  66. package/vendor/libarchive/libarchive/archive_blake2s_ref.c +369 -0
  67. package/vendor/libarchive/libarchive/archive_blake2sp_ref.c +361 -0
  68. package/vendor/libarchive/libarchive/archive_check_magic.c +183 -0
  69. package/vendor/libarchive/libarchive/archive_cmdline.c +211 -0
  70. package/vendor/libarchive/libarchive/archive_cmdline_private.h +45 -0
  71. package/vendor/libarchive/libarchive/archive_crc32.h +123 -0
  72. package/vendor/libarchive/libarchive/archive_cryptor.c +534 -0
  73. package/vendor/libarchive/libarchive/archive_cryptor_private.h +199 -0
  74. package/vendor/libarchive/libarchive/archive_digest.c +1584 -0
  75. package/vendor/libarchive/libarchive/archive_digest_private.h +431 -0
  76. package/vendor/libarchive/libarchive/archive_disk_acl_darwin.c +558 -0
  77. package/vendor/libarchive/libarchive/archive_disk_acl_freebsd.c +712 -0
  78. package/vendor/libarchive/libarchive/archive_disk_acl_linux.c +760 -0
  79. package/vendor/libarchive/libarchive/archive_disk_acl_sunos.c +824 -0
  80. package/vendor/libarchive/libarchive/archive_endian.h +234 -0
  81. package/vendor/libarchive/libarchive/archive_entry.3 +147 -0
  82. package/vendor/libarchive/libarchive/archive_entry.c +2297 -0
  83. package/vendor/libarchive/libarchive/archive_entry.h +763 -0
  84. package/vendor/libarchive/libarchive/archive_entry_acl.3 +458 -0
  85. package/vendor/libarchive/libarchive/archive_entry_copy_bhfi.c +55 -0
  86. package/vendor/libarchive/libarchive/archive_entry_copy_stat.c +82 -0
  87. package/vendor/libarchive/libarchive/archive_entry_link_resolver.c +472 -0
  88. package/vendor/libarchive/libarchive/archive_entry_linkify.3 +224 -0
  89. package/vendor/libarchive/libarchive/archive_entry_locale.h +90 -0
  90. package/vendor/libarchive/libarchive/archive_entry_misc.3 +63 -0
  91. package/vendor/libarchive/libarchive/archive_entry_paths.3 +153 -0
  92. package/vendor/libarchive/libarchive/archive_entry_perms.3 +210 -0
  93. package/vendor/libarchive/libarchive/archive_entry_private.h +205 -0
  94. package/vendor/libarchive/libarchive/archive_entry_sparse.c +156 -0
  95. package/vendor/libarchive/libarchive/archive_entry_stat.3 +274 -0
  96. package/vendor/libarchive/libarchive/archive_entry_stat.c +121 -0
  97. package/vendor/libarchive/libarchive/archive_entry_strmode.c +69 -0
  98. package/vendor/libarchive/libarchive/archive_entry_time.3 +127 -0
  99. package/vendor/libarchive/libarchive/archive_entry_xattr.c +155 -0
  100. package/vendor/libarchive/libarchive/archive_hmac.c +345 -0
  101. package/vendor/libarchive/libarchive/archive_hmac_private.h +119 -0
  102. package/vendor/libarchive/libarchive/archive_integer.h +267 -0
  103. package/vendor/libarchive/libarchive/archive_match.c +1869 -0
  104. package/vendor/libarchive/libarchive/archive_openssl_evp_private.h +54 -0
  105. package/vendor/libarchive/libarchive/archive_openssl_hmac_private.h +54 -0
  106. package/vendor/libarchive/libarchive/archive_options.c +219 -0
  107. package/vendor/libarchive/libarchive/archive_options_private.h +49 -0
  108. package/vendor/libarchive/libarchive/archive_pack_dev.c +330 -0
  109. package/vendor/libarchive/libarchive/archive_pack_dev.h +49 -0
  110. package/vendor/libarchive/libarchive/archive_parse_date.c +1173 -0
  111. package/vendor/libarchive/libarchive/archive_pathmatch.c +480 -0
  112. package/vendor/libarchive/libarchive/archive_pathmatch.h +50 -0
  113. package/vendor/libarchive/libarchive/archive_platform.h +213 -0
  114. package/vendor/libarchive/libarchive/archive_platform_acl.h +53 -0
  115. package/vendor/libarchive/libarchive/archive_platform_stat.h +45 -0
  116. package/vendor/libarchive/libarchive/archive_platform_xattr.h +45 -0
  117. package/vendor/libarchive/libarchive/archive_ppmd7.c +1173 -0
  118. package/vendor/libarchive/libarchive/archive_ppmd7_private.h +119 -0
  119. package/vendor/libarchive/libarchive/archive_ppmd8.c +1293 -0
  120. package/vendor/libarchive/libarchive/archive_ppmd8_private.h +123 -0
  121. package/vendor/libarchive/libarchive/archive_ppmd_private.h +159 -0
  122. package/vendor/libarchive/libarchive/archive_private.h +209 -0
  123. package/vendor/libarchive/libarchive/archive_random.c +274 -0
  124. package/vendor/libarchive/libarchive/archive_random_private.h +36 -0
  125. package/vendor/libarchive/libarchive/archive_rb.c +709 -0
  126. package/vendor/libarchive/libarchive/archive_rb.h +113 -0
  127. package/vendor/libarchive/libarchive/archive_read.3 +250 -0
  128. package/vendor/libarchive/libarchive/archive_read.c +1814 -0
  129. package/vendor/libarchive/libarchive/archive_read_add_passphrase.3 +72 -0
  130. package/vendor/libarchive/libarchive/archive_read_add_passphrase.c +189 -0
  131. package/vendor/libarchive/libarchive/archive_read_append_filter.c +209 -0
  132. package/vendor/libarchive/libarchive/archive_read_data.3 +128 -0
  133. package/vendor/libarchive/libarchive/archive_read_data_into_fd.c +207 -0
  134. package/vendor/libarchive/libarchive/archive_read_disk.3 +422 -0
  135. package/vendor/libarchive/libarchive/archive_read_disk_entry_from_file.c +1086 -0
  136. package/vendor/libarchive/libarchive/archive_read_disk_posix.c +2639 -0
  137. package/vendor/libarchive/libarchive/archive_read_disk_private.h +97 -0
  138. package/vendor/libarchive/libarchive/archive_read_disk_set_standard_lookup.c +315 -0
  139. package/vendor/libarchive/libarchive/archive_read_disk_windows.c +2603 -0
  140. package/vendor/libarchive/libarchive/archive_read_extract.3 +135 -0
  141. package/vendor/libarchive/libarchive/archive_read_extract.c +59 -0
  142. package/vendor/libarchive/libarchive/archive_read_extract2.c +154 -0
  143. package/vendor/libarchive/libarchive/archive_read_filter.3 +163 -0
  144. package/vendor/libarchive/libarchive/archive_read_format.3 +190 -0
  145. package/vendor/libarchive/libarchive/archive_read_free.3 +91 -0
  146. package/vendor/libarchive/libarchive/archive_read_header.3 +89 -0
  147. package/vendor/libarchive/libarchive/archive_read_new.3 +57 -0
  148. package/vendor/libarchive/libarchive/archive_read_open.3 +247 -0
  149. package/vendor/libarchive/libarchive/archive_read_open_fd.c +236 -0
  150. package/vendor/libarchive/libarchive/archive_read_open_file.c +257 -0
  151. package/vendor/libarchive/libarchive/archive_read_open_filename.c +652 -0
  152. package/vendor/libarchive/libarchive/archive_read_open_memory.c +188 -0
  153. package/vendor/libarchive/libarchive/archive_read_private.h +274 -0
  154. package/vendor/libarchive/libarchive/archive_read_set_format.c +116 -0
  155. package/vendor/libarchive/libarchive/archive_read_set_options.3 +290 -0
  156. package/vendor/libarchive/libarchive/archive_read_set_options.c +132 -0
  157. package/vendor/libarchive/libarchive/archive_read_support_filter_all.c +84 -0
  158. package/vendor/libarchive/libarchive/archive_read_support_filter_by_code.c +68 -0
  159. package/vendor/libarchive/libarchive/archive_read_support_filter_bzip2.c +360 -0
  160. package/vendor/libarchive/libarchive/archive_read_support_filter_compress.c +457 -0
  161. package/vendor/libarchive/libarchive/archive_read_support_filter_grzip.c +108 -0
  162. package/vendor/libarchive/libarchive/archive_read_support_filter_gzip.c +538 -0
  163. package/vendor/libarchive/libarchive/archive_read_support_filter_lrzip.c +119 -0
  164. package/vendor/libarchive/libarchive/archive_read_support_filter_lz4.c +829 -0
  165. package/vendor/libarchive/libarchive/archive_read_support_filter_lzop.c +493 -0
  166. package/vendor/libarchive/libarchive/archive_read_support_filter_none.c +51 -0
  167. package/vendor/libarchive/libarchive/archive_read_support_filter_program.c +497 -0
  168. package/vendor/libarchive/libarchive/archive_read_support_filter_rpm.c +249 -0
  169. package/vendor/libarchive/libarchive/archive_read_support_filter_uu.c +739 -0
  170. package/vendor/libarchive/libarchive/archive_read_support_filter_xz.c +792 -0
  171. package/vendor/libarchive/libarchive/archive_read_support_filter_zstd.c +356 -0
  172. package/vendor/libarchive/libarchive/archive_read_support_format_7zip.c +4650 -0
  173. package/vendor/libarchive/libarchive/archive_read_support_format_all.c +88 -0
  174. package/vendor/libarchive/libarchive/archive_read_support_format_ar.c +597 -0
  175. package/vendor/libarchive/libarchive/archive_read_support_format_by_code.c +76 -0
  176. package/vendor/libarchive/libarchive/archive_read_support_format_cab.c +3410 -0
  177. package/vendor/libarchive/libarchive/archive_read_support_format_cpio.c +1152 -0
  178. package/vendor/libarchive/libarchive/archive_read_support_format_empty.c +95 -0
  179. package/vendor/libarchive/libarchive/archive_read_support_format_iso9660.c +3516 -0
  180. package/vendor/libarchive/libarchive/archive_read_support_format_lha.c +2931 -0
  181. package/vendor/libarchive/libarchive/archive_read_support_format_mtree.c +2113 -0
  182. package/vendor/libarchive/libarchive/archive_read_support_format_rar.c +3932 -0
  183. package/vendor/libarchive/libarchive/archive_read_support_format_rar5.c +4501 -0
  184. package/vendor/libarchive/libarchive/archive_read_support_format_raw.c +194 -0
  185. package/vendor/libarchive/libarchive/archive_read_support_format_tar.c +3785 -0
  186. package/vendor/libarchive/libarchive/archive_read_support_format_warc.c +875 -0
  187. package/vendor/libarchive/libarchive/archive_read_support_format_xar.c +3770 -0
  188. package/vendor/libarchive/libarchive/archive_read_support_format_zip.c +4710 -0
  189. package/vendor/libarchive/libarchive/archive_string.c +4391 -0
  190. package/vendor/libarchive/libarchive/archive_string.h +244 -0
  191. package/vendor/libarchive/libarchive/archive_string_composition.h +2289 -0
  192. package/vendor/libarchive/libarchive/archive_string_sprintf.c +200 -0
  193. package/vendor/libarchive/libarchive/archive_time.c +168 -0
  194. package/vendor/libarchive/libarchive/archive_time_private.h +47 -0
  195. package/vendor/libarchive/libarchive/archive_util.3 +239 -0
  196. package/vendor/libarchive/libarchive/archive_util.c +668 -0
  197. package/vendor/libarchive/libarchive/archive_version_details.c +516 -0
  198. package/vendor/libarchive/libarchive/archive_virtual.c +162 -0
  199. package/vendor/libarchive/libarchive/archive_windows.c +1035 -0
  200. package/vendor/libarchive/libarchive/archive_windows.h +332 -0
  201. package/vendor/libarchive/libarchive/archive_write.3 +266 -0
  202. package/vendor/libarchive/libarchive/archive_write.c +896 -0
  203. package/vendor/libarchive/libarchive/archive_write_add_filter.c +71 -0
  204. package/vendor/libarchive/libarchive/archive_write_add_filter_b64encode.c +329 -0
  205. package/vendor/libarchive/libarchive/archive_write_add_filter_by_name.c +76 -0
  206. package/vendor/libarchive/libarchive/archive_write_add_filter_bzip2.c +411 -0
  207. package/vendor/libarchive/libarchive/archive_write_add_filter_compress.c +459 -0
  208. package/vendor/libarchive/libarchive/archive_write_add_filter_grzip.c +143 -0
  209. package/vendor/libarchive/libarchive/archive_write_add_filter_gzip.c +493 -0
  210. package/vendor/libarchive/libarchive/archive_write_add_filter_lrzip.c +214 -0
  211. package/vendor/libarchive/libarchive/archive_write_add_filter_lz4.c +710 -0
  212. package/vendor/libarchive/libarchive/archive_write_add_filter_lzop.c +500 -0
  213. package/vendor/libarchive/libarchive/archive_write_add_filter_none.c +42 -0
  214. package/vendor/libarchive/libarchive/archive_write_add_filter_program.c +398 -0
  215. package/vendor/libarchive/libarchive/archive_write_add_filter_uuencode.c +320 -0
  216. package/vendor/libarchive/libarchive/archive_write_add_filter_xz.c +547 -0
  217. package/vendor/libarchive/libarchive/archive_write_add_filter_zstd.c +608 -0
  218. package/vendor/libarchive/libarchive/archive_write_blocksize.3 +112 -0
  219. package/vendor/libarchive/libarchive/archive_write_data.3 +88 -0
  220. package/vendor/libarchive/libarchive/archive_write_disk.3 +360 -0
  221. package/vendor/libarchive/libarchive/archive_write_disk_posix.c +4789 -0
  222. package/vendor/libarchive/libarchive/archive_write_disk_private.h +43 -0
  223. package/vendor/libarchive/libarchive/archive_write_disk_set_standard_lookup.c +265 -0
  224. package/vendor/libarchive/libarchive/archive_write_disk_windows.c +2952 -0
  225. package/vendor/libarchive/libarchive/archive_write_filter.3 +140 -0
  226. package/vendor/libarchive/libarchive/archive_write_finish_entry.3 +77 -0
  227. package/vendor/libarchive/libarchive/archive_write_format.3 +187 -0
  228. package/vendor/libarchive/libarchive/archive_write_free.3 +94 -0
  229. package/vendor/libarchive/libarchive/archive_write_header.3 +71 -0
  230. package/vendor/libarchive/libarchive/archive_write_new.3 +56 -0
  231. package/vendor/libarchive/libarchive/archive_write_open.3 +270 -0
  232. package/vendor/libarchive/libarchive/archive_write_open_fd.c +141 -0
  233. package/vendor/libarchive/libarchive/archive_write_open_file.c +102 -0
  234. package/vendor/libarchive/libarchive/archive_write_open_filename.c +272 -0
  235. package/vendor/libarchive/libarchive/archive_write_open_memory.c +110 -0
  236. package/vendor/libarchive/libarchive/archive_write_private.h +166 -0
  237. package/vendor/libarchive/libarchive/archive_write_set_format.c +124 -0
  238. package/vendor/libarchive/libarchive/archive_write_set_format_7zip.c +2571 -0
  239. package/vendor/libarchive/libarchive/archive_write_set_format_ar.c +540 -0
  240. package/vendor/libarchive/libarchive/archive_write_set_format_by_name.c +93 -0
  241. package/vendor/libarchive/libarchive/archive_write_set_format_cpio.c +11 -0
  242. package/vendor/libarchive/libarchive/archive_write_set_format_cpio_binary.c +618 -0
  243. package/vendor/libarchive/libarchive/archive_write_set_format_cpio_newc.c +457 -0
  244. package/vendor/libarchive/libarchive/archive_write_set_format_cpio_odc.c +508 -0
  245. package/vendor/libarchive/libarchive/archive_write_set_format_filter_by_ext.c +141 -0
  246. package/vendor/libarchive/libarchive/archive_write_set_format_gnutar.c +790 -0
  247. package/vendor/libarchive/libarchive/archive_write_set_format_iso9660.c +8216 -0
  248. package/vendor/libarchive/libarchive/archive_write_set_format_mtree.c +2307 -0
  249. package/vendor/libarchive/libarchive/archive_write_set_format_pax.c +2249 -0
  250. package/vendor/libarchive/libarchive/archive_write_set_format_private.h +40 -0
  251. package/vendor/libarchive/libarchive/archive_write_set_format_raw.c +123 -0
  252. package/vendor/libarchive/libarchive/archive_write_set_format_shar.c +650 -0
  253. package/vendor/libarchive/libarchive/archive_write_set_format_ustar.c +768 -0
  254. package/vendor/libarchive/libarchive/archive_write_set_format_v7tar.c +648 -0
  255. package/vendor/libarchive/libarchive/archive_write_set_format_warc.c +491 -0
  256. package/vendor/libarchive/libarchive/archive_write_set_format_xar.c +3799 -0
  257. package/vendor/libarchive/libarchive/archive_write_set_format_zip.c +2548 -0
  258. package/vendor/libarchive/libarchive/archive_write_set_options.3 +779 -0
  259. package/vendor/libarchive/libarchive/archive_write_set_options.c +129 -0
  260. package/vendor/libarchive/libarchive/archive_write_set_passphrase.3 +72 -0
  261. package/vendor/libarchive/libarchive/archive_write_set_passphrase.c +95 -0
  262. package/vendor/libarchive/libarchive/archive_xxhash.h +48 -0
  263. package/vendor/libarchive/libarchive/config_freebsd.h +275 -0
  264. package/vendor/libarchive/libarchive/cpio.5 +389 -0
  265. package/vendor/libarchive/libarchive/filter_fork.h +44 -0
  266. package/vendor/libarchive/libarchive/filter_fork_posix.c +269 -0
  267. package/vendor/libarchive/libarchive/filter_fork_windows.c +270 -0
  268. package/vendor/libarchive/libarchive/libarchive-formats.5 +478 -0
  269. package/vendor/libarchive/libarchive/libarchive.3 +297 -0
  270. package/vendor/libarchive/libarchive/libarchive_changes.3 +339 -0
  271. package/vendor/libarchive/libarchive/libarchive_internals.3 +363 -0
  272. package/vendor/libarchive/libarchive/module.modulemap +34 -0
  273. package/vendor/libarchive/libarchive/mtree.5 +323 -0
  274. package/vendor/libarchive/libarchive/tar.5 +947 -0
  275. package/vendor/libarchive/libarchive/xxhash.c +531 -0
  276. package/ios/PapyrusNativeEngine.podspec +0 -15
@@ -0,0 +1,2370 @@
1
+ #import "PapyrusSelectionMenu.h"
2
+ #import "PapyrusPdfDocumentView.h"
3
+
4
+ #import <QuartzCore/QuartzCore.h>
5
+ #import <PencilKit/PencilKit.h>
6
+ #import <dispatch/dispatch.h>
7
+ #import <math.h>
8
+
9
+ #import "PapyrusEngineStore.h"
10
+ #import "PapyrusPdfPageTheme.h"
11
+ #import "PapyrusPageRotationRegistry.h"
12
+
13
+ static const CGFloat PapyrusPdfMinimumZoom = 0.5;
14
+ static const CGFloat PapyrusPdfMaximumZoom = 4.0;
15
+ static const CGFloat PapyrusPdfZoomEventTolerance = 0.02;
16
+ static const NSTimeInterval PapyrusPdfZoomEventInterval = 0.10;
17
+ static const NSTimeInterval PapyrusPdfScrollEventInterval = 0.08;
18
+ static void *PapyrusPdfScrollObservationContext = &PapyrusPdfScrollObservationContext;
19
+
20
+ static void PapyrusInvalidateViewTree(UIView *view) {
21
+ [view setNeedsDisplay];
22
+ [view.layer setNeedsDisplay];
23
+ for (UIView *subview in view.subviews) {
24
+ PapyrusInvalidateViewTree(subview);
25
+ }
26
+ }
27
+
28
+ static UIColor *PapyrusPageThemeCanvasColor(NSString *theme) {
29
+ if ([theme isEqualToString:@"sepia"]) {
30
+ return [UIColor colorWithRed:0.96 green:0.92 blue:0.83 alpha:1.0];
31
+ }
32
+ if ([theme isEqualToString:@"dark"]) {
33
+ return [UIColor colorWithWhite:0.08 alpha:1.0];
34
+ }
35
+ if ([theme isEqualToString:@"high-contrast"]) {
36
+ return UIColor.blackColor;
37
+ }
38
+ return UIColor.whiteColor;
39
+ }
40
+
41
+ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBounds) {
42
+ if (CGRectIsNull(rect) || CGRectIsEmpty(rect)) return nil;
43
+ rect = CGRectIntersection(rect, pageBounds);
44
+ if (CGRectIsNull(rect) || CGRectIsEmpty(rect)) return nil;
45
+
46
+ CGFloat pageWidth = CGRectGetWidth(pageBounds);
47
+ CGFloat pageHeight = CGRectGetHeight(pageBounds);
48
+ if (!isfinite(pageWidth) || !isfinite(pageHeight) || pageWidth <= 0 || pageHeight <= 0) {
49
+ return nil;
50
+ }
51
+
52
+ CGFloat x = (CGRectGetMinX(rect) - CGRectGetMinX(pageBounds)) / pageWidth;
53
+ CGFloat y = 1.0 - ((CGRectGetMaxY(rect) - CGRectGetMinY(pageBounds)) / pageHeight);
54
+ CGFloat width = CGRectGetWidth(rect) / pageWidth;
55
+ CGFloat height = CGRectGetHeight(rect) / pageHeight;
56
+ if (!isfinite(x) || !isfinite(y) || !isfinite(width) || !isfinite(height)) return nil;
57
+
58
+ x = MIN(1.0, MAX(0.0, x));
59
+ y = MIN(1.0, MAX(0.0, y));
60
+ width = MIN(1.0 - x, MAX(0.0, width));
61
+ height = MIN(1.0 - y, MAX(0.0, height));
62
+ if (width <= 0 || height <= 0) return nil;
63
+
64
+ return @{@"x" : @(x), @"y" : @(y), @"width" : @(width), @"height" : @(height)};
65
+ }
66
+
67
+ static CGRect PapyrusPdfRectFromNormalizedRect(NSDictionary *normalizedRect, CGRect pageBounds) {
68
+ if (![normalizedRect isKindOfClass:NSDictionary.class] ||
69
+ CGRectIsNull(pageBounds) || CGRectIsEmpty(pageBounds)) {
70
+ return CGRectNull;
71
+ }
72
+
73
+ id xValue = normalizedRect[@"x"];
74
+ id yValue = normalizedRect[@"y"];
75
+ id widthValue = normalizedRect[@"width"];
76
+ id heightValue = normalizedRect[@"height"];
77
+ if (![xValue respondsToSelector:@selector(doubleValue)] ||
78
+ ![yValue respondsToSelector:@selector(doubleValue)] ||
79
+ ![widthValue respondsToSelector:@selector(doubleValue)] ||
80
+ ![heightValue respondsToSelector:@selector(doubleValue)]) {
81
+ return CGRectNull;
82
+ }
83
+
84
+ CGFloat x = [xValue doubleValue];
85
+ CGFloat y = [yValue doubleValue];
86
+ CGFloat width = [widthValue doubleValue];
87
+ CGFloat height = [heightValue doubleValue];
88
+ if (!isfinite(x) || !isfinite(y) || !isfinite(width) || !isfinite(height) ||
89
+ width <= 0 || height <= 0) {
90
+ return CGRectNull;
91
+ }
92
+
93
+ CGFloat normalizedX = MIN(1.0, MAX(0.0, x));
94
+ CGFloat normalizedY = MIN(1.0, MAX(0.0, y));
95
+ CGFloat normalizedRight = MIN(1.0, MAX(normalizedX, x + width));
96
+ CGFloat normalizedBottom = MIN(1.0, MAX(normalizedY, y + height));
97
+ CGFloat normalizedWidth = normalizedRight - normalizedX;
98
+ CGFloat normalizedHeight = normalizedBottom - normalizedY;
99
+ if (normalizedWidth <= 0 || normalizedHeight <= 0) return CGRectNull;
100
+
101
+ return CGRectMake(
102
+ CGRectGetMinX(pageBounds) + normalizedX * CGRectGetWidth(pageBounds),
103
+ CGRectGetMinY(pageBounds) +
104
+ (1.0 - normalizedY - normalizedHeight) * CGRectGetHeight(pageBounds),
105
+ normalizedWidth * CGRectGetWidth(pageBounds),
106
+ normalizedHeight * CGRectGetHeight(pageBounds));
107
+ }
108
+
109
+ static UIColor *PapyrusAnnotationColor(NSString *hexColor, CGFloat opacity) {
110
+ NSString *source = [hexColor isKindOfClass:NSString.class] ? hexColor : @"#fbbf24";
111
+ NSString *hex = [[source stringByTrimmingCharactersInSet:
112
+ NSCharacterSet.whitespaceAndNewlineCharacterSet] uppercaseString];
113
+ if ([hex hasPrefix:@"#"]) hex = [hex substringFromIndex:1];
114
+ if (hex.length == 3) {
115
+ NSMutableString *expanded = [NSMutableString string];
116
+ for (NSUInteger index = 0; index < hex.length; index += 1) {
117
+ unichar digit = [hex characterAtIndex:index];
118
+ [expanded appendFormat:@"%C%C", digit, digit];
119
+ }
120
+ hex = expanded;
121
+ }
122
+
123
+ unsigned int rgb = 0;
124
+ NSScanner *scanner = [NSScanner scannerWithString:hex];
125
+ UIColor *baseColor = [scanner scanHexInt:&rgb] && scanner.isAtEnd && hex.length == 6
126
+ ? [UIColor colorWithRed:((rgb >> 16) & 0xff) / 255.0
127
+ green:((rgb >> 8) & 0xff) / 255.0
128
+ blue:(rgb & 0xff) / 255.0
129
+ alpha:1.0]
130
+ : [UIColor colorWithRed:1.0 green:0.75 blue:0.1 alpha:1.0];
131
+ return [baseColor colorWithAlphaComponent:MIN(1.0, MAX(0.0, opacity))];
132
+ }
133
+
134
+ static NSMapTable<UIWindow *, PKToolPicker *> *PapyrusToolPickersByWindow(void) {
135
+ static NSMapTable<UIWindow *, PKToolPicker *> *pickers;
136
+ static dispatch_once_t onceToken;
137
+ dispatch_once(&onceToken, ^{
138
+ pickers = [NSMapTable weakToStrongObjectsMapTable];
139
+ });
140
+ return pickers;
141
+ }
142
+
143
+ static NSString *PapyrusHexColorFromUIColor(UIColor *color, CGFloat *opacity) {
144
+ CGFloat red = 0;
145
+ CGFloat green = 0;
146
+ CGFloat blue = 0;
147
+ CGFloat alpha = 1;
148
+ if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {
149
+ CGColorRef cgColor = color.CGColor;
150
+ const CGFloat *components = CGColorGetComponents(cgColor);
151
+ size_t componentCount = CGColorGetNumberOfComponents(cgColor);
152
+ CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(cgColor));
153
+ if (components && model == kCGColorSpaceModelMonochrome && componentCount >= 2) {
154
+ red = green = blue = components[0];
155
+ alpha = components[1];
156
+ } else if (components && componentCount >= 4) {
157
+ red = components[0];
158
+ green = components[1];
159
+ blue = components[2];
160
+ alpha = components[3];
161
+ }
162
+ }
163
+ if (opacity) *opacity = MIN(1.0, MAX(0.0, alpha));
164
+ return [NSString stringWithFormat:@"#%02X%02X%02X",
165
+ (unsigned int)lrint(MIN(1.0, MAX(0.0, red)) * 255.0),
166
+ (unsigned int)lrint(MIN(1.0, MAX(0.0, green)) * 255.0),
167
+ (unsigned int)lrint(MIN(1.0, MAX(0.0, blue)) * 255.0)];
168
+ }
169
+
170
+ @interface PapyrusPdfPageInkCanvasView : PKCanvasView
171
+ @property (nonatomic, assign) NSInteger papyrusPageIndex;
172
+ @property (nonatomic, assign) BOOL applyingStoreDrawing;
173
+ @property (nonatomic, assign) BOOL hasUncommittedChanges;
174
+ @property (nonatomic, assign) NSUInteger pendingCommitGeneration;
175
+ @property (nonatomic, copy) NSString *appliedStoreSignature;
176
+ @property (nonatomic, weak) PKToolPicker *observedToolPicker;
177
+ @end
178
+
179
+ @implementation PapyrusPdfPageInkCanvasView
180
+ @end
181
+
182
+ @interface PapyrusSquigglyPdfAnnotation : PDFAnnotation
183
+ @end
184
+
185
+ @implementation PapyrusSquigglyPdfAnnotation
186
+ - (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
187
+ (void)box;
188
+ CGRect bounds = self.bounds;
189
+ if (CGRectIsNull(bounds) || CGRectIsEmpty(bounds) || !context) return;
190
+
191
+ CGFloat height = CGRectGetHeight(bounds);
192
+ CGFloat wavelength = MAX(2.0, height * 0.7);
193
+ CGFloat amplitude = MAX(0.6, height * 0.16);
194
+ CGFloat centerY = CGRectGetMidY(bounds);
195
+ CGContextSaveGState(context);
196
+ CGContextSetStrokeColorWithColor(context, self.color.CGColor);
197
+ CGContextSetLineWidth(context, MAX(0.65, height * 0.08));
198
+ CGMutablePathRef path = CGPathCreateMutable();
199
+ CGFloat minX = CGRectGetMinX(bounds);
200
+ CGFloat maxX = CGRectGetMaxX(bounds);
201
+ BOOL first = YES;
202
+ for (CGFloat x = minX; x <= maxX; x += 1.5) {
203
+ CGFloat y = centerY + sin((x - minX) * M_PI * 2.0 / wavelength) * amplitude;
204
+ if (first) {
205
+ CGPathMoveToPoint(path, NULL, x, y);
206
+ first = NO;
207
+ } else {
208
+ CGPathAddLineToPoint(path, NULL, x, y);
209
+ }
210
+ }
211
+ CGPathAddLineToPoint(path, NULL, maxX, centerY);
212
+ CGContextAddPath(context, path);
213
+ CGContextStrokePath(context);
214
+ CGPathRelease(path);
215
+ CGContextRestoreGState(context);
216
+ }
217
+ @end
218
+
219
+ @interface PapyrusCommentPdfAnnotation : PDFAnnotation
220
+ @property (nonatomic, assign) BOOL groupHidden;
221
+ @property (nonatomic, assign) NSInteger groupCount;
222
+ @end
223
+
224
+ @implementation PapyrusCommentPdfAnnotation
225
+ - (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
226
+ (void)box;
227
+ if (self.groupHidden) return;
228
+ CGRect bounds = self.bounds;
229
+ if (CGRectIsNull(bounds) || CGRectIsEmpty(bounds) || !context) return;
230
+
231
+ CGFloat inset = MAX(1.0, CGRectGetHeight(bounds) * 0.08);
232
+ CGRect noteRect = CGRectInset(bounds, inset, inset);
233
+ CGFloat fold = MIN(CGRectGetWidth(noteRect), CGRectGetHeight(noteRect)) * 0.24;
234
+ CGFloat radius = MIN(CGRectGetHeight(noteRect) * 0.12, 4.0);
235
+ CGPathRef notePath = CGPathCreateWithRoundedRect(noteRect, radius, radius, NULL);
236
+ CGContextSaveGState(context);
237
+ CGContextAddPath(context, notePath);
238
+ CGContextSetFillColorWithColor(context, self.color.CGColor);
239
+ CGContextFillPath(context);
240
+ CGPathRelease(notePath);
241
+
242
+ CGContextSetStrokeColorWithColor(context, UIColor.whiteColor.CGColor);
243
+ CGContextSetLineWidth(context, MAX(0.7, CGRectGetHeight(noteRect) * 0.045));
244
+ CGFloat left = CGRectGetMinX(noteRect) + inset;
245
+ CGFloat right = CGRectGetMaxX(noteRect) - fold - inset;
246
+ CGFloat firstY = CGRectGetMinY(noteRect) + CGRectGetHeight(noteRect) * 0.38;
247
+ CGFloat secondY = CGRectGetMinY(noteRect) + CGRectGetHeight(noteRect) * 0.62;
248
+ CGContextMoveToPoint(context, left, firstY);
249
+ CGContextAddLineToPoint(context, right, firstY);
250
+ CGContextMoveToPoint(context, left, secondY);
251
+ CGContextAddLineToPoint(context, right, secondY);
252
+ CGContextStrokePath(context);
253
+ if (self.groupCount > 1) {
254
+ UIGraphicsPushContext(context);
255
+ CGContextTranslateCTM(context, CGRectGetMidX(bounds), CGRectGetMidY(bounds));
256
+ CGContextScaleCTM(context, 1, -1);
257
+ NSString *label = [NSString stringWithFormat:@"%ld", (long)self.groupCount];
258
+ NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:MAX(8, bounds.size.height * 0.6)], NSForegroundColorAttributeName:UIColor.whiteColor};
259
+ CGSize size = [label sizeWithAttributes:attributes];
260
+ [label drawAtPoint:CGPointMake(-size.width/2, -size.height/2) withAttributes:attributes];
261
+ UIGraphicsPopContext();
262
+ }
263
+ CGContextRestoreGState(context);
264
+ }
265
+ @end
266
+
267
+ @interface PapyrusSelectionOutlinePdfAnnotation : PDFAnnotation
268
+ @end
269
+
270
+ @implementation PapyrusSelectionOutlinePdfAnnotation
271
+ - (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
272
+ (void)box;
273
+ CGRect bounds = self.bounds;
274
+ if (CGRectIsNull(bounds) || CGRectIsEmpty(bounds) || !context) return;
275
+
276
+ CGFloat lineWidth = 1.5;
277
+ CGRect outline = CGRectInset(bounds, lineWidth / 2.0, lineWidth / 2.0);
278
+ if (CGRectIsNull(outline) || CGRectIsEmpty(outline)) return;
279
+ CGContextSaveGState(context);
280
+ CGContextSetStrokeColorWithColor(context, self.color.CGColor);
281
+ CGContextSetLineWidth(context, lineWidth);
282
+ CGContextStrokeRect(context, outline);
283
+ CGContextRestoreGState(context);
284
+ }
285
+ @end
286
+
287
+ @interface PapyrusPdfDocumentView () <UIEditMenuInteractionDelegate,
288
+ PDFPageOverlayViewProvider,
289
+ PKCanvasViewDelegate,
290
+ PKToolPickerObserver>
291
+ @property (nonatomic, strong) PDFView *pdfView;
292
+ @property (nonatomic, copy, nullable) NSString *pageThemeLeaseToken;
293
+ @property (nonatomic, strong) UIEditMenuInteraction *editMenuInteraction;
294
+ @property (nonatomic, copy) NSArray<PDFSelection *> *searchSelections;
295
+ @property (nonatomic, copy) NSDictionary<NSNumber *, PDFSelection *> *searchSelectionsByResultIndex;
296
+ @property (nonatomic, strong) NSMutableDictionary<NSString *, NSArray<PDFAnnotation *> *> *papyrusAnnotationsById;
297
+ @property (nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *papyrusAnnotationSignaturesById;
298
+ @property (nonatomic, strong) NSMapTable<PDFAnnotation *, NSString *> *papyrusAnnotationIdsByObject;
299
+ @property (nonatomic, copy) NSArray<PDFAnnotation *> *selectedAnnotationAdornmentAnnotations;
300
+ @property (nonatomic, copy, nullable) NSString *contextualAnnotationMenuId;
301
+ @property (nonatomic, copy, nullable) NSString *contextualAnnotationMenuConfigurationId;
302
+ @property (nonatomic, assign) CGPoint contextualAnnotationMenuSourcePoint;
303
+ @property (nonatomic, assign) NSUInteger searchNavigationGeneration;
304
+ @property (nonatomic, weak) UIScrollView *observedScrollView;
305
+ @property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;
306
+ @property (nonatomic, strong) UITapGestureRecognizer *doubleTapRecognizer;
307
+ @property (nonatomic, strong) UILongPressGestureRecognizer *longPressRecognizer;
308
+ @property (nonatomic, assign) CGSize lastLayoutSize;
309
+ @property (nonatomic, assign) NSInteger lastEmittedPage;
310
+ @property (nonatomic, assign) CGFloat lastEmittedZoom;
311
+ @property (nonatomic, copy) NSString *lastVisiblePagesSignature;
312
+ @property (nonatomic, assign) BOOL zoomEventScheduled;
313
+ @property (nonatomic, assign) BOOL suppressScaleSynchronization;
314
+ @property (nonatomic, assign) BOOL scrollEventScheduled;
315
+ @property (nonatomic, assign) CGFloat pendingScrollOffsetY;
316
+ @property (nonatomic, assign) CFTimeInterval lastScrollEventTime;
317
+ @property (nonatomic, copy) NSString *lastSelectionSignature;
318
+ @property (nonatomic, assign) NSInteger lastSelectionPageIndex;
319
+ @property (nonatomic, assign) BOOL lastSelectionWasActive;
320
+ @property (nonatomic, assign) NSUInteger selectionMenuGeneration;
321
+ @property (nonatomic, strong) NSMutableDictionary<NSNumber *, PapyrusPdfPageInkCanvasView *> *inkCanvasesByPageIndex;
322
+ @property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *inkAnnotationSignaturesByPageIndex;
323
+ @property (nonatomic, weak) PapyrusPdfPageInkCanvasView *activeInkCanvas;
324
+ @property (nonatomic, strong) PKToolPicker *activeInkToolPicker;
325
+ @property (nonatomic, copy) NSString *lastAppliedInkToolConfiguration;
326
+ - (void)scheduleSelectionEditMenuForSignature:(NSString *)signature;
327
+ - (void)attemptSelectionEditMenuForSignature:(NSString *)signature generation:(NSUInteger)generation;
328
+ - (BOOL)hasActiveGestureInView:(UIView *)view;
329
+ - (void)emitDefineSelection;
330
+ - (BOOL)isSingleWordSelection:(NSString *)text;
331
+ - (void)rebuildSearchHighlights;
332
+ - (void)updateSearchHighlightColorsFromResultIndex:(NSInteger)previousSearchIndex;
333
+ - (void)scheduleNavigationToSearchResultAtIndex:(NSInteger)activeSearchIndex;
334
+ - (UIColor *)searchHighlightColorForActive:(BOOL)isActive;
335
+ - (void)reconcilePapyrusAnnotations;
336
+ - (void)updateSelectedAnnotationAdornment;
337
+ - (void)removeSelectedAnnotationAdornment;
338
+ - (void)dismissAnnotationMenuForDocumentChange;
339
+ - (void)removePapyrusAnnotationWithId:(NSString *)annotationId;
340
+ - (void)clearPapyrusAnnotationsForDocument:(nullable PDFDocument *)document;
341
+ - (NSArray<PDFAnnotation *> *)createPdfAnnotationsForPapyrusAnnotation:(NSDictionary *)annotation;
342
+ - (NSString *)annotationSignature:(NSDictionary *)annotation;
343
+ - (void)emitAnnotationFromCurrentSelectionWithType:(NSString *)type;
344
+ - (void)presentAnnotationEditMenuForId:(NSString *)annotationId atPoint:(CGPoint)point;
345
+ - (void)emitAnnotationDeleteWithId:(NSString *)annotationId;
346
+ - (void)emitCommentAtPage:(PDFPage *)page pageIndex:(NSInteger)pageIndex normalizedPoint:(CGPoint)point;
347
+ - (void)reconcileInkOverlays;
348
+ - (void)applyStoreInkAnnotationsToCanvas:(PapyrusPdfPageInkCanvasView *)canvas force:(BOOL)force;
349
+ - (void)updateInkCanvasInputAndPicker;
350
+ - (void)activateInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
351
+ - (void)deactivateInkCanvas;
352
+ - (void)releaseInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
353
+ - (void)commitInkDrawingForCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
354
+ - (NSString *)inkAnnotationSignatureForPage:(NSInteger)pageIndex;
355
+ - (NSArray<NSDictionary *> *)inkDrawingPayloadForCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
356
+ - (void)resetInkOverlaysForDocumentChange;
357
+ - (void)releasePageThemeLeaseForDocument:(nullable PDFDocument *)document;
358
+ - (void)acquireOrUpdatePageThemeLeaseForDocument:(nullable PDFDocument *)document;
359
+ @end
360
+
361
+ @implementation PapyrusPdfDocumentView
362
+
363
+ - (void)dealloc {
364
+ [self releasePageThemeLeaseForDocument:self.pdfView.document];
365
+ [self stopObservingScrollView];
366
+ [self resetInkOverlaysForDocumentChange];
367
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
368
+ self.tapRecognizer.delegate = nil;
369
+ self.doubleTapRecognizer.delegate = nil;
370
+ self.longPressRecognizer.delegate = nil;
371
+ [self clearPapyrusAnnotationsForDocument:self.pdfView.document];
372
+ }
373
+
374
+ - (instancetype)initWithFrame:(CGRect)frame {
375
+ self = [super initWithFrame:frame];
376
+ if (!self) return nil;
377
+
378
+ _pageTheme = @"normal";
379
+ _viewMode = @"continuous";
380
+ _zoom = 1.0;
381
+ _currentPage = 1;
382
+ _searchResults = @[];
383
+ _activeSearchIndex = -1;
384
+ _searchSelections = @[];
385
+ _searchSelectionsByResultIndex = @{};
386
+ _annotations = @[];
387
+ _activeTool = @"select";
388
+ _activeDrawToolPreset = @"ink";
389
+ _inkStrokeWidth = 0.006;
390
+ _annotationColor = @"#fbbf24";
391
+ _annotationSelectionColor = @"#2563eb";
392
+ _annotationOpacity = 1.0;
393
+ _papyrusAnnotationsById = [NSMutableDictionary dictionary];
394
+ _papyrusAnnotationSignaturesById = [NSMutableDictionary dictionary];
395
+ _papyrusAnnotationIdsByObject = [NSMapTable strongToStrongObjectsMapTable];
396
+ _selectedAnnotationAdornmentAnnotations = @[];
397
+ _inkCanvasesByPageIndex = [NSMutableDictionary dictionary];
398
+ _inkAnnotationSignaturesByPageIndex = [NSMutableDictionary dictionary];
399
+ _searchNavigationGeneration = 0;
400
+ _lastEmittedPage = NSNotFound;
401
+ _lastSelectionPageIndex = NSNotFound;
402
+ _lastEmittedZoom = NAN;
403
+ _lastLayoutSize = CGSizeZero;
404
+ _defineLabel = NSLocalizedString(@"Define", nil);
405
+ _annotateLabel = NSLocalizedString(@"Annotate", nil);
406
+ _annotationHighlightLabel = NSLocalizedString(@"Highlight", nil);
407
+ _annotationUnderlineLabel = NSLocalizedString(@"Underline", nil);
408
+ _annotationStrikeoutLabel = NSLocalizedString(@"Strikeout", nil);
409
+ _annotationSquigglyLabel = NSLocalizedString(@"Squiggly", nil);
410
+ _annotationNoteLabel = NSLocalizedString(@"Note", nil);
411
+ self.clipsToBounds = YES;
412
+ self.backgroundColor = UIColor.whiteColor;
413
+
414
+ _pdfView = [[PDFView alloc] initWithFrame:CGRectZero];
415
+ _pdfView.displayBox = kPDFDisplayBoxCropBox;
416
+ _pdfView.displayDirection = kPDFDisplayDirectionVertical;
417
+ _pdfView.displayMode = kPDFDisplaySinglePageContinuous;
418
+ _pdfView.displaysPageBreaks = YES;
419
+ _pdfView.autoScales = YES;
420
+ _pdfView.userInteractionEnabled = YES;
421
+ _pdfView.backgroundColor = UIColor.whiteColor;
422
+ _pdfView.clipsToBounds = YES;
423
+ [self addSubview:_pdfView];
424
+
425
+ if (@available(iOS 16.0, *)) {
426
+ _pdfView.pageOverlayViewProvider = self;
427
+ _editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self];
428
+ [_pdfView addInteraction:_editMenuInteraction];
429
+ }
430
+
431
+ _tapRecognizer = [[UITapGestureRecognizer alloc]
432
+ initWithTarget:self
433
+ action:@selector(handleDocumentTap:)];
434
+ _tapRecognizer.delegate = self;
435
+ _tapRecognizer.cancelsTouchesInView = NO;
436
+ _tapRecognizer.delaysTouchesBegan = NO;
437
+ [_pdfView addGestureRecognizer:_tapRecognizer];
438
+
439
+ _doubleTapRecognizer = [[UITapGestureRecognizer alloc]
440
+ initWithTarget:self
441
+ action:@selector(handleDocumentDoubleTap:)];
442
+ _doubleTapRecognizer.numberOfTapsRequired = 2;
443
+ _doubleTapRecognizer.delegate = self;
444
+ _doubleTapRecognizer.cancelsTouchesInView = NO;
445
+ _doubleTapRecognizer.delaysTouchesBegan = NO;
446
+ [_pdfView addGestureRecognizer:_doubleTapRecognizer];
447
+ [_tapRecognizer requireGestureRecognizerToFail:_doubleTapRecognizer];
448
+ _longPressRecognizer = [[UILongPressGestureRecognizer alloc]
449
+ initWithTarget:self action:@selector(handleDocumentLongPress:)];
450
+ _longPressRecognizer.delegate = self;
451
+ _longPressRecognizer.cancelsTouchesInView = NO;
452
+ [_pdfView addGestureRecognizer:_longPressRecognizer];
453
+ [_tapRecognizer requireGestureRecognizerToFail:_longPressRecognizer];
454
+
455
+ NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
456
+ [center addObserver:self
457
+ selector:@selector(handlePdfPageChanged:)
458
+ name:PDFViewPageChangedNotification
459
+ object:_pdfView];
460
+ [center addObserver:self
461
+ selector:@selector(handlePdfScaleChanged:)
462
+ name:PDFViewScaleChangedNotification
463
+ object:_pdfView];
464
+ [center addObserver:self
465
+ selector:@selector(handlePdfVisiblePagesChanged:)
466
+ name:PDFViewVisiblePagesChangedNotification
467
+ object:_pdfView];
468
+ [center addObserver:self
469
+ selector:@selector(handlePdfSelectionChanged:)
470
+ name:PDFViewSelectionChangedNotification
471
+ object:_pdfView];
472
+ [center addObserver:self
473
+ selector:@selector(handleStoredDocumentChanged:)
474
+ name:PapyrusEngineStoreDocumentDidChangeNotification
475
+ object:[PapyrusEngineStore shared]];
476
+
477
+ return self;
478
+ }
479
+
480
+ - (void)setSelectionActive:(BOOL)selectionActive {
481
+ _selectionActive = selectionActive;
482
+ }
483
+
484
+ - (void)layoutSubviews {
485
+ [super layoutSubviews];
486
+ self.pdfView.frame = self.bounds;
487
+
488
+ if (!CGSizeEqualToSize(self.lastLayoutSize, self.bounds.size)) {
489
+ self.lastLayoutSize = self.bounds.size;
490
+ [self updateFitScalePreservingViewport];
491
+ }
492
+
493
+ [self refreshScrollViewObservation];
494
+ [self emitVisiblePagesIfNeeded];
495
+ }
496
+
497
+ - (void)setEngineId:(NSString *)engineId {
498
+ NSString *normalized = engineId.length > 0 ? [engineId copy] : nil;
499
+ if ((_engineId == normalized) || [_engineId isEqualToString:normalized]) return;
500
+ _engineId = normalized;
501
+ [self reloadDocumentFromStore];
502
+ }
503
+
504
+ - (void)setPageTheme:(NSString *)pageTheme {
505
+ NSSet<NSString *> *supportedThemes =
506
+ [NSSet setWithArray:@[@"normal", @"sepia", @"dark", @"high-contrast"]];
507
+ NSString *normalizedTheme = pageTheme.length > 0 &&
508
+ [supportedThemes containsObject:pageTheme]
509
+ ? [pageTheme copy]
510
+ : @"normal";
511
+ BOOL didChange = ![_pageTheme isEqualToString:normalizedTheme];
512
+ _pageTheme = normalizedTheme;
513
+ if (self.window) {
514
+ [self acquireOrUpdatePageThemeLeaseForDocument:self.pdfView.document];
515
+ } else {
516
+ [self releasePageThemeLeaseForDocument:self.pdfView.document];
517
+ }
518
+
519
+ UIColor *canvasColor = PapyrusPageThemeCanvasColor(normalizedTheme);
520
+ self.backgroundColor = canvasColor;
521
+ self.pdfView.backgroundColor = canvasColor;
522
+ if (didChange) {
523
+ PapyrusInvalidateViewTree(self.pdfView);
524
+ }
525
+ }
526
+
527
+ - (void)releasePageThemeLeaseForDocument:(PDFDocument *)document {
528
+ if (document && self.pageThemeLeaseToken.length > 0) {
529
+ PapyrusReleasePdfPageThemeLease(document, self.pageThemeLeaseToken);
530
+ }
531
+ self.pageThemeLeaseToken = nil;
532
+ }
533
+
534
+ - (void)acquireOrUpdatePageThemeLeaseForDocument:(PDFDocument *)document {
535
+ if (!document) return;
536
+ if (self.pageThemeLeaseToken.length > 0) {
537
+ PapyrusUpdatePdfPageThemeLease(document, self.pageThemeLeaseToken, self.pageTheme);
538
+ } else {
539
+ self.pageThemeLeaseToken =
540
+ PapyrusAcquirePdfPageThemeLease(document, self.pageTheme);
541
+ }
542
+ }
543
+
544
+ - (void)setActiveTool:(NSString *)activeTool {
545
+ _activeTool = activeTool.length > 0 ? [activeTool copy] : @"select";
546
+ [self updateInkCanvasInputAndPicker];
547
+ }
548
+
549
+ - (void)setActiveDrawToolPreset:(NSString *)activeDrawToolPreset {
550
+ NSSet<NSString *> *presets = [NSSet setWithArray:@[@"ink", @"highlight", @"underline"]];
551
+ _activeDrawToolPreset = [presets containsObject:activeDrawToolPreset]
552
+ ? [activeDrawToolPreset copy] : @"ink";
553
+ self.lastAppliedInkToolConfiguration = nil;
554
+ [self updateInkCanvasInputAndPicker];
555
+ }
556
+
557
+ - (void)setInkStrokeWidth:(CGFloat)inkStrokeWidth {
558
+ if (!isfinite(inkStrokeWidth)) return;
559
+ _inkStrokeWidth = MIN(0.02, MAX(0.0025, inkStrokeWidth));
560
+ self.lastAppliedInkToolConfiguration = nil;
561
+ [self updateInkCanvasInputAndPicker];
562
+ }
563
+
564
+ - (void)setAnnotationColor:(NSString *)annotationColor {
565
+ _annotationColor = annotationColor.length > 0 ? [annotationColor copy] : @"#fbbf24";
566
+ self.lastAppliedInkToolConfiguration = nil;
567
+ [self updateInkCanvasInputAndPicker];
568
+ }
569
+
570
+ - (void)setAnnotationOpacity:(CGFloat)annotationOpacity {
571
+ if (!isfinite(annotationOpacity)) return;
572
+ _annotationOpacity = MIN(1.0, MAX(0.1, annotationOpacity));
573
+ self.lastAppliedInkToolConfiguration = nil;
574
+ [self updateInkCanvasInputAndPicker];
575
+ }
576
+
577
+ - (void)setViewMode:(NSString *)viewMode {
578
+ NSString *normalized = [viewMode isEqualToString:@"single"] ? @"single" : @"continuous";
579
+ if ([_viewMode isEqualToString:normalized]) return;
580
+ CGFloat desiredZoom = [self clampedZoom:self.zoom];
581
+ BOOL wasSuppressingScaleSynchronization = self.suppressScaleSynchronization;
582
+ self.suppressScaleSynchronization = YES;
583
+ PDFPage *currentPage = self.pdfView.currentPage;
584
+ _viewMode = normalized;
585
+ self.pdfView.displayMode = [normalized isEqualToString:@"single"]
586
+ ? kPDFDisplaySinglePage
587
+ : kPDFDisplaySinglePageContinuous;
588
+ _zoom = desiredZoom;
589
+ [self updateFitScalePreservingViewport];
590
+ if (currentPage) {
591
+ [self.pdfView goToPage:currentPage];
592
+ } else {
593
+ [self applyCurrentPage];
594
+ }
595
+ _zoom = desiredZoom;
596
+ [self applyNormalizedZoom];
597
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
598
+ }
599
+
600
+ - (void)setCurrentPage:(NSInteger)currentPage {
601
+ _currentPage = MAX(1, currentPage);
602
+ [self applyCurrentPage];
603
+ }
604
+
605
+ - (void)setZoom:(CGFloat)zoom {
606
+ if (!isfinite(zoom)) return;
607
+ CGFloat normalized = [self clampedZoom:zoom];
608
+ CGFloat currentNativeZoom = [self normalizedZoomForPdfView];
609
+ _zoom = normalized;
610
+ if (currentNativeZoom > 0 && fabs(currentNativeZoom - normalized) <= 0.015) {
611
+ self.lastEmittedZoom = normalized;
612
+ return;
613
+ }
614
+ [self applyNormalizedZoom];
615
+ self.lastEmittedZoom = normalized;
616
+ }
617
+
618
+ - (void)handleStoredDocumentChanged:(NSNotification *)notification {
619
+ NSString *changedEngineId = [notification.userInfo[PapyrusEngineStoreEngineIdKey] copy];
620
+ if (changedEngineId.length == 0) return;
621
+
622
+ __weak typeof(self) weakSelf = self;
623
+ dispatch_async(dispatch_get_main_queue(), ^{
624
+ typeof(self) strongSelf = weakSelf;
625
+ if (!strongSelf || ![changedEngineId isEqualToString:strongSelf.engineId]) return;
626
+ [strongSelf reloadDocumentFromStore];
627
+ });
628
+ }
629
+
630
+ - (void)reloadDocumentFromStore {
631
+ NSAssert(NSThread.isMainThread, @"PDFView must only be updated on the main thread");
632
+ PDFDocument *document = self.engineId.length > 0
633
+ ? [[PapyrusEngineStore shared] documentForEngine:self.engineId]
634
+ : nil;
635
+ PDFDocument *currentDocument = self.pdfView.document;
636
+ PapyrusPageRotationRegistry *rotationRegistry =
637
+ [PapyrusPageRotationRegistry sharedRegistry];
638
+ if (currentDocument) {
639
+ [rotationRegistry restoreAllRotationsForDocument:currentDocument];
640
+ }
641
+ if (document && document != currentDocument) {
642
+ [rotationRegistry restoreAllRotationsForDocument:document];
643
+ }
644
+ if (self.pdfView.document == document) {
645
+ if (self.window) {
646
+ [self acquireOrUpdatePageThemeLeaseForDocument:document];
647
+ } else {
648
+ [self releasePageThemeLeaseForDocument:document];
649
+ }
650
+ [self applyCurrentPage];
651
+ [self rebuildSearchHighlights];
652
+ [self reconcilePapyrusAnnotations];
653
+ [self reconcileInkOverlays];
654
+ return;
655
+ }
656
+
657
+ [self dismissAnnotationMenuForDocumentChange];
658
+ CGFloat desiredZoom = [self clampedZoom:self.zoom];
659
+ BOOL wasSuppressingScaleSynchronization = self.suppressScaleSynchronization;
660
+ self.suppressScaleSynchronization = YES;
661
+ self.lastVisiblePagesSignature = nil;
662
+ self.lastEmittedPage = NSNotFound;
663
+ [self resetInkOverlaysForDocumentChange];
664
+ [self clearPapyrusAnnotationsForDocument:self.pdfView.document];
665
+ [self clearCurrentSelection];
666
+ [self releasePageThemeLeaseForDocument:currentDocument];
667
+ if (document && self.window) {
668
+ self.pageThemeLeaseToken =
669
+ PapyrusAcquirePdfPageThemeLease(document, self.pageTheme);
670
+ }
671
+ self.pdfView.document = document;
672
+ if (!document) {
673
+ [self rebuildSearchHighlights];
674
+ [self reconcilePapyrusAnnotations];
675
+ self.lastEmittedZoom = NAN;
676
+ _zoom = desiredZoom;
677
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
678
+ return;
679
+ }
680
+
681
+ [self configureDisplayMode];
682
+ self.pdfView.autoScales = YES;
683
+ [self.pdfView layoutDocumentView];
684
+ [self updateScaleLimitsForFitScale:self.pdfView.scaleFactorForSizeToFit];
685
+ self.pdfView.autoScales = NO;
686
+ _zoom = desiredZoom;
687
+ [self applyNormalizedZoom];
688
+ [self applyCurrentPage];
689
+ _zoom = desiredZoom;
690
+ [self applyNormalizedZoom];
691
+ [self refreshScrollViewObservation];
692
+ [self emitVisiblePagesIfNeeded];
693
+ [self rebuildSearchHighlights];
694
+ [self reconcilePapyrusAnnotations];
695
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
696
+ }
697
+
698
+ - (void)setSearchResults:(NSArray<NSDictionary *> *)searchResults {
699
+ _searchResults = [searchResults copy] ?: @[];
700
+ [self rebuildSearchHighlights];
701
+ }
702
+
703
+ - (void)setActiveSearchIndex:(NSInteger)activeSearchIndex {
704
+ NSInteger previousSearchIndex = _activeSearchIndex;
705
+ _activeSearchIndex = activeSearchIndex;
706
+ [self updateSearchHighlightColorsFromResultIndex:previousSearchIndex];
707
+ [self scheduleNavigationToSearchResultAtIndex:activeSearchIndex];
708
+ }
709
+
710
+ - (void)setAnnotations:(NSArray<NSDictionary *> *)annotations {
711
+ _annotations = [annotations copy] ?: @[];
712
+ [self reconcilePapyrusAnnotations];
713
+ [self reconcileInkOverlays];
714
+ }
715
+
716
+ - (UIView *)pdfView:(PDFView *)pdfView overlayViewForPage:(PDFPage *)page {
717
+ if (@available(iOS 16.0, *)) {
718
+ PDFDocument *document = pdfView.document;
719
+ NSInteger pageIndex = document ? (NSInteger)[document indexForPage:page] : NSNotFound;
720
+ if (pageIndex < 0 || pageIndex == NSNotFound) return nil;
721
+
722
+ NSNumber *key = @(pageIndex);
723
+ PapyrusPdfPageInkCanvasView *canvas = self.inkCanvasesByPageIndex[key];
724
+ if (!canvas) {
725
+ canvas = [[PapyrusPdfPageInkCanvasView alloc] initWithFrame:CGRectZero];
726
+ canvas.papyrusPageIndex = pageIndex;
727
+ canvas.backgroundColor = UIColor.clearColor;
728
+ canvas.opaque = NO;
729
+ canvas.clipsToBounds = YES;
730
+ canvas.drawingPolicy = PKCanvasViewDrawingPolicyAnyInput;
731
+ canvas.scrollEnabled = NO;
732
+ canvas.delegate = self;
733
+ canvas.userInteractionEnabled = NO;
734
+ self.inkCanvasesByPageIndex[key] = canvas;
735
+ [self applyStoreInkAnnotationsToCanvas:canvas force:YES];
736
+ }
737
+ return canvas;
738
+ }
739
+ return nil;
740
+ }
741
+
742
+ - (void)pdfView:(PDFView *)pdfView
743
+ willDisplayOverlayView:(UIView *)overlayView
744
+ forPage:(PDFPage *)page {
745
+ (void)page;
746
+ if (![overlayView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) return;
747
+ UIView *ancestor = overlayView.superview;
748
+ while (ancestor && ancestor != pdfView) {
749
+ ancestor.userInteractionEnabled = YES;
750
+ ancestor = ancestor.superview;
751
+ }
752
+ PapyrusPdfPageInkCanvasView *canvas = (PapyrusPdfPageInkCanvasView *)overlayView;
753
+ self.inkCanvasesByPageIndex[@(canvas.papyrusPageIndex)] = canvas;
754
+ [self applyStoreInkAnnotationsToCanvas:canvas force:NO];
755
+ [self updateInkCanvasInputAndPicker];
756
+ }
757
+
758
+ - (void)pdfView:(PDFView *)pdfView
759
+ willEndDisplayingOverlayView:(UIView *)overlayView
760
+ forPage:(PDFPage *)page {
761
+ (void)pdfView;
762
+ (void)page;
763
+ if ([overlayView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) {
764
+ [self releaseInkCanvas:(PapyrusPdfPageInkCanvasView *)overlayView];
765
+ }
766
+ }
767
+
768
+ - (NSString *)inkAnnotationSignatureForPage:(NSInteger)pageIndex {
769
+ NSMutableArray<NSDictionary *> *pageAnnotations = [NSMutableArray array];
770
+ for (id value in self.annotations) {
771
+ if (![value isKindOfClass:NSDictionary.class]) continue;
772
+ NSDictionary *annotation = (NSDictionary *)value;
773
+ if (![annotation[@"type"] isEqual:@"ink"] ||
774
+ [annotation[@"pageIndex"] integerValue] != pageIndex) {
775
+ continue;
776
+ }
777
+ [pageAnnotations addObject:@{
778
+ @"path" : annotation[@"path"] ?: @[],
779
+ @"color" : annotation[@"color"] ?: @"#111827",
780
+ @"opacity" : annotation[@"opacity"] ?: @1,
781
+ @"strokeWidth" : annotation[@"strokeWidth"] ?: @0.006
782
+ }];
783
+ }
784
+
785
+ NSError *error = nil;
786
+ NSData *data = [NSJSONSerialization dataWithJSONObject:pageAnnotations
787
+ options:NSJSONWritingSortedKeys
788
+ error:&error];
789
+ if (!data || error) return pageAnnotations.description ?: @"[]";
790
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"[]";
791
+ }
792
+
793
+ - (void)applyStoreInkAnnotationsToCanvas:(PapyrusPdfPageInkCanvasView *)canvas
794
+ force:(BOOL)force {
795
+ if (!canvas || !self.pdfView.document) return;
796
+ NSInteger pageIndex = canvas.papyrusPageIndex;
797
+ NSString *signature = [self inkAnnotationSignatureForPage:pageIndex];
798
+ if (!force && [canvas.appliedStoreSignature isEqualToString:signature]) return;
799
+
800
+ CGFloat canvasWidth = CGRectGetWidth(canvas.bounds);
801
+ CGFloat canvasHeight = CGRectGetHeight(canvas.bounds);
802
+ PDFPage *page = [self.pdfView.document pageAtIndex:(NSUInteger)pageIndex];
803
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
804
+ if (canvasWidth <= 0) canvasWidth = CGRectGetWidth(pageBounds);
805
+ if (canvasHeight <= 0) canvasHeight = CGRectGetHeight(pageBounds);
806
+ if (canvasWidth <= 0 || canvasHeight <= 0) return;
807
+
808
+ NSMutableArray<PKStroke *> *strokes = [NSMutableArray array];
809
+ for (id value in self.annotations) {
810
+ if (![value isKindOfClass:NSDictionary.class]) continue;
811
+ NSDictionary *annotation = (NSDictionary *)value;
812
+ if (![annotation[@"type"] isEqual:@"ink"] ||
813
+ [annotation[@"pageIndex"] integerValue] != pageIndex) {
814
+ continue;
815
+ }
816
+ NSArray *pathValues = [annotation[@"path"] isKindOfClass:NSArray.class]
817
+ ? annotation[@"path"] : @[];
818
+ if (pathValues.count == 0) continue;
819
+
820
+ CGFloat opacity = [annotation[@"opacity"] respondsToSelector:@selector(doubleValue)]
821
+ ? [annotation[@"opacity"] doubleValue] : 1.0;
822
+ opacity = isfinite(opacity) ? MIN(1.0, MAX(0.0, opacity)) : 1.0;
823
+ NSString *hexColor = [annotation[@"color"] isKindOfClass:NSString.class]
824
+ ? annotation[@"color"] : @"#111827";
825
+ UIColor *color = PapyrusAnnotationColor(hexColor, opacity);
826
+ PKInkType inkType = opacity <= 0.35 ? PKInkTypeMarker : PKInkTypePen;
827
+ PKInk *ink = [[PKInk alloc] initWithInkType:inkType color:color];
828
+ CGFloat normalizedWidth = [annotation[@"strokeWidth"] respondsToSelector:@selector(doubleValue)]
829
+ ? [annotation[@"strokeWidth"] doubleValue] : 0.006;
830
+ if (!isfinite(normalizedWidth) || normalizedWidth <= 0) normalizedWidth = 0.006;
831
+ CGFloat pointWidth = MAX(0.6, normalizedWidth * canvasWidth);
832
+
833
+ NSMutableArray<PKStrokePoint *> *controlPoints = [NSMutableArray array];
834
+ for (id pointValue in pathValues) {
835
+ if (![pointValue isKindOfClass:NSDictionary.class]) continue;
836
+ NSDictionary *point = (NSDictionary *)pointValue;
837
+ CGFloat x = [point[@"x"] respondsToSelector:@selector(doubleValue)]
838
+ ? [point[@"x"] doubleValue] : NAN;
839
+ CGFloat y = [point[@"y"] respondsToSelector:@selector(doubleValue)]
840
+ ? [point[@"y"] doubleValue] : NAN;
841
+ if (!isfinite(x) || !isfinite(y)) continue;
842
+ CGPoint location = CGPointMake(
843
+ MIN(1.0, MAX(0.0, x)) * canvasWidth,
844
+ MIN(1.0, MAX(0.0, y)) * canvasHeight);
845
+ NSTimeInterval timeOffset = (NSTimeInterval)controlPoints.count / 60.0;
846
+ [controlPoints addObject:[[PKStrokePoint alloc]
847
+ initWithLocation:location
848
+ timeOffset:timeOffset
849
+ size:CGSizeMake(pointWidth, pointWidth)
850
+ opacity:1.0
851
+ force:1.0
852
+ azimuth:0.0
853
+ altitude:(CGFloat)M_PI_2]];
854
+ }
855
+ if (controlPoints.count == 0) continue;
856
+ if (controlPoints.count == 1) {
857
+ PKStrokePoint *firstPoint = controlPoints.firstObject;
858
+ [controlPoints addObject:[[PKStrokePoint alloc]
859
+ initWithLocation:firstPoint.location
860
+ timeOffset:firstPoint.timeOffset + (1.0 / 60.0)
861
+ size:firstPoint.size
862
+ opacity:firstPoint.opacity
863
+ force:firstPoint.force
864
+ azimuth:firstPoint.azimuth
865
+ altitude:firstPoint.altitude]];
866
+ }
867
+
868
+ PKStrokePath *strokePath = [[PKStrokePath alloc]
869
+ initWithControlPoints:controlPoints
870
+ creationDate:NSDate.date];
871
+ PKStroke *stroke = [[PKStroke alloc]
872
+ initWithInk:ink
873
+ strokePath:strokePath
874
+ transform:CGAffineTransformIdentity
875
+ mask:nil];
876
+ [strokes addObject:stroke];
877
+ }
878
+
879
+ canvas.applyingStoreDrawing = YES;
880
+ canvas.drawing = [[PKDrawing alloc] initWithStrokes:strokes];
881
+ canvas.applyingStoreDrawing = NO;
882
+ canvas.hasUncommittedChanges = NO;
883
+ canvas.pendingCommitGeneration += 1;
884
+ canvas.appliedStoreSignature = signature;
885
+ self.inkAnnotationSignaturesByPageIndex[@(pageIndex)] = signature;
886
+ }
887
+
888
+ - (void)reconcileInkOverlays {
889
+ for (NSNumber *pageKey in self.inkCanvasesByPageIndex.allKeys.copy) {
890
+ PapyrusPdfPageInkCanvasView *canvas = self.inkCanvasesByPageIndex[pageKey];
891
+ [self applyStoreInkAnnotationsToCanvas:canvas force:NO];
892
+ }
893
+ }
894
+
895
+ - (void)updateInkCanvasInputAndPicker {
896
+ BOOL drawingActive = [self.activeTool isEqualToString:@"ink"];
897
+ for (PapyrusPdfPageInkCanvasView *canvas in self.inkCanvasesByPageIndex.allValues) {
898
+ canvas.userInteractionEnabled = drawingActive;
899
+ }
900
+ if (!drawingActive) {
901
+ if (self.activeInkCanvas.hasUncommittedChanges) {
902
+ [self commitInkDrawingForCanvas:self.activeInkCanvas];
903
+ }
904
+ [self deactivateInkCanvas];
905
+ return;
906
+ }
907
+
908
+ PDFPage *page = self.pdfView.currentPage;
909
+ NSInteger pageIndex = page && self.pdfView.document
910
+ ? (NSInteger)[self.pdfView.document indexForPage:page] : NSNotFound;
911
+ PapyrusPdfPageInkCanvasView *canvas =
912
+ pageIndex == NSNotFound ? nil : self.inkCanvasesByPageIndex[@(pageIndex)];
913
+ if (!canvas) canvas = self.inkCanvasesByPageIndex.allValues.firstObject;
914
+ if (canvas) [self activateInkCanvas:canvas];
915
+ }
916
+
917
+ - (void)activateInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
918
+ if (!canvas || !canvas.window || ![self.activeTool isEqualToString:@"ink"]) return;
919
+ if (self.activeInkCanvas != canvas) [self deactivateInkCanvas];
920
+
921
+ UIWindow *window = canvas.window;
922
+ PKToolPicker *picker = [PapyrusToolPickersByWindow() objectForKey:window];
923
+ if (!picker) {
924
+ picker = [[PKToolPicker alloc] init];
925
+ [PapyrusToolPickersByWindow() setObject:picker forKey:window];
926
+ }
927
+ for (PapyrusPdfPageInkCanvasView *visibleCanvas in self.inkCanvasesByPageIndex.allValues) {
928
+ if (visibleCanvas.observedToolPicker == picker) continue;
929
+ [visibleCanvas.observedToolPicker removeObserver:visibleCanvas];
930
+ [picker addObserver:visibleCanvas];
931
+ visibleCanvas.observedToolPicker = picker;
932
+ }
933
+ if (self.activeInkToolPicker != picker) [picker addObserver:self];
934
+ self.activeInkToolPicker = picker;
935
+ self.activeInkCanvas = canvas;
936
+ canvas.delegate = self;
937
+ canvas.userInteractionEnabled = YES;
938
+
939
+ NSString *configuration = [NSString stringWithFormat:@"%@|%@|%.5f|%.5f",
940
+ self.activeDrawToolPreset ?: @"ink",
941
+ self.annotationColor ?: @"#111827",
942
+ self.annotationOpacity,
943
+ self.inkStrokeWidth];
944
+ if (![self.lastAppliedInkToolConfiguration isEqualToString:configuration]) {
945
+ PDFPage *page = [self.pdfView.document pageAtIndex:(NSUInteger)canvas.papyrusPageIndex];
946
+ CGFloat pageWidth = CGRectGetWidth([page boundsForBox:kPDFDisplayBoxCropBox]);
947
+ CGFloat toolWidth = MAX(0.6, self.inkStrokeWidth * pageWidth);
948
+ PKInkType type = [self.activeDrawToolPreset isEqualToString:@"highlight"]
949
+ ? PKInkTypeMarker : PKInkTypePen;
950
+ picker.selectedTool = [[PKInkingTool alloc]
951
+ initWithInkType:type
952
+ color:PapyrusAnnotationColor(self.annotationColor, self.annotationOpacity)
953
+ width:toolWidth];
954
+ self.lastAppliedInkToolConfiguration = configuration;
955
+ }
956
+
957
+ [canvas becomeFirstResponder];
958
+ if (@available(iOS 16.0, *)) {
959
+ [picker setVisible:YES forFirstResponder:canvas];
960
+ }
961
+ }
962
+
963
+ - (void)deactivateInkCanvas {
964
+ PapyrusPdfPageInkCanvasView *canvas = self.activeInkCanvas;
965
+ PKToolPicker *picker = self.activeInkToolPicker;
966
+ for (PapyrusPdfPageInkCanvasView *visibleCanvas in self.inkCanvasesByPageIndex.allValues) {
967
+ PKToolPicker *observedPicker = visibleCanvas.observedToolPicker;
968
+ if (observedPicker) [observedPicker removeObserver:visibleCanvas];
969
+ visibleCanvas.observedToolPicker = nil;
970
+ }
971
+ if (picker) {
972
+ [picker removeObserver:self];
973
+ if (canvas) {
974
+ if (@available(iOS 16.0, *)) {
975
+ [picker setVisible:NO forFirstResponder:canvas];
976
+ }
977
+ [canvas resignFirstResponder];
978
+ }
979
+ }
980
+ canvas.userInteractionEnabled = NO;
981
+ self.activeInkCanvas = nil;
982
+ self.activeInkToolPicker = nil;
983
+ }
984
+
985
+ - (void)releaseInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
986
+ if (!canvas) return;
987
+ if (canvas.hasUncommittedChanges) [self commitInkDrawingForCanvas:canvas];
988
+ if (self.activeInkCanvas == canvas) [self deactivateInkCanvas];
989
+ else if (canvas.observedToolPicker) {
990
+ [canvas.observedToolPicker removeObserver:canvas];
991
+ canvas.observedToolPicker = nil;
992
+ }
993
+ NSNumber *key = @(canvas.papyrusPageIndex);
994
+ if (self.inkCanvasesByPageIndex[key] == canvas) {
995
+ [self.inkCanvasesByPageIndex removeObjectForKey:key];
996
+ [self.inkAnnotationSignaturesByPageIndex removeObjectForKey:key];
997
+ }
998
+ canvas.delegate = nil;
999
+ canvas.userInteractionEnabled = NO;
1000
+ }
1001
+
1002
+ - (void)canvasViewDrawingDidChange:(PKCanvasView *)canvasView {
1003
+ if (![canvasView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) return;
1004
+ PapyrusPdfPageInkCanvasView *canvas = (PapyrusPdfPageInkCanvasView *)canvasView;
1005
+ if (canvas.applyingStoreDrawing || ![self.activeTool isEqualToString:@"ink"]) return;
1006
+ canvas.hasUncommittedChanges = YES;
1007
+ NSUInteger generation = ++canvas.pendingCommitGeneration;
1008
+ __weak typeof(self) weakSelf = self;
1009
+ __weak PapyrusPdfPageInkCanvasView *weakCanvas = canvas;
1010
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.40 * NSEC_PER_SEC)),
1011
+ dispatch_get_main_queue(), ^{
1012
+ typeof(self) strongSelf = weakSelf;
1013
+ PapyrusPdfPageInkCanvasView *strongCanvas = weakCanvas;
1014
+ if (!strongSelf || !strongCanvas ||
1015
+ strongCanvas.pendingCommitGeneration != generation ||
1016
+ !strongCanvas.hasUncommittedChanges) return;
1017
+ UIGestureRecognizerState state = strongCanvas.drawingGestureRecognizer.state;
1018
+ if (state == UIGestureRecognizerStateBegan ||
1019
+ state == UIGestureRecognizerStateChanged) {
1020
+ [strongSelf canvasViewDrawingDidChange:strongCanvas];
1021
+ return;
1022
+ }
1023
+ [strongSelf commitInkDrawingForCanvas:strongCanvas];
1024
+ });
1025
+ }
1026
+
1027
+ - (void)canvasViewDidEndUsingTool:(PKCanvasView *)canvasView {
1028
+ if ([canvasView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) {
1029
+ [self commitInkDrawingForCanvas:(PapyrusPdfPageInkCanvasView *)canvasView];
1030
+ }
1031
+ }
1032
+
1033
+ - (void)commitInkDrawingForCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
1034
+ if (!canvas || !canvas.hasUncommittedChanges) return;
1035
+ canvas.pendingCommitGeneration += 1;
1036
+ canvas.hasUncommittedChanges = NO;
1037
+ NSArray<NSDictionary *> *strokes = [self inkDrawingPayloadForCanvas:canvas];
1038
+ canvas.appliedStoreSignature = nil;
1039
+ if (self.onInkDrawingCommitted) {
1040
+ self.onInkDrawingCommitted(@{
1041
+ @"pageIndex" : @(canvas.papyrusPageIndex),
1042
+ @"strokes" : strokes
1043
+ });
1044
+ }
1045
+ }
1046
+
1047
+ - (NSArray<NSDictionary *> *)inkDrawingPayloadForCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
1048
+ CGFloat width = CGRectGetWidth(canvas.bounds);
1049
+ CGFloat height = CGRectGetHeight(canvas.bounds);
1050
+ if (width <= 0 || height <= 0) return @[];
1051
+
1052
+ NSMutableArray<NSDictionary *> *payload = [NSMutableArray array];
1053
+ for (PKStroke *stroke in canvas.drawing.strokes) {
1054
+ // The universal Papyrus path has no clipping mask. Use the vector eraser so
1055
+ // erased strokes disappear as complete paths instead of persisting masked ink.
1056
+ if (stroke.mask != nil) continue;
1057
+ PKStrokePath *path = stroke.path;
1058
+ NSMutableArray<NSDictionary *> *points = [NSMutableArray array];
1059
+ NSMutableArray<NSNumber *> *strokeWidthSamples = [NSMutableArray array];
1060
+ CGAffineTransform strokeTransform = stroke.transform;
1061
+ CGFloat transformDeterminant =
1062
+ strokeTransform.a * strokeTransform.d - strokeTransform.b * strokeTransform.c;
1063
+ CGFloat strokeWidthScale = sqrt(fabs(transformDeterminant));
1064
+ if (!isfinite(strokeWidthScale) || strokeWidthScale <= 0) strokeWidthScale = 1.0;
1065
+ for (NSUInteger index = 0; index < path.count; index += 1) {
1066
+ PKStrokePoint *strokePoint = [path pointAtIndex:index];
1067
+ CGPoint location = CGPointApplyAffineTransform(strokePoint.location, strokeTransform);
1068
+ CGFloat x = MIN(1.0, MAX(0.0, location.x / width));
1069
+ CGFloat y = MIN(1.0, MAX(0.0, location.y / height));
1070
+ if (!isfinite(x) || !isfinite(y)) continue;
1071
+ [points addObject:@{@"x" : @(x), @"y" : @(y)}];
1072
+
1073
+ CGFloat pointWidth = strokePoint.size.width * strokeWidthScale;
1074
+ if (isfinite(pointWidth) && pointWidth > 0) {
1075
+ [strokeWidthSamples addObject:@(pointWidth)];
1076
+ }
1077
+ }
1078
+ if (points.count == 0) continue;
1079
+ if (points.count == 1) [points addObject:points.firstObject];
1080
+
1081
+ CGFloat opacity = 1.0;
1082
+ NSString *color = PapyrusHexColorFromUIColor(stroke.ink.color, &opacity);
1083
+ if ([stroke.ink.inkType isEqualToString:PKInkTypeMarker]) {
1084
+ // The universal Papyrus ink contract uses opacity <= 0.35 to restore a marker.
1085
+ opacity = MIN(opacity, 0.28);
1086
+ }
1087
+
1088
+ CGFloat representativeWidth = width * 0.006;
1089
+ if (strokeWidthSamples.count > 0) {
1090
+ NSArray<NSNumber *> *sortedWidthSamples =
1091
+ [strokeWidthSamples sortedArrayUsingSelector:@selector(compare:)];
1092
+ NSUInteger middleIndex = sortedWidthSamples.count / 2;
1093
+ if (sortedWidthSamples.count % 2 == 0) {
1094
+ representativeWidth =
1095
+ (sortedWidthSamples[middleIndex - 1].doubleValue +
1096
+ sortedWidthSamples[middleIndex].doubleValue) / 2.0;
1097
+ } else {
1098
+ representativeWidth = sortedWidthSamples[middleIndex].doubleValue;
1099
+ }
1100
+ }
1101
+
1102
+ CGFloat normalizedWidth = representativeWidth / width;
1103
+ if (!isfinite(normalizedWidth) || normalizedWidth <= 0) normalizedWidth = 0.006;
1104
+ [payload addObject:@{
1105
+ @"path" : points,
1106
+ @"color" : color ?: @"#111827",
1107
+ @"opacity" : @(opacity),
1108
+ @"strokeWidth" : @(normalizedWidth)
1109
+ }];
1110
+ }
1111
+ return [payload copy];
1112
+ }
1113
+
1114
+ - (void)toolPickerSelectedToolDidChange:(PKToolPicker *)toolPicker {
1115
+ PKTool *selectedTool = toolPicker.selectedTool;
1116
+ if (![selectedTool isKindOfClass:PKEraserTool.class]) return;
1117
+ PKEraserTool *eraser = (PKEraserTool *)selectedTool;
1118
+ if (eraser.eraserType == PKEraserTypeVector) return;
1119
+ // Papyrus stores normalized centerlines rather than PencilKit masks, so keep
1120
+ // erasing stroke-based and representable by the shared Annotation model.
1121
+ toolPicker.selectedTool = [[PKEraserTool alloc] initWithEraserType:PKEraserTypeVector];
1122
+ }
1123
+
1124
+ - (void)toolPickerVisibilityDidChange:(PKToolPicker *)toolPicker {
1125
+ if (toolPicker != self.activeInkToolPicker) return;
1126
+ if (self.onInkToolPickerVisibilityChange) {
1127
+ self.onInkToolPickerVisibilityChange(@{@"visible" : @(toolPicker.isVisible)});
1128
+ }
1129
+ }
1130
+
1131
+ - (void)resetInkOverlaysForDocumentChange {
1132
+ [self deactivateInkCanvas];
1133
+ for (PapyrusPdfPageInkCanvasView *canvas in self.inkCanvasesByPageIndex.allValues) {
1134
+ canvas.delegate = nil;
1135
+ canvas.userInteractionEnabled = NO;
1136
+ }
1137
+ [self.inkCanvasesByPageIndex removeAllObjects];
1138
+ [self.inkAnnotationSignaturesByPageIndex removeAllObjects];
1139
+ }
1140
+
1141
+ - (void)didMoveToWindow {
1142
+ [super didMoveToWindow];
1143
+ if (!self.window) {
1144
+ [self releasePageThemeLeaseForDocument:self.pdfView.document];
1145
+ PapyrusInvalidateViewTree(self.pdfView);
1146
+ [self deactivateInkCanvas];
1147
+ for (PapyrusPdfPageInkCanvasView *canvas in self.inkCanvasesByPageIndex.allValues) {
1148
+ canvas.userInteractionEnabled = NO;
1149
+ }
1150
+ return;
1151
+ }
1152
+ [self acquireOrUpdatePageThemeLeaseForDocument:self.pdfView.document];
1153
+ PapyrusInvalidateViewTree(self.pdfView);
1154
+ [self updateInkCanvasInputAndPicker];
1155
+ }
1156
+
1157
+ - (void)setAnnotationSelectionColor:(NSString *)annotationSelectionColor {
1158
+ NSString *normalized = annotationSelectionColor.length > 0
1159
+ ? [annotationSelectionColor copy] : @"#2563eb";
1160
+ if ([_annotationSelectionColor isEqualToString:normalized]) return;
1161
+ _annotationSelectionColor = normalized;
1162
+ [self updateSelectedAnnotationAdornment];
1163
+ }
1164
+
1165
+ - (void)setAnnotationNavigationRequest:(NSDictionary *)request {
1166
+ _annotationNavigationRequest = [request copy];
1167
+ if (!request) return;
1168
+ PDFDocument *document = self.pdfView.document;
1169
+ dispatch_async(dispatch_get_main_queue(), ^{
1170
+ if (self.pdfView.document != document || ![self.annotationNavigationRequest isEqual:request]) return;
1171
+ NSInteger index = [request[@"pageIndex"] integerValue];
1172
+ if (index < 0 || index >= document.pageCount || ![request[@"rect"] isKindOfClass:[NSDictionary class]]) return;
1173
+ PDFPage *page = [document pageAtIndex:index];
1174
+ CGRect rect = PapyrusPdfRectFromNormalizedRect(request[@"rect"], [page boundsForBox:kPDFDisplayBoxCropBox]);
1175
+ if (!CGRectIsEmpty(rect)) [self.pdfView goToRect:rect onPage:page];
1176
+ });
1177
+ }
1178
+
1179
+ - (void)setSelectedAnnotationId:(NSString *)selectedAnnotationId {
1180
+ NSString *normalized = selectedAnnotationId.length > 0
1181
+ ? [selectedAnnotationId copy] : nil;
1182
+ if ((_selectedAnnotationId == normalized) ||
1183
+ [_selectedAnnotationId isEqualToString:normalized]) return;
1184
+ _selectedAnnotationId = normalized;
1185
+ [self updateSelectedAnnotationAdornment];
1186
+ }
1187
+
1188
+ - (NSString *)annotationSignature:(NSDictionary *)annotation {
1189
+ NSArray<NSString *> *signatureKeys = @[
1190
+ @"id", @"type", @"pageIndex", @"rect", @"rects", @"color", @"opacity", @"content", @"anchor", @"markupStyle", @"noteContent"
1191
+ ];
1192
+ NSMutableDictionary *signatureFields = [NSMutableDictionary dictionary];
1193
+ for (NSString *key in signatureKeys) {
1194
+ id value = annotation[key];
1195
+ if (value) signatureFields[key] = value;
1196
+ }
1197
+ if (![NSJSONSerialization isValidJSONObject:signatureFields]) {
1198
+ return signatureFields.description ?: @"";
1199
+ }
1200
+ NSError *error = nil;
1201
+ NSData *data = [NSJSONSerialization dataWithJSONObject:signatureFields
1202
+ options:NSJSONWritingSortedKeys
1203
+ error:&error];
1204
+ if (!data || error) return annotation.description ?: @"";
1205
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"";
1206
+ }
1207
+
1208
+ - (void)removePapyrusAnnotationWithId:(NSString *)annotationId {
1209
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[annotationId] ?: @[];
1210
+ for (PDFAnnotation *annotation in representations) {
1211
+ NSString *registeredId = [self.papyrusAnnotationIdsByObject objectForKey:annotation];
1212
+ if (![registeredId isEqualToString:annotationId]) continue;
1213
+ PDFPage *page = annotation.page;
1214
+ if (page) [page removeAnnotation:annotation];
1215
+ [self.papyrusAnnotationIdsByObject removeObjectForKey:annotation];
1216
+ }
1217
+ [self.papyrusAnnotationsById removeObjectForKey:annotationId];
1218
+ [self.papyrusAnnotationSignaturesById removeObjectForKey:annotationId];
1219
+ }
1220
+
1221
+ - (void)clearPapyrusAnnotationsForDocument:(PDFDocument *)document {
1222
+ (void)document;
1223
+ [self removeSelectedAnnotationAdornment];
1224
+ NSArray<NSString *> *annotationIds = self.papyrusAnnotationsById.allKeys.copy;
1225
+ for (NSString *annotationId in annotationIds) {
1226
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[annotationId] ?: @[];
1227
+ for (PDFAnnotation *annotation in representations) {
1228
+ NSString *registeredId = [self.papyrusAnnotationIdsByObject objectForKey:annotation];
1229
+ if ([registeredId isEqualToString:annotationId] && annotation.page) {
1230
+ [annotation.page removeAnnotation:annotation];
1231
+ }
1232
+ [self.papyrusAnnotationIdsByObject removeObjectForKey:annotation];
1233
+ }
1234
+ }
1235
+ [self.papyrusAnnotationsById removeAllObjects];
1236
+ [self.papyrusAnnotationSignaturesById removeAllObjects];
1237
+ [self.papyrusAnnotationIdsByObject removeAllObjects];
1238
+ }
1239
+
1240
+ - (void)removeSelectedAnnotationAdornment {
1241
+ for (PDFAnnotation *annotation in self.selectedAnnotationAdornmentAnnotations ?: @[]) {
1242
+ PDFPage *page = annotation.page;
1243
+ if (page) [page removeAnnotation:annotation];
1244
+ }
1245
+ self.selectedAnnotationAdornmentAnnotations = @[];
1246
+ }
1247
+
1248
+ - (void)updateSelectedAnnotationAdornment {
1249
+ [self removeSelectedAnnotationAdornment];
1250
+ NSString *annotationId = self.selectedAnnotationId;
1251
+ NSArray<PDFAnnotation *> *representations = annotationId.length > 0
1252
+ ? self.papyrusAnnotationsById[annotationId] : @[];
1253
+ if (representations.count == 0) {
1254
+ [self.pdfView setNeedsDisplay];
1255
+ return;
1256
+ }
1257
+
1258
+ UIColor *selectionColor = PapyrusAnnotationColor(self.annotationSelectionColor, 1.0);
1259
+ NSMutableArray<PDFAnnotation *> *adornments = [NSMutableArray array];
1260
+ for (PDFAnnotation *representation in representations) {
1261
+ PDFPage *page = representation.page;
1262
+ CGRect bounds = representation.bounds;
1263
+ if (!page || CGRectIsNull(bounds) || CGRectIsEmpty(bounds)) continue;
1264
+
1265
+ PDFAnnotation *adornment = [[PapyrusSelectionOutlinePdfAnnotation alloc]
1266
+ initWithBounds:bounds forType:@"Stamp" withProperties:nil];
1267
+ adornment.color = selectionColor;
1268
+ adornment.shouldDisplay = YES;
1269
+ [page addAnnotation:adornment];
1270
+ [adornments addObject:adornment];
1271
+ }
1272
+ self.selectedAnnotationAdornmentAnnotations = [adornments copy];
1273
+ [self.pdfView setNeedsDisplay];
1274
+ }
1275
+
1276
+ - (NSArray<PDFAnnotation *> *)createPdfAnnotationsForPapyrusAnnotation:(NSDictionary *)annotation {
1277
+ PDFDocument *document = self.pdfView.document;
1278
+ if (!document || ![annotation isKindOfClass:NSDictionary.class]) return @[];
1279
+ id pageIndexValue = annotation[@"pageIndex"];
1280
+ if (![pageIndexValue isKindOfClass:NSNumber.class]) return @[];
1281
+ double pageIndexNumber = [pageIndexValue doubleValue];
1282
+ if (!isfinite(pageIndexNumber) || floor(pageIndexNumber) != pageIndexNumber ||
1283
+ pageIndexNumber < 0 || pageIndexNumber >= (double)document.pageCount) {
1284
+ return @[];
1285
+ }
1286
+
1287
+ NSString *type = [annotation[@"type"] isKindOfClass:NSString.class]
1288
+ ? annotation[@"type"] : @"";
1289
+ NSString *markup = [annotation[@"markupStyle"] isKindOfClass:NSString.class] ? annotation[@"markupStyle"] : ([@[@"highlight",@"underline",@"strikeout",@"squiggly"] containsObject:annotation[@"type"]] ? annotation[@"type"] : nil);
1290
+ BOOL hasContextNote = annotation[@"noteContent"] != nil;
1291
+ if (hasContextNote && !annotation[@"papyrusIndicatorOnly"]) {
1292
+ NSMutableArray *parts = [NSMutableArray array];
1293
+ if (markup.length && ![markup isEqual:@"none"]) {
1294
+ NSMutableDictionary *mark = [annotation mutableCopy];
1295
+ mark[@"type"] = markup; [mark removeObjectForKey:@"noteContent"]; [mark removeObjectForKey:@"markupStyle"];
1296
+ [parts addObjectsFromArray:[self createPdfAnnotationsForPapyrusAnnotation:mark]];
1297
+ }
1298
+ NSMutableDictionary *note = [annotation mutableCopy];
1299
+ note[@"type"] = @"comment"; note[@"papyrusIndicatorOnly"] = @YES;
1300
+ [parts addObjectsFromArray:[self createPdfAnnotationsForPapyrusAnnotation:note]];
1301
+ return parts;
1302
+ }
1303
+ if (markup.length && !hasContextNote) {
1304
+ if ([markup isEqual:@"none"]) return @[];
1305
+ type = markup;
1306
+ }
1307
+ NSString *subtype = nil;
1308
+ if ([type isEqualToString:@"highlight"]) subtype = @"Highlight";
1309
+ else if ([type isEqualToString:@"underline"]) subtype = @"Underline";
1310
+ else if ([type isEqualToString:@"strikeout"]) subtype = @"StrikeOut";
1311
+ else if ([type isEqualToString:@"squiggly"] ||
1312
+ [type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1313
+ // Custom drawing stays in the subclasses; Stamp is a PDFKit-supported carrier subtype.
1314
+ subtype = @"Stamp";
1315
+ }
1316
+ if (!subtype) return @[];
1317
+
1318
+ PDFPage *page = [document pageAtIndex:(NSUInteger)pageIndexNumber];
1319
+ if (!page) return @[];
1320
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1321
+ if (CGRectIsNull(pageBounds) || CGRectIsEmpty(pageBounds)) return @[];
1322
+
1323
+ NSArray *rects = [annotation[@"rects"] isKindOfClass:NSArray.class]
1324
+ ? annotation[@"rects"] : @[];
1325
+ if ([type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1326
+ NSDictionary *rect = rects.lastObject ?: annotation[@"rect"];
1327
+ if ([rect isKindOfClass:NSDictionary.class]) {
1328
+ CGFloat width = MIN(0.06, 18.0/MAX(1,CGRectGetWidth(pageBounds)));
1329
+ CGFloat height = MIN(0.06, 18.0/MAX(1,CGRectGetHeight(pageBounds)));
1330
+ CGFloat x = MIN(1-width,MAX(0,[rect[@"x"] doubleValue]+[rect[@"width"] doubleValue]));
1331
+ CGFloat y = MIN(1-height,MAX(0,[rect[@"y"] doubleValue]));
1332
+ rects = @[@{@"x":@(x),@"y":@(y),@"width":@(width),@"height":@(height)}];
1333
+ } else rects = @[];
1334
+ } else if (rects.count == 0 && [annotation[@"rect"] isKindOfClass:NSDictionary.class]) {
1335
+ rects = @[annotation[@"rect"]];
1336
+ }
1337
+ if (rects.count == 0) return @[];
1338
+
1339
+ CGFloat defaultOpacity = [type isEqualToString:@"highlight"] ? 0.38 : 1.0;
1340
+ CGFloat opacity = [annotation[@"opacity"] respondsToSelector:@selector(doubleValue)]
1341
+ ? [annotation[@"opacity"] doubleValue] : defaultOpacity;
1342
+ if (!isfinite(opacity)) opacity = 1.0;
1343
+ NSString *hexColor = [annotation[@"color"] isKindOfClass:NSString.class]
1344
+ ? annotation[@"color"] : self.annotationColor;
1345
+ UIColor *color = PapyrusAnnotationColor(hexColor, opacity);
1346
+ NSString *content = [annotation[@"content"] isKindOfClass:NSString.class]
1347
+ ? annotation[@"content"] : @"";
1348
+ NSMutableArray<PDFAnnotation *> *representations = [NSMutableArray array];
1349
+
1350
+ for (id rectValue in rects) {
1351
+ if (![rectValue isKindOfClass:NSDictionary.class]) continue;
1352
+ CGRect pageRect = PapyrusPdfRectFromNormalizedRect(rectValue, pageBounds);
1353
+ if (CGRectIsNull(pageRect) || CGRectIsEmpty(pageRect)) continue;
1354
+
1355
+ PDFAnnotation *representation = nil;
1356
+ if ([type isEqualToString:@"squiggly"]) {
1357
+ representation = [[PapyrusSquigglyPdfAnnotation alloc]
1358
+ initWithBounds:pageRect forType:subtype withProperties:nil];
1359
+ } else if ([type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1360
+ representation = [[PapyrusCommentPdfAnnotation alloc]
1361
+ initWithBounds:pageRect forType:subtype withProperties:nil];
1362
+ } else {
1363
+ representation = [[PDFAnnotation alloc]
1364
+ initWithBounds:pageRect forType:subtype withProperties:nil];
1365
+ }
1366
+ representation.color = color;
1367
+ representation.contents = content;
1368
+ representation.shouldDisplay = YES;
1369
+
1370
+ if ([type isEqualToString:@"highlight"] || [type isEqualToString:@"underline"] ||
1371
+ [type isEqualToString:@"strikeout"]) {
1372
+ CGFloat width = CGRectGetWidth(pageRect);
1373
+ CGFloat height = CGRectGetHeight(pageRect);
1374
+ representation.quadrilateralPoints = @[
1375
+ [NSValue valueWithCGPoint:CGPointMake(0, height)],
1376
+ [NSValue valueWithCGPoint:CGPointMake(width, height)],
1377
+ [NSValue valueWithCGPoint:CGPointMake(0, 0)],
1378
+ [NSValue valueWithCGPoint:CGPointMake(width, 0)]
1379
+ ];
1380
+ }
1381
+
1382
+ [page addAnnotation:representation];
1383
+ [representations addObject:representation];
1384
+ }
1385
+ return [representations copy];
1386
+ }
1387
+
1388
+ - (void)reconcilePapyrusAnnotations {
1389
+ PDFDocument *document = self.pdfView.document;
1390
+ if (!document) return;
1391
+ BOOL didChangeRepresentations = NO;
1392
+
1393
+ NSMutableDictionary<NSString *, NSDictionary *> *incomingById = [NSMutableDictionary dictionary];
1394
+ for (id value in self.annotations) {
1395
+ if (![value isKindOfClass:NSDictionary.class]) continue;
1396
+ NSDictionary *annotation = (NSDictionary *)value;
1397
+ NSString *annotationId = [annotation[@"id"] isKindOfClass:NSString.class]
1398
+ ? annotation[@"id"] : @"";
1399
+ if (annotationId.length == 0) continue;
1400
+ incomingById[annotationId] = annotation;
1401
+ }
1402
+
1403
+ for (NSString *existingId in self.papyrusAnnotationsById.allKeys.copy) {
1404
+ NSDictionary *updated = incomingById[existingId];
1405
+ NSString *nextSignature = updated ? [self annotationSignature:updated] : nil;
1406
+ if (!updated || ![nextSignature isEqualToString:self.papyrusAnnotationSignaturesById[existingId]]) {
1407
+ [self removePapyrusAnnotationWithId:existingId];
1408
+ didChangeRepresentations = YES;
1409
+ }
1410
+ }
1411
+
1412
+ for (NSString *annotationId in incomingById) {
1413
+ if (self.papyrusAnnotationSignaturesById[annotationId]) continue;
1414
+ NSDictionary *annotation = incomingById[annotationId];
1415
+ NSArray<PDFAnnotation *> *representations =
1416
+ [self createPdfAnnotationsForPapyrusAnnotation:annotation];
1417
+ for (PDFAnnotation *representation in representations) {
1418
+ [self.papyrusAnnotationIdsByObject setObject:annotationId forKey:representation];
1419
+ }
1420
+ self.papyrusAnnotationsById[annotationId] = representations;
1421
+ self.papyrusAnnotationSignaturesById[annotationId] =
1422
+ [self annotationSignature:annotation];
1423
+ didChangeRepresentations = YES;
1424
+ }
1425
+ if (didChangeRepresentations) {
1426
+ NSMutableDictionary<NSString *, PapyrusCommentPdfAnnotation *> *leaders = [NSMutableDictionary dictionary];
1427
+ for (NSString *annotationId in self.papyrusAnnotationsById) {
1428
+ for (PDFAnnotation *representation in self.papyrusAnnotationsById[annotationId]) {
1429
+ if (![representation isKindOfClass:PapyrusCommentPdfAnnotation.class]) continue;
1430
+ PapyrusCommentPdfAnnotation *note = (PapyrusCommentPdfAnnotation *)representation;
1431
+ note.groupHidden = NO; note.groupCount = 1;
1432
+ CGRect pageBounds = [note.page boundsForBox:kPDFDisplayBoxCropBox];
1433
+ NSString *key = [NSString stringWithFormat:@"%ld:%ld:%ld", (long)[document indexForPage:note.page], (long)floor((CGRectGetMinX(note.bounds)-pageBounds.origin.x)/(pageBounds.size.width * 0.035)), (long)floor((CGRectGetMinY(note.bounds)-pageBounds.origin.y)/(pageBounds.size.height * 0.035))];
1434
+ PapyrusCommentPdfAnnotation *leader = leaders[key];
1435
+ if (leader) { note.groupHidden = YES; leader.groupCount++; } else {leaders[key] = note;}
1436
+ }
1437
+ }
1438
+ [self updateSelectedAnnotationAdornment];
1439
+ [self.pdfView setNeedsDisplay];
1440
+ }
1441
+ }
1442
+
1443
+ - (void)emitAnnotationFromCurrentSelectionWithType:(NSString *)type {
1444
+ if (!self.onAnnotationCreated) return;
1445
+ PDFSelection *selection = self.pdfView.currentSelection;
1446
+ NSString *text = selection.string ?: @"";
1447
+ PDFDocument *document = self.pdfView.document;
1448
+ PDFPage *page = selection.pages.firstObject;
1449
+ NSInteger pageIndex = document && page ? [document indexForPage:page] : NSNotFound;
1450
+ if (!document || !page || pageIndex == NSNotFound || text.length == 0) return;
1451
+
1452
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1453
+ if (CGRectIsNull(pageBounds) || CGRectIsEmpty(pageBounds)) return;
1454
+ NSMutableArray<NSDictionary *> *rects = [NSMutableArray array];
1455
+ for (PDFSelection *line in selection.selectionsByLine) {
1456
+ if (![line.pages containsObject:page]) continue;
1457
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1458
+ [line boundsForPage:page], pageBounds);
1459
+ if (normalizedRect) [rects addObject:normalizedRect];
1460
+ }
1461
+ if (rects.count == 0) {
1462
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1463
+ [selection boundsForPage:page], pageBounds);
1464
+ if (normalizedRect) [rects addObject:normalizedRect];
1465
+ }
1466
+ if (rects.count == 0) return;
1467
+
1468
+ CGFloat minX = 1.0, minY = 1.0, maxX = 0.0, maxY = 0.0;
1469
+ for (NSDictionary *rect in rects) {
1470
+ CGFloat x = [rect[@"x"] doubleValue];
1471
+ CGFloat y = [rect[@"y"] doubleValue];
1472
+ minX = MIN(minX, x);
1473
+ minY = MIN(minY, y);
1474
+ maxX = MAX(maxX, x + [rect[@"width"] doubleValue]);
1475
+ maxY = MAX(maxY, y + [rect[@"height"] doubleValue]);
1476
+ }
1477
+
1478
+ CGFloat opacity = MIN(1.0, MAX(0.0, self.annotationOpacity));
1479
+ NSDictionary *annotationRect = nil;
1480
+ if ([type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1481
+ NSDictionary *firstRect = rects.firstObject;
1482
+ CGFloat width = MIN(1.0, MAX(0.08, [firstRect[@"width"] doubleValue]));
1483
+ CGFloat height = MIN(1.0, MAX(0.06, [firstRect[@"height"] doubleValue]));
1484
+ CGFloat x = MIN(1.0 - width, MAX(0.0, [firstRect[@"x"] doubleValue]));
1485
+ CGFloat y = MIN(1.0 - height, MAX(0.0, [firstRect[@"y"] doubleValue]));
1486
+ annotationRect = @{@"x" : @(x), @"y" : @(y), @"width" : @(width), @"height" : @(height)};
1487
+ } else {
1488
+ annotationRect = @{@"x" : @(minX), @"y" : @(minY), @"width" : @(maxX - minX), @"height" : @(maxY - minY)};
1489
+ }
1490
+
1491
+ NSDictionary *annotation = @{
1492
+ @"id" : [[NSUUID UUID] UUIDString],
1493
+ @"pageIndex" : @(pageIndex),
1494
+ @"type" : type,
1495
+ @"rect" : annotationRect,
1496
+ @"rects" : rects,
1497
+ @"color" : self.annotationColor ?: @"#fbbf24",
1498
+ @"opacity" : @(opacity),
1499
+ @"content" : text,
1500
+ @"createdAt" : @((long long)([[NSDate date] timeIntervalSince1970] * 1000.0))
1501
+ };
1502
+ self.onAnnotationCreated(annotation);
1503
+ }
1504
+
1505
+ - (void)emitCommentAtPage:(PDFPage *)page pageIndex:(NSInteger)pageIndex normalizedPoint:(CGPoint)point {
1506
+ if (!self.onAnnotationCreated || !page || pageIndex < 0) return;
1507
+ CGFloat x = MIN(0.92, MAX(0.0, point.x - 0.02));
1508
+ CGFloat y = MIN(0.94, MAX(0.0, point.y - 0.02));
1509
+ NSDictionary *rect = @{@"x" : @(x), @"y" : @(y), @"width" : @0.08, @"height" : @0.06};
1510
+ NSDictionary *annotation = @{
1511
+ @"id" : [[NSUUID UUID] UUIDString],
1512
+ @"pageIndex" : @(pageIndex),
1513
+ @"type" : @"comment",
1514
+ @"rect" : rect,
1515
+ @"rects" : @[rect],
1516
+ @"color" : self.annotationColor ?: @"#fbbf24",
1517
+ @"opacity" : @(MIN(1.0, MAX(0.0, self.annotationOpacity))),
1518
+ @"content" : @"",
1519
+ @"createdAt" : @((long long)([[NSDate date] timeIntervalSince1970] * 1000.0))
1520
+ };
1521
+ self.onAnnotationCreated(annotation);
1522
+ }
1523
+
1524
+ - (UIColor *)searchHighlightColorForActive:(BOOL)isActive {
1525
+ return isActive
1526
+ ? [UIColor colorWithRed:1.0 green:0.66 blue:0.08 alpha:0.54]
1527
+ : [UIColor colorWithRed:1.0 green:0.82 blue:0.20 alpha:0.25];
1528
+ }
1529
+
1530
+ - (void)rebuildSearchHighlights {
1531
+ PDFDocument *document = self.pdfView.document;
1532
+ if (!document || self.searchResults.count == 0) {
1533
+ self.searchSelections = @[];
1534
+ self.searchSelectionsByResultIndex = @{};
1535
+ self.pdfView.highlightedSelections = nil;
1536
+ [self scheduleNavigationToSearchResultAtIndex:self.activeSearchIndex];
1537
+ return;
1538
+ }
1539
+
1540
+ NSMutableArray<PDFSelection *> *selections =
1541
+ [NSMutableArray arrayWithCapacity:self.searchResults.count];
1542
+ NSMutableDictionary<NSNumber *, PDFSelection *> *selectionsByResultIndex =
1543
+ [NSMutableDictionary dictionaryWithCapacity:self.searchResults.count];
1544
+ for (NSUInteger resultIndex = 0; resultIndex < self.searchResults.count; resultIndex += 1) {
1545
+ id resultValue = self.searchResults[resultIndex];
1546
+ if (![resultValue isKindOfClass:NSDictionary.class]) continue;
1547
+ NSDictionary *result = (NSDictionary *)resultValue;
1548
+ id pageIndexValue = result[@"pageIndex"];
1549
+ if (![pageIndexValue isKindOfClass:NSNumber.class]) continue;
1550
+ double pageIndexNumber = [pageIndexValue doubleValue];
1551
+ if (!isfinite(pageIndexNumber) || floor(pageIndexNumber) != pageIndexNumber ||
1552
+ pageIndexNumber < 0 || pageIndexNumber >= (double)document.pageCount) {
1553
+ continue;
1554
+ }
1555
+ NSUInteger pageIndex = (NSUInteger)pageIndexNumber;
1556
+
1557
+ PDFPage *page = [document pageAtIndex:pageIndex];
1558
+ id rectsValue = result[@"rects"];
1559
+ NSArray *rects = [rectsValue isKindOfClass:NSArray.class] ? rectsValue : @[];
1560
+ if (!page || rects.count == 0) continue;
1561
+
1562
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1563
+ if (pageBounds.size.width <= 0 || pageBounds.size.height <= 0) continue;
1564
+
1565
+ PDFSelection *match = [[PDFSelection alloc] initWithDocument:document];
1566
+ BOOL hasSelectedText = NO;
1567
+ for (id rectValue in rects) {
1568
+ if (![rectValue isKindOfClass:NSDictionary.class]) continue;
1569
+ CGRect pageRect = PapyrusPdfRectFromNormalizedRect((NSDictionary *)rectValue, pageBounds);
1570
+ if (CGRectIsNull(pageRect) || CGRectIsEmpty(pageRect)) continue;
1571
+ PDFSelection *lineSelection = [page selectionForRect:pageRect];
1572
+ if (!lineSelection.string.length) continue;
1573
+
1574
+ [match addSelection:lineSelection];
1575
+ hasSelectedText = YES;
1576
+ }
1577
+
1578
+ if (!hasSelectedText) continue;
1579
+ match.color = [self searchHighlightColorForActive:
1580
+ ((NSInteger)resultIndex == self.activeSearchIndex)];
1581
+ [selections addObject:match];
1582
+ selectionsByResultIndex[@(resultIndex)] = match;
1583
+ }
1584
+
1585
+ self.searchSelections = [selections copy];
1586
+ self.searchSelectionsByResultIndex = [selectionsByResultIndex copy];
1587
+ self.pdfView.highlightedSelections =
1588
+ self.searchSelections.count > 0 ? self.searchSelections : nil;
1589
+ [self scheduleNavigationToSearchResultAtIndex:self.activeSearchIndex];
1590
+ }
1591
+
1592
+ - (void)updateSearchHighlightColorsFromResultIndex:(NSInteger)previousSearchIndex {
1593
+ if (previousSearchIndex == self.activeSearchIndex) return;
1594
+
1595
+ PDFSelection *previousSelection =
1596
+ self.searchSelectionsByResultIndex[@(previousSearchIndex)];
1597
+ PDFSelection *activeSelection =
1598
+ self.searchSelectionsByResultIndex[@(self.activeSearchIndex)];
1599
+ if (previousSelection) {
1600
+ previousSelection.color = [self searchHighlightColorForActive:NO];
1601
+ }
1602
+ if (activeSelection) {
1603
+ activeSelection.color = [self searchHighlightColorForActive:YES];
1604
+ }
1605
+ if (previousSelection || activeSelection) {
1606
+ self.pdfView.highlightedSelections = self.searchSelections;
1607
+ }
1608
+ }
1609
+
1610
+ - (void)scheduleNavigationToSearchResultAtIndex:(NSInteger)activeSearchIndex {
1611
+ NSUInteger generation = ++self.searchNavigationGeneration;
1612
+ dispatch_async(dispatch_get_main_queue(), ^{
1613
+ if (self.searchNavigationGeneration != generation ||
1614
+ self.activeSearchIndex != activeSearchIndex) {
1615
+ return;
1616
+ }
1617
+ PDFSelection *selection =
1618
+ self.searchSelectionsByResultIndex[@(activeSearchIndex)];
1619
+ if (!selection) return;
1620
+ [self.pdfView goToSelection:selection];
1621
+ });
1622
+ }
1623
+
1624
+ - (void)configureDisplayMode {
1625
+ self.pdfView.displayBox = kPDFDisplayBoxCropBox;
1626
+ self.pdfView.displayDirection = kPDFDisplayDirectionVertical;
1627
+ self.pdfView.displaysPageBreaks = YES;
1628
+ self.pdfView.displayMode = [self.viewMode isEqualToString:@"single"]
1629
+ ? kPDFDisplaySinglePage
1630
+ : kPDFDisplaySinglePageContinuous;
1631
+ }
1632
+
1633
+ - (void)updateFitScalePreservingViewport {
1634
+ if (!self.pdfView.document || CGRectGetWidth(self.bounds) <= 0 || CGRectGetHeight(self.bounds) <= 0) return;
1635
+
1636
+ CGFloat desiredZoom = [self clampedZoom:self.zoom];
1637
+ BOOL wasSuppressingScaleSynchronization = self.suppressScaleSynchronization;
1638
+ self.suppressScaleSynchronization = YES;
1639
+ PDFPage *currentPage = self.pdfView.currentPage;
1640
+ self.pdfView.autoScales = YES;
1641
+ [self.pdfView layoutDocumentView];
1642
+ [self updateScaleLimitsForFitScale:self.pdfView.scaleFactorForSizeToFit];
1643
+ self.pdfView.autoScales = NO;
1644
+ _zoom = desiredZoom;
1645
+ [self applyNormalizedZoom];
1646
+
1647
+ if (currentPage) {
1648
+ [self.pdfView goToPage:currentPage];
1649
+ } else {
1650
+ [self applyCurrentPage];
1651
+ }
1652
+ _zoom = desiredZoom;
1653
+ [self applyNormalizedZoom];
1654
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
1655
+ }
1656
+
1657
+ - (void)updateScaleLimitsForFitScale:(CGFloat)fitScale {
1658
+ if (!isfinite(fitScale) || fitScale <= 0) return;
1659
+ self.pdfView.minScaleFactor = fitScale * PapyrusPdfMinimumZoom;
1660
+ self.pdfView.maxScaleFactor = fitScale * PapyrusPdfMaximumZoom;
1661
+ }
1662
+
1663
+ - (void)applyNormalizedZoom {
1664
+ CGFloat fitScale = self.pdfView.scaleFactorForSizeToFit;
1665
+ if (!isfinite(fitScale) || fitScale <= 0) return;
1666
+ [self updateScaleLimitsForFitScale:fitScale];
1667
+
1668
+ CGFloat targetScale = fitScale * [self clampedZoom:self.zoom];
1669
+ targetScale = MAX(self.pdfView.minScaleFactor,
1670
+ MIN(self.pdfView.maxScaleFactor, targetScale));
1671
+ if (fabs(self.pdfView.scaleFactor - targetScale) > 0.001) {
1672
+ self.pdfView.scaleFactor = targetScale;
1673
+ }
1674
+ }
1675
+
1676
+ - (CGFloat)normalizedZoomForPdfView {
1677
+ CGFloat fitScale = self.pdfView.scaleFactorForSizeToFit;
1678
+ if (!isfinite(fitScale) || fitScale <= 0) return 0;
1679
+ CGFloat normalized = self.pdfView.scaleFactor / fitScale;
1680
+ return isfinite(normalized) ? [self clampedZoom:normalized] : 0;
1681
+ }
1682
+
1683
+ - (CGFloat)clampedZoom:(CGFloat)zoom {
1684
+ return MAX(PapyrusPdfMinimumZoom, MIN(PapyrusPdfMaximumZoom, zoom));
1685
+ }
1686
+
1687
+ - (void)applyCurrentPage {
1688
+ PDFDocument *document = self.pdfView.document;
1689
+ if (!document || document.pageCount <= 0 || self.currentPage <= 0) return;
1690
+ NSInteger targetPage = MAX(1, MIN(self.currentPage, document.pageCount));
1691
+ _currentPage = targetPage;
1692
+ PDFPage *page = [document pageAtIndex:targetPage - 1];
1693
+ if (page && self.pdfView.currentPage != page) {
1694
+ [self.pdfView goToPage:page];
1695
+ }
1696
+ }
1697
+
1698
+ - (void)handlePdfPageChanged:(NSNotification *)notification {
1699
+ if (notification.object != self.pdfView) return;
1700
+ [self updateInkCanvasInputAndPicker];
1701
+ [self emitCurrentPageIfNeeded];
1702
+ [self emitVisiblePagesIfNeeded];
1703
+ }
1704
+
1705
+ - (void)emitCurrentPageIfNeeded {
1706
+ PDFDocument *document = self.pdfView.document;
1707
+ PDFPage *page = self.pdfView.currentPage;
1708
+ if (!document || !page) return;
1709
+ NSInteger pageNumber = [document indexForPage:page] + 1;
1710
+ if (pageNumber <= 0 || pageNumber == self.lastEmittedPage) return;
1711
+
1712
+ _currentPage = pageNumber;
1713
+ self.lastEmittedPage = pageNumber;
1714
+ if (self.onPageChange) {
1715
+ self.onPageChange(@{@"page" : @(pageNumber)});
1716
+ }
1717
+ }
1718
+
1719
+ - (void)handlePdfScaleChanged:(NSNotification *)notification {
1720
+ if (notification.object != self.pdfView) return;
1721
+ if (self.suppressScaleSynchronization) return;
1722
+ CGFloat normalized = [self normalizedZoomForPdfView];
1723
+ if (normalized <= 0) return;
1724
+ _zoom = normalized;
1725
+ if (self.zoomEventScheduled) return;
1726
+
1727
+ self.zoomEventScheduled = YES;
1728
+ __weak typeof(self) weakSelf = self;
1729
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
1730
+ (int64_t)(PapyrusPdfZoomEventInterval * NSEC_PER_SEC)),
1731
+ dispatch_get_main_queue(), ^{
1732
+ typeof(self) strongSelf = weakSelf;
1733
+ if (!strongSelf) return;
1734
+ strongSelf.zoomEventScheduled = NO;
1735
+ [strongSelf emitZoomIfNeeded];
1736
+ });
1737
+ }
1738
+
1739
+ - (void)emitZoomIfNeeded {
1740
+ CGFloat normalized = [self normalizedZoomForPdfView];
1741
+ if (normalized <= 0) return;
1742
+ if (isfinite(self.lastEmittedZoom) &&
1743
+ fabs(normalized - self.lastEmittedZoom) <= PapyrusPdfZoomEventTolerance) {
1744
+ return;
1745
+ }
1746
+
1747
+ _zoom = normalized;
1748
+ self.lastEmittedZoom = normalized;
1749
+ if (self.onZoomChange) {
1750
+ self.onZoomChange(@{@"zoom" : @(normalized)});
1751
+ }
1752
+ }
1753
+
1754
+ - (void)handlePdfVisiblePagesChanged:(NSNotification *)notification {
1755
+ if (notification.object != self.pdfView) return;
1756
+ [self emitVisiblePagesIfNeeded];
1757
+ }
1758
+
1759
+ - (void)handlePdfSelectionChanged:(NSNotification *)notification {
1760
+ if (notification.object != self.pdfView) return;
1761
+ [self applyTemporarySelectionColor];
1762
+ [self emitCurrentSelectionIfNeeded];
1763
+ }
1764
+
1765
+ - (void)applyTemporarySelectionColor {
1766
+ PDFSelection *selection = self.pdfView.currentSelection;
1767
+ if (!selection.string.length) return;
1768
+
1769
+ // PDFKit owns selection geometry and its drag handles. Setting the color on
1770
+ // that same selection keeps the highlight attached to text through zoom,
1771
+ // page rotation, and scrolling without adding a screen-space overlay.
1772
+ selection.color = [UIColor.systemBlueColor colorWithAlphaComponent:0.30];
1773
+ [self.pdfView setNeedsDisplay];
1774
+ }
1775
+
1776
+ - (void)emitCurrentSelectionIfNeeded {
1777
+ PDFSelection *selection = self.pdfView.currentSelection;
1778
+ NSString *text = selection.string ?: @"";
1779
+ PDFDocument *document = self.pdfView.document;
1780
+ PDFPage *page = selection.pages.firstObject;
1781
+ NSInteger pageIndex = document && page ? [document indexForPage:page] : NSNotFound;
1782
+ if (!document || !page || pageIndex == NSNotFound || text.length == 0 ||
1783
+ [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length == 0) {
1784
+ [self emitSelectionClearedIfNeeded];
1785
+ return;
1786
+ }
1787
+
1788
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1789
+ if (CGRectIsEmpty(pageBounds)) {
1790
+ [self emitSelectionClearedIfNeeded];
1791
+ return;
1792
+ }
1793
+
1794
+ NSMutableArray<NSDictionary *> *rects = [NSMutableArray array];
1795
+ for (PDFSelection *line in selection.selectionsByLine) {
1796
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1797
+ [line boundsForPage:page], pageBounds);
1798
+ if (normalizedRect) [rects addObject:normalizedRect];
1799
+ }
1800
+
1801
+ if (rects.count == 0) {
1802
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1803
+ [selection boundsForPage:page], pageBounds);
1804
+ if (normalizedRect) [rects addObject:normalizedRect];
1805
+ }
1806
+
1807
+ NSString *signature = [NSString stringWithFormat:@"%ld|%@|%@", (long)pageIndex, text, rects];
1808
+ if (self.lastSelectionWasActive && [signature isEqualToString:self.lastSelectionSignature]) return;
1809
+ self.lastSelectionWasActive = YES;
1810
+ self.lastSelectionPageIndex = pageIndex;
1811
+ self.lastSelectionSignature = signature;
1812
+ if (self.onTextSelected) {
1813
+ self.onTextSelected(@{@"text" : text, @"pageIndex" : @(pageIndex), @"rects" : rects});
1814
+ }
1815
+ [self scheduleSelectionEditMenuForSignature:signature];
1816
+ }
1817
+
1818
+ - (void)emitSelectionClearedIfNeeded {
1819
+ if (!self.lastSelectionWasActive) return;
1820
+ self.selectionMenuGeneration += 1;
1821
+ if (@available(iOS 16.0, *)) {
1822
+ [self.editMenuInteraction dismissMenu];
1823
+ }
1824
+ NSInteger pageIndex = self.lastSelectionPageIndex;
1825
+ if (pageIndex == NSNotFound) pageIndex = MAX(0, self.currentPage - 1);
1826
+ self.lastSelectionWasActive = NO;
1827
+ self.lastSelectionSignature = nil;
1828
+ self.lastSelectionPageIndex = NSNotFound;
1829
+ if (self.onTextSelected) {
1830
+ self.onTextSelected(@{@"text" : @"", @"pageIndex" : @(pageIndex), @"rects" : @[]});
1831
+ }
1832
+ }
1833
+
1834
+ - (void)scheduleSelectionEditMenuForSignature:(NSString *)signature {
1835
+ if (@available(iOS 16.0, *)) {
1836
+ UIEditMenuInteraction *interaction = self.editMenuInteraction;
1837
+ if (!interaction || signature.length == 0) return;
1838
+
1839
+ NSUInteger generation = ++self.selectionMenuGeneration;
1840
+ __weak typeof(self) weakSelf = self;
1841
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.22 * NSEC_PER_SEC)),
1842
+ dispatch_get_main_queue(), ^{
1843
+ typeof(self) strongSelf = weakSelf;
1844
+ [strongSelf attemptSelectionEditMenuForSignature:signature generation:generation];
1845
+ });
1846
+ }
1847
+ }
1848
+
1849
+ - (void)attemptSelectionEditMenuForSignature:(NSString *)signature generation:(NSUInteger)generation {
1850
+ if (@available(iOS 16.0, *)) {
1851
+ if (generation != self.selectionMenuGeneration ||
1852
+ ![signature isEqualToString:self.lastSelectionSignature]) {
1853
+ return;
1854
+ }
1855
+
1856
+ if ([self hasActiveGestureInView:self.pdfView]) {
1857
+ __weak typeof(self) weakSelf = self;
1858
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.10 * NSEC_PER_SEC)),
1859
+ dispatch_get_main_queue(), ^{
1860
+ typeof(self) strongSelf = weakSelf;
1861
+ [strongSelf attemptSelectionEditMenuForSignature:signature generation:generation];
1862
+ });
1863
+ return;
1864
+ }
1865
+
1866
+ UIEditMenuInteraction *interaction = self.editMenuInteraction;
1867
+ PDFSelection *selection = self.pdfView.currentSelection;
1868
+ PDFPage *page = selection.pages.firstObject;
1869
+ if (!interaction || !selection.string.length || !page ||
1870
+ (!self.onDefineSelection && !self.onAnnotationCreated)) return;
1871
+
1872
+ CGRect selectionRect = [selection boundsForPage:page];
1873
+ CGRect viewRect = [self.pdfView convertRect:selectionRect fromPage:page];
1874
+ if (CGRectIsNull(viewRect) || CGRectIsEmpty(viewRect)) return;
1875
+ self.contextualAnnotationMenuId = nil;
1876
+ self.contextualAnnotationMenuConfigurationId = nil;
1877
+ CGPoint sourcePoint = CGPointMake(CGRectGetMidX(viewRect), CGRectGetMidY(viewRect));
1878
+ UIEditMenuConfiguration *configuration =
1879
+ [UIEditMenuConfiguration configurationWithIdentifier:signature sourcePoint:sourcePoint];
1880
+ [interaction presentEditMenuWithConfiguration:configuration];
1881
+ }
1882
+ }
1883
+
1884
+ - (void)presentAnnotationEditMenuForId:(NSString *)annotationId atPoint:(CGPoint)point {
1885
+ if (@available(iOS 16.0, *)) {
1886
+ UIEditMenuInteraction *interaction = self.editMenuInteraction;
1887
+ if (!interaction || !self.onAnnotationDelete ||
1888
+ self.annotationDeleteLabel.length == 0 || annotationId.length == 0) return;
1889
+
1890
+ NSString *configurationId = [NSString stringWithFormat:
1891
+ @"com.papyrus.annotation.delete.%@.%@", annotationId, [[NSUUID UUID] UUIDString]];
1892
+ self.contextualAnnotationMenuId = [annotationId copy];
1893
+ self.contextualAnnotationMenuConfigurationId = configurationId;
1894
+ self.contextualAnnotationMenuSourcePoint = point;
1895
+ UIEditMenuConfiguration *configuration = [UIEditMenuConfiguration configurationWithIdentifier:configurationId sourcePoint:point];
1896
+ [interaction presentEditMenuWithConfiguration:configuration];
1897
+ }
1898
+ }
1899
+
1900
+ - (void)dismissAnnotationMenuForDocumentChange {
1901
+ self.contextualAnnotationMenuId = nil;
1902
+ self.contextualAnnotationMenuConfigurationId = nil;
1903
+ self.contextualAnnotationMenuSourcePoint = CGPointZero;
1904
+ if (@available(iOS 16.0, *)) {
1905
+ [self.editMenuInteraction dismissMenu];
1906
+ }
1907
+ if (self.onAnnotationDeselected) self.onAnnotationDeselected(@{});
1908
+ }
1909
+
1910
+ - (BOOL)hasActiveGestureInView:(UIView *)view {
1911
+ for (UIGestureRecognizer *recognizer in view.gestureRecognizers) {
1912
+ if (recognizer.state == UIGestureRecognizerStateBegan ||
1913
+ recognizer.state == UIGestureRecognizerStateChanged) {
1914
+ return YES;
1915
+ }
1916
+ }
1917
+
1918
+ for (UIView *subview in view.subviews) {
1919
+ if ([self hasActiveGestureInView:subview]) return YES;
1920
+ }
1921
+ return NO;
1922
+ }
1923
+
1924
+ - (nullable UIMenu *)editMenuInteraction:(UIEditMenuInteraction *)interaction
1925
+ menuForConfiguration:(UIEditMenuConfiguration *)configuration
1926
+ suggestedActions:(NSArray<UIMenuElement *> *)suggestedActions API_AVAILABLE(ios(16.0)) {
1927
+ if (self.contextualAnnotationMenuId.length > 0 &&
1928
+ [(NSString *)configuration.identifier isEqualToString:self.contextualAnnotationMenuConfigurationId]) {
1929
+ NSString *annotationId = [self.contextualAnnotationMenuId copy];
1930
+ if (!self.onAnnotationDelete || self.annotationDeleteLabel.length == 0) return nil;
1931
+ PDFDocument *documentAtPresentation = self.pdfView.document;
1932
+ __weak typeof(self) weakSelf = self;
1933
+ UIAction *deleteAction = [UIAction
1934
+ actionWithTitle:self.annotationDeleteLabel
1935
+ image:[UIImage systemImageNamed:@"trash"]
1936
+ identifier:@"com.papyrus.annotation.delete"
1937
+ handler:^(__kindof UIAction *action) {
1938
+ typeof(self) strongSelf = weakSelf;
1939
+ if (!strongSelf || strongSelf.pdfView.document != documentAtPresentation) return;
1940
+ [strongSelf emitAnnotationDeleteWithId:annotationId];
1941
+ }];
1942
+ return [UIMenu menuWithChildren:@[deleteAction]];
1943
+ }
1944
+
1945
+ NSMutableArray<UIMenuElement *> *rootActions = [NSMutableArray array];
1946
+ NSArray<UIMenuElement *> *localizedSystemActions =
1947
+ PapyrusLocalizedSelectionActions(suggestedActions ?: @[], self.copyLabel, self.selectAllLabel);
1948
+ UIMenuElement *nativeCopyAction = nil;
1949
+ for (UIMenuElement *element in localizedSystemActions) {
1950
+ if ([element isKindOfClass:UICommand.class] &&
1951
+ ((UICommand *)element).action == @selector(copy:)) {
1952
+ nativeCopyAction = element;
1953
+ [rootActions addObject:element];
1954
+ break;
1955
+ }
1956
+ }
1957
+
1958
+ if (self.onDefineSelection && self.defineLabel.length > 0 &&
1959
+ self.pdfView.currentSelection.string.length > 0 &&
1960
+ (![self.defineSelectionMode isEqualToString:@"single-word"] ||
1961
+ [self isSingleWordSelection:self.pdfView.currentSelection.string])) {
1962
+ __weak typeof(self) weakSelf = self;
1963
+ UIAction *defineAction = [UIAction
1964
+ actionWithTitle:self.defineLabel
1965
+ image:[UIImage systemImageNamed:@"text.magnifyingglass"]
1966
+ identifier:@"com.papyrus.define-selection"
1967
+ handler:^(__kindof UIAction *action) {
1968
+ [weakSelf emitDefineSelection];
1969
+ }];
1970
+ [rootActions addObject:defineAction];
1971
+ }
1972
+
1973
+ UIAction *highlightAction = nil;
1974
+ if (self.onAnnotationCreated && self.annotateLabel.length > 0 &&
1975
+ self.pdfView.currentSelection.string.length > 0) {
1976
+ __weak typeof(self) weakSelf = self;
1977
+ highlightAction = [UIAction
1978
+ actionWithTitle:self.annotationHighlightLabel
1979
+ image:[UIImage systemImageNamed:@"highlighter"]
1980
+ identifier:@"com.papyrus.annotation.highlight"
1981
+ handler:^(__kindof UIAction *action) {
1982
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"highlight"];
1983
+ }];
1984
+ UIAction *underlineAction = [UIAction
1985
+ actionWithTitle:self.annotationUnderlineLabel
1986
+ image:[UIImage systemImageNamed:@"underline"]
1987
+ identifier:@"com.papyrus.annotation.underline"
1988
+ handler:^(__kindof UIAction *action) {
1989
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"underline"];
1990
+ }];
1991
+ UIAction *strikeoutAction = [UIAction
1992
+ actionWithTitle:self.annotationStrikeoutLabel
1993
+ image:[UIImage systemImageNamed:@"strikethrough"]
1994
+ identifier:@"com.papyrus.annotation.strikeout"
1995
+ handler:^(__kindof UIAction *action) {
1996
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"strikeout"];
1997
+ }];
1998
+ UIAction *squigglyAction = [UIAction
1999
+ actionWithTitle:self.annotationSquigglyLabel
2000
+ image:[UIImage systemImageNamed:@"scribble"]
2001
+ identifier:@"com.papyrus.annotation.squiggly"
2002
+ handler:^(__kindof UIAction *action) {
2003
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"squiggly"];
2004
+ }];
2005
+ UIAction *noteAction = [UIAction
2006
+ actionWithTitle:self.annotationNoteLabel
2007
+ image:[UIImage systemImageNamed:@"note.text"]
2008
+ identifier:@"com.papyrus.annotation.comment"
2009
+ handler:^(__kindof UIAction *action) {
2010
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"comment"];
2011
+ }];
2012
+ [rootActions addObject:highlightAction];
2013
+ UIMenu *annotationMenu = [UIMenu menuWithTitle:self.annotateLabel
2014
+ children:@[underlineAction, strikeoutAction,
2015
+ squigglyAction, noteAction]];
2016
+ [rootActions addObject:annotationMenu];
2017
+ }
2018
+
2019
+ NSMutableArray<UIMenuElement *> *remainingSystemActions = [NSMutableArray array];
2020
+ for (UIMenuElement *element in localizedSystemActions) {
2021
+ if (element != nativeCopyAction) [remainingSystemActions addObject:element];
2022
+ }
2023
+ [rootActions addObjectsFromArray:remainingSystemActions];
2024
+
2025
+ UIMenu *rootMenu = [UIMenu menuWithChildren:rootActions];
2026
+ if (@available(iOS 16.0, *)) {
2027
+ // UIKit may still choose a platform-specific layout for edit menus.
2028
+ rootMenu.preferredElementSize = UIMenuElementSizeMedium;
2029
+ }
2030
+ return rootMenu;
2031
+ }
2032
+
2033
+ - (BOOL)isSingleWordSelection:(NSString *)text {
2034
+ NSString *trimmed = [text stringByTrimmingCharactersInSet:
2035
+ NSCharacterSet.whitespaceAndNewlineCharacterSet];
2036
+ if (trimmed.length == 0) return NO;
2037
+ NSArray<NSString *> *words = [trimmed componentsSeparatedByCharactersInSet:
2038
+ NSCharacterSet.whitespaceAndNewlineCharacterSet];
2039
+ return words.count == 1 && words.firstObject.length > 0;
2040
+ }
2041
+
2042
+ - (CGRect)editMenuInteraction:(UIEditMenuInteraction *)interaction
2043
+ targetRectForConfiguration:(UIEditMenuConfiguration *)configuration API_AVAILABLE(ios(16.0)) {
2044
+ if (self.contextualAnnotationMenuId.length > 0 &&
2045
+ [(NSString *)configuration.identifier isEqualToString:self.contextualAnnotationMenuConfigurationId]) {
2046
+ CGPoint point = self.contextualAnnotationMenuSourcePoint;
2047
+ return CGRectMake(point.x, point.y, 1.0, 1.0);
2048
+ }
2049
+
2050
+ PDFSelection *selection = self.pdfView.currentSelection;
2051
+ PDFPage *page = selection.pages.firstObject;
2052
+ if (!selection || !page) return CGRectZero;
2053
+
2054
+ CGRect selectionRect = [selection boundsForPage:page];
2055
+ CGRect viewRect = [self.pdfView convertRect:selectionRect fromPage:page];
2056
+ return CGRectIsNull(viewRect) || CGRectIsEmpty(viewRect) ? CGRectZero : viewRect;
2057
+ }
2058
+
2059
+ - (void)editMenuInteraction:(UIEditMenuInteraction *)interaction
2060
+ willDismissMenuForConfiguration:(UIEditMenuConfiguration *)configuration
2061
+ animator:(id<UIEditMenuInteractionAnimating>)animator API_AVAILABLE(ios(16.0)) {
2062
+ if (self.contextualAnnotationMenuId.length == 0 ||
2063
+ ![(NSString *)configuration.identifier isEqualToString:self.contextualAnnotationMenuConfigurationId]) return;
2064
+
2065
+ self.contextualAnnotationMenuId = nil;
2066
+ self.contextualAnnotationMenuConfigurationId = nil;
2067
+ self.contextualAnnotationMenuSourcePoint = CGPointZero;
2068
+ if (self.onAnnotationDeselected) self.onAnnotationDeselected(@{});
2069
+ }
2070
+
2071
+ - (void)emitDefineSelection {
2072
+ if (!self.onDefineSelection) return;
2073
+ PDFSelection *selection = self.pdfView.currentSelection;
2074
+ NSString *text = selection.string ?: @"";
2075
+ PDFDocument *document = self.pdfView.document;
2076
+ PDFPage *page = selection.pages.firstObject;
2077
+ NSInteger pageIndex = document && page ? [document indexForPage:page] : NSNotFound;
2078
+ if (text.length == 0 || !document || !page || pageIndex == NSNotFound) return;
2079
+
2080
+ self.onDefineSelection(@{@"text" : text, @"pageIndex" : @(pageIndex)});
2081
+ }
2082
+
2083
+ - (void)emitAnnotationDeleteWithId:(NSString *)annotationId {
2084
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[annotationId];
2085
+ if (annotationId.length == 0 || representations.count == 0 || !self.onAnnotationDelete) return;
2086
+ self.onAnnotationDelete(@{@"id" : annotationId});
2087
+ }
2088
+
2089
+ - (void)clearCurrentSelection {
2090
+ if (self.pdfView.currentSelection) {
2091
+ self.pdfView.currentSelection = nil;
2092
+ }
2093
+ [self emitSelectionClearedIfNeeded];
2094
+ }
2095
+
2096
+ - (void)emitVisiblePagesIfNeeded {
2097
+ PDFDocument *document = self.pdfView.document;
2098
+ if (!document || self.pdfView.bounds.size.width <= 0 || self.pdfView.bounds.size.height <= 0) return;
2099
+
2100
+ NSMutableArray<NSDictionary *> *pages = [NSMutableArray array];
2101
+ NSMutableArray<NSString *> *signatureParts = [NSMutableArray array];
2102
+ for (PDFPage *page in self.pdfView.visiblePages) {
2103
+ NSInteger pageIndex = [document indexForPage:page];
2104
+ if (pageIndex == NSNotFound) continue;
2105
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
2106
+ CGRect viewBounds = [self.pdfView convertRect:pageBounds fromPage:page];
2107
+ CGRect intersection = CGRectIntersection(self.pdfView.bounds, viewBounds);
2108
+ CGFloat pageArea = CGRectGetWidth(viewBounds) * CGRectGetHeight(viewBounds);
2109
+ CGFloat visibleArea = CGRectIsNull(intersection)
2110
+ ? 0
2111
+ : CGRectGetWidth(intersection) * CGRectGetHeight(intersection);
2112
+ if (!isfinite(pageArea) || pageArea <= 0 || visibleArea <= 0) continue;
2113
+
2114
+ CGFloat visibleRatio = MIN(1.0, MAX(0.0, visibleArea / pageArea));
2115
+ if (visibleRatio <= 0) continue;
2116
+ [pages addObject:@{@"pageIndex" : @(pageIndex), @"visibleRatio" : @(visibleRatio)}];
2117
+ NSInteger bucket = (NSInteger)llround(visibleRatio * 20.0);
2118
+ [signatureParts addObject:[NSString stringWithFormat:@"%ld:%ld", (long)pageIndex, (long)bucket]];
2119
+ }
2120
+
2121
+ if (pages.count == 0) return;
2122
+ NSString *signature = [signatureParts componentsJoinedByString:@"|"];
2123
+ if ([signature isEqualToString:self.lastVisiblePagesSignature]) return;
2124
+ self.lastVisiblePagesSignature = signature;
2125
+ if (self.onVisiblePagesChange) {
2126
+ self.onVisiblePagesChange(@{@"pages" : pages});
2127
+ }
2128
+ }
2129
+
2130
+ - (UIScrollView *)findScrollViewInView:(UIView *)view {
2131
+ for (UIView *subview in view.subviews) {
2132
+ if ([subview isKindOfClass:[UIScrollView class]]) {
2133
+ return (UIScrollView *)subview;
2134
+ }
2135
+ UIScrollView *nested = [self findScrollViewInView:subview];
2136
+ if (nested) return nested;
2137
+ }
2138
+ return nil;
2139
+ }
2140
+
2141
+ - (void)refreshScrollViewObservation {
2142
+ UIScrollView *scrollView = [self findScrollViewInView:self.pdfView];
2143
+ if (scrollView == self.observedScrollView) return;
2144
+ [self stopObservingScrollView];
2145
+ self.observedScrollView = scrollView;
2146
+ if (!scrollView) return;
2147
+
2148
+ @try {
2149
+ [scrollView addObserver:self
2150
+ forKeyPath:@"contentOffset"
2151
+ options:NSKeyValueObservingOptionNew
2152
+ context:PapyrusPdfScrollObservationContext];
2153
+ } @catch (__unused NSException *exception) {
2154
+ self.observedScrollView = nil;
2155
+ }
2156
+ }
2157
+
2158
+ - (void)stopObservingScrollView {
2159
+ UIScrollView *scrollView = self.observedScrollView;
2160
+ if (!scrollView) return;
2161
+ @try {
2162
+ [scrollView removeObserver:self
2163
+ forKeyPath:@"contentOffset"
2164
+ context:PapyrusPdfScrollObservationContext];
2165
+ } @catch (__unused NSException *exception) {
2166
+ }
2167
+ self.observedScrollView = nil;
2168
+ }
2169
+
2170
+ - (void)observeValueForKeyPath:(NSString *)keyPath
2171
+ ofObject:(id)object
2172
+ change:(NSDictionary<NSKeyValueChangeKey, id> *)change
2173
+ context:(void *)context {
2174
+ if (context != PapyrusPdfScrollObservationContext) {
2175
+ [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
2176
+ return;
2177
+ }
2178
+ if (![keyPath isEqualToString:@"contentOffset"]) return;
2179
+ if (!NSThread.isMainThread) {
2180
+ __weak typeof(self) weakSelf = self;
2181
+ dispatch_async(dispatch_get_main_queue(), ^{
2182
+ typeof(self) strongSelf = weakSelf;
2183
+ if (strongSelf && object == strongSelf.observedScrollView) {
2184
+ UIScrollView *scrollView = strongSelf.observedScrollView;
2185
+ [strongSelf scheduleScrollEventWithOffsetY:scrollView.contentOffset.y];
2186
+ }
2187
+ });
2188
+ return;
2189
+ }
2190
+ if (object != self.observedScrollView) return;
2191
+ UIScrollView *scrollView = self.observedScrollView;
2192
+ CGFloat offsetY = scrollView.contentOffset.y;
2193
+ [self scheduleScrollEventWithOffsetY:offsetY];
2194
+ }
2195
+
2196
+ - (void)scheduleScrollEventWithOffsetY:(CGFloat)offsetY {
2197
+ self.pendingScrollOffsetY = offsetY;
2198
+ CFTimeInterval now = CACurrentMediaTime();
2199
+ CFTimeInterval elapsed = now - self.lastScrollEventTime;
2200
+ if (elapsed >= PapyrusPdfScrollEventInterval && !self.scrollEventScheduled) {
2201
+ [self emitScrollEvent];
2202
+ return;
2203
+ }
2204
+ if (self.scrollEventScheduled) return;
2205
+
2206
+ self.scrollEventScheduled = YES;
2207
+ CFTimeInterval delay = MAX(0, PapyrusPdfScrollEventInterval - elapsed);
2208
+ __weak typeof(self) weakSelf = self;
2209
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
2210
+ dispatch_get_main_queue(), ^{
2211
+ typeof(self) strongSelf = weakSelf;
2212
+ if (!strongSelf) return;
2213
+ strongSelf.scrollEventScheduled = NO;
2214
+ [strongSelf emitScrollEvent];
2215
+ });
2216
+ }
2217
+
2218
+ - (void)emitScrollEvent {
2219
+ self.lastScrollEventTime = CACurrentMediaTime();
2220
+ if (self.onScroll) {
2221
+ self.onScroll(@{@"offsetY" : @(self.pendingScrollOffsetY)});
2222
+ }
2223
+ }
2224
+
2225
+ - (void)handleDocumentTap:(UITapGestureRecognizer *)recognizer {
2226
+ if (recognizer.state != UIGestureRecognizerStateEnded) return;
2227
+ if ([self.activeTool isEqualToString:@"ink"]) return;
2228
+ PDFDocument *document = self.pdfView.document;
2229
+ if (!document) return;
2230
+
2231
+ CGPoint viewPoint = [recognizer locationInView:self.pdfView];
2232
+ PDFPage *page = [self.pdfView pageForPoint:viewPoint nearest:YES];
2233
+ if (!page) return;
2234
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
2235
+ if (CGRectGetWidth(pageBounds) <= 0 || CGRectGetHeight(pageBounds) <= 0) return;
2236
+ CGPoint pagePoint = [self.pdfView convertPoint:viewPoint toPage:page];
2237
+ CGFloat x = (pagePoint.x - CGRectGetMinX(pageBounds)) / CGRectGetWidth(pageBounds);
2238
+ CGFloat y = 1.0 - ((pagePoint.y - CGRectGetMinY(pageBounds)) / CGRectGetHeight(pageBounds));
2239
+ NSInteger pageIndex = [document indexForPage:page];
2240
+ if (pageIndex == NSNotFound) return;
2241
+
2242
+ PDFAnnotation *hitAnnotation = nil;
2243
+ NSString *annotationId = nil;
2244
+ for (id candidateValue in [self.annotations reverseObjectEnumerator]) {
2245
+ if (![candidateValue isKindOfClass:NSDictionary.class]) continue;
2246
+ NSDictionary *candidate = (NSDictionary *)candidateValue;
2247
+ NSString *candidateId = [candidate[@"id"] isKindOfClass:NSString.class]
2248
+ ? candidate[@"id"] : nil;
2249
+ if (candidateId.length == 0) continue;
2250
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[candidateId] ?: @[];
2251
+ for (PDFAnnotation *representation in [representations reverseObjectEnumerator]) {
2252
+ if (representation.page != page ||
2253
+ !CGRectContainsPoint(CGRectInset(representation.bounds, -4.0, -4.0), pagePoint)) {
2254
+ continue;
2255
+ }
2256
+ NSString *registeredId = [self.papyrusAnnotationIdsByObject objectForKey:representation];
2257
+ if (![registeredId isEqualToString:candidateId]) continue;
2258
+ hitAnnotation = representation;
2259
+ annotationId = candidateId;
2260
+ break;
2261
+ }
2262
+ if (hitAnnotation) break;
2263
+ }
2264
+ if (annotationId.length > 0) {
2265
+ NSDictionary *papyrusAnnotation = nil;
2266
+ for (id value in self.annotations) {
2267
+ if (![value isKindOfClass:NSDictionary.class]) continue;
2268
+ NSDictionary *candidate = (NSDictionary *)value;
2269
+ if ([candidate[@"id"] isEqual:annotationId]) {
2270
+ papyrusAnnotation = candidate;
2271
+ break;
2272
+ }
2273
+ }
2274
+ if (@available(iOS 16.0, *)) {
2275
+ [self.editMenuInteraction dismissMenu];
2276
+ }
2277
+ if (self.onAnnotationTap) {
2278
+ self.onAnnotationTap(@{
2279
+ @"id" : annotationId,
2280
+ @"pageIndex" : @(pageIndex),
2281
+ @"type" : papyrusAnnotation[@"type"] ?: @"",
2282
+ @"color" : papyrusAnnotation[@"color"] ?: @""
2283
+ });
2284
+ }
2285
+ NSString *annotationType = [papyrusAnnotation[@"type"] isKindOfClass:NSString.class]
2286
+ ? papyrusAnnotation[@"type"] : @"";
2287
+ if (!papyrusAnnotation[@"noteContent"] && ![annotationType isEqualToString:@"comment"] &&
2288
+ ![annotationType isEqualToString:@"text"]) {
2289
+ [self presentAnnotationEditMenuForId:annotationId atPoint:viewPoint];
2290
+ }
2291
+ return;
2292
+ }
2293
+
2294
+ if (self.pdfView.currentSelection && ![self selectionContainsViewPoint:viewPoint]) {
2295
+ [self clearCurrentSelection];
2296
+ return;
2297
+ }
2298
+
2299
+ CGPoint normalizedPoint = CGPointMake(MIN(1.0, MAX(0.0, x)),
2300
+ MIN(1.0, MAX(0.0, y)));
2301
+ if ([self.activeTool isEqualToString:@"comment"]) {
2302
+ CGRect pageViewBounds = [self.pdfView convertRect:pageBounds fromPage:page];
2303
+ if (CGRectContainsPoint(pageViewBounds, viewPoint)) {
2304
+ [self emitCommentAtPage:page pageIndex:pageIndex normalizedPoint:normalizedPoint];
2305
+ }
2306
+ return;
2307
+ }
2308
+
2309
+ if (self.onTap) {
2310
+ self.onTap(@{
2311
+ @"pageIndex" : @(pageIndex),
2312
+ @"x" : @(normalizedPoint.x),
2313
+ @"y" : @(normalizedPoint.y)
2314
+ });
2315
+ }
2316
+ }
2317
+
2318
+ - (void)handleDocumentDoubleTap:(UITapGestureRecognizer *)recognizer {
2319
+ if (recognizer.state != UIGestureRecognizerStateEnded) return;
2320
+ if ([self.activeTool isEqualToString:@"ink"]) return;
2321
+ PDFDocument *document = self.pdfView.document;
2322
+ if (!document) return;
2323
+
2324
+ [self selectWordAtViewPoint:[recognizer locationInView:self.pdfView]];
2325
+ }
2326
+
2327
+ - (void)handleDocumentLongPress:(UILongPressGestureRecognizer *)recognizer {
2328
+ if (recognizer.state != UIGestureRecognizerStateBegan ||
2329
+ [self.activeTool isEqualToString:@"ink"]) return;
2330
+ CGPoint point = [recognizer locationInView:self.pdfView];
2331
+ // Existing native handles must retain ownership of an extension gesture.
2332
+ if ([self selectionContainsViewPoint:point]) return;
2333
+ [self selectWordAtViewPoint:point];
2334
+ }
2335
+
2336
+ - (void)selectWordAtViewPoint:(CGPoint)viewPoint {
2337
+ PDFPage *page = [self.pdfView pageForPoint:viewPoint nearest:NO];
2338
+ if (!page) return;
2339
+ PDFSelection *selection = [page selectionForWordAtPoint:
2340
+ [self.pdfView convertPoint:viewPoint toPage:page]];
2341
+ if (!selection.string.length) return;
2342
+ [self.pdfView becomeFirstResponder];
2343
+ selection.color = [UIColor.systemBlueColor colorWithAlphaComponent:0.30];
2344
+ [self.pdfView setCurrentSelection:selection animate:NO];
2345
+ [self emitCurrentSelectionIfNeeded];
2346
+ }
2347
+
2348
+ - (BOOL)selectionContainsViewPoint:(CGPoint)viewPoint {
2349
+ PDFSelection *selection = self.pdfView.currentSelection;
2350
+ if (!selection) return NO;
2351
+
2352
+ NSArray<PDFSelection *> *lines = selection.selectionsByLine;
2353
+ if (lines.count == 0) lines = @[selection];
2354
+ for (PDFPage *page in selection.pages) {
2355
+ for (PDFSelection *line in lines) {
2356
+ CGRect pageRect = [line boundsForPage:page];
2357
+ if (CGRectIsNull(pageRect) || CGRectIsEmpty(pageRect)) continue;
2358
+ CGRect viewRect = [self.pdfView convertRect:pageRect fromPage:page];
2359
+ if (CGRectContainsPoint(CGRectInset(viewRect, -6, -6), viewPoint)) return YES;
2360
+ }
2361
+ }
2362
+ return NO;
2363
+ }
2364
+
2365
+ - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
2366
+ shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
2367
+ return YES;
2368
+ }
2369
+
2370
+ @end