@ng-native/desktop 0.0.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (393) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -0
  3. package/app.plugin.cjs +17 -0
  4. package/bin/app-config.mjs +168 -0
  5. package/bin/autolink.mjs +224 -0
  6. package/bin/cli.mjs +158 -0
  7. package/bin/host.mjs +427 -0
  8. package/bin/ng-native-desktop.mjs +4 -0
  9. package/bin/package.mjs +971 -0
  10. package/bin/plist.mjs +68 -0
  11. package/bin/prebuilt.mjs +328 -0
  12. package/bin/toolchain.mjs +192 -0
  13. package/native/CMakeLists.txt +276 -0
  14. package/native/appkit/CMakeLists.txt +109 -0
  15. package/native/appkit/address-search.h +26 -0
  16. package/native/appkit/address-search.mm +277 -0
  17. package/native/appkit/animation-frames.h +14 -0
  18. package/native/appkit/animation-frames.mm +106 -0
  19. package/native/appkit/app-info.h +12 -0
  20. package/native/appkit/app-info.mm +98 -0
  21. package/native/appkit/app-updater.mm +128 -0
  22. package/native/appkit/app-windows.h +81 -0
  23. package/native/appkit/app-windows.mm +318 -0
  24. package/native/appkit/appkit-backend.h +73 -0
  25. package/native/appkit/appkit-backend.mm +276 -0
  26. package/native/appkit/apple-authentication.h +19 -0
  27. package/native/appkit/apple-authentication.mm +248 -0
  28. package/native/appkit/apple-button-view.h +10 -0
  29. package/native/appkit/apple-button-view.mm +37 -0
  30. package/native/appkit/apple-id-button.h +16 -0
  31. package/native/appkit/apple-id-button.mm +50 -0
  32. package/native/appkit/audio.h +16 -0
  33. package/native/appkit/audio.mm +275 -0
  34. package/native/appkit/battery.h +13 -0
  35. package/native/appkit/battery.mm +92 -0
  36. package/native/appkit/bookmarks.h +17 -0
  37. package/native/appkit/bookmarks.mm +145 -0
  38. package/native/appkit/calendar.h +25 -0
  39. package/native/appkit/calendar.mm +660 -0
  40. package/native/appkit/camera-view.h +15 -0
  41. package/native/appkit/camera-view.mm +130 -0
  42. package/native/appkit/camera.h +39 -0
  43. package/native/appkit/camera.mm +362 -0
  44. package/native/appkit/cg-canvas.h +17 -0
  45. package/native/appkit/cg-canvas.mm +518 -0
  46. package/native/appkit/component-view.h +17 -0
  47. package/native/appkit/crypto.h +19 -0
  48. package/native/appkit/crypto.mm +78 -0
  49. package/native/appkit/desktop-expo.h +29 -0
  50. package/native/appkit/desktop-expo.mm +385 -0
  51. package/native/appkit/expo-image-drawing.h +46 -0
  52. package/native/appkit/expo-image-drawing.mm +131 -0
  53. package/native/appkit/expo-image-view.h +15 -0
  54. package/native/appkit/expo-image-view.mm +182 -0
  55. package/native/appkit/expo-ui-renderer.h +68 -0
  56. package/native/appkit/expo-ui-renderer.mm +101 -0
  57. package/native/appkit/expo-ui-view.h +26 -0
  58. package/native/appkit/expo-ui-view.mm +134 -0
  59. package/native/appkit/expo-ui.swift +1284 -0
  60. package/native/appkit/file-system.h +16 -0
  61. package/native/appkit/file-system.mm +140 -0
  62. package/native/appkit/fonts.h +12 -0
  63. package/native/appkit/fonts.mm +48 -0
  64. package/native/appkit/geocoder.h +19 -0
  65. package/native/appkit/geocoder.mm +101 -0
  66. package/native/appkit/glass-effect.h +22 -0
  67. package/native/appkit/glass-effect.mm +63 -0
  68. package/native/appkit/glass-view.h +8 -0
  69. package/native/appkit/glass-view.mm +65 -0
  70. package/native/appkit/header-toolbar.h +60 -0
  71. package/native/appkit/header-toolbar.mm +629 -0
  72. package/native/appkit/host-view.h +54 -0
  73. package/native/appkit/host-view.mm +1200 -0
  74. package/native/appkit/image-manipulator.h +14 -0
  75. package/native/appkit/image-manipulator.mm +191 -0
  76. package/native/appkit/image-request.h +22 -0
  77. package/native/appkit/image-request.mm +62 -0
  78. package/native/appkit/image-view.h +8 -0
  79. package/native/appkit/image-view.mm +142 -0
  80. package/native/appkit/input-replay.h +25 -0
  81. package/native/appkit/input-replay.mm +418 -0
  82. package/native/appkit/language-model.h +14 -0
  83. package/native/appkit/language-model.mm +99 -0
  84. package/native/appkit/language-model.swift +472 -0
  85. package/native/appkit/local-authentication.h +15 -0
  86. package/native/appkit/local-authentication.mm +133 -0
  87. package/native/appkit/location.h +16 -0
  88. package/native/appkit/location.mm +214 -0
  89. package/native/appkit/main.mm +1515 -0
  90. package/native/appkit/map-view.h +15 -0
  91. package/native/appkit/map-view.mm +109 -0
  92. package/native/appkit/maps.h +35 -0
  93. package/native/appkit/maps.mm +343 -0
  94. package/native/appkit/menu-bar.h +22 -0
  95. package/native/appkit/menu-bar.mm +208 -0
  96. package/native/appkit/modal-focus.h +16 -0
  97. package/native/appkit/modal-focus.mm +26 -0
  98. package/native/appkit/modal-host-view.h +79 -0
  99. package/native/appkit/modal-host-view.mm +442 -0
  100. package/native/appkit/native-controls.h +22 -0
  101. package/native/appkit/native-controls.mm +431 -0
  102. package/native/appkit/network-state.h +12 -0
  103. package/native/appkit/network-state.mm +64 -0
  104. package/native/appkit/network.h +14 -0
  105. package/native/appkit/network.mm +396 -0
  106. package/native/appkit/notifications.h +19 -0
  107. package/native/appkit/notifications.mm +309 -0
  108. package/native/appkit/photo-library.h +33 -0
  109. package/native/appkit/photo-library.mm +548 -0
  110. package/native/appkit/pointer-buttons.h +32 -0
  111. package/native/appkit/presentation-label.h +15 -0
  112. package/native/appkit/presentation-label.mm +12 -0
  113. package/native/appkit/presented-screen.h +19 -0
  114. package/native/appkit/presented-screen.mm +181 -0
  115. package/native/appkit/printing.h +42 -0
  116. package/native/appkit/printing.mm +393 -0
  117. package/native/appkit/push.h +19 -0
  118. package/native/appkit/push.mm +81 -0
  119. package/native/appkit/red-box.h +26 -0
  120. package/native/appkit/red-box.mm +387 -0
  121. package/native/appkit/screen-capture.h +21 -0
  122. package/native/appkit/screen-capture.mm +92 -0
  123. package/native/appkit/scroll-view.h +13 -0
  124. package/native/appkit/scroll-view.mm +251 -0
  125. package/native/appkit/scrollers.h +25 -0
  126. package/native/appkit/scrollers.mm +43 -0
  127. package/native/appkit/search-field.h +34 -0
  128. package/native/appkit/search-field.mm +291 -0
  129. package/native/appkit/search-toolbar-item.h +19 -0
  130. package/native/appkit/search-toolbar-item.mm +269 -0
  131. package/native/appkit/share-picker.h +34 -0
  132. package/native/appkit/share-picker.mm +121 -0
  133. package/native/appkit/split-view.h +77 -0
  134. package/native/appkit/split-view.mm +1206 -0
  135. package/native/appkit/store-review.h +13 -0
  136. package/native/appkit/store-review.mm +28 -0
  137. package/native/appkit/surface-view.h +45 -0
  138. package/native/appkit/surface-view.mm +558 -0
  139. package/native/appkit/svg-view.h +17 -0
  140. package/native/appkit/svg-view.mm +57 -0
  141. package/native/appkit/symbol-drawing.h +24 -0
  142. package/native/appkit/symbol-drawing.mm +117 -0
  143. package/native/appkit/symbol-view.h +8 -0
  144. package/native/appkit/symbol-view.mm +33 -0
  145. package/native/appkit/system-access.h +34 -0
  146. package/native/appkit/system-access.mm +210 -0
  147. package/native/appkit/system.h +24 -0
  148. package/native/appkit/system.mm +403 -0
  149. package/native/appkit/test-launch.h +36 -0
  150. package/native/appkit/test-launch.mm +115 -0
  151. package/native/appkit/text-input-field.h +76 -0
  152. package/native/appkit/text-input-field.mm +444 -0
  153. package/native/appkit/text-layout.h +58 -0
  154. package/native/appkit/text-layout.mm +477 -0
  155. package/native/appkit/text-recognition.h +13 -0
  156. package/native/appkit/text-recognition.mm +102 -0
  157. package/native/appkit/tracking.h +13 -0
  158. package/native/appkit/tracking.mm +51 -0
  159. package/native/appkit/tray-and-dock.h +45 -0
  160. package/native/appkit/tray-and-dock.mm +130 -0
  161. package/native/appkit/undo.h +23 -0
  162. package/native/appkit/undo.mm +125 -0
  163. package/native/appkit/updates.h +17 -0
  164. package/native/appkit/updates.mm +71 -0
  165. package/native/appkit/video-view.h +10 -0
  166. package/native/appkit/video-view.mm +42 -0
  167. package/native/appkit/video.h +38 -0
  168. package/native/appkit/video.mm +404 -0
  169. package/native/appkit/web-browser.h +12 -0
  170. package/native/appkit/web-browser.mm +97 -0
  171. package/native/appkit/web-view-component.h +9 -0
  172. package/native/appkit/web-view-component.mm +56 -0
  173. package/native/appkit/web-view.h +31 -0
  174. package/native/appkit/web-view.mm +394 -0
  175. package/native/cmake/libraries/react-native-reanimated.cmake +45 -0
  176. package/native/cmake/libraries/react-native-worklets.cmake +46 -0
  177. package/native/cmake/libraries.cmake +109 -0
  178. package/native/cmake/linked-modules.cmake +112 -0
  179. package/native/cmake/react-native.cmake +175 -0
  180. package/native/cmake/runtime-dependencies.cmake +34 -0
  181. package/native/cmake/swift.cmake +43 -0
  182. package/native/cmake/third-party.cmake +74 -0
  183. package/native/core/include/ngn/absent-views.h +27 -0
  184. package/native/core/include/ngn/accessibility.h +140 -0
  185. package/native/core/include/ngn/address-search.h +69 -0
  186. package/native/core/include/ngn/animation-frames.h +39 -0
  187. package/native/core/include/ngn/app-info.h +52 -0
  188. package/native/core/include/ngn/app-menus.h +146 -0
  189. package/native/core/include/ngn/app-windows.h +181 -0
  190. package/native/core/include/ngn/apple-authentication.h +116 -0
  191. package/native/core/include/ngn/asset.h +28 -0
  192. package/native/core/include/ngn/audio.h +125 -0
  193. package/native/core/include/ngn/back-swipe.h +112 -0
  194. package/native/core/include/ngn/battery.h +48 -0
  195. package/native/core/include/ngn/bytes.h +59 -0
  196. package/native/core/include/ngn/calendar.h +180 -0
  197. package/native/core/include/ngn/camera.h +128 -0
  198. package/native/core/include/ngn/control-sizes.h +111 -0
  199. package/native/core/include/ngn/core-modules.h +105 -0
  200. package/native/core/include/ngn/crypto.h +38 -0
  201. package/native/core/include/ngn/default-menu.h +91 -0
  202. package/native/core/include/ngn/desktop-expo.h +193 -0
  203. package/native/core/include/ngn/desktop-modal.h +109 -0
  204. package/native/core/include/ngn/desktop-props.h +75 -0
  205. package/native/core/include/ngn/desktop-view-props.h +110 -0
  206. package/native/core/include/ngn/dev-server.h +33 -0
  207. package/native/core/include/ngn/download.h +24 -0
  208. package/native/core/include/ngn/expo-image.h +192 -0
  209. package/native/core/include/ngn/expo-ui.h +133 -0
  210. package/native/core/include/ngn/file-system.h +274 -0
  211. package/native/core/include/ngn/focus-order.h +63 -0
  212. package/native/core/include/ngn/fonts.h +64 -0
  213. package/native/core/include/ngn/gestures.h +305 -0
  214. package/native/core/include/ngn/glass.h +67 -0
  215. package/native/core/include/ngn/header-bar.h +112 -0
  216. package/native/core/include/ngn/host-state.h +243 -0
  217. package/native/core/include/ngn/image-manipulator.h +70 -0
  218. package/native/core/include/ngn/input-dispatcher.h +211 -0
  219. package/native/core/include/ngn/input-script.h +56 -0
  220. package/native/core/include/ngn/input.h +112 -0
  221. package/native/core/include/ngn/key-value-store.h +41 -0
  222. package/native/core/include/ngn/language-model.h +69 -0
  223. package/native/core/include/ngn/launch-frame.h +47 -0
  224. package/native/core/include/ngn/launch-settings.h +98 -0
  225. package/native/core/include/ngn/layout-animations.h +24 -0
  226. package/native/core/include/ngn/library-components.h +13 -0
  227. package/native/core/include/ngn/library-glue.h +53 -0
  228. package/native/core/include/ngn/live-regions.h +54 -0
  229. package/native/core/include/ngn/local-authentication.h +74 -0
  230. package/native/core/include/ngn/location.h +89 -0
  231. package/native/core/include/ngn/maps.h +226 -0
  232. package/native/core/include/ngn/module-registry.h +51 -0
  233. package/native/core/include/ngn/mounting-backend.h +96 -0
  234. package/native/core/include/ngn/mounting-manager.h +155 -0
  235. package/native/core/include/ngn/native-controls.h +161 -0
  236. package/native/core/include/ngn/native-module.h +109 -0
  237. package/native/core/include/ngn/network-state.h +44 -0
  238. package/native/core/include/ngn/network.h +100 -0
  239. package/native/core/include/ngn/notifications.h +185 -0
  240. package/native/core/include/ngn/photo-library.h +130 -0
  241. package/native/core/include/ngn/printing.h +69 -0
  242. package/native/core/include/ngn/processes.h +114 -0
  243. package/native/core/include/ngn/red-box.h +119 -0
  244. package/native/core/include/ngn/reload-thread.h +258 -0
  245. package/native/core/include/ngn/runtime.h +161 -0
  246. package/native/core/include/ngn/safe-areas.h +77 -0
  247. package/native/core/include/ngn/screen-capture.h +35 -0
  248. package/native/core/include/ngn/screen-presentation.h +85 -0
  249. package/native/core/include/ngn/screen-stacks.h +80 -0
  250. package/native/core/include/ngn/scrollers.h +106 -0
  251. package/native/core/include/ngn/sharing.h +39 -0
  252. package/native/core/include/ngn/spawn-rules.h +78 -0
  253. package/native/core/include/ngn/splash-screen.h +41 -0
  254. package/native/core/include/ngn/split-view.h +270 -0
  255. package/native/core/include/ngn/sqlite.h +38 -0
  256. package/native/core/include/ngn/store-review.h +26 -0
  257. package/native/core/include/ngn/surface-book.h +101 -0
  258. package/native/core/include/ngn/svg.h +393 -0
  259. package/native/core/include/ngn/symbol.h +90 -0
  260. package/native/core/include/ngn/system.h +102 -0
  261. package/native/core/include/ngn/tabs-host.h +171 -0
  262. package/native/core/include/ngn/text-input.h +125 -0
  263. package/native/core/include/ngn/text-measurer.h +38 -0
  264. package/native/core/include/ngn/text-recognition.h +55 -0
  265. package/native/core/include/ngn/tracking.h +34 -0
  266. package/native/core/include/ngn/tray-and-dock.h +107 -0
  267. package/native/core/include/ngn/undo.h +37 -0
  268. package/native/core/include/ngn/updates.h +253 -0
  269. package/native/core/include/ngn/video.h +126 -0
  270. package/native/core/include/ngn/view-box.h +126 -0
  271. package/native/core/include/ngn/view-transform.h +26 -0
  272. package/native/core/include/ngn/view-tree.h +85 -0
  273. package/native/core/include/ngn/web-browser.h +45 -0
  274. package/native/core/include/ngn/web-view.h +133 -0
  275. package/native/core/include/ngn/worklet-host.h +98 -0
  276. package/native/core/src/absent-views.cpp +41 -0
  277. package/native/core/src/accessibility.cpp +374 -0
  278. package/native/core/src/animation-frames.cpp +49 -0
  279. package/native/core/src/app-menus.cpp +352 -0
  280. package/native/core/src/app-windows.cpp +444 -0
  281. package/native/core/src/back-swipe.cpp +91 -0
  282. package/native/core/src/bytes.cpp +158 -0
  283. package/native/core/src/control-sizes.cpp +232 -0
  284. package/native/core/src/default-menu.cpp +96 -0
  285. package/native/core/src/desktop-modal.cpp +162 -0
  286. package/native/core/src/desktop-view-props.cpp +80 -0
  287. package/native/core/src/dev-server-helper.cpp +152 -0
  288. package/native/core/src/dev-server.cpp +103 -0
  289. package/native/core/src/download.cpp +53 -0
  290. package/native/core/src/expo-image.cpp +548 -0
  291. package/native/core/src/expo-ui.cpp +203 -0
  292. package/native/core/src/focus-order.cpp +441 -0
  293. package/native/core/src/gestures.cpp +1806 -0
  294. package/native/core/src/glass.cpp +49 -0
  295. package/native/core/src/header-bar.cpp +104 -0
  296. package/native/core/src/host-services.cpp +50 -0
  297. package/native/core/src/host-state.cpp +61 -0
  298. package/native/core/src/input-dispatcher.cpp +727 -0
  299. package/native/core/src/input-script.cpp +123 -0
  300. package/native/core/src/key-value-store.cpp +169 -0
  301. package/native/core/src/launch-settings.cpp +148 -0
  302. package/native/core/src/layout-animations.cpp +62 -0
  303. package/native/core/src/libraries/RNCWebViewSpec.cpp +80 -0
  304. package/native/core/src/libraries/react-native-reanimated.cpp +216 -0
  305. package/native/core/src/libraries/react-native-worklets.cpp +192 -0
  306. package/native/core/src/libraries/rnscreens.cpp +125 -0
  307. package/native/core/src/libraries/rnsvg.cpp +345 -0
  308. package/native/core/src/libraries/safeareacontext.cpp +70 -0
  309. package/native/core/src/libraries/worklets-idle-frames.js +70 -0
  310. package/native/core/src/library-glue.cpp +35 -0
  311. package/native/core/src/live-regions.cpp +122 -0
  312. package/native/core/src/module-registry.cpp +50 -0
  313. package/native/core/src/modules/accessibility-manager.cpp +98 -0
  314. package/native/core/src/modules/address-search.cpp +219 -0
  315. package/native/core/src/modules/alert-manager.cpp +140 -0
  316. package/native/core/src/modules/app-info.cpp +74 -0
  317. package/native/core/src/modules/app-modules.cpp +405 -0
  318. package/native/core/src/modules/apple-authentication.cpp +188 -0
  319. package/native/core/src/modules/asset.cpp +111 -0
  320. package/native/core/src/modules/async-storage.cpp +192 -0
  321. package/native/core/src/modules/audio.cpp +541 -0
  322. package/native/core/src/modules/battery.cpp +88 -0
  323. package/native/core/src/modules/calendar.cpp +457 -0
  324. package/native/core/src/modules/camera.cpp +221 -0
  325. package/native/core/src/modules/core-modules.cpp +62 -0
  326. package/native/core/src/modules/crypto.cpp +117 -0
  327. package/native/core/src/modules/desktop-expo.cpp +527 -0
  328. package/native/core/src/modules/file-system.cpp +941 -0
  329. package/native/core/src/modules/fonts.cpp +163 -0
  330. package/native/core/src/modules/image-loader.cpp +105 -0
  331. package/native/core/src/modules/image-manipulator.cpp +305 -0
  332. package/native/core/src/modules/language-model.cpp +195 -0
  333. package/native/core/src/modules/local-authentication.cpp +140 -0
  334. package/native/core/src/modules/location.cpp +186 -0
  335. package/native/core/src/modules/maps.cpp +500 -0
  336. package/native/core/src/modules/network-state.cpp +72 -0
  337. package/native/core/src/modules/networking.cpp +387 -0
  338. package/native/core/src/modules/notifications.cpp +549 -0
  339. package/native/core/src/modules/photo-library.cpp +371 -0
  340. package/native/core/src/modules/printing.cpp +201 -0
  341. package/native/core/src/modules/screen-capture.cpp +71 -0
  342. package/native/core/src/modules/sharing.cpp +59 -0
  343. package/native/core/src/modules/splash-screen.cpp +70 -0
  344. package/native/core/src/modules/sqlite.cpp +421 -0
  345. package/native/core/src/modules/store-review.cpp +23 -0
  346. package/native/core/src/modules/text-recognition.cpp +107 -0
  347. package/native/core/src/modules/tracking.cpp +46 -0
  348. package/native/core/src/modules/undo.cpp +59 -0
  349. package/native/core/src/modules/video.cpp +366 -0
  350. package/native/core/src/modules/web-browser.cpp +100 -0
  351. package/native/core/src/modules/web-socket.cpp +266 -0
  352. package/native/core/src/mounting-manager.cpp +380 -0
  353. package/native/core/src/native-controls.cpp +129 -0
  354. package/native/core/src/native-module.cpp +250 -0
  355. package/native/core/src/network.cpp +219 -0
  356. package/native/core/src/posix-launcher.cpp +366 -0
  357. package/native/core/src/processes.cpp +324 -0
  358. package/native/core/src/red-box-errors.js +83 -0
  359. package/native/core/src/red-box.cpp +306 -0
  360. package/native/core/src/runtime.cpp +422 -0
  361. package/native/core/src/safe-areas.cpp +130 -0
  362. package/native/core/src/screen-presentation.cpp +61 -0
  363. package/native/core/src/screen-stacks.cpp +254 -0
  364. package/native/core/src/scrollers.cpp +181 -0
  365. package/native/core/src/spawn-rules.cpp +292 -0
  366. package/native/core/src/split-view.cpp +343 -0
  367. package/native/core/src/svg.cpp +1883 -0
  368. package/native/core/src/symbol.cpp +94 -0
  369. package/native/core/src/tabs-host.cpp +234 -0
  370. package/native/core/src/text-input.cpp +126 -0
  371. package/native/core/src/text-layout-manager.cpp +63 -0
  372. package/native/core/src/tray-and-dock.cpp +154 -0
  373. package/native/core/src/updates.cpp +965 -0
  374. package/native/core/src/view-box.cpp +788 -0
  375. package/native/core/src/view-transform.cpp +45 -0
  376. package/native/core/src/view-tree.cpp +234 -0
  377. package/native/core/src/web-view.cpp +143 -0
  378. package/native/core/src/worklet-host.cpp +10 -0
  379. package/native/scripts/build-hermes.sh +44 -0
  380. package/native/scripts/build.sh +171 -0
  381. package/native/scripts/cache-dir.sh +18 -0
  382. package/native/scripts/codegen-library.sh +193 -0
  383. package/native/scripts/compiler-launcher.sh +17 -0
  384. package/native/scripts/fetch.sh +174 -0
  385. package/native/scripts/hermes-built.sh +10 -0
  386. package/native/scripts/host-dir.sh +16 -0
  387. package/native/scripts/macos-target.sh +8 -0
  388. package/native/scripts/make-prebuilt.mjs +360 -0
  389. package/native/scripts/prebuilt-host-cache.mjs +158 -0
  390. package/native/shim/openssl/sha.h +22 -0
  391. package/native/shim/view-platform/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +37 -0
  392. package/package.json +73 -1
  393. package/prebuilt.json +33 -0
