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

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