@@ -0,0 +1,1883 @@
1
+ #include "ngn/svg.h"
2
+
3
+ #include "ngn/library-glue.h"
4
+
5
+ #include <algorithm>
6
+ #include <cctype>
7
+ #include <cmath>
8
+ #include <cstdlib>
9
+ #include <tuple>
10
+ #include <unordered_map>
11
+ #include <unordered_set>
12
+ #include <vector>
13
+
14
+ namespace ngn {
15
+
16
+ // --- geometry ------------------------------------------------------------------------------------
17
+
18
+ SvgMatrix SvgMatrix::operator*(const SvgMatrix &m) const {
19
+ return {
20
+ a * m.a + c * m.b,
21
+ b * m.a + d * m.b,
22
+ a * m.c + c * m.d,
23
+ b * m.c + d * m.d,
24
+ a * m.e + c * m.f + e,
25
+ b * m.e + d * m.f + f,
26
+ };
27
+ }
28
+
29
+ std::pair<double, double> SvgMatrix::apply(double x, double y) const {
30
+ return {a * x + c * y + e, b * x + d * y + f};
31
+ }
32
+
33
+ void SvgPath::moveTo(double x, double y) {
34
+ segments.push_back({Op::Move, {x, y}});
35
+ }
36
+
37
+ void SvgPath::lineTo(double x, double y) {
38
+ segments.push_back({Op::Line, {x, y}});
39
+ }
40
+
41
+ void SvgPath::cubicTo(double x1, double y1, double x2, double y2, double x, double y) {
42
+ segments.push_back({Op::Cubic, {x1, y1, x2, y2, x, y}});
43
+ }
44
+
45
+ void SvgPath::close() {
46
+ segments.push_back({Op::Close, {}});
47
+ }
48
+
49
+ void SvgPath::append(const SvgPath &other, const SvgMatrix &t) {
50
+ for (auto s : other.segments) {
51
+ int points = s.op == Op::Cubic ? 3 : s.op == Op::Close ? 0 : 1;
52
+ for (int i = 0; i < points; ++i) {
53
+ auto [x, y] = t.apply(s.points[i * 2], s.points[i * 2 + 1]);
54
+ s.points[i * 2] = x;
55
+ s.points[i * 2 + 1] = y;
56
+ }
57
+ segments.push_back(s);
58
+ }
59
+ }
60
+
61
+ std::optional<SvgRect> SvgPath::bounds() const {
62
+ bool any = false;
63
+ double minX = 0, minY = 0, maxX = 0, maxY = 0;
64
+ auto add = [&](double x, double y) {
65
+ if (!any) {
66
+ minX = maxX = x;
67
+ minY = maxY = y;
68
+ any = true;
69
+ }
70
+ minX = std::min(minX, x);
71
+ maxX = std::max(maxX, x);
72
+ minY = std::min(minY, y);
73
+ maxY = std::max(maxY, y);
74
+ };
75
+ // A cubic's extremes along one axis inside the curve, where its derivative is zero: the control
76
+ // points themselves are off the curve and outside the bounds.
77
+ auto extremes = [](double p0, double p1, double p2, double p3) {
78
+ std::vector<double> ts;
79
+ double a = -p0 + 3 * p1 - 3 * p2 + p3, b = 2 * (p0 - 2 * p1 + p2), c = p1 - p0;
80
+ auto inside = [&](double t) {
81
+ if (t > 0 && t < 1) {
82
+ ts.push_back(t);
83
+ }
84
+ };
85
+ if (std::fabs(a) < 1e-12) {
86
+ if (std::fabs(b) > 1e-12) {
87
+ inside(-c / b);
88
+ }
89
+ } else if (double d = b * b - 4 * a * c; d >= 0) {
90
+ inside((-b + std::sqrt(d)) / (2 * a));
91
+ inside((-b - std::sqrt(d)) / (2 * a));
92
+ }
93
+ return ts;
94
+ };
95
+ auto at = [](double t, double p0, double p1, double p2, double p3) {
96
+ double u = 1 - t;
97
+ return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3;
98
+ };
99
+ double x = 0, y = 0, startX = 0, startY = 0;
100
+ for (const auto &s : segments) {
101
+ const auto &p = s.points;
102
+ switch (s.op) {
103
+ case Op::Move:
104
+ startX = x = p[0];
105
+ startY = y = p[1];
106
+ add(x, y);
107
+ break;
108
+ case Op::Line:
109
+ x = p[0];
110
+ y = p[1];
111
+ add(x, y);
112
+ break;
113
+ case Op::Cubic:
114
+ for (double t : extremes(x, p[0], p[2], p[4])) {
115
+ add(at(t, x, p[0], p[2], p[4]), at(t, y, p[1], p[3], p[5]));
116
+ }
117
+ for (double t : extremes(y, p[1], p[3], p[5])) {
118
+ add(at(t, x, p[0], p[2], p[4]), at(t, y, p[1], p[3], p[5]));
119
+ }
120
+ x = p[4];
121
+ y = p[5];
122
+ add(x, y);
123
+ break;
124
+ case Op::Close:
125
+ x = startX;
126
+ y = startY;
127
+ break;
128
+ }
129
+ }
130
+ if (!any) {
131
+ return std::nullopt;
132
+ }
133
+ return SvgRect{minX, minY, maxX - minX, maxY - minY};
134
+ }
135
+
136
+ namespace {
137
+
138
+ constexpr double kPi = 3.14159265358979323846;
139
+
140
+ // Path data's numbers and flags, as SVG's grammar reads them.
141
+ class PathScanner {
142
+ public:
143
+ explicit PathScanner(const std::string &d) : d_(d) {}
144
+
145
+ void skipSeparators() {
146
+ while (i_ < d_.size() && (std::isspace(static_cast<unsigned char>(d_[i_])) || d_[i_] == ',')) {
147
+ ++i_;
148
+ }
149
+ }
150
+
151
+ bool atEnd() {
152
+ skipSeparators();
153
+ return i_ >= d_.size();
154
+ }
155
+
156
+ bool atNumber() {
157
+ skipSeparators();
158
+ if (i_ >= d_.size()) {
159
+ return false;
160
+ }
161
+ char c = d_[i_];
162
+ return std::isdigit(static_cast<unsigned char>(c)) || c == '-' || c == '+' || c == '.';
163
+ }
164
+
165
+ std::optional<char> command() {
166
+ skipSeparators();
167
+ if (i_ >= d_.size() || !std::isalpha(static_cast<unsigned char>(d_[i_]))) {
168
+ return std::nullopt;
169
+ }
170
+ return d_[i_++];
171
+ }
172
+
173
+ std::optional<double> number() {
174
+ skipSeparators();
175
+ size_t start = i_;
176
+ if (i_ < d_.size() && (d_[i_] == '-' || d_[i_] == '+')) {
177
+ ++i_;
178
+ }
179
+ bool digits = false;
180
+ while (i_ < d_.size() && std::isdigit(static_cast<unsigned char>(d_[i_]))) {
181
+ ++i_;
182
+ digits = true;
183
+ }
184
+ if (i_ < d_.size() && d_[i_] == '.') {
185
+ ++i_;
186
+ while (i_ < d_.size() && std::isdigit(static_cast<unsigned char>(d_[i_]))) {
187
+ ++i_;
188
+ digits = true;
189
+ }
190
+ }
191
+ if (!digits) {
192
+ i_ = start;
193
+ return std::nullopt;
194
+ }
195
+ if (i_ < d_.size() && (d_[i_] == 'e' || d_[i_] == 'E')) {
196
+ size_t mark = i_++;
197
+ if (i_ < d_.size() && (d_[i_] == '-' || d_[i_] == '+')) {
198
+ ++i_;
199
+ }
200
+ if (i_ < d_.size() && std::isdigit(static_cast<unsigned char>(d_[i_]))) {
201
+ while (i_ < d_.size() && std::isdigit(static_cast<unsigned char>(d_[i_]))) {
202
+ ++i_;
203
+ }
204
+ } else {
205
+ i_ = mark;
206
+ }
207
+ }
208
+ return std::strtod(d_.substr(start, i_ - start).c_str(), nullptr);
209
+ }
210
+
211
+ // An arc's flag: one character, 0 or 1, which may run into the next number.
212
+ std::optional<bool> flag() {
213
+ skipSeparators();
214
+ if (i_ < d_.size() && (d_[i_] == '0' || d_[i_] == '1')) {
215
+ return d_[i_++] == '1';
216
+ }
217
+ return std::nullopt;
218
+ }
219
+
220
+ private:
221
+ const std::string &d_;
222
+ size_t i_{0};
223
+ };
224
+
225
+ double angleBetween(double ux, double uy, double vx, double vy) {
226
+ double sign = ux * vy - uy * vx < 0 ? -1 : 1;
227
+ double dot = ux * vx + uy * vy;
228
+ double length = std::hypot(ux, uy) * std::hypot(vx, vy);
229
+ return sign * std::acos(std::clamp(dot / length, -1.0, 1.0));
230
+ }
231
+
232
+ // SVG's endpoint arc as cubics (SVG 1.1 implementation notes F.6.5 and F.6.6).
233
+ void arcTo(SvgPath &path, double x0, double y0, double rx, double ry, double degrees, bool large, bool sweep, double x, double y) {
234
+ if (x0 == x && y0 == y) {
235
+ return;
236
+ }
237
+ rx = std::fabs(rx);
238
+ ry = std::fabs(ry);
239
+ if (rx == 0 || ry == 0) {
240
+ path.lineTo(x, y);
241
+ return;
242
+ }
243
+ double phi = degrees * kPi / 180;
244
+ double cosPhi = std::cos(phi), sinPhi = std::sin(phi);
245
+ double dx = (x0 - x) / 2, dy = (y0 - y) / 2;
246
+ double x1p = cosPhi * dx + sinPhi * dy;
247
+ double y1p = -sinPhi * dx + cosPhi * dy;
248
+ double lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
249
+ if (lambda > 1) {
250
+ double s = std::sqrt(lambda);
251
+ rx *= s;
252
+ ry *= s;
253
+ }
254
+ double num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
255
+ double den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
256
+ double coef = (large == sweep ? -1 : 1) * std::sqrt(std::max(0.0, num / den));
257
+ double cxp = coef * rx * y1p / ry;
258
+ double cyp = -coef * ry * x1p / rx;
259
+ double cx = cosPhi * cxp - sinPhi * cyp + (x0 + x) / 2;
260
+ double cy = sinPhi * cxp + cosPhi * cyp + (y0 + y) / 2;
261
+ double theta = angleBetween(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
262
+ double delta = angleBetween((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
263
+ if (!sweep && delta > 0) {
264
+ delta -= 2 * kPi;
265
+ } else if (sweep && delta < 0) {
266
+ delta += 2 * kPi;
267
+ }
268
+ int pieces = std::max(1, static_cast<int>(std::ceil(std::fabs(delta) / (kPi / 2) - 1e-9)));
269
+ double step = delta / pieces;
270
+ double k = 4.0 / 3.0 * std::tan(step / 4);
271
+ auto point = [&](double angle) {
272
+ double px = rx * std::cos(angle), py = ry * std::sin(angle);
273
+ return std::pair<double, double>{cosPhi * px - sinPhi * py + cx, sinPhi * px + cosPhi * py + cy};
274
+ };
275
+ double angle = theta;
276
+ for (int i = 0; i < pieces; ++i) {
277
+ double next = angle + step;
278
+ // The controls in the ellipse's own frame, then rotated and moved like its points.
279
+ double ax = rx * std::cos(angle) - k * rx * std::sin(angle);
280
+ double ay = ry * std::sin(angle) + k * ry * std::cos(angle);
281
+ double bx = rx * std::cos(next) + k * rx * std::sin(next);
282
+ double by = ry * std::sin(next) - k * ry * std::cos(next);
283
+ bool last = i == pieces - 1;
284
+ auto end = last ? std::pair<double, double>{x, y} : point(next);
285
+ path.cubicTo(
286
+ cosPhi * ax - sinPhi * ay + cx,
287
+ sinPhi * ax + cosPhi * ay + cy,
288
+ cosPhi * bx - sinPhi * by + cx,
289
+ sinPhi * bx + cosPhi * by + cy,
290
+ end.first,
291
+ end.second);
292
+ angle = next;
293
+ }
294
+ }
295
+
296
+ } // namespace
297
+
298
+ SvgPath parseSvgPath(const std::string &d) {
299
+ SvgPath path;
300
+ PathScanner in(d);
301
+ double x = 0, y = 0, startX = 0, startY = 0;
302
+ // The last curve's second control point, for a smooth curve's reflection.
303
+ double lastCx = 0, lastCy = 0;
304
+ char lastCommand = 0;
305
+ bool closed = false;
306
+ std::optional<char> command;
307
+ while (!in.atEnd()) {
308
+ if (auto next = in.command()) {
309
+ command = next;
310
+ } else if (!command || !in.atNumber()) {
311
+ break;
312
+ } else if (*command == 'M') {
313
+ command = 'L';
314
+ } else if (*command == 'm') {
315
+ command = 'l';
316
+ }
317
+ char c = *command;
318
+ char upper = static_cast<char>(std::toupper(c));
319
+ bool relative = c != upper;
320
+ double ox = relative ? x : 0, oy = relative ? y : 0;
321
+ if (path.empty() && upper != 'M') {
322
+ break;
323
+ }
324
+ if (upper == 'Z') {
325
+ path.close();
326
+ x = startX;
327
+ y = startY;
328
+ closed = true;
329
+ lastCommand = 'Z';
330
+ // Z takes no numbers, so a number after it is an error that ends the path.
331
+ command.reset();
332
+ continue;
333
+ }
334
+ // A drawing command right after a close starts a new subpath where the closed one started.
335
+ if (closed && upper != 'M') {
336
+ path.moveTo(x, y);
337
+ }
338
+ closed = false;
339
+ auto n = [&]() { return in.number(); };
340
+ bool ok = true;
341
+ switch (upper) {
342
+ case 'M': {
343
+ auto px = n(), py = n();
344
+ if (!px || !py) {
345
+ ok = false;
346
+ break;
347
+ }
348
+ // A relative move after a close starts from the closed subpath's start.
349
+ x = ox + *px;
350
+ y = oy + *py;
351
+ startX = x;
352
+ startY = y;
353
+ path.moveTo(x, y);
354
+ break;
355
+ }
356
+ case 'L': {
357
+ auto px = n(), py = n();
358
+ if (!px || !py) {
359
+ ok = false;
360
+ break;
361
+ }
362
+ x = ox + *px;
363
+ y = oy + *py;
364
+ path.lineTo(x, y);
365
+ break;
366
+ }
367
+ case 'H': {
368
+ auto px = n();
369
+ if (!px) {
370
+ ok = false;
371
+ break;
372
+ }
373
+ x = ox + *px;
374
+ path.lineTo(x, y);
375
+ break;
376
+ }
377
+ case 'V': {
378
+ auto py = n();
379
+ if (!py) {
380
+ ok = false;
381
+ break;
382
+ }
383
+ y = oy + *py;
384
+ path.lineTo(x, y);
385
+ break;
386
+ }
387
+ case 'C':
388
+ case 'S': {
389
+ double x1, y1;
390
+ if (upper == 'C') {
391
+ auto a = n(), b = n();
392
+ if (!a || !b) {
393
+ ok = false;
394
+ break;
395
+ }
396
+ x1 = ox + *a;
397
+ y1 = oy + *b;
398
+ } else {
399
+ bool after = lastCommand == 'C' || lastCommand == 'S';
400
+ x1 = after ? 2 * x - lastCx : x;
401
+ y1 = after ? 2 * y - lastCy : y;
402
+ }
403
+ auto a = n(), b = n(), e = n(), f = n();
404
+ if (!a || !b || !e || !f) {
405
+ ok = false;
406
+ break;
407
+ }
408
+ lastCx = ox + *a;
409
+ lastCy = oy + *b;
410
+ x = ox + *e;
411
+ y = oy + *f;
412
+ path.cubicTo(x1, y1, lastCx, lastCy, x, y);
413
+ break;
414
+ }
415
+ case 'Q':
416
+ case 'T': {
417
+ double qx, qy;
418
+ if (upper == 'Q') {
419
+ auto a = n(), b = n();
420
+ if (!a || !b) {
421
+ ok = false;
422
+ break;
423
+ }
424
+ qx = ox + *a;
425
+ qy = oy + *b;
426
+ } else {
427
+ bool after = lastCommand == 'Q' || lastCommand == 'T';
428
+ qx = after ? 2 * x - lastCx : x;
429
+ qy = after ? 2 * y - lastCy : y;
430
+ }
431
+ auto e = n(), f = n();
432
+ if (!e || !f) {
433
+ ok = false;
434
+ break;
435
+ }
436
+ double ex = ox + *e, ey = oy + *f;
437
+ path.cubicTo(x + 2.0 / 3 * (qx - x), y + 2.0 / 3 * (qy - y), ex + 2.0 / 3 * (qx - ex), ey + 2.0 / 3 * (qy - ey), ex, ey);
438
+ // A quadratic's control, which a smooth quadratic reflects.
439
+ lastCx = qx;
440
+ lastCy = qy;
441
+ x = ex;
442
+ y = ey;
443
+ break;
444
+ }
445
+ case 'A': {
446
+ auto rx = n(), ry = n(), rotation = n();
447
+ auto large = in.flag();
448
+ auto sweep = in.flag();
449
+ auto ex = n(), ey = n();
450
+ if (!rx || !ry || !rotation || !large || !sweep || !ex || !ey) {
451
+ ok = false;
452
+ break;
453
+ }
454
+ double tx = ox + *ex, ty = oy + *ey;
455
+ arcTo(path, x, y, *rx, *ry, *rotation, *large, *sweep, tx, ty);
456
+ x = tx;
457
+ y = ty;
458
+ break;
459
+ }
460
+ default:
461
+ ok = false;
462
+ }
463
+ if (!ok) {
464
+ break;
465
+ }
466
+ lastCommand = upper;
467
+ }
468
+ return path;
469
+ }
470
+
471
+ // --- props ---------------------------------------------------------------------------------------
472
+
473
+ SvgLength svgLength(const folly::dynamic &value) {
474
+ if (value.isNumber()) {
475
+ return {.value = value.asDouble(), .set = true};
476
+ }
477
+ if (!value.isString()) {
478
+ return {};
479
+ }
480
+ const auto &text = value.getString();
481
+ const char *begin = text.c_str();
482
+ char *end = nullptr;
483
+ double number = std::strtod(begin, &end);
484
+ if (end == begin) {
485
+ return {};
486
+ }
487
+ std::string unit(end);
488
+ unit.erase(std::remove_if(unit.begin(), unit.end(), [](unsigned char c) { return std::isspace(c); }), unit.end());
489
+ if (unit == "%") {
490
+ return {.value = number, .unit = SvgLength::Unit::Percent, .set = true};
491
+ }
492
+ if (unit == "em") {
493
+ return {.value = number, .unit = SvgLength::Unit::Em, .set = true};
494
+ }
495
+ // Absolute units at CSS's 96 to the inch, which is one user unit per px.
496
+ static const std::map<std::string, double> absolute = {
497
+ {"", 1}, {"px", 1}, {"pt", 4.0 / 3}, {"pc", 16}, {"in", 96}, {"cm", 96 / 2.54}, {"mm", 96 / 25.4}};
498
+ auto found = absolute.find(unit);
499
+ if (found == absolute.end()) {
500
+ return {};
501
+ }
502
+ return {.value = number * found->second, .set = true};
503
+ }
504
+
505
+ std::vector<SvgLength> svgLengths(const folly::dynamic &value) {
506
+ std::vector<SvgLength> out;
507
+ if (value.isArray()) {
508
+ for (const auto &item : value) {
509
+ auto length = svgLength(item);
510
+ if (length.set) {
511
+ out.push_back(length);
512
+ }
513
+ }
514
+ } else if (auto length = svgLength(value); length.set) {
515
+ out.push_back(length);
516
+ }
517
+ return out;
518
+ }
519
+
520
+ SvgBrush svgBrush(const folly::dynamic &value) {
521
+ if (value.isNumber()) {
522
+ return {.type = SvgBrush::Type::Color, .argb = static_cast<uint32_t>(value.asInt())};
523
+ }
524
+ if (!value.isObject()) {
525
+ return {};
526
+ }
527
+ auto type = value.getDefault("type", -1);
528
+ int kind = type.isNumber() ? static_cast<int>(type.asInt()) : -1;
529
+ if (kind == 0) {
530
+ auto payload = value.getDefault("payload", nullptr);
531
+ if (!payload.isNumber()) {
532
+ return {.type = SvgBrush::Type::None};
533
+ }
534
+ return {.type = SvgBrush::Type::Color, .argb = static_cast<uint32_t>(static_cast<int64_t>(payload.asDouble()))};
535
+ }
536
+ if (kind == 1) {
537
+ auto ref = value.getDefault("brushRef", "");
538
+ return {.type = SvgBrush::Type::Ref, .ref = ref.isString() ? ref.getString() : ""};
539
+ }
540
+ if (kind == 2) {
541
+ return {.type = SvgBrush::Type::CurrentColor};
542
+ }
543
+ return {.type = SvgBrush::Type::None};
544
+ }
545
+
546
+ SvgMatrix svgViewBoxTransform(const SvgRect &box, const std::string &align, int meetOrSlice, double width, double height) {
547
+ if (box.width <= 0 || box.height <= 0) {
548
+ return {};
549
+ }
550
+ double sx = width / box.width, sy = height / box.height;
551
+ if (align == "none") {
552
+ return SvgMatrix{sx, 0, 0, sy, -box.x * sx, -box.y * sy};
553
+ }
554
+ double s = meetOrSlice == 1 ? std::max(sx, sy) : std::min(sx, sy);
555
+ std::string a = align.empty() ? "xMidYMid" : align;
556
+ double tx = -box.x * s, ty = -box.y * s;
557
+ double extraX = width - box.width * s, extraY = height - box.height * s;
558
+ if (a.find("xMid") != std::string::npos) {
559
+ tx += extraX / 2;
560
+ } else if (a.find("xMax") != std::string::npos) {
561
+ tx += extraX;
562
+ }
563
+ if (a.find("YMid") != std::string::npos) {
564
+ ty += extraY / 2;
565
+ } else if (a.find("YMax") != std::string::npos) {
566
+ ty += extraY;
567
+ }
568
+ return SvgMatrix{s, 0, 0, s, tx, ty};
569
+ }
570
+
571
+ // --- drawing -------------------------------------------------------------------------------------
572
+
573
+ namespace {
574
+
575
+ bool isIdentity(const SvgMatrix &m) {
576
+ return m == SvgMatrix{};
577
+ }
578
+
579
+ SvgPath rectPath(double x, double y, double w, double h) {
580
+ SvgPath p;
581
+ p.moveTo(x, y);
582
+ p.lineTo(x + w, y);
583
+ p.lineTo(x + w, y + h);
584
+ p.lineTo(x, y + h);
585
+ p.close();
586
+ return p;
587
+ }
588
+
589
+ // The magic number for a quarter ellipse as a cubic.
590
+ constexpr double kQuarter = 0.5522847498307936;
591
+
592
+ SvgPath ellipsePath(double cx, double cy, double rx, double ry) {
593
+ SvgPath p;
594
+ double kx = rx * kQuarter, ky = ry * kQuarter;
595
+ p.moveTo(cx + rx, cy);
596
+ p.cubicTo(cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry);
597
+ p.cubicTo(cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy);
598
+ p.cubicTo(cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry);
599
+ p.cubicTo(cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy);
600
+ p.close();
601
+ return p;
602
+ }
603
+
604
+ SvgPath roundedRectPath(double x, double y, double w, double h, double rx, double ry) {
605
+ rx = std::min(rx, w / 2);
606
+ ry = std::min(ry, h / 2);
607
+ if (rx <= 0 || ry <= 0) {
608
+ return rectPath(x, y, w, h);
609
+ }
610
+ double kx = rx * (1 - kQuarter), ky = ry * (1 - kQuarter);
611
+ SvgPath p;
612
+ p.moveTo(x + rx, y);
613
+ p.lineTo(x + w - rx, y);
614
+ p.cubicTo(x + w - kx, y, x + w, y + ky, x + w, y + ry);
615
+ p.lineTo(x + w, y + h - ry);
616
+ p.cubicTo(x + w, y + h - ky, x + w - kx, y + h, x + w - rx, y + h);
617
+ p.lineTo(x + rx, y + h);
618
+ p.cubicTo(x + kx, y + h, x, y + h - ky, x, y + h - ry);
619
+ p.lineTo(x, y + ry);
620
+ p.cubicTo(x, y + ky, x + kx, y, x + rx, y);
621
+ p.close();
622
+ return p;
623
+ }
624
+
625
+ std::optional<SvgRect> unite(std::optional<SvgRect> a, std::optional<SvgRect> b) {
626
+ if (!a) {
627
+ return b;
628
+ }
629
+ if (!b) {
630
+ return a;
631
+ }
632
+ double minX = std::min(a->x, b->x), minY = std::min(a->y, b->y);
633
+ double maxX = std::max(a->x + a->width, b->x + b->width), maxY = std::max(a->y + a->height, b->y + b->height);
634
+ return SvgRect{minX, minY, maxX - minX, maxY - minY};
635
+ }
636
+
637
+ std::optional<SvgRect> transformed(std::optional<SvgRect> r, const SvgMatrix &m) {
638
+ if (!r) {
639
+ return r;
640
+ }
641
+ SvgPath corners = rectPath(r->x, r->y, r->width, r->height);
642
+ SvgPath out;
643
+ out.append(corners, m);
644
+ return out.bounds();
645
+ }
646
+
647
+ bool listed(const std::vector<std::string> &list, const char *name) {
648
+ return std::find(list.begin(), list.end(), name) != list.end();
649
+ }
650
+
651
+ // The presentation an element draws with, after inheritance.
652
+ struct Style {
653
+ SvgBrush fill{.type = SvgBrush::Type::Color, .argb = 0xff000000};
654
+ double fillOpacity{1};
655
+ int fillRule{1};
656
+ SvgBrush stroke{.type = SvgBrush::Type::None};
657
+ double strokeOpacity{1};
658
+ SvgLength strokeWidth{.value = 1, .set = true};
659
+ int strokeLinecap{0};
660
+ int strokeLinejoin{0};
661
+ std::vector<SvgLength> strokeDasharray;
662
+ double strokeDashoffset{0};
663
+ double strokeMiterlimit{4};
664
+ uint32_t color{0xff000000};
665
+ double fontSize{12};
666
+ std::string fontFamily;
667
+ std::string fontWeight;
668
+ // The attributes set somewhere above or on the element, which its children inherit.
669
+ std::unordered_set<std::string> list;
670
+ };
671
+
672
+ class Renderer {
673
+ public:
674
+ Renderer(const SvgDocument &document, double width, double height, SvgCanvas &canvas)
675
+ : document_(document), width_(width), height_(height), canvas_(&canvas) {
676
+ index(document.root);
677
+ }
678
+
679
+ void draw() {
680
+ const auto &root = document_.root.element;
681
+ double vw = root.bbWidth.set ? resolveIn(root.bbWidth, width_) : width_;
682
+ double vh = root.bbHeight.set ? resolveIn(root.bbHeight, height_) : height_;
683
+ canvas_->save();
684
+ if (root.vbWidth > 0 && root.vbHeight > 0) {
685
+ auto m = svgViewBoxTransform({root.minX, root.minY, root.vbWidth, root.vbHeight}, root.align, root.meetOrSlice, vw, vh);
686
+ if (!isIdentity(m)) {
687
+ canvas_->concat(m);
688
+ }
689
+ vw_ = root.vbWidth;
690
+ vh_ = root.vbHeight;
691
+ } else {
692
+ vw_ = vw;
693
+ vh_ = vh;
694
+ }
695
+ Style style;
696
+ if (root.color) {
697
+ style.color = *root.color;
698
+ }
699
+ for (const auto &child : document_.root.children) {
700
+ drawNode(child, style);
701
+ }
702
+ canvas_->restore();
703
+ }
704
+
705
+ private:
706
+ enum class Axis { X, Y, Other };
707
+
708
+ void index(const SvgNode &node) {
709
+ if (!node.element.name.empty()) {
710
+ names_.emplace(node.element.name, &node);
711
+ }
712
+ for (const auto &child : node.children) {
713
+ index(child);
714
+ }
715
+ }
716
+
717
+ const SvgNode *named(const std::string &name, std::initializer_list<SvgKind> kinds = {}) const {
718
+ auto found = names_.find(name);
719
+ if (found == names_.end()) {
720
+ return nullptr;
721
+ }
722
+ if (kinds.size() > 0 && std::find(kinds.begin(), kinds.end(), found->second->element.kind) == kinds.end()) {
723
+ return nullptr;
724
+ }
725
+ return found->second;
726
+ }
727
+
728
+ static double resolveIn(const SvgLength &l, double base, double fontSize = 12) {
729
+ switch (l.unit) {
730
+ case SvgLength::Unit::Percent:
731
+ return base * l.value / 100;
732
+ case SvgLength::Unit::Em:
733
+ return l.value * fontSize;
734
+ default:
735
+ return l.value;
736
+ }
737
+ }
738
+
739
+ double resolve(const SvgLength &l, Axis axis, double fontSize = 12) const {
740
+ double base = axis == Axis::X ? vw_ : axis == Axis::Y ? vh_ : std::sqrt((vw_ * vw_ + vh_ * vh_) / 2);
741
+ return resolveIn(l, base, fontSize);
742
+ }
743
+
744
+ double length(const SvgElement &e, const char *name, Axis axis, double fallback = 0) const {
745
+ auto found = e.lengths.find(name);
746
+ return found == e.lengths.end() || !found->second.set ? fallback : resolve(found->second, axis);
747
+ }
748
+
749
+ bool has(const SvgElement &e, const char *name) const {
750
+ auto found = e.lengths.find(name);
751
+ return found != e.lengths.end() && found->second.set;
752
+ }
753
+
754
+ static Style merge(const Style &parent, const SvgElement &e) {
755
+ Style s;
756
+ s.color = e.color.value_or(parent.color);
757
+ s.fontSize = parent.fontSize;
758
+ s.fontFamily = e.fontFamily.empty() ? parent.fontFamily : e.fontFamily;
759
+ s.fontWeight = e.fontWeight.empty() ? parent.fontWeight : e.fontWeight;
760
+ if (e.fontSize.set) {
761
+ s.fontSize = resolveIn(e.fontSize, parent.fontSize, parent.fontSize);
762
+ }
763
+ s.list = parent.list;
764
+ for (const auto &name : e.propList) {
765
+ s.list.insert(name);
766
+ }
767
+ // An attribute the element lists is its own; one it does not is its parent's where the parent
768
+ // has it, else the element's own value as sent.
769
+ auto take = [&](const char *name, auto &field, const auto &own, const auto &inherited) {
770
+ field = !listed(e.propList, name) && parent.list.contains(name) ? inherited : own;
771
+ };
772
+ auto brush = [&](const SvgBrush &b, bool fill) {
773
+ if (b.type != SvgBrush::Type::Unset) {
774
+ return b;
775
+ }
776
+ // Null in propList is `none`; never sent is SVG's default, black for a fill.
777
+ bool listedHere = listed(e.propList, fill ? "fill" : "stroke");
778
+ if (fill && !listedHere) {
779
+ return SvgBrush{.type = SvgBrush::Type::Color, .argb = 0xff000000};
780
+ }
781
+ return SvgBrush{.type = SvgBrush::Type::None};
782
+ };
783
+ take("fill", s.fill, brush(e.fill, true), parent.fill);
784
+ take("fillOpacity", s.fillOpacity, e.fillOpacity, parent.fillOpacity);
785
+ take("fillRule", s.fillRule, e.fillRule, parent.fillRule);
786
+ take("stroke", s.stroke, brush(e.stroke, false), parent.stroke);
787
+ take("strokeOpacity", s.strokeOpacity, e.strokeOpacity, parent.strokeOpacity);
788
+ take("strokeWidth", s.strokeWidth, e.strokeWidth.set ? e.strokeWidth : SvgLength{.value = 1, .set = true}, parent.strokeWidth);
789
+ take("strokeLinecap", s.strokeLinecap, e.strokeLinecap, parent.strokeLinecap);
790
+ take("strokeLinejoin", s.strokeLinejoin, e.strokeLinejoin, parent.strokeLinejoin);
791
+ take("strokeDasharray", s.strokeDasharray, e.strokeDasharray, parent.strokeDasharray);
792
+ take("strokeDashoffset", s.strokeDashoffset, e.strokeDashoffset, parent.strokeDashoffset);
793
+ take("strokeMiterlimit", s.strokeMiterlimit, e.strokeMiterlimit >= 1 ? e.strokeMiterlimit : 4.0, parent.strokeMiterlimit);
794
+ return s;
795
+ }
796
+
797
+ std::optional<SvgPath> shape(const SvgElement &e) const {
798
+ switch (e.kind) {
799
+ case SvgKind::Path:
800
+ return parseSvgPath(e.d);
801
+ case SvgKind::Rect: {
802
+ double x = length(e, "x", Axis::X), y = length(e, "y", Axis::Y);
803
+ double w = length(e, "width", Axis::X), h = length(e, "height", Axis::Y);
804
+ if (w <= 0 || h <= 0) {
805
+ return SvgPath{};
806
+ }
807
+ bool hasRx = has(e, "rx"), hasRy = has(e, "ry");
808
+ double rx = hasRx ? length(e, "rx", Axis::X) : 0, ry = hasRy ? length(e, "ry", Axis::Y) : 0;
809
+ if (hasRx && !hasRy) {
810
+ ry = rx;
811
+ } else if (hasRy && !hasRx) {
812
+ rx = ry;
813
+ }
814
+ return rx > 0 || ry > 0 ? roundedRectPath(x, y, w, h, rx, ry) : rectPath(x, y, w, h);
815
+ }
816
+ case SvgKind::Circle: {
817
+ double r = length(e, "r", Axis::Other);
818
+ if (r <= 0) {
819
+ return SvgPath{};
820
+ }
821
+ return ellipsePath(length(e, "cx", Axis::X), length(e, "cy", Axis::Y), r, r);
822
+ }
823
+ case SvgKind::Ellipse: {
824
+ double rx = length(e, "rx", Axis::X), ry = length(e, "ry", Axis::Y);
825
+ if (rx <= 0 || ry <= 0) {
826
+ return SvgPath{};
827
+ }
828
+ return ellipsePath(length(e, "cx", Axis::X), length(e, "cy", Axis::Y), rx, ry);
829
+ }
830
+ case SvgKind::Line: {
831
+ SvgPath p;
832
+ p.moveTo(length(e, "x1", Axis::X), length(e, "y1", Axis::Y));
833
+ p.lineTo(length(e, "x2", Axis::X), length(e, "y2", Axis::Y));
834
+ return p;
835
+ }
836
+ default:
837
+ return std::nullopt;
838
+ }
839
+ }
840
+
841
+ // What `node` covers in its own user space (before its own transform), for a gradient's or a
842
+ // mask's objectBoundingBox.
843
+ std::optional<SvgRect> bounds(const SvgNode &node) const {
844
+ if (auto p = shape(node.element)) {
845
+ return p->bounds();
846
+ }
847
+ if (node.element.kind != SvgKind::Group) {
848
+ return std::nullopt;
849
+ }
850
+ std::optional<SvgRect> out;
851
+ for (const auto &child : node.children) {
852
+ auto b = bounds(child);
853
+ out = unite(out, child.element.matrix ? transformed(b, *child.element.matrix) : b);
854
+ }
855
+ return out;
856
+ }
857
+
858
+ std::optional<SvgPaint> paint(const SvgBrush &brush, double opacity, const Style &style, const std::optional<SvgRect> &box) const {
859
+ switch (brush.type) {
860
+ case SvgBrush::Type::Color:
861
+ return SvgPaint{.argb = brush.argb, .opacity = opacity};
862
+ case SvgBrush::Type::CurrentColor:
863
+ return SvgPaint{.argb = style.color, .opacity = opacity};
864
+ case SvgBrush::Type::Ref: {
865
+ const auto *node = named(brush.ref, {SvgKind::LinearGradient, SvgKind::RadialGradient});
866
+ if (node == nullptr) {
867
+ return std::nullopt;
868
+ }
869
+ return gradient(node->element, opacity, box);
870
+ }
871
+ default:
872
+ return std::nullopt;
873
+ }
874
+ }
875
+
876
+ std::optional<SvgPaint> gradient(const SvgElement &g, double opacity, const std::optional<SvgRect> &box) const {
877
+ if (g.stops.empty()) {
878
+ return std::nullopt;
879
+ }
880
+ if (g.stops.size() == 1) {
881
+ return SvgPaint{.argb = g.stops[0].second, .opacity = opacity};
882
+ }
883
+ bool bounding = g.units == 0;
884
+ if (bounding && (!box || box->width <= 0 || box->height <= 0)) {
885
+ return std::nullopt;
886
+ }
887
+ auto at = [&](const char *name, Axis axis, double fallbackFraction) {
888
+ auto found = g.lengths.find(name);
889
+ if (found == g.lengths.end() || !found->second.set) {
890
+ return bounding ? fallbackFraction : resolve({.value = fallbackFraction * 100, .unit = SvgLength::Unit::Percent}, axis);
891
+ }
892
+ const auto &l = found->second;
893
+ if (bounding) {
894
+ return l.unit == SvgLength::Unit::Percent ? l.value / 100 : l.value;
895
+ }
896
+ return resolve(l, axis);
897
+ };
898
+ SvgGradient out{.radial = g.kind == SvgKind::RadialGradient, .stops = g.stops};
899
+ if (out.radial) {
900
+ out.x1 = at("cx", Axis::X, 0.5);
901
+ out.y1 = at("cy", Axis::Y, 0.5);
902
+ out.r = at("rx", Axis::Other, 0.5);
903
+ bool hasFx = g.lengths.contains("fx") && g.lengths.at("fx").set;
904
+ bool hasFy = g.lengths.contains("fy") && g.lengths.at("fy").set;
905
+ out.x2 = hasFx ? at("fx", Axis::X, 0.5) : out.x1;
906
+ out.y2 = hasFy ? at("fy", Axis::Y, 0.5) : out.y1;
907
+ } else {
908
+ out.x1 = at("x1", Axis::X, 0);
909
+ out.y1 = at("y1", Axis::Y, 0);
910
+ out.x2 = at("x2", Axis::X, 1);
911
+ out.y2 = at("y2", Axis::Y, 0);
912
+ }
913
+ SvgMatrix space = bounding ? SvgMatrix{box->width, 0, 0, box->height, box->x, box->y} : SvgMatrix{};
914
+ out.transform = g.gradientTransform ? space * *g.gradientTransform : space;
915
+ return SvgPaint{.gradient = std::move(out), .opacity = opacity};
916
+ }
917
+
918
+ SvgPath clipPathOf(const SvgNode &clip) const {
919
+ SvgPath out;
920
+ std::unordered_set<const SvgNode *> within;
921
+ for (const auto &child : clip.children) {
922
+ collectClip(child, clip.element.matrix.value_or(SvgMatrix{}), out, within);
923
+ }
924
+ return out;
925
+ }
926
+
927
+ // `within` holds the uses being expanded, so a use that leads back to itself, directly or
928
+ // through others, is an invalid reference that adds nothing, as SVG has it.
929
+ void collectClip(const SvgNode &node, const SvgMatrix &outer, SvgPath &out, std::unordered_set<const SvgNode *> &within) const {
930
+ if (node.element.hidden) {
931
+ return;
932
+ }
933
+ SvgMatrix m = node.element.matrix ? outer * *node.element.matrix : outer;
934
+ if (auto p = shape(node.element)) {
935
+ out.append(*p, m);
936
+ return;
937
+ }
938
+ if (node.element.kind == SvgKind::Use) {
939
+ if (const auto *target = named(node.element.href); target != nullptr && within.insert(&node).second) {
940
+ double x = length(node.element, "x", Axis::X), y = length(node.element, "y", Axis::Y);
941
+ collectClip(*target, m * SvgMatrix::translate(x, y), out, within);
942
+ within.erase(&node);
943
+ }
944
+ return;
945
+ }
946
+ for (const auto &child : node.children) {
947
+ collectClip(child, m, out, within);
948
+ }
949
+ }
950
+
951
+ void drawNode(const SvgNode &node, const Style &parent) {
952
+ const auto &e = node.element;
953
+ if (e.hidden) {
954
+ return;
955
+ }
956
+ switch (e.kind) {
957
+ case SvgKind::Svg:
958
+ case SvgKind::Defs:
959
+ case SvgKind::LinearGradient:
960
+ case SvgKind::RadialGradient:
961
+ case SvgKind::ClipPath:
962
+ case SvgKind::Mask:
963
+ case SvgKind::Symbol:
964
+ case SvgKind::Marker:
965
+ case SvgKind::Pattern:
966
+ case SvgKind::Filter:
967
+ case SvgKind::FeGaussianBlur:
968
+ case SvgKind::FeOffset:
969
+ case SvgKind::FeColorMatrix:
970
+ case SvgKind::FeFlood:
971
+ case SvgKind::FeComposite:
972
+ case SvgKind::FeMerge:
973
+ return;
974
+ default:
975
+ break;
976
+ }
977
+ if (active_.contains(&node)) {
978
+ return;
979
+ }
980
+ // A filter that is found but cannot run (no steps, or an empty box for its units) leaves the
981
+ // element undrawn, as SVG says; one that is not found is ignored.
982
+ std::optional<SvgFilter> filter;
983
+ if (const SvgNode *f = e.filter.empty() ? nullptr : named(e.filter, {SvgKind::Filter})) {
984
+ filter = filterOf(*f, bounds(node));
985
+ if (!filter) {
986
+ return;
987
+ }
988
+ }
989
+ Style style = merge(parent, e);
990
+ const SvgNode *clip = e.clipPath.empty() ? nullptr : named(e.clipPath, {SvgKind::ClipPath});
991
+ const SvgNode *mask = e.mask.empty() ? nullptr : named(e.mask, {SvgKind::Mask});
992
+ bool saved = e.matrix.has_value() || clip != nullptr;
993
+ if (saved) {
994
+ canvas_->save();
995
+ if (e.matrix) {
996
+ canvas_->concat(*e.matrix);
997
+ }
998
+ if (clip != nullptr) {
999
+ canvas_->clip(clipPathOf(*clip), e.clipRule == 0);
1000
+ }
1001
+ }
1002
+ bool layer = e.opacity < 1;
1003
+ if (layer) {
1004
+ canvas_->beginLayer(std::max(0.0, e.opacity));
1005
+ }
1006
+ // Active before its mask is drawn: a mask that holds the node, or one masked by that mask
1007
+ // again, is a circular reference that draws it no further.
1008
+ active_.insert(&node);
1009
+ if (mask != nullptr) {
1010
+ beginMask(*mask, bounds(node));
1011
+ }
1012
+ if (filter) {
1013
+ canvas_->beginFilter(*filter);
1014
+ }
1015
+ drawContent(node, style);
1016
+ active_.erase(&node);
1017
+ if (filter) {
1018
+ canvas_->endFilter();
1019
+ }
1020
+ if (mask != nullptr) {
1021
+ canvas_->endMasked();
1022
+ }
1023
+ if (layer) {
1024
+ canvas_->endLayer();
1025
+ }
1026
+ if (saved) {
1027
+ canvas_->restore();
1028
+ }
1029
+ }
1030
+
1031
+ void beginMask(const SvgNode &mask, const std::optional<SvgRect> &box) {
1032
+ const auto &m = mask.element;
1033
+ canvas_->beginMask(m.maskType == 1);
1034
+ bool bounding = m.units == 0;
1035
+ SvgRect b = box.value_or(SvgRect{});
1036
+ auto at = [&](const char *name, Axis axis, double fraction) {
1037
+ auto found = m.lengths.find(name);
1038
+ SvgLength l = found != m.lengths.end() && found->second.set ? found->second
1039
+ : SvgLength{.value = fraction * 100, .unit = SvgLength::Unit::Percent, .set = true};
1040
+ if (bounding) {
1041
+ double f = l.unit == SvgLength::Unit::Percent ? l.value / 100 : l.value;
1042
+ return f * (axis == Axis::X ? b.width : b.height);
1043
+ }
1044
+ return resolve(l, axis);
1045
+ };
1046
+ double x = at("x", Axis::X, -0.1) + (bounding ? b.x : 0);
1047
+ double y = at("y", Axis::Y, -0.1) + (bounding ? b.y : 0);
1048
+ canvas_->clip(rectPath(x, y, at("width", Axis::X, 1.2), at("height", Axis::Y, 1.2)), false);
1049
+ bool content = m.contentUnits == 0 && box;
1050
+ if (content) {
1051
+ canvas_->save();
1052
+ canvas_->concat(SvgMatrix{b.width, 0, 0, b.height, b.x, b.y});
1053
+ }
1054
+ Style style = merge(Style{}, m);
1055
+ for (const auto &child : mask.children) {
1056
+ drawNode(child, style);
1057
+ }
1058
+ if (content) {
1059
+ canvas_->restore();
1060
+ }
1061
+ canvas_->endMask();
1062
+ }
1063
+
1064
+ void drawContent(const SvgNode &node, const Style &style) {
1065
+ const auto &e = node.element;
1066
+ if (auto p = shape(e)) {
1067
+ if (p->empty()) {
1068
+ return;
1069
+ }
1070
+ auto box = p->bounds();
1071
+ if (e.kind != SvgKind::Line) {
1072
+ if (const SvgNode *pattern = patternOf(style.fill)) {
1073
+ canvas_->save();
1074
+ canvas_->clip(*p, style.fillRule == 0);
1075
+ drawPattern(*pattern, style.fillOpacity, box);
1076
+ canvas_->restore();
1077
+ } else if (auto fill = paint(style.fill, style.fillOpacity, style, box)) {
1078
+ canvas_->fill(*p, style.fillRule == 0, *fill);
1079
+ }
1080
+ }
1081
+ double width = resolve(style.strokeWidth, Axis::Other);
1082
+ if (width > 0) {
1083
+ if (const SvgNode *pattern = patternOf(style.stroke)) {
1084
+ canvas_->save();
1085
+ canvas_->clipToStroke(*p, strokeOf(style, width));
1086
+ drawPattern(*pattern, style.strokeOpacity, box);
1087
+ canvas_->restore();
1088
+ } else if (auto stroke = paint(style.stroke, style.strokeOpacity, style, box)) {
1089
+ canvas_->stroke(*p, strokeOf(style, width), *stroke);
1090
+ }
1091
+ }
1092
+ if ((e.kind == SvgKind::Path || e.kind == SvgKind::Line) &&
1093
+ !(e.markerStart.empty() && e.markerMid.empty() && e.markerEnd.empty())) {
1094
+ drawMarkers(e, *p, width);
1095
+ }
1096
+ return;
1097
+ }
1098
+ switch (e.kind) {
1099
+ case SvgKind::Group:
1100
+ for (const auto &child : node.children) {
1101
+ drawNode(child, style);
1102
+ }
1103
+ break;
1104
+ case SvgKind::Use:
1105
+ drawUse(e, style);
1106
+ break;
1107
+ case SvgKind::Image: {
1108
+ double w = length(e, "width", Axis::X), h = length(e, "height", Axis::Y);
1109
+ if (!e.uri.empty() && w > 0 && h > 0) {
1110
+ canvas_->image(e.uri, {length(e, "x", Axis::X), length(e, "y", Axis::Y), w, h}, e.align, e.meetOrSlice, 1);
1111
+ }
1112
+ break;
1113
+ }
1114
+ case SvgKind::Text:
1115
+ case SvgKind::TSpan: {
1116
+ double x = 0, y = 0;
1117
+ drawText(node, style, x, y);
1118
+ break;
1119
+ }
1120
+ default:
1121
+ break;
1122
+ }
1123
+ }
1124
+
1125
+ SvgStroke strokeOf(const Style &style, double width) const {
1126
+ SvgStroke s{
1127
+ .width = width,
1128
+ .cap = style.strokeLinecap,
1129
+ .join = style.strokeLinejoin,
1130
+ .miterLimit = style.strokeMiterlimit,
1131
+ .dashOffset = style.strokeDashoffset};
1132
+ double total = 0;
1133
+ bool negative = false;
1134
+ for (const auto &d : style.strokeDasharray) {
1135
+ double v = resolve(d, Axis::Other);
1136
+ negative = negative || v < 0;
1137
+ total += v;
1138
+ s.dashes.push_back(v);
1139
+ }
1140
+ if (negative || total <= 0) {
1141
+ s.dashes.clear();
1142
+ } else if (s.dashes.size() % 2 == 1) {
1143
+ // An odd list repeats to make an even one, as SVG says.
1144
+ auto copy = s.dashes;
1145
+ s.dashes.insert(s.dashes.end(), copy.begin(), copy.end());
1146
+ }
1147
+ return s;
1148
+ }
1149
+
1150
+ const SvgNode *patternOf(const SvgBrush &brush) const {
1151
+ return brush.type == SvgBrush::Type::Ref ? named(brush.ref, {SvgKind::Pattern}) : nullptr;
1152
+ }
1153
+
1154
+ // A length of a pattern's, a filter's or a step's: a fraction of `box` (added to its origin for
1155
+ // a position) in objectBoundingBox units, a user length otherwise; `fallback` when unset.
1156
+ double unitLength(const SvgElement &e, const char *name, Axis axis, bool bounding, const SvgRect &box, double fallback) const {
1157
+ auto found = e.lengths.find(name);
1158
+ if (found == e.lengths.end() || !found->second.set) {
1159
+ return fallback;
1160
+ }
1161
+ if (!bounding) {
1162
+ return resolve(found->second, axis);
1163
+ }
1164
+ const auto &l = found->second;
1165
+ double fraction = l.unit == SvgLength::Unit::Percent ? l.value / 100 : l.value;
1166
+ return fraction * (axis == Axis::X ? box.width : box.height);
1167
+ }
1168
+
1169
+ // Fills the clip with a pattern's tile repeated, the tile drawn on the canvas the canvas gives.
1170
+ void drawPattern(const SvgNode &pattern, double opacity, const std::optional<SvgRect> &box) {
1171
+ const auto &p = pattern.element;
1172
+ bool bounding = p.units == 0;
1173
+ if (active_.contains(&pattern) || (bounding && (!box || box->width <= 0 || box->height <= 0))) {
1174
+ return;
1175
+ }
1176
+ SvgRect b = box.value_or(SvgRect{});
1177
+ SvgPatternTile tile{
1178
+ .tile =
1179
+ {unitLength(p, "x", Axis::X, bounding, b, 0) + (bounding ? b.x : 0),
1180
+ unitLength(p, "y", Axis::Y, bounding, b, 0) + (bounding ? b.y : 0),
1181
+ unitLength(p, "width", Axis::X, bounding, b, 0),
1182
+ unitLength(p, "height", Axis::Y, bounding, b, 0)},
1183
+ .transform = p.gradientTransform.value_or(SvgMatrix{}),
1184
+ };
1185
+ if (tile.tile.width <= 0 || tile.tile.height <= 0) {
1186
+ return;
1187
+ }
1188
+ // Content in the tile's own space: through the viewBox if it has one, else in fractions of the
1189
+ // box for objectBoundingBox content units.
1190
+ std::optional<SvgMatrix> content;
1191
+ if (p.vbWidth > 0 && p.vbHeight > 0) {
1192
+ content = svgViewBoxTransform({p.minX, p.minY, p.vbWidth, p.vbHeight}, p.align, p.meetOrSlice, tile.tile.width, tile.tile.height);
1193
+ } else if (p.contentUnits == 0 && box) {
1194
+ content = SvgMatrix{b.width, 0, 0, b.height, 0, 0};
1195
+ }
1196
+ Style style = merge(Style{}, p);
1197
+ SvgCanvas *outer = canvas_;
1198
+ active_.insert(&pattern);
1199
+ outer->pattern(tile, opacity, [&](SvgCanvas &tileCanvas) {
1200
+ canvas_ = &tileCanvas;
1201
+ if (content) {
1202
+ canvas_->save();
1203
+ canvas_->concat(*content);
1204
+ }
1205
+ for (const auto &child : pattern.children) {
1206
+ drawNode(child, style);
1207
+ }
1208
+ if (content) {
1209
+ canvas_->restore();
1210
+ }
1211
+ canvas_ = outer;
1212
+ });
1213
+ active_.erase(&pattern);
1214
+ }
1215
+
1216
+ void drawMarkers(const SvgElement &e, const SvgPath &path, double strokeWidth) {
1217
+ auto vertices = svgMarkerVertices(path);
1218
+ auto draw = [&](const std::string &name, const SvgMarkerVertex &v) {
1219
+ const SvgNode *marker = name.empty() ? nullptr : named(name, {SvgKind::Marker});
1220
+ if (marker != nullptr && !active_.contains(marker)) {
1221
+ drawMarker(*marker, v, strokeWidth);
1222
+ }
1223
+ };
1224
+ for (const auto &v : vertices) {
1225
+ switch (v.place) {
1226
+ case SvgMarkerVertex::Place::Start:
1227
+ draw(e.markerStart, v);
1228
+ if (vertices.size() == 1) {
1229
+ draw(e.markerEnd, v);
1230
+ }
1231
+ break;
1232
+ case SvgMarkerVertex::Place::Mid:
1233
+ draw(e.markerMid, v);
1234
+ break;
1235
+ case SvgMarkerVertex::Place::End:
1236
+ draw(e.markerEnd, v);
1237
+ break;
1238
+ }
1239
+ }
1240
+ }
1241
+
1242
+ void drawMarker(const SvgNode &marker, const SvgMarkerVertex &v, double strokeWidth) {
1243
+ const auto &m = marker.element;
1244
+ double mw = length(m, "markerWidth", Axis::X, 3), mh = length(m, "markerHeight", Axis::Y, 3);
1245
+ if (mw <= 0 || mh <= 0) {
1246
+ return;
1247
+ }
1248
+ double angle = 0;
1249
+ if (m.orient == "auto") {
1250
+ angle = v.angle;
1251
+ } else if (m.orient == "auto-start-reverse") {
1252
+ angle = v.place == SvgMarkerVertex::Place::Start ? v.angle + 180 : v.angle;
1253
+ } else if (!m.orient.empty()) {
1254
+ angle = std::strtod(m.orient.c_str(), nullptr);
1255
+ }
1256
+ double scale = m.markerUnits == "userSpaceOnUse" ? 1 : strokeWidth;
1257
+ double radians = angle * M_PI / 180;
1258
+ double cos = std::cos(radians), sin = std::sin(radians);
1259
+ SvgMatrix place = SvgMatrix::translate(v.x, v.y) * SvgMatrix{cos, sin, -sin, cos, 0, 0} * SvgMatrix::scale(scale, scale);
1260
+ SvgMatrix fit = m.vbWidth > 0 && m.vbHeight > 0
1261
+ ? svgViewBoxTransform({m.minX, m.minY, m.vbWidth, m.vbHeight}, m.align, m.meetOrSlice, mw, mh)
1262
+ : SvgMatrix{};
1263
+ // The ref point, in the marker's content, sits on the vertex.
1264
+ auto [refX, refY] = fit.apply(length(m, "refX", Axis::X), length(m, "refY", Axis::Y));
1265
+ canvas_->save();
1266
+ canvas_->concat(place);
1267
+ if (refX != 0 || refY != 0) {
1268
+ canvas_->concat(SvgMatrix::translate(-refX, -refY));
1269
+ }
1270
+ // A marker's overflow is hidden: its content shows only in its box.
1271
+ canvas_->clip(rectPath(0, 0, mw, mh), false);
1272
+ if (!isIdentity(fit)) {
1273
+ canvas_->concat(fit);
1274
+ }
1275
+ Style style = merge(Style{}, m);
1276
+ active_.insert(&marker);
1277
+ for (const auto &child : marker.children) {
1278
+ drawNode(child, style);
1279
+ }
1280
+ active_.erase(&marker);
1281
+ canvas_->restore();
1282
+ }
1283
+
1284
+ // A filter's steps for an element whose box is `box`, or nothing when it cannot run.
1285
+ std::optional<SvgFilter> filterOf(const SvgNode &filter, const std::optional<SvgRect> &box) const {
1286
+ const auto &f = filter.element;
1287
+ bool bounding = f.units == 0;
1288
+ bool primitiveBounding = f.contentUnits == 0;
1289
+ if ((bounding || primitiveBounding) && (!box || box->width <= 0 || box->height <= 0)) {
1290
+ return std::nullopt;
1291
+ }
1292
+ SvgRect b = box.value_or(SvgRect{});
1293
+ // The region SVG gives a filter that says nothing: a tenth over each side.
1294
+ auto regionLength = [&](const char *name, Axis axis, double fraction, bool position) {
1295
+ double fallback = bounding ? fraction * (axis == Axis::X ? b.width : b.height)
1296
+ : resolve({.value = fraction * 100, .unit = SvgLength::Unit::Percent, .set = true}, axis);
1297
+ return unitLength(f, name, axis, bounding, b, fallback) + (bounding && position ? (axis == Axis::X ? b.x : b.y) : 0);
1298
+ };
1299
+ SvgFilter out{
1300
+ .region =
1301
+ {regionLength("x", Axis::X, -0.1, true),
1302
+ regionLength("y", Axis::Y, -0.1, true),
1303
+ regionLength("width", Axis::X, 1.2, false),
1304
+ regionLength("height", Axis::Y, 1.2, false)},
1305
+ .steps = {},
1306
+ };
1307
+ if (out.region.width <= 0 || out.region.height <= 0) {
1308
+ return std::nullopt;
1309
+ }
1310
+ std::string previous = "SourceGraphic";
1311
+ for (const auto &child : filter.children) {
1312
+ const auto &e = child.element;
1313
+ SvgFilterStep step;
1314
+ switch (e.kind) {
1315
+ case SvgKind::FeGaussianBlur:
1316
+ step.type = SvgFilterStep::Type::GaussianBlur;
1317
+ step.stdDeviationX = std::max(0.0, e.stdDeviationX) * (primitiveBounding ? b.width : 1);
1318
+ step.stdDeviationY = std::max(0.0, e.stdDeviationY) * (primitiveBounding ? b.height : 1);
1319
+ break;
1320
+ case SvgKind::FeOffset:
1321
+ step.type = SvgFilterStep::Type::Offset;
1322
+ step.dx = unitLength(e, "dx", Axis::X, primitiveBounding, b, 0);
1323
+ step.dy = unitLength(e, "dy", Axis::Y, primitiveBounding, b, 0);
1324
+ break;
1325
+ case SvgKind::FeColorMatrix:
1326
+ step.type = SvgFilterStep::Type::ColorMatrix;
1327
+ step.matrix = svgColorMatrix(e.op, e.values);
1328
+ break;
1329
+ case SvgKind::FeFlood: {
1330
+ step.type = SvgFilterStep::Type::Flood;
1331
+ step.argb = e.flood.type == SvgBrush::Type::Color ? e.flood.argb : 0;
1332
+ step.opacity = std::clamp(e.floodOpacity, 0.0, 1.0);
1333
+ break;
1334
+ }
1335
+ case SvgKind::FeComposite:
1336
+ step.type = SvgFilterStep::Type::Composite;
1337
+ step.op = e.op;
1338
+ step.k = e.k;
1339
+ break;
1340
+ case SvgKind::FeMerge:
1341
+ step.type = SvgFilterStep::Type::Merge;
1342
+ for (const auto &input : e.nodes) {
1343
+ step.inputs.push_back(input.empty() ? previous : input);
1344
+ }
1345
+ break;
1346
+ default:
1347
+ continue;
1348
+ }
1349
+ step.in1 = e.in1.empty() ? previous : e.in1;
1350
+ step.in2 = e.in2.empty() ? previous : e.in2;
1351
+ step.result = e.result.empty() ? "#" + std::to_string(out.steps.size()) : e.result;
1352
+ // A step's own x, y, width and height cut it within the region.
1353
+ auto sub = [&](const char *name, Axis axis, double fallback, bool position) {
1354
+ auto found = e.lengths.find(name);
1355
+ if (found == e.lengths.end() || !found->second.set) {
1356
+ return fallback;
1357
+ }
1358
+ return unitLength(e, name, axis, primitiveBounding, b, fallback) +
1359
+ (primitiveBounding && position ? (axis == Axis::X ? b.x : b.y) : 0);
1360
+ };
1361
+ step.subregion = {
1362
+ sub("x", Axis::X, out.region.x, true),
1363
+ sub("y", Axis::Y, out.region.y, true),
1364
+ sub("width", Axis::X, out.region.width, false),
1365
+ sub("height", Axis::Y, out.region.height, false)};
1366
+ previous = step.result;
1367
+ out.steps.push_back(std::move(step));
1368
+ }
1369
+ if (out.steps.empty()) {
1370
+ return std::nullopt;
1371
+ }
1372
+ return out;
1373
+ }
1374
+
1375
+ void drawUse(const SvgElement &use, const Style &style) {
1376
+ const SvgNode *target = named(use.href);
1377
+ if (target == nullptr || active_.contains(target)) {
1378
+ return;
1379
+ }
1380
+ double x = length(use, "x", Axis::X), y = length(use, "y", Axis::Y);
1381
+ bool moved = x != 0 || y != 0;
1382
+ if (moved) {
1383
+ canvas_->save();
1384
+ canvas_->concat(SvgMatrix::translate(x, y));
1385
+ }
1386
+ if (target->element.kind == SvgKind::Symbol) {
1387
+ const auto &symbol = target->element;
1388
+ Style inner = merge(style, symbol);
1389
+ bool fitted = symbol.vbWidth > 0 && symbol.vbHeight > 0;
1390
+ if (fitted) {
1391
+ double w = has(use, "width") ? length(use, "width", Axis::X) : vw_;
1392
+ double h = has(use, "height") ? length(use, "height", Axis::Y) : vh_;
1393
+ auto m = svgViewBoxTransform({symbol.minX, symbol.minY, symbol.vbWidth, symbol.vbHeight}, symbol.align, symbol.meetOrSlice, w, h);
1394
+ canvas_->save();
1395
+ canvas_->concat(m);
1396
+ }
1397
+ active_.insert(target);
1398
+ for (const auto &child : target->children) {
1399
+ drawNode(child, inner);
1400
+ }
1401
+ active_.erase(target);
1402
+ if (fitted) {
1403
+ canvas_->restore();
1404
+ }
1405
+ } else {
1406
+ drawNode(*target, style);
1407
+ }
1408
+ if (moved) {
1409
+ canvas_->restore();
1410
+ }
1411
+ }
1412
+
1413
+ // A text or a span: its own position, if it sets one, then its characters, then its spans, each
1414
+ // starting where the last one ended.
1415
+ void drawText(const SvgNode &node, const Style &style, double &x, double &y) {
1416
+ const auto &e = node.element;
1417
+ if (!e.xs.empty()) {
1418
+ x = resolve(e.xs[0], Axis::X, style.fontSize);
1419
+ }
1420
+ if (!e.ys.empty()) {
1421
+ y = resolve(e.ys[0], Axis::Y, style.fontSize);
1422
+ }
1423
+ if (!e.dxs.empty()) {
1424
+ x += resolve(e.dxs[0], Axis::X, style.fontSize);
1425
+ }
1426
+ if (!e.dys.empty()) {
1427
+ y += resolve(e.dys[0], Axis::Y, style.fontSize);
1428
+ }
1429
+ if (!e.content.empty()) {
1430
+ auto fill = paint(style.fill, style.fillOpacity, style, std::nullopt);
1431
+ x += canvas_->text(e.content, x, y, style.fontSize, style.fontFamily, style.fontWeight, fill ? &*fill : nullptr);
1432
+ }
1433
+ for (const auto &child : node.children) {
1434
+ if (child.element.hidden || (child.element.kind != SvgKind::TSpan && child.element.kind != SvgKind::Text)) {
1435
+ continue;
1436
+ }
1437
+ Style inner = merge(style, child.element);
1438
+ drawText(child, inner, x, y);
1439
+ }
1440
+ }
1441
+
1442
+ const SvgDocument &document_;
1443
+ double width_, height_;
1444
+ double vw_{0}, vh_{0};
1445
+ // The canvas drawn on: the svg's own, or a pattern's tile's while one is drawn.
1446
+ SvgCanvas *canvas_;
1447
+ std::unordered_map<std::string, const SvgNode *> names_;
1448
+ // What is being drawn, so a `use` of it, or of what holds it, draws nothing.
1449
+ std::unordered_set<const SvgNode *> active_;
1450
+ };
1451
+
1452
+ } // namespace
1453
+
1454
+ std::vector<SvgMarkerVertex> svgMarkerVertices(const SvgPath &path) {
1455
+ // Directions in degrees, NaN where a vertex has none that way.
1456
+ struct Vertex {
1457
+ double x, y;
1458
+ double in{NAN}, out{NAN};
1459
+ };
1460
+ auto direction = [](double x0, double y0, double x1, double y1) { return std::atan2(y1 - y0, x1 - x0) * 180 / M_PI; };
1461
+ std::vector<Vertex> vertices;
1462
+ size_t subpath = 0;
1463
+ double cx = 0, cy = 0;
1464
+ for (const auto &s : path.segments) {
1465
+ const double *p = s.points;
1466
+ switch (s.op) {
1467
+ case SvgPath::Op::Move:
1468
+ vertices.push_back({p[0], p[1]});
1469
+ subpath = vertices.size() - 1;
1470
+ cx = p[0];
1471
+ cy = p[1];
1472
+ break;
1473
+ case SvgPath::Op::Line: {
1474
+ if (vertices.empty()) {
1475
+ vertices.push_back({cx, cy});
1476
+ }
1477
+ double d = direction(cx, cy, p[0], p[1]);
1478
+ if (std::isnan(vertices.back().out)) {
1479
+ vertices.back().out = d;
1480
+ }
1481
+ vertices.push_back({p[0], p[1], d});
1482
+ cx = p[0];
1483
+ cy = p[1];
1484
+ break;
1485
+ }
1486
+ case SvgPath::Op::Cubic: {
1487
+ if (vertices.empty()) {
1488
+ vertices.push_back({cx, cy});
1489
+ }
1490
+ // Leaving towards the first control point that is not on the start, arriving from the last
1491
+ // that is not on the end.
1492
+ double out = p[0] != cx || p[1] != cy ? direction(cx, cy, p[0], p[1])
1493
+ : p[2] != cx || p[3] != cy ? direction(cx, cy, p[2], p[3])
1494
+ : direction(cx, cy, p[4], p[5]);
1495
+ double in = p[2] != p[4] || p[3] != p[5] ? direction(p[2], p[3], p[4], p[5])
1496
+ : p[0] != p[4] || p[1] != p[5] ? direction(p[0], p[1], p[4], p[5])
1497
+ : direction(cx, cy, p[4], p[5]);
1498
+ if (std::isnan(vertices.back().out)) {
1499
+ vertices.back().out = out;
1500
+ }
1501
+ vertices.push_back({p[4], p[5], in});
1502
+ cx = p[4];
1503
+ cy = p[5];
1504
+ break;
1505
+ }
1506
+ case SvgPath::Op::Close: {
1507
+ if (vertices.empty()) {
1508
+ break;
1509
+ }
1510
+ const Vertex start = vertices[subpath];
1511
+ double d = direction(cx, cy, start.x, start.y);
1512
+ if (std::isnan(vertices.back().out)) {
1513
+ vertices.back().out = d;
1514
+ }
1515
+ // A closed subpath's ends both bisect the closing line and its first segment.
1516
+ vertices.push_back({start.x, start.y, d, start.out});
1517
+ vertices[subpath].in = d;
1518
+ cx = start.x;
1519
+ cy = start.y;
1520
+ break;
1521
+ }
1522
+ }
1523
+ }
1524
+ std::vector<SvgMarkerVertex> out;
1525
+ for (size_t i = 0; i < vertices.size(); ++i) {
1526
+ const auto &v = vertices[i];
1527
+ double angle = 0;
1528
+ if (!std::isnan(v.in) && !std::isnan(v.out)) {
1529
+ double a = v.in * M_PI / 180, b = v.out * M_PI / 180;
1530
+ angle = std::atan2(std::sin(a) + std::sin(b), std::cos(a) + std::cos(b)) * 180 / M_PI;
1531
+ } else if (!std::isnan(v.out)) {
1532
+ angle = v.out;
1533
+ } else if (!std::isnan(v.in)) {
1534
+ angle = v.in;
1535
+ }
1536
+ auto place = i == 0 ? SvgMarkerVertex::Place::Start
1537
+ : i + 1 == vertices.size() ? SvgMarkerVertex::Place::End
1538
+ : SvgMarkerVertex::Place::Mid;
1539
+ out.push_back({.place = place, .x = v.x, .y = v.y, .angle = angle});
1540
+ }
1541
+ return out;
1542
+ }
1543
+
1544
+ std::array<double, 20> svgColorMatrix(int type, const std::vector<double> &values) {
1545
+ std::array<double, 20> m{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0};
1546
+ switch (type) {
1547
+ case 0:
1548
+ if (values.size() == 20) {
1549
+ std::copy(values.begin(), values.end(), m.begin());
1550
+ }
1551
+ break;
1552
+ case 1: {
1553
+ double s = values.empty() ? 1 : values[0];
1554
+ m = {0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0,
1555
+ 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0,
1556
+ 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0,
1557
+ 0, 0, 0, 1, 0};
1558
+ break;
1559
+ }
1560
+ case 2: {
1561
+ double a = (values.empty() ? 0 : values[0]) * M_PI / 180;
1562
+ double c = std::cos(a), s = std::sin(a);
1563
+ m = {0.213 + c * 0.787 - s * 0.213, 0.715 - c * 0.715 - s * 0.715, 0.072 - c * 0.072 + s * 0.928, 0, 0,
1564
+ 0.213 - c * 0.213 + s * 0.143, 0.715 + c * 0.285 + s * 0.140, 0.072 - c * 0.072 - s * 0.283, 0, 0,
1565
+ 0.213 - c * 0.213 - s * 0.787, 0.715 - c * 0.715 + s * 0.715, 0.072 + c * 0.928 + s * 0.072, 0, 0,
1566
+ 0, 0, 0, 1, 0};
1567
+ break;
1568
+ }
1569
+ case 3:
1570
+ m = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2125, 0.7154, 0.0721, 0, 0};
1571
+ break;
1572
+ default:
1573
+ break;
1574
+ }
1575
+ return m;
1576
+ }
1577
+
1578
+ namespace {
1579
+
1580
+ // A filter's working image: premultiplied RGBA in 0 to 1.
1581
+ struct FloatImage {
1582
+ int width{0}, height{0};
1583
+ std::vector<float> rgba;
1584
+ float *at(int x, int y) { return &rgba[static_cast<size_t>((y * width + x) * 4)]; }
1585
+ const float *at(int x, int y) const { return &rgba[static_cast<size_t>((y * width + x) * 4)]; }
1586
+ };
1587
+
1588
+ FloatImage blank(int width, int height) {
1589
+ return {.width = width, .height = height, .rgba = std::vector<float>(static_cast<size_t>(width * height * 4), 0.0f)};
1590
+ }
1591
+
1592
+ struct PixelBox {
1593
+ int x0, y0, x1, y1;
1594
+ };
1595
+
1596
+ // The pixels a user-space rectangle covers: the bounds of its corners through `m`.
1597
+ PixelBox pixelBox(const SvgRect &r, const SvgMatrix &m, int width, int height) {
1598
+ double xs[4], ys[4];
1599
+ std::tie(xs[0], ys[0]) = m.apply(r.x, r.y);
1600
+ std::tie(xs[1], ys[1]) = m.apply(r.x + r.width, r.y);
1601
+ std::tie(xs[2], ys[2]) = m.apply(r.x, r.y + r.height);
1602
+ std::tie(xs[3], ys[3]) = m.apply(r.x + r.width, r.y + r.height);
1603
+ auto [minX, maxX] = std::minmax({xs[0], xs[1], xs[2], xs[3]});
1604
+ auto [minY, maxY] = std::minmax({ys[0], ys[1], ys[2], ys[3]});
1605
+ auto clampTo = [](double v, int limit) { return static_cast<int>(std::clamp(v, 0.0, static_cast<double>(limit))); };
1606
+ return {clampTo(std::floor(minX + 1e-6), width), clampTo(std::floor(minY + 1e-6), height), clampTo(std::ceil(maxX - 1e-6), width),
1607
+ clampTo(std::ceil(maxY - 1e-6), height)};
1608
+ }
1609
+
1610
+ void cut(FloatImage &image, const PixelBox &box) {
1611
+ for (int y = 0; y < image.height; ++y) {
1612
+ for (int x = 0; x < image.width; ++x) {
1613
+ if (x < box.x0 || x >= box.x1 || y < box.y0 || y >= box.y1) {
1614
+ std::fill_n(image.at(x, y), 4, 0.0f);
1615
+ }
1616
+ }
1617
+ }
1618
+ }
1619
+
1620
+ // One box blur along a row or a column, averaging `left` pixels before each and `right` after it,
1621
+ // transparent beyond the edges.
1622
+ void boxBlur(FloatImage &image, int left, int right, bool horizontal) {
1623
+ int size = left + right + 1;
1624
+ int lines = horizontal ? image.height : image.width;
1625
+ int length = horizontal ? image.width : image.height;
1626
+ std::vector<float> line(static_cast<size_t>(length * 4));
1627
+ for (int l = 0; l < lines; ++l) {
1628
+ auto pixel = [&](int i) { return horizontal ? image.at(i, l) : image.at(l, i); };
1629
+ for (int c = 0; c < 4; ++c) {
1630
+ // The window around the first pixel: only the pixels inside the image add anything.
1631
+ double sum = 0;
1632
+ for (int i = 0; i <= std::min(right, length - 1); ++i) {
1633
+ sum += pixel(i)[c];
1634
+ }
1635
+ for (int i = 0; i < length; ++i) {
1636
+ line[static_cast<size_t>(i * 4 + c)] = static_cast<float>(sum / size);
1637
+ int leaving = i - left, entering = i + right + 1;
1638
+ sum -= leaving >= 0 && leaving < length ? pixel(leaving)[c] : 0;
1639
+ sum += entering >= 0 && entering < length ? pixel(entering)[c] : 0;
1640
+ }
1641
+ }
1642
+ for (int i = 0; i < length; ++i) {
1643
+ std::copy_n(&line[static_cast<size_t>(i * 4)], 4, pixel(i));
1644
+ }
1645
+ }
1646
+ }
1647
+
1648
+ // Three box blurs a way approximate a Gaussian of `deviation` pixels, as SVG says: three of an odd
1649
+ // size d centred, or for an even d, two of d each half a pixel off centre, one each way, and one of
1650
+ // d + 1 centred.
1651
+ void gaussianBlur(FloatImage &image, double deviation, bool horizontal) {
1652
+ if (deviation <= 0) {
1653
+ return;
1654
+ }
1655
+ // Past a box far wider than any image, every pixel averages to the same nothing: capped, so the
1656
+ // size stays an int.
1657
+ int d = static_cast<int>(std::min(std::floor(deviation * 3 * std::sqrt(2 * M_PI) / 4 + 0.5), double{1 << 24}));
1658
+ if (d < 1) {
1659
+ return;
1660
+ }
1661
+ if (d % 2 == 1) {
1662
+ for (int i = 0; i < 3; ++i) {
1663
+ boxBlur(image, d / 2, d / 2, horizontal);
1664
+ }
1665
+ } else {
1666
+ boxBlur(image, d / 2, d / 2 - 1, horizontal);
1667
+ boxBlur(image, d / 2 - 1, d / 2, horizontal);
1668
+ boxBlur(image, d / 2, d / 2, horizontal);
1669
+ }
1670
+ }
1671
+
1672
+ FloatImage offset(const FloatImage &in, int dx, int dy) {
1673
+ FloatImage out = blank(in.width, in.height);
1674
+ for (int y = 0; y < in.height; ++y) {
1675
+ for (int x = 0; x < in.width; ++x) {
1676
+ int sx = x - dx, sy = y - dy;
1677
+ if (sx >= 0 && sx < in.width && sy >= 0 && sy < in.height) {
1678
+ std::copy_n(in.at(sx, sy), 4, out.at(x, y));
1679
+ }
1680
+ }
1681
+ }
1682
+ return out;
1683
+ }
1684
+
1685
+ FloatImage colorMatrix(const FloatImage &in, const std::array<double, 20> &m) {
1686
+ FloatImage out = blank(in.width, in.height);
1687
+ for (size_t i = 0; i < in.rgba.size(); i += 4) {
1688
+ double a = in.rgba[i + 3];
1689
+ double c[4] = {a > 0 ? in.rgba[i] / a : 0, a > 0 ? in.rgba[i + 1] / a : 0, a > 0 ? in.rgba[i + 2] / a : 0, a};
1690
+ double r[4];
1691
+ for (int row = 0; row < 4; ++row) {
1692
+ const double *k = &m[static_cast<size_t>(row * 5)];
1693
+ r[row] = std::clamp(k[0] * c[0] + k[1] * c[1] + k[2] * c[2] + k[3] * c[3] + k[4], 0.0, 1.0);
1694
+ }
1695
+ for (int ch = 0; ch < 3; ++ch) {
1696
+ out.rgba[i + ch] = static_cast<float>(r[ch] * r[3]);
1697
+ }
1698
+ out.rgba[i + 3] = static_cast<float>(r[3]);
1699
+ }
1700
+ return out;
1701
+ }
1702
+
1703
+ FloatImage composite(const FloatImage &a, const FloatImage &b, int op, const std::array<double, 4> &k) {
1704
+ FloatImage out = blank(a.width, a.height);
1705
+ for (size_t i = 0; i < a.rgba.size(); i += 4) {
1706
+ double aa = a.rgba[i + 3], ba = b.rgba[i + 3];
1707
+ for (int ch = 0; ch < 4; ++ch) {
1708
+ double A = a.rgba[i + ch], B = b.rgba[i + ch], v = 0;
1709
+ switch (op) {
1710
+ case 1:
1711
+ v = A * ba;
1712
+ break;
1713
+ case 2:
1714
+ v = A * (1 - ba);
1715
+ break;
1716
+ case 3:
1717
+ v = A * ba + B * (1 - aa);
1718
+ break;
1719
+ case 4:
1720
+ v = A * (1 - ba) + B * (1 - aa);
1721
+ break;
1722
+ case 5:
1723
+ v = k[0] * A * B + k[1] * A + k[2] * B + k[3];
1724
+ break;
1725
+ default:
1726
+ v = A + B * (1 - aa);
1727
+ break;
1728
+ }
1729
+ out.rgba[i + ch] = static_cast<float>(std::clamp(v, 0.0, 1.0));
1730
+ }
1731
+ // Arithmetic can make colour beyond its alpha: premultiplied colour never exceeds it.
1732
+ for (int ch = 0; ch < 3; ++ch) {
1733
+ out.rgba[i + ch] = std::min(out.rgba[i + ch], out.rgba[i + 3]);
1734
+ }
1735
+ }
1736
+ return out;
1737
+ }
1738
+
1739
+ } // namespace
1740
+
1741
+ SvgPixels runSvgFilter(const SvgFilter &filter, const SvgPixels &source, const SvgMatrix &toPixels) {
1742
+ int width = source.width, height = source.height;
1743
+ std::unordered_map<std::string, FloatImage> results;
1744
+ FloatImage graphic = blank(width, height);
1745
+ for (size_t i = 0; i < graphic.rgba.size() && i < source.rgba.size(); ++i) {
1746
+ graphic.rgba[i] = source.rgba[i] / 255.0f;
1747
+ }
1748
+ FloatImage alpha = blank(width, height);
1749
+ for (size_t i = 3; i < graphic.rgba.size(); i += 4) {
1750
+ alpha.rgba[i] = graphic.rgba[i];
1751
+ }
1752
+ results.emplace("SourceGraphic", std::move(graphic));
1753
+ results.emplace("SourceAlpha", std::move(alpha));
1754
+ auto input = [&](const std::string &name) {
1755
+ auto found = results.find(name);
1756
+ return found != results.end() ? found->second : blank(width, height);
1757
+ };
1758
+ // How far a user unit goes each way in pixels, for lengths that have no direction.
1759
+ double scaleX = std::hypot(toPixels.a, toPixels.b), scaleY = std::hypot(toPixels.c, toPixels.d);
1760
+ FloatImage last = blank(width, height);
1761
+ for (const auto &step : filter.steps) {
1762
+ FloatImage out;
1763
+ switch (step.type) {
1764
+ case SvgFilterStep::Type::GaussianBlur:
1765
+ out = input(step.in1);
1766
+ gaussianBlur(out, step.stdDeviationX * scaleX, true);
1767
+ gaussianBlur(out, step.stdDeviationY * scaleY, false);
1768
+ break;
1769
+ case SvgFilterStep::Type::Offset: {
1770
+ double dx = toPixels.a * step.dx + toPixels.c * step.dy, dy = toPixels.b * step.dx + toPixels.d * step.dy;
1771
+ out = offset(input(step.in1), static_cast<int>(std::lround(dx)), static_cast<int>(std::lround(dy)));
1772
+ break;
1773
+ }
1774
+ case SvgFilterStep::Type::ColorMatrix:
1775
+ out = colorMatrix(input(step.in1), step.matrix);
1776
+ break;
1777
+ case SvgFilterStep::Type::Flood: {
1778
+ out = blank(width, height);
1779
+ float a = static_cast<float>(((step.argb >> 24) & 0xff) / 255.0 * step.opacity);
1780
+ float c[4] = {((step.argb >> 16) & 0xff) / 255.0f * a, ((step.argb >> 8) & 0xff) / 255.0f * a, (step.argb & 0xff) / 255.0f * a, a};
1781
+ for (size_t i = 0; i < out.rgba.size(); i += 4) {
1782
+ std::copy_n(c, 4, &out.rgba[i]);
1783
+ }
1784
+ break;
1785
+ }
1786
+ case SvgFilterStep::Type::Composite:
1787
+ out = composite(input(step.in1), input(step.in2), step.op, step.k);
1788
+ break;
1789
+ case SvgFilterStep::Type::Merge:
1790
+ out = blank(width, height);
1791
+ for (const auto &name : step.inputs) {
1792
+ out = composite(input(name), out, 0, {});
1793
+ }
1794
+ break;
1795
+ }
1796
+ cut(out, pixelBox(step.subregion, toPixels, width, height));
1797
+ results[step.result] = out;
1798
+ last = std::move(out);
1799
+ }
1800
+ cut(last, pixelBox(filter.region, toPixels, width, height));
1801
+ SvgPixels result{.width = width, .height = height, .rgba = std::vector<uint8_t>(last.rgba.size())};
1802
+ for (size_t i = 0; i < last.rgba.size(); ++i) {
1803
+ result.rgba[i] = static_cast<uint8_t>(std::lround(std::clamp(last.rgba[i], 0.0f, 1.0f) * 255));
1804
+ }
1805
+ return result;
1806
+ }
1807
+
1808
+ void drawSvg(const SvgDocument &document, double width, double height, SvgCanvas &canvas) {
1809
+ Renderer(document, width, height, canvas).draw();
1810
+ }
1811
+
1812
+ // --- the svgs mounted ----------------------------------------------------------------------------
1813
+
1814
+ SvgDrawings::SvgDrawings(Reader reader) : reader_(std::move(reader)) {}
1815
+
1816
+ std::optional<SvgElement> SvgDrawings::element(const ViewTree &tree, Tag tag) const {
1817
+ const auto *found = tree.find(tag);
1818
+ if (found == nullptr || !found->view.props) {
1819
+ return std::nullopt;
1820
+ }
1821
+ if (reader_) {
1822
+ return reader_(*found->view.props);
1823
+ }
1824
+ const auto &glue = libraryGlue().svgElement;
1825
+ return glue ? glue(*found->view.props) : std::nullopt;
1826
+ }
1827
+
1828
+ void SvgDrawings::changed(const ViewTree &tree, Tag tag) {
1829
+ for (Tag at = tag; at != -1;) {
1830
+ auto e = element(tree, at);
1831
+ if (!e) {
1832
+ return;
1833
+ }
1834
+ if (e->kind == SvgKind::Svg) {
1835
+ dirty_.insert(at);
1836
+ return;
1837
+ }
1838
+ const auto *found = tree.find(at);
1839
+ at = found == nullptr ? -1 : found->parent;
1840
+ }
1841
+ }
1842
+
1843
+ void SvgDrawings::deleted(Tag tag) {
1844
+ dirty_.erase(tag);
1845
+ drawn_.erase(tag);
1846
+ }
1847
+
1848
+ std::optional<SvgNode> SvgDrawings::node(const ViewTree &tree, Tag tag) const {
1849
+ auto e = element(tree, tag);
1850
+ if (!e) {
1851
+ return std::nullopt;
1852
+ }
1853
+ SvgNode out{.element = std::move(*e)};
1854
+ for (Tag child : tree.find(tag)->children) {
1855
+ if (auto c = node(tree, child); c && c->element.kind != SvgKind::Svg) {
1856
+ out.children.push_back(std::move(*c));
1857
+ }
1858
+ }
1859
+ return out;
1860
+ }
1861
+
1862
+ std::vector<SvgDrawings::Drawing> SvgDrawings::settle(const ViewTree &tree) {
1863
+ std::vector<Tag> dirty(dirty_.begin(), dirty_.end());
1864
+ dirty_.clear();
1865
+ std::sort(dirty.begin(), dirty.end());
1866
+ std::vector<Drawing> out;
1867
+ for (Tag tag : dirty) {
1868
+ auto root = node(tree, tag);
1869
+ if (!root || root->element.kind != SvgKind::Svg) {
1870
+ continue;
1871
+ }
1872
+ auto document = std::make_shared<const SvgDocument>(SvgDocument{.root = std::move(*root)});
1873
+ auto known = drawn_.find(tag);
1874
+ if (known != drawn_.end() && *known->second == *document) {
1875
+ continue;
1876
+ }
1877
+ drawn_[tag] = document;
1878
+ out.push_back({.svg = tag, .document = std::move(document)});
1879
+ }
1880
+ return out;
1881
+ }
1882
+
1883
+ } // namespace ngn