├── .github ├── FUNDING.yml └── workflows │ ├── check.yml │ └── playground_without_softlink.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── package.json ├── pnpm-workspace.yaml ├── soft-skia-wasm ├── .appveyor.yml ├── .cargo-ok ├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE_APACHE ├── LICENSE_MIT ├── README.md ├── src │ ├── lib.rs │ └── utils.rs └── tests │ └── web.rs ├── soft-skia ├── Cargo.toml ├── assets │ └── Roboto-Regular.ttf └── src │ ├── instance.rs │ ├── lib.rs │ ├── provider.rs │ ├── shape.rs │ ├── tree.rs │ └── util.rs ├── src └── lib.rs ├── vue-playground ├── .browserslistrc ├── .eslintrc.js ├── .gitignore ├── README.md ├── babel.config.js ├── package-ci.json ├── package.json ├── public │ ├── NanumPenScript-Regular.ttf │ ├── OFL.txt │ ├── favicon.ico │ └── index.html ├── src │ ├── App.vue │ ├── CustomLayout.vue │ ├── assets │ │ └── logo.png │ ├── code.ts │ ├── loading-code.ts │ ├── main.ts │ └── shims-vue.d.ts ├── tsconfig.json └── vue.config.js └── vue-skia-framework ├── .gitignore ├── LICENSE ├── README.md ├── common.ts ├── components ├── VCircle.vue ├── VGroup.vue ├── VGroupClip.vue ├── VImage.vue ├── VLine.vue ├── VPoints.vue ├── VRect.vue ├── VRoundRect.vue ├── VSurface.vue └── VText.vue ├── launch.ts ├── main.js ├── package-publish.json ├── package.json ├── plugin └── index.ts ├── surface └── index.ts ├── tsconfig.json └── type.ts /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [meloalright, rustq] 2 | -------------------------------------------------------------------------------- /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: Check 2 | 3 | on: 4 | push: 5 | branches: 6 | - '**' 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | - uses: actions/setup-node@v3.8.1 15 | with: 16 | node-version: 16.x 17 | # File containing the ve 18 | - uses: actions-rs/toolchain@v1 19 | with: 20 | toolchain: stable 21 | components: clippy 22 | override: true 23 | 24 | - name: soft-skia 25 | run: | 26 | cd soft-skia 27 | cargo build 28 | cargo test 29 | 30 | - name: Install pnpm 31 | uses: pnpm/action-setup@v2 32 | 33 | - name: soft-skia-wasm 34 | run: | 35 | cargo install wasm-pack 36 | cd soft-skia-wasm 37 | wasm-pack build --release --target web 38 | 39 | - name: vue-skia-framework 40 | run: | 41 | cd vue-skia-framework 42 | pnpm i 43 | pnpm run build 44 | 45 | - name: vue-playground 46 | run: | 47 | cd vue-playground 48 | pnpm i 49 | pnpm run build 50 | 51 | - name: Archive vue-skia-framework artifacts 52 | uses: actions/upload-artifact@v3 53 | with: 54 | name: vue-skia-framework 55 | path: | 56 | vue-skia-framework/lib 57 | vue-skia-framework/type.d.ts 58 | vue-skia-framework/main.js 59 | vue-skia-framework/main.d.ts 60 | vue-skia-framework/components 61 | vue-skia-framework/LICENSE 62 | vue-skia-framework/package-publish.json 63 | 64 | - name: Archive soft-skia-wasm artifacts 65 | uses: actions/upload-artifact@v3 66 | with: 67 | name: soft-skia-wasm 68 | path: | 69 | soft-skia-wasm/pkg 70 | 71 | - name: Archive vue-playground in monorepo artifacts 72 | uses: actions/upload-artifact@v3 73 | with: 74 | name: vue-playground 75 | path: | 76 | vue-playground 77 | !vue-playground/node_modules 78 | -------------------------------------------------------------------------------- /.github/workflows/playground_without_softlink.yml: -------------------------------------------------------------------------------- 1 | name: Playground Without Softlink 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - uses: actions/setup-node@v3.8.1 18 | with: 19 | node-version: 16.x 20 | - uses: actions-rs/toolchain@v1 21 | with: 22 | toolchain: stable 23 | components: clippy 24 | override: true 25 | 26 | - name: vue-playground 27 | run: | 28 | cd vue-playground 29 | cp package-ci.json package.json 30 | npm i 31 | npm run build 32 | 33 | - name: Archive vue-playground results 34 | uses: actions/upload-artifact@v3 35 | with: 36 | name: vue-playground-without-softlink 37 | path: | 38 | vue-playground 39 | !vue-playground/node_modules -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | target 12 | 13 | # NodeJS 14 | node_modules 15 | package-lock.json 16 | 17 | # defination 18 | *.d.ts 19 | 20 | # MacOS 21 | .DS_Store 22 | 23 | # Output 24 | *.node 25 | lib/ 26 | typings/ 27 | .idea 28 | 29 | # pnpm 30 | pnpm-lock.yaml -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vue-skia" 3 | version = "0.0.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | crate-type = ["cdylib"] 8 | 9 | [workspace] 10 | members = ["soft-skia", "soft-skia-wasm"] 11 | 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | 14 | [dependencies] 15 | png = "0.17.5" 16 | colorsys = "0.6.5" 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 rustq 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vue Skia 2 | 3 | [![license](https://img.shields.io/badge/license-MIT-cyan)](https://revolunet.mit-license.org/) ![vue-3.x](https://img.shields.io/badge/vue-3.x-lightgreen) [![crates](https://img.shields.io/crates/v/soft-skia)](https://crates.io/crates/soft_skia) [![npm](https://img.shields.io/npm/v/vue-skia?color=purple)](https://www.npmjs.com/package/vue-skia) [![downloads](https://img.shields.io/npm/dm/vue-skia)](https://www.npmjs.com/package/vue-skia) 4 | 5 | 6 | The `vue-skia` is a `skia` based 2d graphics `vue` rendering library. It is based on `Rust` to implement software rasterization to perform rendering. It takes up less memory than the native canvas, however it is still an experimental project. And it's based entirely on `vue` syntax. 7 | 8 | 基于 `Skia` 的 2D 图形 `Vue` 渲染库 —— 使用 `Rust` 语言实现纯软件光栅化渲染,相比原生画布占用更少的内存,不过目前仍然是一个实验项目;此外使用层面完全基于 `Vue` 语法。 9 | 10 | 11 | [![usage](https://user-images.githubusercontent.com/11075892/260789003-8bc6cf06-1525-468a-ad70-357771e9969f.png)](https://vue-skia.netlify.app) 12 | 13 | Live Demo: [https://vue-skia.netlify.app](https://vue-skia.netlify.app) 14 | 15 | ## Usage 16 | 17 | ```shell 18 | $ npm i vue-skia 19 | ``` 20 | 21 | `main.ts` 22 | 23 | ```ts 24 | import { createApp } from "vue"; 25 | import App from "./App.vue"; 26 | import { VueSkia } from 'vue-skia' 27 | 28 | const app = createApp(App); 29 | app.use(VueSkia); 30 | app.mount("#app"); 31 | ``` 32 | 33 | `App.vue` 34 | 35 | ```vue 36 | 58 | 59 | 85 | ``` 86 | 87 | ## Library Development 88 | 89 | #### Soft Skia Development 90 | 91 | ```shell 92 | $ cd soft-skia 93 | $ cargo test 94 | ``` 95 | 96 | #### Soft Skia WASM Development 97 | 98 | ```shell 99 | $ cd soft-skia-wasm 100 | $ wasm-pack build --release --target web 101 | ``` 102 | 103 | #### Vue Skia Framework Development 104 | 105 | ```shell 106 | $ cd vue-skia-framework 107 | $ pnpm i 108 | $ pnpm run build 109 | ``` 110 | 111 | #### Vue Playground Development 112 | 113 | ```shell 114 | $ cd vue-playground 115 | $ pnpm i 116 | $ pnpm run serve 117 | ``` 118 | 119 | ## License 120 | 121 | [MIT](https://opensource.org/licenses/MIT) 122 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "monorepo", 3 | "version": "0.1.2", 4 | "private": "true", 5 | "scripts": {}, 6 | "packageManager": "pnpm@7.32.0" 7 | } 8 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - vue-skia-framework 3 | - vue-playground 4 | - soft-skia-wasm/pkg 5 | -------------------------------------------------------------------------------- /soft-skia-wasm/.appveyor.yml: -------------------------------------------------------------------------------- 1 | install: 2 | - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe 3 | - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly 4 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 5 | - rustc -V 6 | - cargo -V 7 | 8 | build: false 9 | 10 | test_script: 11 | - cargo test --locked 12 | -------------------------------------------------------------------------------- /soft-skia-wasm/.cargo-ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rustq/vue-skia/4d4c29c54b7f609a0f6a3cd106343c4d52f06fef/soft-skia-wasm/.cargo-ok -------------------------------------------------------------------------------- /soft-skia-wasm/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | bin/ 5 | pkg/ 6 | wasm-pack.log 7 | -------------------------------------------------------------------------------- /soft-skia-wasm/.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | cache: cargo 5 | 6 | matrix: 7 | include: 8 | 9 | # Builds with wasm-pack. 10 | - rust: beta 11 | env: RUST_BACKTRACE=1 12 | addons: 13 | firefox: latest 14 | chrome: stable 15 | before_script: 16 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 17 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 18 | - cargo install-update -a 19 | - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f 20 | script: 21 | - cargo generate --git . --name testing 22 | # Having a broken Cargo.toml (in that it has curlies in fields) anywhere 23 | # in any of our parent dirs is problematic. 24 | - mv Cargo.toml Cargo.toml.tmpl 25 | - cd testing 26 | - wasm-pack build 27 | - wasm-pack test --chrome --firefox --headless 28 | 29 | # Builds on nightly. 30 | - rust: nightly 31 | env: RUST_BACKTRACE=1 32 | before_script: 33 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 34 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 35 | - cargo install-update -a 36 | - rustup target add wasm32-unknown-unknown 37 | script: 38 | - cargo generate --git . --name testing 39 | - mv Cargo.toml Cargo.toml.tmpl 40 | - cd testing 41 | - cargo check 42 | - cargo check --target wasm32-unknown-unknown 43 | - cargo check --no-default-features 44 | - cargo check --target wasm32-unknown-unknown --no-default-features 45 | - cargo check --no-default-features --features console_error_panic_hook 46 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 47 | - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" 48 | - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" 49 | 50 | # Builds on beta. 51 | - rust: beta 52 | env: RUST_BACKTRACE=1 53 | before_script: 54 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 55 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 56 | - cargo install-update -a 57 | - rustup target add wasm32-unknown-unknown 58 | script: 59 | - cargo generate --git . --name testing 60 | - mv Cargo.toml Cargo.toml.tmpl 61 | - cd testing 62 | - cargo check 63 | - cargo check --target wasm32-unknown-unknown 64 | - cargo check --no-default-features 65 | - cargo check --target wasm32-unknown-unknown --no-default-features 66 | - cargo check --no-default-features --features console_error_panic_hook 67 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 68 | # Note: no enabling the `wee_alloc` feature here because it requires 69 | # nightly for now. 70 | -------------------------------------------------------------------------------- /soft-skia-wasm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "soft-skia-wasm" 3 | version = "0.12.0" 4 | authors = ["meloalright "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["cdylib", "rlib"] 9 | 10 | [features] 11 | default = ["console_error_panic_hook"] 12 | 13 | [dependencies] 14 | serde = { version = "1.0", features = ["derive"] } 15 | serde-wasm-bindgen = "0.5.0" 16 | wasm-bindgen = "0.2.63" 17 | base64 = "0.21.0" 18 | csscolorparser = "0.7.0" 19 | soft_skia = { path = "../soft-skia" } 20 | 21 | # The `console_error_panic_hook` crate provides better debugging of panics by 22 | # logging them with `console.error`. This is great for development, but requires 23 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 24 | # code size when deploying. 25 | console_error_panic_hook = { version = "0.1.6", optional = true } 26 | 27 | # `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size 28 | # compared to the default allocator's ~10K. It is slower than the default 29 | # allocator, however. 30 | wee_alloc = { version = "0.4.5", optional = true } 31 | 32 | [dev-dependencies] 33 | wasm-bindgen-test = "0.3.13" 34 | 35 | [profile.release] 36 | # Tell `rustc` to optimize for small code size. 37 | opt-level = "s" 38 | -------------------------------------------------------------------------------- /soft-skia-wasm/LICENSE_APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /soft-skia-wasm/LICENSE_MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 meloalright 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /soft-skia-wasm/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

wasm-pack-template

4 | 5 | A template for kick starting a Rust and WebAssembly project using wasm-pack. 6 | 7 |

8 | Build Status 9 |

10 | 11 |

12 | Tutorial 13 | | 14 | Chat 15 |

16 | 17 | Built with 🦀🕸 by The Rust and WebAssembly Working Group 18 |
19 | 20 | ## About 21 | 22 | [**📚 Read this template tutorial! 📚**][template-docs] 23 | 24 | This template is designed for compiling Rust libraries into WebAssembly and 25 | publishing the resulting package to NPM. 26 | 27 | Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other 28 | templates and usages of `wasm-pack`. 29 | 30 | [tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html 31 | [template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html 32 | 33 | ## 🚴 Usage 34 | 35 | ### 🐑 Use `cargo generate` to Clone this Template 36 | 37 | [Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate) 38 | 39 | ``` 40 | cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project 41 | cd my-project 42 | ``` 43 | 44 | ### 🛠️ Build with `wasm-pack build` 45 | 46 | ``` 47 | wasm-pack build 48 | ``` 49 | 50 | ### 🔬 Test in Headless Browsers with `wasm-pack test` 51 | 52 | ``` 53 | wasm-pack test --headless --firefox 54 | ``` 55 | 56 | ### 🎁 Publish to NPM with `wasm-pack publish` 57 | 58 | ``` 59 | wasm-pack publish 60 | ``` 61 | 62 | ## 🔋 Batteries Included 63 | 64 | * [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating 65 | between WebAssembly and JavaScript. 66 | * [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook) 67 | for logging panic messages to the developer console. 68 | * [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized 69 | for small code size. 70 | * `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you 71 | 72 | ## License 73 | 74 | Licensed under either of 75 | 76 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 77 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 78 | 79 | at your option. 80 | 81 | ### Contribution 82 | 83 | Unless you explicitly state otherwise, any contribution intentionally 84 | submitted for inclusion in the work by you, as defined in the Apache-2.0 85 | license, shall be dual licensed as above, without any additional terms or 86 | conditions. -------------------------------------------------------------------------------- /soft-skia-wasm/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate soft_skia; 2 | mod utils; 3 | 4 | use base64; 5 | use soft_skia::instance::Instance; 6 | use soft_skia::provider::{Group, GroupClip, Providers}; 7 | use soft_skia::shape::ColorU8; 8 | use soft_skia::shape::Pixmap; 9 | use soft_skia::shape::Rect; 10 | use soft_skia::shape::{Circle, Image, Line, PaintStyle, Points, RoundRect, Shapes, Text}; 11 | use soft_skia::tree::Node; 12 | use wasm_bindgen::prelude::*; 13 | use csscolorparser; 14 | 15 | // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global 16 | // allocator. 17 | #[cfg(feature = "wee_alloc")] 18 | #[global_allocator] 19 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 20 | 21 | #[wasm_bindgen] 22 | pub struct SoftSkiaWASM(Instance); 23 | 24 | use serde::{Deserialize, Serialize}; 25 | 26 | #[derive(Serialize, Deserialize, Debug)] 27 | pub struct WASMRectAttr { 28 | width: u32, 29 | height: u32, 30 | x: u32, 31 | y: u32, 32 | color: Option, 33 | style: Option, 34 | } 35 | 36 | #[derive(Serialize, Deserialize, Debug)] 37 | pub struct WASMCircleAttr { 38 | cx: u32, 39 | cy: u32, 40 | r: u32, 41 | color: Option, 42 | style: Option, 43 | } 44 | 45 | #[derive(Serialize, Deserialize, Debug)] 46 | pub struct WASMRoundRectAttr { 47 | width: u32, 48 | height: u32, 49 | r: u32, 50 | x: u32, 51 | y: u32, 52 | color: Option, 53 | style: Option, 54 | } 55 | 56 | #[derive(Serialize, Deserialize, Debug)] 57 | pub struct WASMLineAttr { 58 | p1: [u32; 2], 59 | p2: [u32; 2], 60 | color: Option, 61 | stroke_width: Option, 62 | } 63 | 64 | #[derive(Serialize, Deserialize, Debug)] 65 | pub struct WASMPointsAttr { 66 | points: Vec<[u32; 2]>, 67 | color: Option, 68 | stroke_width: Option, 69 | style: Option, 70 | } 71 | 72 | #[derive(Serialize, Deserialize, Debug)] 73 | pub struct WASMGroupAttr { 74 | x: Option, 75 | y: Option, 76 | color: Option, 77 | style: Option, 78 | stroke_width: Option, 79 | invert_clip: Option, 80 | } 81 | 82 | #[derive(Serialize, Deserialize, Debug)] 83 | pub struct WASMGroupClipAttr { 84 | clip: usize, 85 | } 86 | 87 | #[derive(Serialize, Deserialize, Debug)] 88 | pub struct WASMImageAttr { 89 | image: String, 90 | x: i32, 91 | y: i32, 92 | width: u32, 93 | height: u32, 94 | blur: Option, 95 | grayscale: Option, 96 | brighten: Option, 97 | invert: Option, 98 | } 99 | 100 | #[derive(Serialize, Deserialize, Debug)] 101 | pub struct WASMTextAttr { 102 | text: String, 103 | x: i32, 104 | y: i32, 105 | font_size: Option, 106 | color: Option, 107 | max_width: Option, 108 | } 109 | 110 | #[derive(Serialize, Deserialize, Debug)] 111 | pub enum WASMShapesAttr { 112 | R(WASMRectAttr), 113 | C(WASMCircleAttr), 114 | RR(WASMRoundRectAttr), 115 | L(WASMLineAttr), 116 | P(WASMPointsAttr), 117 | G(WASMGroupAttr), 118 | GC(WASMGroupClipAttr), 119 | I(WASMImageAttr), 120 | T(WASMTextAttr), 121 | } 122 | 123 | #[derive(Serialize, Deserialize, Debug)] 124 | pub struct WASMShape { 125 | pub attr: WASMShapesAttr, 126 | } 127 | 128 | #[wasm_bindgen] 129 | impl SoftSkiaWASM { 130 | #[wasm_bindgen(constructor)] 131 | pub fn new(id: usize) -> Self { 132 | utils::set_panic_hook(); 133 | let instance = Instance::new(id); 134 | SoftSkiaWASM(instance) 135 | } 136 | 137 | #[wasm_bindgen(js_name = createChildAppendToContainer)] 138 | pub fn create_child_append_to_container(&mut self, child_id: usize, container_id: usize) { 139 | self.0 140 | .create_child_append_to_container(child_id, container_id) 141 | } 142 | 143 | #[wasm_bindgen(js_name = createChildInsertBeforeElementOfContainer)] 144 | pub fn create_child_insert_before_element_of_container( 145 | &mut self, 146 | child_id: usize, 147 | insert_before_id: usize, 148 | container_id: usize, 149 | ) { 150 | self.0.create_child_insert_before_element_of_container( 151 | child_id, 152 | insert_before_id, 153 | container_id, 154 | ); 155 | } 156 | 157 | #[wasm_bindgen(js_name = removeChildFromContainer)] 158 | pub fn remove_child_from_container(&mut self, child_id: usize, container_id: usize) { 159 | self.0.remove_child_from_container(child_id, container_id) 160 | } 161 | 162 | #[cfg(debug_assertions)] 163 | #[wasm_bindgen(js_name = toDebug)] 164 | pub fn to_debug(&mut self) -> String { 165 | format!("{:?}", self.0) 166 | } 167 | 168 | #[wasm_bindgen(js_name = toBase64)] 169 | pub fn to_base64(&mut self) -> String { 170 | let root = self.0.tree.get_root(); 171 | let mut pixmap = match root.shape { 172 | Shapes::R(Rect { 173 | x, 174 | y, 175 | width, 176 | height, 177 | color, 178 | style, 179 | }) => Pixmap::new(width, height).unwrap(), 180 | _ => Pixmap::new(0, 0).unwrap(), 181 | }; 182 | 183 | Self::recursive_rasterization_node_to_pixmap(root, &mut pixmap); 184 | 185 | let data = pixmap.clone().encode_png().unwrap(); 186 | let data_url = base64::encode(&data); 187 | format!("data:image/png;base64,{}", data_url) 188 | } 189 | 190 | fn recursive_rasterization_node_to_pixmap(node: &mut Node, pixmap: &mut Pixmap) -> () { 191 | let context = node.provider.as_ref().and_then(|p| p.get_context()); 192 | 193 | for item in node.children.iter_mut() { 194 | let inactive = *context 195 | .and_then(|c| c.inactive_nodes_map.as_ref().and_then(|m| m.get(&item.id))) 196 | .unwrap_or(&false); 197 | 198 | if inactive { 199 | continue; 200 | } 201 | 202 | item.draw(pixmap, context); 203 | 204 | if let Some(provider) = item.provider.as_mut() { 205 | provider.set_context(pixmap, node.provider.as_ref()); 206 | 207 | // 这段感觉放这有点重,想搬走 208 | match provider { 209 | Providers::G(group) => { 210 | if let Some(clip) = &group.clip { 211 | if let Some(clip_id) = clip.id { 212 | if let Some(clip_path) = 213 | item.children.iter_mut().find(|n| n.id == clip_id).and_then( 214 | |n| Some(n.shape.get_path(group.context.as_ref().unwrap())), 215 | ) 216 | { 217 | group.set_context_mask(pixmap, &clip_path); 218 | } 219 | } 220 | } 221 | } 222 | } 223 | } 224 | 225 | Self::recursive_rasterization_node_to_pixmap(item, pixmap); 226 | } 227 | if let Some(context) = context { 228 | if let Some(mask) = &context.mask { 229 | pixmap.apply_mask(mask) 230 | } 231 | } 232 | } 233 | 234 | #[wasm_bindgen(js_name = setAttrBySerde)] 235 | pub fn set_attr_by_serde(&mut self, id: usize, value: JsValue) { 236 | let message: WASMShape = serde_wasm_bindgen::from_value(value).unwrap(); 237 | match message.attr { 238 | WASMShapesAttr::R(WASMRectAttr { 239 | width, 240 | height, 241 | x, 242 | y, 243 | color, 244 | style, 245 | }) => { 246 | let color = parse_color(color); 247 | let style = parse_style(style); 248 | self.0.set_shape_to_child( 249 | id, 250 | Shapes::R(Rect { 251 | x, 252 | y, 253 | width, 254 | height, 255 | color, 256 | style, 257 | }), 258 | ) 259 | } 260 | WASMShapesAttr::C(WASMCircleAttr { 261 | cx, 262 | cy, 263 | r, 264 | color, 265 | style, 266 | }) => { 267 | let color = parse_color(color); 268 | let style = parse_style(style); 269 | self.0.set_shape_to_child( 270 | id, 271 | Shapes::C(Circle { 272 | cx, 273 | cy, 274 | r, 275 | color, 276 | style, 277 | }), 278 | ) 279 | } 280 | WASMShapesAttr::RR(WASMRoundRectAttr { 281 | width, 282 | height, 283 | r, 284 | x, 285 | y, 286 | color, 287 | style, 288 | }) => { 289 | let color = parse_color(color); 290 | let style = parse_style(style); 291 | 292 | self.0.set_shape_to_child( 293 | id, 294 | Shapes::RR(RoundRect { 295 | x, 296 | y, 297 | r, 298 | width, 299 | height, 300 | color, 301 | style, 302 | }), 303 | ) 304 | } 305 | WASMShapesAttr::L(WASMLineAttr { 306 | p1, 307 | p2, 308 | stroke_width, 309 | color, 310 | }) => { 311 | let color = parse_color(color); 312 | self.0.set_shape_to_child( 313 | id, 314 | Shapes::L(Line { 315 | p1, 316 | p2, 317 | stroke_width, 318 | color, 319 | }), 320 | ) 321 | } 322 | WASMShapesAttr::P(WASMPointsAttr { 323 | points, 324 | color, 325 | stroke_width, 326 | style, 327 | }) => { 328 | let color = parse_color(color); 329 | let style = parse_style(style); 330 | self.0.set_shape_to_child( 331 | id, 332 | Shapes::P(Points { 333 | points, 334 | stroke_width, 335 | color, 336 | style, 337 | }), 338 | ) 339 | } 340 | WASMShapesAttr::G(WASMGroupAttr { 341 | x, 342 | y, 343 | color, 344 | stroke_width, 345 | style, 346 | invert_clip, 347 | }) => { 348 | let color = parse_color(color); 349 | let style = parse_style(style); 350 | let provider = self.0.get_tree_node_by_id(id).unwrap().provider.as_ref(); 351 | // reuse original clip 352 | let mut clip = if let Some(Providers::G(group)) = provider { 353 | group.clip.clone().unwrap_or_default() 354 | } else { 355 | GroupClip::default() 356 | }; 357 | clip.invert = invert_clip; 358 | 359 | self.0.set_provider_to_child( 360 | id, 361 | Providers::G(Group { 362 | x, 363 | y, 364 | color, 365 | style, 366 | stroke_width, 367 | clip: Some(clip), 368 | context: None, 369 | }), 370 | ) 371 | } 372 | WASMShapesAttr::GC(WASMGroupClipAttr { clip }) => { 373 | let provider = self 374 | .0 375 | .get_tree_node_by_id(id) 376 | .unwrap() 377 | .provider 378 | .as_mut() 379 | .unwrap(); 380 | 381 | match provider { 382 | Providers::G(ref mut group) => group.set_clip_id(clip), 383 | } 384 | } 385 | WASMShapesAttr::I(WASMImageAttr { 386 | x, 387 | y, 388 | image, 389 | width, 390 | height, 391 | blur, 392 | grayscale, 393 | brighten, 394 | invert, 395 | }) => self.0.set_shape_to_child( 396 | id, 397 | Shapes::I(Image { 398 | image, 399 | x, 400 | y, 401 | width, 402 | height, 403 | blur, 404 | grayscale, 405 | brighten, 406 | invert, 407 | }), 408 | ), 409 | WASMShapesAttr::T(WASMTextAttr { 410 | x, 411 | y, 412 | text, 413 | font_size, 414 | color, 415 | max_width, 416 | }) => { 417 | let color = parse_color(color); 418 | let font_size = font_size.unwrap_or(16.0); 419 | self.0.set_shape_to_child( 420 | id, 421 | Shapes::T(Text { 422 | text, 423 | x, 424 | y, 425 | font_size, 426 | color, 427 | max_width, 428 | }), 429 | ) 430 | } 431 | WASMShapesAttr::T(WASMTextAttr { 432 | x, 433 | y, 434 | text, 435 | font_size, 436 | color, 437 | max_width, 438 | }) => { 439 | let color = parse_color(color); 440 | let font_size = font_size.unwrap_or(16.0); 441 | self.0.set_shape_to_child( 442 | id, 443 | Shapes::T(Text { 444 | text, 445 | x, 446 | y, 447 | font_size, 448 | color, 449 | max_width, 450 | }), 451 | ) 452 | } 453 | }; 454 | } 455 | } 456 | 457 | fn parse_color(color: Option) -> Option { 458 | if let Some(color_str) = color { 459 | if let Ok(css_color) = csscolorparser::parse(&color_str) { 460 | let css_rgba8 = css_color.to_rgba8(); 461 | return Some(ColorU8::from_rgba(css_rgba8[0], css_rgba8[1], css_rgba8[2], css_rgba8[3])) 462 | } 463 | } 464 | None 465 | } 466 | 467 | fn parse_style(style: Option) -> Option { 468 | match style.as_deref() { 469 | Some("stroke") => Some(PaintStyle::Stroke), 470 | Some("fill") => Some(PaintStyle::Fill), 471 | _ => None, 472 | } 473 | } 474 | -------------------------------------------------------------------------------- /soft-skia-wasm/src/utils.rs: -------------------------------------------------------------------------------- 1 | pub fn set_panic_hook() { 2 | // When the `console_error_panic_hook` feature is enabled, we can call the 3 | // `set_panic_hook` function at least once during initialization, and then 4 | // we will get better error messages if our code ever panics. 5 | // 6 | // For more details see 7 | // https://github.com/rustwasm/console_error_panic_hook#readme 8 | #[cfg(feature = "console_error_panic_hook")] 9 | console_error_panic_hook::set_once(); 10 | } 11 | -------------------------------------------------------------------------------- /soft-skia-wasm/tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | fn pass() { 12 | assert_eq!(1 + 1, 2); 13 | } 14 | -------------------------------------------------------------------------------- /soft-skia/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "soft_skia" 3 | version = "0.12.0" 4 | edition = "2021" 5 | description="software rasterization skia binding" 6 | license = "MIT" 7 | 8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 9 | 10 | [dependencies] 11 | png = "0.17.5" 12 | tiny-skia = "0.10.0" 13 | base64 = "0.21.0" 14 | fontdue = "0.7.3" 15 | image = "0.25.1" 16 | 17 | [dependencies.web-sys] 18 | version = "0.3" 19 | features = [ 20 | "console", 21 | ] -------------------------------------------------------------------------------- /soft-skia/assets/Roboto-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rustq/vue-skia/4d4c29c54b7f609a0f6a3cd106343c4d52f06fef/soft-skia/assets/Roboto-Regular.ttf -------------------------------------------------------------------------------- /soft-skia/src/instance.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use crate::provider::Providers; 4 | use crate::shape::Rect; 5 | use crate::shape::Shape; 6 | use crate::shape::Shapes; 7 | use crate::tree::Node; 8 | use crate::tree::Tree; 9 | 10 | #[derive(Debug)] 11 | pub struct Instance { 12 | pub tree: Tree, 13 | pub node_ptr_map: HashMap, 14 | } 15 | 16 | impl Instance { 17 | pub fn new(id: usize) -> Self { 18 | Instance { 19 | tree: Tree::default(id), 20 | node_ptr_map: HashMap::new(), 21 | } 22 | } 23 | 24 | pub fn create_child_append_to_container(&mut self, child_id: usize, container_id: usize) { 25 | let mut child = Box::new(Node::default(child_id, Shapes::R(Rect::default()))); 26 | let container = self.get_tree_node_by_id(container_id).unwrap(); 27 | let raw_child: *mut _ = &mut *child; 28 | container.append_boxed_node(child); 29 | self.node_ptr_map.insert(child_id, raw_child); 30 | } 31 | 32 | pub fn create_child_insert_before_element_of_container( 33 | &mut self, 34 | child_id: usize, 35 | insert_before_id: usize, 36 | container_id: usize, 37 | ) { 38 | let mut child = Box::new(Node::default(child_id, Shapes::R(Rect::default()))); 39 | let container = self.get_tree_node_by_id(container_id).unwrap(); 40 | let raw_child: *mut _ = &mut *child; 41 | container.insert_boxed_node_before_id(insert_before_id, child); 42 | self.node_ptr_map.insert(child_id, raw_child); 43 | } 44 | 45 | pub fn set_shape_to_child(&mut self, child_id: usize, shape: Shapes) { 46 | let mut child = self.get_tree_node_by_id(child_id).unwrap(); 47 | child.shape = shape; 48 | } 49 | 50 | pub fn set_provider_to_child(&mut self, child_id: usize, provider: Providers) { 51 | let mut child = self.get_tree_node_by_id(child_id).unwrap(); 52 | child.provider = Some(provider); 53 | } 54 | 55 | pub fn remove_child_from_container(&mut self, child_id: usize, container_id: usize) { 56 | let container = self.get_tree_node_by_id(container_id).unwrap(); 57 | container.remove_child_by_id(child_id); 58 | self.node_ptr_map.remove(&child_id); 59 | } 60 | 61 | pub fn get_tree_node_by_id(&mut self, id: usize) -> Option<&mut Node> { 62 | let root = self.tree.get_root(); 63 | 64 | if id == root.id { 65 | Some(root) 66 | } else { 67 | let raw_node = self.node_ptr_map.get(&id); 68 | match raw_node { 69 | Some(row_node) => unsafe { Some(&mut **row_node) }, 70 | _ => None, 71 | } 72 | } 73 | } 74 | } 75 | 76 | #[cfg(test)] 77 | mod test { 78 | use super::Instance; 79 | use crate::shape::PaintStyle; 80 | use crate::shape::Rect; 81 | use crate::shape::Shapes; 82 | use tiny_skia::ColorU8; 83 | 84 | #[test] 85 | fn test_get_tree_node_by_id() { 86 | let mut instance = Instance::new(0); 87 | 88 | let target_0 = instance.get_tree_node_by_id(0); 89 | assert_eq!(target_0.is_none(), false); 90 | assert_eq!(target_0.unwrap().id, 0); 91 | 92 | let target_3 = instance.get_tree_node_by_id(3); 93 | assert_eq!(target_3.is_none(), true); 94 | } 95 | 96 | #[test] 97 | fn test_append() { 98 | let mut instance = Instance::new(0); 99 | assert_eq!( 100 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 101 | 0 102 | ); 103 | 104 | instance.create_child_append_to_container(1, 0); 105 | instance.create_child_append_to_container(2, 0); 106 | instance.create_child_append_to_container(3, 0); 107 | 108 | assert_eq!( 109 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 110 | 3 111 | ); 112 | } 113 | 114 | #[test] 115 | fn test_set_shape() { 116 | let mut instance = Instance::new(0); 117 | assert_eq!( 118 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 119 | 0 120 | ); 121 | 122 | instance.create_child_append_to_container(1, 0); 123 | assert_eq!( 124 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 125 | 1 126 | ); 127 | 128 | match instance.get_tree_node_by_id(1).unwrap().shape { 129 | Shapes::R(Rect { 130 | x, 131 | y, 132 | width, 133 | height, 134 | color, 135 | style, 136 | }) => { 137 | assert_eq!(x, 0); 138 | assert_eq!(y, 0); 139 | } 140 | _ => { 141 | panic!() 142 | } 143 | } 144 | 145 | instance.set_shape_to_child( 146 | 1, 147 | Shapes::R(Rect { 148 | x: 20, 149 | y: 20, 150 | width: 200, 151 | height: 200, 152 | color: Some(ColorU8::from_rgba(0, 100, 0, 255)), 153 | style: None, 154 | }), 155 | ); 156 | 157 | match instance.get_tree_node_by_id(1).unwrap().shape { 158 | Shapes::R(Rect { 159 | x, 160 | y, 161 | width, 162 | height, 163 | color, 164 | style, 165 | }) => { 166 | assert_eq!(x, 20); 167 | assert_eq!(y, 20); 168 | assert_eq!(width, 200); 169 | assert_eq!(height, 200); 170 | assert_eq!(color.unwrap().green(), 100); 171 | } 172 | _ => { 173 | panic!() 174 | } 175 | } 176 | } 177 | 178 | #[test] 179 | fn test_remove() { 180 | let mut instance = Instance::new(0); 181 | instance.create_child_append_to_container(1, 0); 182 | instance.create_child_append_to_container(2, 0); 183 | instance.create_child_append_to_container(3, 0); 184 | 185 | assert_eq!( 186 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 187 | 3 188 | ); 189 | 190 | instance.remove_child_from_container(2, 0); 191 | assert_eq!( 192 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 193 | 2 194 | ); 195 | 196 | instance.remove_child_from_container(3, 0); 197 | assert_eq!( 198 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 199 | 1 200 | ); 201 | 202 | instance.remove_child_from_container(1, 0); 203 | assert_eq!( 204 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 205 | 0 206 | ); 207 | 208 | instance.remove_child_from_container(1, 0); 209 | instance.remove_child_from_container(1, 0); 210 | instance.remove_child_from_container(1, 0); 211 | instance.remove_child_from_container(100, 0); 212 | instance.remove_child_from_container(100, 0); 213 | instance.remove_child_from_container(100, 0); 214 | assert_eq!( 215 | instance.get_tree_node_by_id(0).unwrap().get_children_len(), 216 | 0 217 | ); 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /soft-skia/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod instance; 2 | pub mod provider; 3 | pub mod shape; 4 | pub mod tree; 5 | mod util; 6 | -------------------------------------------------------------------------------- /soft-skia/src/provider.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use tiny_skia::{ColorU8, FillRule, Pixmap, Transform}; 4 | pub use tiny_skia::{Mask, Path}; 5 | 6 | use crate::shape::{DrawContext, PaintStyle}; 7 | 8 | #[derive(Debug)] 9 | pub enum Providers { 10 | G(Group), 11 | } 12 | 13 | pub trait Provider { 14 | fn default() -> Self; 15 | fn get_context(&self) -> Option<&DrawContext>; 16 | fn set_context(&mut self, pixmap: &mut Pixmap, parent: Option<&Providers>) -> (); 17 | } 18 | 19 | impl Providers { 20 | pub fn get_context(&self) -> Option<&DrawContext> { 21 | match self { 22 | Providers::G(group) => group.get_context(), 23 | } 24 | } 25 | pub fn set_context(&mut self, pixmap: &mut Pixmap, parent: Option<&Providers>) -> () { 26 | match self { 27 | Providers::G(group) => group.set_context(pixmap, parent), 28 | } 29 | } 30 | } 31 | 32 | #[derive(Debug, Default, Clone)] 33 | pub struct GroupClip { 34 | pub id: Option, 35 | pub invert: Option, 36 | } 37 | 38 | impl GroupClip { 39 | pub fn default() -> Self { 40 | GroupClip { 41 | id: None, 42 | invert: None, 43 | } 44 | } 45 | } 46 | 47 | #[derive(Debug)] 48 | pub struct Group { 49 | pub x: Option, 50 | pub y: Option, 51 | pub color: Option, 52 | pub style: Option, 53 | pub stroke_width: Option, 54 | pub clip: Option, 55 | pub context: Option, 56 | } 57 | 58 | impl Provider for Group { 59 | fn default() -> Self { 60 | Group { 61 | x: None, 62 | y: None, 63 | color: None, 64 | style: None, 65 | stroke_width: None, 66 | clip: None, 67 | context: None, 68 | } 69 | } 70 | 71 | fn get_context(&self) -> Option<&DrawContext> { 72 | return self.context.as_ref(); 73 | } 74 | 75 | fn set_context(&mut self, _pixmap: &mut Pixmap, parent: Option<&Providers>) { 76 | let mut inactive_nodes_map = HashMap::new(); 77 | 78 | if let Some(clip_id) = self.clip.as_ref().and_then(|c| c.id) { 79 | inactive_nodes_map.insert(clip_id, true); 80 | } 81 | 82 | let mut context = DrawContext { 83 | offset_x: self.x.unwrap_or(0), 84 | offset_y: self.y.unwrap_or(0), 85 | color: self.color, 86 | style: self.style, 87 | stroke_width: self.stroke_width, 88 | mask: None, 89 | inactive_nodes_map: Some(inactive_nodes_map), 90 | }; 91 | 92 | match parent { 93 | Some(Providers::G(group)) => { 94 | if let Some(parent_context) = group.context.as_ref() { 95 | context.offset_x = parent_context.offset_x + context.offset_x; 96 | context.offset_y = parent_context.offset_y + context.offset_y; 97 | context.color = context.color.or(parent_context.color); 98 | context.style = context.style.or(parent_context.style); 99 | context.stroke_width = context.stroke_width.or(parent_context.stroke_width); 100 | } 101 | } 102 | _ => {} 103 | }; 104 | 105 | self.context = Some(context); 106 | } 107 | } 108 | 109 | impl Group { 110 | pub fn set_clip_id(&mut self, id: usize) { 111 | if self.clip.is_none() { 112 | self.clip = Some(GroupClip::default()); 113 | } 114 | 115 | self.clip.as_mut().unwrap().id = Some(id); 116 | } 117 | 118 | pub fn set_context_mask(&mut self, pixmap: &mut Pixmap, path: &Path) { 119 | let mut mask: Option = None; 120 | 121 | if let Some(GroupClip { invert, .. }) = &self.clip { 122 | let mut clip_mask = Mask::new(pixmap.width(), pixmap.height()).unwrap(); 123 | 124 | clip_mask.fill_path(path, FillRule::Winding, true, Transform::default()); 125 | 126 | if let Some(true) = invert { 127 | clip_mask.invert(); 128 | } 129 | 130 | mask = Some(clip_mask); 131 | } 132 | 133 | self.context.as_mut().unwrap().mask = mask; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /soft-skia/src/shape.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use fontdue::{ 4 | layout::{CoordinateSystem, Layout, LayoutSettings, TextStyle}, 5 | Font, 6 | }; 7 | use std::iter::zip; 8 | pub use tiny_skia::{ColorU8, FillRule, Mask, Paint, PathBuilder, Pixmap, Stroke, Transform}; 9 | use tiny_skia::{LineCap, LineJoin, Path, PixmapPaint}; 10 | use image::io::Reader as ImageReader; 11 | use std::io::Cursor; 12 | 13 | #[derive(Debug)] 14 | pub enum Shapes { 15 | R(Rect), 16 | C(Circle), 17 | RR(RoundRect), 18 | L(Line), 19 | P(Points), 20 | I(Image), 21 | T(Text), 22 | } 23 | 24 | #[derive(Debug)] 25 | pub struct DrawContext { 26 | pub offset_x: u32, 27 | pub offset_y: u32, 28 | pub color: Option, 29 | pub style: Option, 30 | pub stroke_width: Option, 31 | pub mask: Option, 32 | pub inactive_nodes_map: Option>, 33 | } 34 | 35 | impl DrawContext { 36 | pub fn default() -> Self { 37 | DrawContext { 38 | offset_x: 0, 39 | offset_y: 0, 40 | color: None, 41 | style: None, 42 | stroke_width: None, 43 | mask: None, 44 | inactive_nodes_map: None, 45 | } 46 | } 47 | } 48 | 49 | pub trait Shape { 50 | fn default() -> Self; 51 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> (); 52 | fn get_path(&self, context: &DrawContext) -> Path { 53 | let pb = PathBuilder::new(); 54 | pb.finish().unwrap() 55 | } 56 | } 57 | 58 | #[derive(Debug, Clone, Copy)] 59 | pub enum PaintStyle { 60 | Stroke, 61 | Fill, 62 | } 63 | 64 | #[derive(Debug)] 65 | pub struct Rect { 66 | pub x: u32, 67 | pub y: u32, 68 | pub width: u32, 69 | pub height: u32, 70 | pub color: Option, 71 | pub style: Option, 72 | } 73 | 74 | #[derive(Debug)] 75 | pub struct Circle { 76 | pub cx: u32, 77 | pub cy: u32, 78 | pub r: u32, 79 | pub color: Option, 80 | pub style: Option, 81 | } 82 | 83 | #[derive(Debug)] 84 | pub struct RoundRect { 85 | pub x: u32, 86 | pub y: u32, 87 | pub width: u32, 88 | pub height: u32, 89 | pub r: u32, 90 | pub color: Option, 91 | pub style: Option, 92 | } 93 | 94 | #[derive(Debug)] 95 | pub struct Line { 96 | pub p1: [u32; 2], 97 | pub p2: [u32; 2], 98 | pub color: Option, 99 | pub stroke_width: Option, 100 | } 101 | 102 | #[derive(Debug)] 103 | pub struct Points { 104 | pub points: Vec<[u32; 2]>, 105 | pub color: Option, 106 | pub stroke_width: Option, 107 | pub style: Option, 108 | } 109 | 110 | #[derive(Debug)] 111 | pub struct Image { 112 | pub image: String, 113 | pub x: i32, 114 | pub y: i32, 115 | pub width: u32, 116 | pub height: u32, 117 | pub blur: Option, 118 | pub grayscale: Option, 119 | pub brighten: Option, 120 | pub invert: Option, 121 | } 122 | 123 | #[derive(Debug)] 124 | pub struct Text { 125 | pub text: String, 126 | pub x: i32, 127 | pub y: i32, 128 | pub font_size: f32, 129 | pub color: Option, 130 | pub max_width: Option, 131 | } 132 | 133 | impl Shapes { 134 | pub fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 135 | match self { 136 | Shapes::R(rect) => rect.draw(pixmap, context), 137 | Shapes::C(circle) => circle.draw(pixmap, context), 138 | Shapes::RR(round_rect) => round_rect.draw(pixmap, context), 139 | Shapes::L(line) => line.draw(pixmap, context), 140 | Shapes::P(points) => points.draw(pixmap, context), 141 | Shapes::I(image) => image.draw(pixmap, context), 142 | Shapes::T(text) => text.draw(pixmap, context), 143 | } 144 | } 145 | 146 | pub fn get_path(&self, context: &DrawContext) -> Path { 147 | match self { 148 | Shapes::R(rect) => rect.get_path(context), 149 | Shapes::C(circle) => circle.get_path(context), 150 | Shapes::RR(round_rect) => round_rect.get_path(context), 151 | Shapes::L(line) => line.get_path(context), 152 | Shapes::P(points) => points.get_path(context), 153 | Shapes::I(image) => image.get_path(context), 154 | Shapes::T(text) => text.get_path(context), 155 | } 156 | } 157 | } 158 | 159 | impl Shape for Rect { 160 | fn default() -> Self { 161 | Rect { 162 | x: 0, 163 | y: 0, 164 | width: 0, 165 | height: 0, 166 | color: None, 167 | style: None, 168 | } 169 | } 170 | 171 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 172 | let DrawContext { 173 | color, 174 | style, 175 | stroke_width, 176 | .. 177 | } = context; 178 | 179 | let path = self.get_path(context); 180 | 181 | let mut paint = Paint::default(); 182 | let color = self 183 | .color 184 | .unwrap_or(color.unwrap_or(ColorU8::from_rgba(0, 0, 0, 255))); 185 | let style = self.style.unwrap_or(style.unwrap_or(PaintStyle::Fill)); 186 | 187 | paint.set_color_rgba8(color.red(), color.green(), color.blue(), color.alpha()); 188 | 189 | match style { 190 | PaintStyle::Stroke => { 191 | let mut stroke = Stroke::default(); 192 | 193 | if let &Some(w) = stroke_width { 194 | stroke.width = w as f32 195 | } 196 | 197 | pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), None); 198 | } 199 | PaintStyle::Fill => { 200 | paint.anti_alias = true; 201 | pixmap.fill_path( 202 | &path, 203 | &paint, 204 | FillRule::Winding, 205 | Transform::identity(), 206 | None, 207 | ); 208 | } 209 | _ => {} 210 | } 211 | } 212 | 213 | fn get_path( 214 | &self, 215 | DrawContext { 216 | offset_x, offset_y, .. 217 | }: &DrawContext, 218 | ) -> Path { 219 | let mut pb = PathBuilder::new(); 220 | let x = self.x + offset_x; 221 | let y = self.y + offset_y; 222 | 223 | pb.move_to(x as f32, y as f32); 224 | pb.line_to((x + self.width) as f32, y as f32); 225 | pb.line_to((x + self.width) as f32, (y + self.height) as f32); 226 | pb.line_to(x as f32, (y + self.height) as f32); 227 | pb.line_to(x as f32, y as f32); 228 | pb.close(); 229 | 230 | pb.finish().unwrap() 231 | } 232 | } 233 | 234 | impl Shape for Circle { 235 | fn default() -> Self { 236 | todo!() 237 | } 238 | 239 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 240 | let DrawContext { 241 | color, 242 | style, 243 | stroke_width, 244 | .. 245 | } = context; 246 | 247 | let path = self.get_path(context); 248 | 249 | let mut paint = Paint::default(); 250 | let color = self 251 | .color 252 | .unwrap_or(color.unwrap_or(ColorU8::from_rgba(0, 0, 0, 255))); 253 | let style = self.style.unwrap_or(style.unwrap_or(PaintStyle::Fill)); 254 | 255 | paint.set_color_rgba8(color.red(), color.green(), color.blue(), color.alpha()); 256 | paint.anti_alias = true; 257 | 258 | match style { 259 | PaintStyle::Stroke => { 260 | let mut stroke = Stroke::default(); 261 | 262 | if let &Some(w) = stroke_width { 263 | stroke.width = w as f32 264 | } 265 | 266 | pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), None); 267 | } 268 | PaintStyle::Fill => { 269 | paint.anti_alias = true; 270 | pixmap.fill_path( 271 | &path, 272 | &paint, 273 | FillRule::Winding, 274 | Transform::identity(), 275 | None, 276 | ); 277 | } 278 | _ => {} 279 | } 280 | } 281 | 282 | fn get_path( 283 | &self, 284 | DrawContext { 285 | offset_x, offset_y, .. 286 | }: &DrawContext, 287 | ) -> Path { 288 | let mut pb: PathBuilder = PathBuilder::new(); 289 | let x = self.cx + offset_x; 290 | let y = self.cy + offset_y; 291 | 292 | pb.push_circle(x as f32, y as f32, self.r as f32); 293 | pb.close(); 294 | 295 | pb.finish().unwrap() 296 | } 297 | } 298 | 299 | impl Shape for RoundRect { 300 | fn default() -> Self { 301 | todo!() 302 | } 303 | 304 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 305 | let DrawContext { 306 | color, 307 | style, 308 | stroke_width, 309 | .. 310 | } = context; 311 | 312 | let path = self.get_path(context); 313 | 314 | let mut paint = Paint::default(); 315 | let color = self 316 | .color 317 | .unwrap_or(color.unwrap_or(ColorU8::from_rgba(0, 0, 0, 255))); 318 | let style = self.style.unwrap_or(style.unwrap_or(PaintStyle::Fill)); 319 | 320 | paint.set_color_rgba8(color.red(), color.green(), color.blue(), color.alpha()); 321 | paint.anti_alias = true; 322 | 323 | match style { 324 | PaintStyle::Stroke => { 325 | let mut stroke = Stroke::default(); 326 | 327 | if let &Some(w) = stroke_width { 328 | stroke.width = w as f32 329 | } 330 | 331 | pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), None); 332 | } 333 | PaintStyle::Fill => { 334 | paint.anti_alias = true; 335 | pixmap.fill_path( 336 | &path, 337 | &paint, 338 | FillRule::Winding, 339 | Transform::identity(), 340 | None, 341 | ); 342 | } 343 | _ => {} 344 | } 345 | } 346 | 347 | fn get_path( 348 | &self, 349 | DrawContext { 350 | offset_x, offset_y, .. 351 | }: &DrawContext, 352 | ) -> Path { 353 | let mut pb = PathBuilder::new(); 354 | let x = self.x + offset_x; 355 | let y = self.y + offset_y; 356 | 357 | pb.move_to((x + self.r) as f32, y as f32); 358 | pb.line_to((x + self.width - self.r) as f32, y as f32); 359 | pb.quad_to( 360 | (x + self.width) as f32, 361 | y as f32, 362 | (x + self.width) as f32, 363 | (y + self.r) as f32, 364 | ); 365 | pb.line_to((x + self.width) as f32, (y + self.height - self.r) as f32); 366 | pb.quad_to( 367 | (x + self.width) as f32, 368 | (y + self.height) as f32, 369 | (x + self.width - self.r) as f32, 370 | (y + self.height) as f32, 371 | ); 372 | pb.line_to((x + self.r) as f32, (y + self.height) as f32); 373 | pb.quad_to( 374 | x as f32, 375 | (y + self.height) as f32, 376 | x as f32, 377 | (y + self.height - self.r) as f32, 378 | ); 379 | pb.line_to(x as f32, (y + self.r) as f32); 380 | pb.quad_to(x as f32, y as f32, (x + self.r) as f32, y as f32); 381 | pb.close(); 382 | 383 | pb.finish().unwrap() 384 | } 385 | } 386 | 387 | impl Shape for Line { 388 | fn default() -> Self { 389 | todo!() 390 | } 391 | 392 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 393 | let DrawContext { 394 | color, 395 | stroke_width, 396 | .. 397 | } = context; 398 | 399 | let path = self.get_path(context); 400 | 401 | let mut paint = Paint::default(); 402 | let color = self 403 | .color 404 | .unwrap_or(color.unwrap_or(ColorU8::from_rgba(0, 0, 0, 255))); 405 | let stroke_width = self.stroke_width.unwrap_or(stroke_width.unwrap_or(1)); 406 | 407 | let stroke = Stroke { 408 | width: stroke_width as f32, 409 | miter_limit: 4.0, 410 | line_cap: LineCap::Butt, 411 | line_join: LineJoin::Miter, 412 | dash: None, 413 | }; 414 | 415 | paint.set_color_rgba8(color.red(), color.green(), color.blue(), color.alpha()); 416 | pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), None); 417 | } 418 | 419 | fn get_path( 420 | &self, 421 | DrawContext { 422 | offset_x, offset_y, .. 423 | }: &DrawContext, 424 | ) -> Path { 425 | let mut pb = PathBuilder::new(); 426 | let p1 = [self.p1[0] + offset_x, self.p1[1] + offset_y]; 427 | let p2 = [self.p2[0] + offset_x, self.p2[1] + offset_y]; 428 | 429 | pb.move_to(p1[0] as f32, p1[1] as f32); 430 | pb.line_to(p2[0] as f32, p2[1] as f32); 431 | pb.close(); 432 | 433 | pb.finish().unwrap() 434 | } 435 | } 436 | 437 | impl Shape for Points { 438 | fn default() -> Self { 439 | todo!() 440 | } 441 | 442 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 443 | let DrawContext { 444 | color, 445 | style, 446 | stroke_width, 447 | .. 448 | } = context; 449 | 450 | let path = self.get_path(context); 451 | 452 | let mut paint = Paint::default(); 453 | let color = self 454 | .color 455 | .unwrap_or(color.unwrap_or(ColorU8::from_rgba(0, 0, 0, 255))); 456 | let style = self.style.unwrap_or(style.unwrap_or(PaintStyle::Fill)); 457 | let stroke_width = self.stroke_width.unwrap_or(stroke_width.unwrap_or(1)); 458 | 459 | paint.set_color_rgba8(color.red(), color.green(), color.blue(), color.alpha()); 460 | 461 | match style { 462 | PaintStyle::Stroke => { 463 | let stroke = Stroke { 464 | width: stroke_width as f32, 465 | miter_limit: 4.0, 466 | line_cap: LineCap::Butt, 467 | line_join: LineJoin::Miter, 468 | dash: None, 469 | }; 470 | pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), None); 471 | } 472 | PaintStyle::Fill => { 473 | paint.anti_alias = true; 474 | pixmap.fill_path( 475 | &path, 476 | &paint, 477 | FillRule::Winding, 478 | Transform::identity(), 479 | None, 480 | ); 481 | } 482 | _ => {} 483 | } 484 | } 485 | 486 | fn get_path( 487 | &self, 488 | DrawContext { 489 | offset_x, offset_y, .. 490 | }: &DrawContext, 491 | ) -> Path { 492 | let mut pb = PathBuilder::new(); 493 | 494 | pb.move_to( 495 | (self.points[0][0] + offset_x) as f32, 496 | (self.points[0][1] + offset_y) as f32, 497 | ); 498 | for i in 1..self.points.len() { 499 | pb.line_to( 500 | (self.points[i][0] + offset_x) as f32, 501 | (self.points[i][1] + offset_y) as f32, 502 | ); 503 | } 504 | 505 | pb.close(); 506 | 507 | pb.finish().unwrap() 508 | } 509 | } 510 | 511 | impl Shape for Image { 512 | fn default() -> Self { 513 | todo!() 514 | } 515 | 516 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 517 | let u8_array = base64::decode(&self.image).expect("base64 decode failed"); 518 | let mut bytes: Vec = Vec::new(); 519 | 520 | let mut img = ImageReader::new(Cursor::new(&u8_array as &[u8])).with_guessed_format().unwrap().decode().unwrap(); 521 | 522 | if let Some(blur) = self.blur { 523 | img = img.blur(blur); 524 | } 525 | if let Some(grayscale) = self.grayscale { 526 | if grayscale { 527 | img = img.grayscale(); 528 | } 529 | } 530 | if let Some(brighten) = self.brighten { 531 | img = img.brighten(brighten); 532 | } 533 | if let Some(invert) = self.invert { 534 | if invert { 535 | img.invert(); 536 | } 537 | } 538 | 539 | img.write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); 540 | 541 | let p = Pixmap::decode_png(&bytes).expect("decode png failed"); 542 | let scale_x = self.width as f32 / p.width() as f32; 543 | let scale_y = self.height as f32 / p.height() as f32; 544 | pixmap.draw_pixmap( 545 | self.x, 546 | self.y, 547 | p.as_ref(), 548 | &PixmapPaint::default(), 549 | Transform::from_row(scale_x, 0.0, 0.0, scale_y, 0.0, 0.0), 550 | None, 551 | ); 552 | } 553 | } 554 | 555 | impl Shape for Text { 556 | fn default() -> Self { 557 | todo!() 558 | } 559 | 560 | fn draw(&self, pixmap: &mut Pixmap, context: &DrawContext) -> () { 561 | let font = include_bytes!("../assets/Roboto-Regular.ttf") as &[u8]; 562 | let roboto_regular = Font::from_bytes(font, fontdue::FontSettings::default()).unwrap(); 563 | let fonts = &[roboto_regular]; 564 | let mut layout = Layout::new(CoordinateSystem::PositiveYDown); 565 | layout.reset(&LayoutSettings { 566 | max_width: self.max_width, 567 | ..LayoutSettings::default() 568 | }); 569 | layout.append(fonts, &TextStyle::new(&self.text, self.font_size, 0)); 570 | 571 | let mut glyphs: Vec> = vec![]; 572 | self.text.chars().for_each(|c| { 573 | let (_, bitmap) = fonts[0].rasterize(c, self.font_size); 574 | glyphs.push(bitmap); 575 | }); 576 | let dim = compute_dim(&layout); 577 | 578 | let mut bitmap: Vec = vec![0; dim.0 * dim.1]; 579 | for (pos, char_bitmap) in zip(layout.glyphs(), &glyphs) { 580 | let x = pos.x as i32; 581 | let y = pos.y as i32 as i32; 582 | let width = pos.width as usize; 583 | let height = pos.height as usize; 584 | let mut i = 0; 585 | for y in y..y + height as i32 { 586 | for x in x..x + width as i32 { 587 | let index = (y * dim.0 as i32 + x) as usize; 588 | if index < bitmap.len() { 589 | bitmap[index] = char_bitmap[i]; 590 | } 591 | i += 1; 592 | } 593 | } 594 | } 595 | let mut rgba_bitmap: Vec = vec![]; 596 | for i in 0..bitmap.len() { 597 | if bitmap[i] == 0 { 598 | rgba_bitmap.extend([0, 0, 0, 0].iter()); 599 | continue; 600 | } 601 | if let Some(color) = self.color { 602 | rgba_bitmap.extend([color.red(), color.green(), color.blue(), bitmap[i]].iter()); 603 | } else { 604 | rgba_bitmap.extend([0, 0, 0, bitmap[i]].iter()); 605 | } 606 | } 607 | let p = Pixmap::from_vec( 608 | rgba_bitmap, 609 | tiny_skia::IntSize::from_wh(dim.0 as u32, dim.1 as u32).unwrap(), 610 | ) 611 | .unwrap(); 612 | pixmap.draw_pixmap( 613 | self.x, 614 | self.y, 615 | p.as_ref(), 616 | &PixmapPaint::default(), 617 | Transform::from_row(1.0, 0.0, 0.0, 1.0, 0.0, 0.0), 618 | None, 619 | ); 620 | } 621 | } 622 | 623 | fn compute_dim(layout: &Layout) -> (usize, usize) { 624 | let (mut x1, mut y1, mut x2, mut y2): (i32, i32, i32, i32) = (0, 0, 0, 0); 625 | for pos in layout.glyphs() { 626 | x1 = x1.min(pos.x as i32); 627 | y1 = y1.min(pos.y as i32); 628 | x2 = x2.max(pos.x as i32 + pos.width as i32); 629 | y2 = y2.max(pos.y as i32 + pos.height as i32); 630 | } 631 | return (1 + (x2 - x1) as usize, (y2 - y1) as usize); 632 | } 633 | 634 | #[cfg(test)] 635 | mod test { 636 | use super::{ColorU8, FillRule, Paint, PathBuilder, Pixmap, Stroke, Transform}; 637 | use crate::shape::Circle; 638 | use crate::shape::DrawContext; 639 | use crate::shape::PaintStyle; 640 | use crate::shape::Rect; 641 | use crate::shape::Shape; 642 | 643 | #[test] 644 | fn test_draw_rect() { 645 | let mut pixmap = Pixmap::new(400 as u32, 400 as u32).unwrap(); 646 | 647 | let shape_0 = Rect { 648 | x: 20, 649 | y: 20, 650 | width: 200, 651 | height: 200, 652 | color: None, 653 | style: None, 654 | }; 655 | let shape_1 = Rect { 656 | x: 120, 657 | y: 80, 658 | width: 200, 659 | height: 200, 660 | color: None, 661 | style: None, 662 | }; 663 | 664 | shape_0.draw(&mut pixmap, &DrawContext::default()); 665 | shape_1.draw(&mut pixmap, &DrawContext::default()); 666 | 667 | let data = pixmap.clone().encode_png().unwrap(); 668 | let data_url = base64::encode(&data); 669 | 670 | println!("{}", format!("data:image/png;base64,{}", data_url)); 671 | } 672 | } 673 | -------------------------------------------------------------------------------- /soft-skia/src/tree.rs: -------------------------------------------------------------------------------- 1 | use crate::provider::Providers; 2 | use crate::shape::Circle; 3 | use crate::shape::DrawContext; 4 | use crate::shape::Rect; 5 | use crate::shape::Shape; 6 | use crate::shape::Shapes; 7 | use std::slice::Iter; 8 | use std::slice::IterMut; 9 | use tiny_skia::ColorU8; 10 | use tiny_skia::Pixmap; 11 | 12 | #[derive(Debug)] 13 | pub struct Tree { 14 | root: Box, 15 | } 16 | 17 | #[derive(Debug)] 18 | pub struct Node { 19 | pub id: usize, 20 | pub shape: Shapes, 21 | pub provider: Option, 22 | pub children: Vec>, 23 | } 24 | 25 | impl Tree { 26 | pub fn default(id: usize) -> Self { 27 | Tree { 28 | root: Box::new(Node { 29 | id, 30 | shape: Shapes::R(Rect::default()), 31 | children: Vec::new(), 32 | provider: None, 33 | }), 34 | } 35 | } 36 | 37 | pub fn get_root(&mut self) -> &mut Node { 38 | self.root.as_mut() 39 | } 40 | } 41 | 42 | impl Node { 43 | pub fn default(id: usize, shape: Shapes) -> Self { 44 | Node { 45 | id, 46 | shape, 47 | children: Vec::new(), 48 | provider: None, 49 | } 50 | } 51 | 52 | pub fn draw(&self, pixmap: &mut Pixmap, context: Option<&DrawContext>) { 53 | self.shape 54 | .draw(pixmap, context.unwrap_or(&DrawContext::default())); 55 | } 56 | 57 | pub fn append_node(&mut self, node: Node) { 58 | self.append_boxed_node(Box::new(node)); 59 | } 60 | 61 | pub fn insert_node_before_id(&mut self, before_id: usize, node: Node) { 62 | self.insert_boxed_node_before_id(before_id, Box::new(node)); 63 | } 64 | 65 | pub fn insert_boxed_node_before_id(&mut self, before_id: usize, boxed_node: Box) { 66 | if let Some(before_index) = self.children.iter().position(|t| t.id == before_id) { 67 | self.children.insert(before_index, boxed_node); 68 | } else { 69 | self.append_boxed_node(boxed_node) 70 | } 71 | } 72 | 73 | pub fn append_boxed_node(&mut self, boxed_node: Box) { 74 | self.children.push(boxed_node); 75 | } 76 | 77 | pub fn get_children_len(&self) -> usize { 78 | self.children.len() 79 | } 80 | 81 | pub fn get_mut_child_by_index(&mut self, index: usize) -> Option<&mut Node> { 82 | Some(self.children[index].as_mut()) 83 | } 84 | 85 | pub fn get_child_by_index(&mut self, index: usize) -> Option<&Node> { 86 | Some(self.children[index].as_ref()) 87 | } 88 | 89 | pub fn children_iter(&mut self) -> Iter> { 90 | self.children.iter() 91 | } 92 | 93 | pub fn children_iter_mut(&mut self) -> IterMut> { 94 | self.children.iter_mut() 95 | } 96 | 97 | pub fn remove_child_by_index(&mut self, index: usize) { 98 | self.children.remove(index); 99 | } 100 | 101 | pub fn remove_child_by_id(&mut self, node_id: usize) { 102 | self.children.retain(|t| t.id != node_id); 103 | } 104 | } 105 | 106 | #[cfg(test)] 107 | mod test { 108 | use crate::shape::PaintStyle; 109 | 110 | use super::Circle; 111 | use super::ColorU8; 112 | use super::Node; 113 | use super::Rect; 114 | use super::Shapes; 115 | use super::Tree; 116 | 117 | #[test] 118 | fn test_tree() { 119 | let mut tree = Tree::default(0); 120 | let mut root = tree.get_root(); 121 | 122 | assert_eq!(root.id, 0); 123 | assert_eq!(root.get_children_len(), 0); 124 | 125 | root.id = 10086; 126 | assert_eq!(root.id, 10086); 127 | 128 | match root.shape { 129 | Shapes::R(Rect { 130 | x, 131 | y, 132 | width, 133 | height, 134 | color, 135 | style, 136 | }) => { 137 | assert_eq!(width, 0); 138 | assert_eq!(height, 0); 139 | } 140 | _ => { 141 | panic!() 142 | } 143 | } 144 | 145 | root.shape = Shapes::R(Rect { 146 | x: 0, 147 | y: 0, 148 | width: 400, 149 | height: 400, 150 | color: None, 151 | style: None, 152 | }); 153 | match root.shape { 154 | Shapes::R(Rect { 155 | x, 156 | y, 157 | width, 158 | height, 159 | color, 160 | style: None, 161 | }) => { 162 | assert_eq!(width, 400); 163 | assert_eq!(height, 400); 164 | } 165 | _ => { 166 | panic!() 167 | } 168 | } 169 | } 170 | 171 | #[test] 172 | fn test_node() { 173 | let mut node = Node { 174 | id: 0, 175 | shape: Shapes::R(Rect { 176 | x: 0, 177 | y: 0, 178 | width: 400, 179 | height: 400, 180 | color: None, 181 | style: None, 182 | }), 183 | children: Vec::new(), 184 | provider: None, 185 | }; 186 | 187 | assert_eq!(node.id, 0); 188 | assert_eq!(node.get_children_len(), 0); 189 | 190 | node.append_node(Node { 191 | id: 1, 192 | shape: Shapes::C(Circle { 193 | cx: 100, 194 | cy: 100, 195 | r: 50, 196 | color: None, 197 | style: None, 198 | }), 199 | children: Vec::new(), 200 | provider: None, 201 | }); 202 | assert_eq!(node.get_children_len(), 1); 203 | 204 | node.append_node(Node { 205 | id: 2, 206 | shape: Shapes::C(Circle { 207 | cx: 100, 208 | cy: 100, 209 | r: 50, 210 | color: None, 211 | style: None, 212 | }), 213 | children: Vec::new(), 214 | provider: None, 215 | }); 216 | assert_eq!(node.get_children_len(), 2); 217 | 218 | node.append_boxed_node(Box::new(Node { 219 | id: 3, 220 | shape: Shapes::C(Circle { 221 | cx: 100, 222 | cy: 100, 223 | r: 50, 224 | color: None, 225 | style: None, 226 | }), 227 | children: Vec::new(), 228 | provider: None, 229 | })); 230 | node.append_boxed_node(Box::new(Node { 231 | id: 4, 232 | shape: Shapes::C(Circle { 233 | cx: 100, 234 | cy: 100, 235 | r: 50, 236 | color: None, 237 | style: None, 238 | }), 239 | children: Vec::new(), 240 | provider: None, 241 | })); 242 | assert_eq!(node.get_children_len(), 4); 243 | 244 | let child_index_0 = node.get_child_by_index(0).unwrap(); 245 | assert_eq!(child_index_0.id, 1); 246 | 247 | let mut child_index_1 = node.get_mut_child_by_index(1).unwrap(); 248 | assert_eq!(child_index_1.id, 2); 249 | child_index_1.id = 100; 250 | assert_eq!(child_index_1.id, 100); 251 | 252 | node.remove_child_by_index(1); 253 | assert_eq!(node.get_children_len(), 3); 254 | assert_eq!(node.children[0].id, 1); 255 | assert_eq!(node.children[1].id, 3); 256 | assert_eq!(node.children[2].id, 4); 257 | 258 | node.remove_child_by_id(3); 259 | assert_eq!(node.get_children_len(), 2); 260 | assert_eq!(node.children[0].id, 1); 261 | assert_eq!(node.children[1].id, 4); 262 | 263 | node.insert_node_before_id( 264 | 4, 265 | Node { 266 | id: 200, 267 | shape: Shapes::C(Circle { 268 | cx: 100, 269 | cy: 100, 270 | r: 50, 271 | color: None, 272 | style: None, 273 | }), 274 | children: Vec::new(), 275 | provider: None, 276 | }, 277 | ); 278 | assert_eq!(node.get_children_len(), 3); 279 | assert_eq!(node.children[0].id, 1); 280 | assert_eq!(node.children[1].id, 200); 281 | assert_eq!(node.children[2].id, 4); 282 | 283 | node.insert_node_before_id( 284 | 4, 285 | Node { 286 | id: 300, 287 | shape: Shapes::C(Circle { 288 | cx: 100, 289 | cy: 100, 290 | r: 50, 291 | color: None, 292 | style: None, 293 | }), 294 | children: Vec::new(), 295 | provider: None, 296 | }, 297 | ); 298 | assert_eq!(node.get_children_len(), 4); 299 | assert_eq!(node.children[0].id, 1); 300 | assert_eq!(node.children[1].id, 200); 301 | assert_eq!(node.children[2].id, 300); 302 | assert_eq!(node.children[3].id, 4); 303 | 304 | for item in node.children_iter_mut() { 305 | match item.shape { 306 | Shapes::C(Circle { 307 | ref mut cx, 308 | cy, 309 | r, 310 | color, 311 | style, 312 | }) => { 313 | assert_eq!(*cx, 100); 314 | *cx = 200; 315 | assert_eq!(*cx, 200); 316 | } 317 | _ => panic!(), 318 | } 319 | } 320 | 321 | for item in node.children_iter() { 322 | match item.shape { 323 | Shapes::C(Circle { 324 | cx, 325 | cy, 326 | r, 327 | color, 328 | style, 329 | }) => { 330 | assert_eq!(cx, 200); 331 | } 332 | _ => panic!(), 333 | } 334 | } 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /soft-skia/src/util.rs: -------------------------------------------------------------------------------- 1 | extern crate web_sys; 2 | 3 | // A macro to provide `println!(..)`-style syntax for `console.log` logging. 4 | #[macro_export] 5 | macro_rules! log { 6 | ( $( $t:tt )* ) => { 7 | web_sys::console::log_1(&format!( $( $t )* ).into()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | todo!() 3 | } 4 | -------------------------------------------------------------------------------- /vue-playground/.browserslistrc: -------------------------------------------------------------------------------- 1 | > 1% 2 | last 2 versions 3 | not dead 4 | not ie 11 5 | -------------------------------------------------------------------------------- /vue-playground/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true, 5 | }, 6 | extends: [ 7 | "plugin:vue/vue3-essential", 8 | "eslint:recommended", 9 | "@vue/typescript/recommended", 10 | "plugin:prettier/recommended", 11 | ], 12 | parserOptions: { 13 | ecmaVersion: 2020, 14 | }, 15 | rules: { 16 | "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", 17 | "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", 18 | }, 19 | }; 20 | -------------------------------------------------------------------------------- /vue-playground/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | 6 | # local env files 7 | .env.local 8 | .env.*.local 9 | 10 | # Log files 11 | npm-debug.log* 12 | yarn-debug.log* 13 | yarn-error.log* 14 | pnpm-debug.log* 15 | 16 | # Editor directories and files 17 | .idea 18 | .vscode 19 | *.suo 20 | *.ntvs* 21 | *.njsproj 22 | *.sln 23 | *.sw? 24 | -------------------------------------------------------------------------------- /vue-playground/README.md: -------------------------------------------------------------------------------- 1 | # vue-playground 2 | 3 | ## Project setup 4 | ``` 5 | npm install 6 | ``` 7 | 8 | ### Compiles and hot-reloads for development 9 | ``` 10 | npm run serve 11 | ``` 12 | 13 | ### How to debug the vue syntax code in playground 14 | 15 | `App.vue` 16 | 17 | ```diff 18 | data() { 19 | return { 20 | CustomLayout: markRaw(CustomLayout), 21 | loading: true, 22 | count: 2, 23 | VSurface, 24 | VRect, 25 | VCircle, 26 | VRoundRect, 27 | VLine, 28 | VPoints, 29 | code, 30 | LoadingCode, 31 | - debug: false, 32 | + debug: true, 33 | error: undefined, 34 | }; 35 | }, 36 | ``` 37 | 38 | ### How to debug the wasm in vue-playgrounnd 39 | 40 | ```shell 41 | $ rm -rf {YOUR_PROJECT_WORK_SPACE}/vue-playground/node_modules/vue-skia/soft-skia-wasm/pkg 42 | $ ln -s {YOUR_PROJECT_WORK_SPACE}/soft-skia-wasm/pkg {YOUR_PROJECT_WORK_SPACE}/vue-playground/node_modules/vue-skia/soft-skia-wasm/pkg 43 | ``` 44 | -------------------------------------------------------------------------------- /vue-playground/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ["@vue/cli-plugin-babel/preset"], 3 | }; 4 | -------------------------------------------------------------------------------- /vue-playground/package-ci.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-playground", 3 | "version": "0.12.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "@uivjs/vue-github-corners": "^1.0.1", 12 | "core-js": "^3.8.3", 13 | "prism-themes": "^1.9.0", 14 | "prismjs": "^1.29.0", 15 | "vue": "^3.2.13", 16 | "vue-live": "^2.5.4", 17 | "vue3-progress": "0.0.1-beta4", 18 | "vue-skia": "0.1.2" 19 | }, 20 | "devDependencies": { 21 | "@types/node": "^20.5.0", 22 | "@typescript-eslint/eslint-plugin": "^5.4.0", 23 | "@typescript-eslint/parser": "^5.4.0", 24 | "@vue/cli-plugin-babel": "~5.0.0", 25 | "@vue/cli-plugin-eslint": "~5.0.0", 26 | "@vue/cli-plugin-typescript": "~5.0.0", 27 | "@vue/cli-service": "~5.0.0", 28 | "@vue/eslint-config-typescript": "^9.1.0", 29 | "eslint": "^7.32.0", 30 | "eslint-config-prettier": "^8.3.0", 31 | "eslint-plugin-prettier": "^4.0.0", 32 | "eslint-plugin-vue": "^8.0.3", 33 | "prettier": "^2.4.1", 34 | "typescript": "~4.5.5", 35 | "url-loader": "^4.1.1" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /vue-playground/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-playground", 3 | "version": "0.1.2", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "@uivjs/vue-github-corners": "^1.0.1", 12 | "core-js": "^3.8.3", 13 | "prism-themes": "^1.9.0", 14 | "prismjs": "^1.29.0", 15 | "vue": "^3.2.13", 16 | "vue-live": "^2.5.4", 17 | "vue3-progress": "0.0.1-beta4", 18 | "vue-skia": "workspace:*" 19 | }, 20 | "devDependencies": { 21 | "@types/node": "^20.5.0", 22 | "@typescript-eslint/eslint-plugin": "^5.4.0", 23 | "@typescript-eslint/parser": "^5.4.0", 24 | "@vue/cli-plugin-babel": "~5.0.0", 25 | "@vue/cli-plugin-eslint": "~5.0.0", 26 | "@vue/cli-plugin-typescript": "~5.0.0", 27 | "@vue/cli-service": "~5.0.0", 28 | "@vue/eslint-config-typescript": "^9.1.0", 29 | "eslint": "^7.32.0", 30 | "eslint-config-prettier": "^8.3.0", 31 | "eslint-plugin-prettier": "^4.0.0", 32 | "eslint-plugin-vue": "^8.0.3", 33 | "prettier": "^2.4.1", 34 | "typescript": "~4.5.5", 35 | "url-loader": "^4.1.1" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /vue-playground/public/NanumPenScript-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rustq/vue-skia/4d4c29c54b7f609a0f6a3cd106343c4d52f06fef/vue-playground/public/NanumPenScript-Regular.ttf -------------------------------------------------------------------------------- /vue-playground/public/OFL.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010, NHN Corporation (http://www.nhncorp.com), 2 | with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver 3 | NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver 4 | NanumBrush, NanumPen, Naver NanumPen. 5 | 6 | 7 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 8 | This license is copied below, and is also available with a FAQ at: 9 | https://openfontlicense.org 10 | 11 | 12 | ----------------------------------------------------------- 13 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 14 | ----------------------------------------------------------- 15 | 16 | PREAMBLE 17 | The goals of the Open Font License (OFL) are to stimulate worldwide 18 | development of collaborative font projects, to support the font creation 19 | efforts of academic and linguistic communities, and to provide a free and 20 | open framework in which fonts may be shared and improved in partnership 21 | with others. 22 | 23 | The OFL allows the licensed fonts to be used, studied, modified and 24 | redistributed freely as long as they are not sold by themselves. The 25 | fonts, including any derivative works, can be bundled, embedded, 26 | redistributed and/or sold with any software provided that any reserved 27 | names are not used by derivative works. The fonts and derivatives, 28 | however, cannot be released under any other type of license. The 29 | requirement for fonts to remain under this license does not apply 30 | to any document created using the fonts or their derivatives. 31 | 32 | DEFINITIONS 33 | "Font Software" refers to the set of files released by the Copyright 34 | Holder(s) under this license and clearly marked as such. This may 35 | include source files, build scripts and documentation. 36 | 37 | "Reserved Font Name" refers to any names specified as such after the 38 | copyright statement(s). 39 | 40 | "Original Version" refers to the collection of Font Software components as 41 | distributed by the Copyright Holder(s). 42 | 43 | "Modified Version" refers to any derivative made by adding to, deleting, 44 | or substituting -- in part or in whole -- any of the components of the 45 | Original Version, by changing formats or by porting the Font Software to a 46 | new environment. 47 | 48 | "Author" refers to any designer, engineer, programmer, technical 49 | writer or other person who contributed to the Font Software. 50 | 51 | PERMISSION & CONDITIONS 52 | Permission is hereby granted, free of charge, to any person obtaining 53 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 54 | redistribute, and sell modified and unmodified copies of the Font 55 | Software, subject to the following conditions: 56 | 57 | 1) Neither the Font Software nor any of its individual components, 58 | in Original or Modified Versions, may be sold by itself. 59 | 60 | 2) Original or Modified Versions of the Font Software may be bundled, 61 | redistributed and/or sold with any software, provided that each copy 62 | contains the above copyright notice and this license. These can be 63 | included either as stand-alone text files, human-readable headers or 64 | in the appropriate machine-readable metadata fields within text or 65 | binary files as long as those fields can be easily viewed by the user. 66 | 67 | 3) No Modified Version of the Font Software may use the Reserved Font 68 | Name(s) unless explicit written permission is granted by the corresponding 69 | Copyright Holder. This restriction only applies to the primary font name as 70 | presented to the users. 71 | 72 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 73 | Software shall not be used to promote, endorse or advertise any 74 | Modified Version, except to acknowledge the contribution(s) of the 75 | Copyright Holder(s) and the Author(s) or with their explicit written 76 | permission. 77 | 78 | 5) The Font Software, modified or unmodified, in part or in whole, 79 | must be distributed entirely under this license, and must not be 80 | distributed under any other license. The requirement for fonts to 81 | remain under this license does not apply to any document created 82 | using the Font Software. 83 | 84 | TERMINATION 85 | This license becomes null and void if any of the above conditions are 86 | not met. 87 | 88 | DISCLAIMER 89 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 90 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 91 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 92 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 93 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 94 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 95 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 96 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 97 | OTHER DEALINGS IN THE FONT SOFTWARE. 98 | -------------------------------------------------------------------------------- /vue-playground/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rustq/vue-skia/4d4c29c54b7f609a0f6a3cd106343c4d52f06fef/vue-playground/public/favicon.ico -------------------------------------------------------------------------------- /vue-playground/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | <%= htmlWebpackPlugin.options.title %> 9 | 15 | 16 | 17 | 20 |
21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /vue-playground/src/App.vue: -------------------------------------------------------------------------------- 1 | 97 | 196 | 197 | 283 | -------------------------------------------------------------------------------- /vue-playground/src/CustomLayout.vue: -------------------------------------------------------------------------------- 1 | 11 | 61 | -------------------------------------------------------------------------------- /vue-playground/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rustq/vue-skia/4d4c29c54b7f609a0f6a3cd106343c4d52f06fef/vue-playground/src/assets/logo.png -------------------------------------------------------------------------------- /vue-playground/src/code.ts: -------------------------------------------------------------------------------- 1 | export default ` 2 | 3 | 4 | 5 | 17 | 28 | 29 | 32 | 33 | 34 | 35 | 36 | 37 | `; 38 | -------------------------------------------------------------------------------- /vue-playground/src/loading-code.ts: -------------------------------------------------------------------------------- 1 | export default ` 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | `; 39 | -------------------------------------------------------------------------------- /vue-playground/src/main.ts: -------------------------------------------------------------------------------- 1 | import { createApp } from "vue"; 2 | import App from "./App.vue"; 3 | import { VueSkia } from 'vue-skia' 4 | import Vue3Progress from "vue3-progress"; 5 | 6 | const app = createApp(App); 7 | app.use(VueSkia); 8 | app.use(Vue3Progress, { 9 | position: "fixed", 10 | color: "rgb(0, 161, 132)", 11 | }) 12 | app.mount("#app"); 13 | -------------------------------------------------------------------------------- /vue-playground/src/shims-vue.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | declare module '*.vue' { 3 | import type { DefineComponent } from 'vue' 4 | const component: DefineComponent<{}, {}, any> 5 | export default component 6 | } 7 | 8 | declare module '*.png' -------------------------------------------------------------------------------- /vue-playground/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "module": "esnext", 5 | "strict": true, 6 | "jsx": "preserve", 7 | "moduleResolution": "node", 8 | "skipLibCheck": true, 9 | "esModuleInterop": true, 10 | "allowSyntheticDefaultImports": true, 11 | "forceConsistentCasingInFileNames": true, 12 | "useDefineForClassFields": true, 13 | "sourceMap": true, 14 | "allowJs": true, 15 | "baseUrl": ".", 16 | "types": [ 17 | "webpack-env" 18 | ], 19 | "paths": { 20 | "@/*": [ 21 | "src/*" 22 | ] 23 | }, 24 | "lib": [ 25 | "esnext", 26 | "dom", 27 | "dom.iterable", 28 | "scripthost" 29 | ] 30 | }, 31 | "include": [ 32 | "src/**/*.ts", 33 | "src/**/*.tsx", 34 | "src/**/*.vue", 35 | "tests/**/*.ts", 36 | "tests/**/*.tsx" 37 | ], 38 | "exclude": [ 39 | "node_modules" 40 | ] 41 | } 42 | -------------------------------------------------------------------------------- /vue-playground/vue.config.js: -------------------------------------------------------------------------------- 1 | const { defineConfig } = require("@vue/cli-service"); 2 | const path = require("path"); 3 | module.exports = defineConfig({ 4 | transpileDependencies: true, 5 | lintOnSave: false, 6 | configureWebpack: { 7 | experiments: { 8 | asyncWebAssembly: true, 9 | }, 10 | module: { 11 | rules: [ 12 | { 13 | test: /\.png/, 14 | use: { 15 | loader: "url-loader", 16 | options: { 17 | limit: true, 18 | }, 19 | }, 20 | }, 21 | ], 22 | }, 23 | }, 24 | chainWebpack: (config) => { 25 | const imageRule = config.module.rule("images"); 26 | imageRule.delete("type"); 27 | }, 28 | }); 29 | -------------------------------------------------------------------------------- /vue-skia-framework/.gitignore: -------------------------------------------------------------------------------- 1 | lib 2 | soft-skia* 3 | package-lock* -------------------------------------------------------------------------------- /vue-skia-framework/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 rustq 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vue-skia-framework/README.md: -------------------------------------------------------------------------------- 1 | # Vue Skia Framework -------------------------------------------------------------------------------- /vue-skia-framework/common.ts: -------------------------------------------------------------------------------- 1 | export class SelfIncreaseCount { 2 | 3 | private static _count = 0; 4 | 5 | static get count(): number { 6 | return SelfIncreaseCount._count++; 7 | } 8 | 9 | static get root(): number { 10 | return 0; 11 | } 12 | } -------------------------------------------------------------------------------- /vue-skia-framework/components/VCircle.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 34 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VGroup.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | 44 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VGroupClip.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 15 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VImage.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 110 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VLine.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 30 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VPoints.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 30 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VRect.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 38 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VRoundRect.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 42 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VSurface.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 24 | -------------------------------------------------------------------------------- /vue-skia-framework/components/VText.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 38 | -------------------------------------------------------------------------------- /vue-skia-framework/launch.ts: -------------------------------------------------------------------------------- 1 | const SSWInitialHelper = { 2 | initialStatus: 0, // 0=default 1=pending 2=succeed 3 | initialSucceedCallbackQueue: [] as Function[] 4 | }; 5 | 6 | const launch = function () { 7 | return new Promise((resolve, _) => { 8 | if (SSWInitialHelper.initialStatus === 0) { 9 | SSWInitialHelper.initialStatus = 1; 10 | const wasm = import("soft-skia-wasm/soft_skia_wasm.js"); 11 | wasm.then(async (ssw) => { 12 | await ssw.default(); 13 | window.ssw = ssw; 14 | while (SSWInitialHelper.initialSucceedCallbackQueue.length) { 15 | SSWInitialHelper.initialSucceedCallbackQueue.pop()(); 16 | } 17 | resolve(void 0) 18 | }) 19 | } else if (SSWInitialHelper.initialStatus === 1) { 20 | SSWInitialHelper.initialSucceedCallbackQueue.push(() => resolve(void 0)); 21 | } else if (SSWInitialHelper.initialStatus === 2) { 22 | resolve(void 0) 23 | } 24 | }); 25 | } 26 | 27 | export default launch; -------------------------------------------------------------------------------- /vue-skia-framework/main.js: -------------------------------------------------------------------------------- 1 | import launch from "./lib/launch"; 2 | import plugin from "./lib/plugin"; 3 | import VSurface from "./components/VSurface.vue"; 4 | import VGroup from "./components/VGroup.vue"; 5 | import VRect from "./components/VRect.vue"; 6 | import VCircle from "./components/VCircle.vue"; 7 | import VRoundRect from "./components/VRoundRect.vue"; 8 | import VLine from "./components/VLine.vue"; 9 | import VPoints from "./components/VPoints.vue"; 10 | import VImage from './components/VImage.vue'; 11 | import VText from './components/VText.vue'; 12 | 13 | export default launch; 14 | export { plugin as VueSkia } 15 | export { VSurface, VGroup, VRect, VCircle, VRoundRect, VLine, VPoints, VImage, VText } -------------------------------------------------------------------------------- /vue-skia-framework/package-publish.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-skia", 3 | "version": "0.1.2", 4 | "files": [ 5 | "lib", 6 | "type.d.ts", 7 | "main.js", 8 | "main.d.ts", 9 | "components", 10 | "LICENSE" 11 | ], 12 | "license": "MIT", 13 | "main": "./main.js", 14 | "module": "./main.js", 15 | "dependencies": { 16 | "soft-skia-wasm": "0.12.0" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /vue-skia-framework/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-skia", 3 | "version": "0.0.0", 4 | "private": "true", 5 | "files": [ 6 | "lib", 7 | "type.d.ts", 8 | "main.js", 9 | "main.d.ts", 10 | "components", 11 | "LICENSE" 12 | ], 13 | "scripts": { 14 | "build": "rm -rf lib; tsc; cp main.js main.d.ts; cp type.ts type.d.ts" 15 | }, 16 | "license": "MIT", 17 | "main": "./main.js", 18 | "module": "./main.js", 19 | "devDependencies": { 20 | "@babel/types": "^7.22.4", 21 | "@webpack-cli/generators": "^3.0.6", 22 | "typescript": "^5.1.3", 23 | "vue": "^3.3.4", 24 | "soft-skia-wasm": "workspace:*" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /vue-skia-framework/plugin/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | h, 3 | onBeforeMount, 4 | onBeforeUnmount, 5 | onUpdated, 6 | getCurrentInstance, 7 | App, 8 | VNodeProps, 9 | SetupContext, 10 | Plugin 11 | } from 'vue'; 12 | import Surface from "../surface"; 13 | import { ComponentInternalInstanceWithSoftSkiaWASM } from "../type"; 14 | import { SelfIncreaseCount } from "../common" 15 | import { SoftSkiaWASM } from '../../soft-skia-wasm/pkg/soft_skia_wasm'; 16 | 17 | const WidgetList = [ 18 | 'Surface', 19 | 'Group', 20 | 'GroupClip', 21 | 'Points', 22 | 'Line', 23 | 'RoundRect', 24 | 'Rect', 25 | 'Circle', 26 | 'Image', 27 | 'Text' 28 | ]; 29 | 30 | const VSKNode = (name: string) => { 31 | if (name === 'Surface') { 32 | return Surface 33 | } 34 | 35 | if (name === "GroupClip") { 36 | return { 37 | props: { 38 | config: { 39 | type: Object, 40 | default: function () { 41 | return {}; 42 | }, 43 | }, 44 | __useStrictMode: { 45 | type: Boolean, 46 | }, 47 | }, 48 | setup(_props: VNodeProps, { slots }: SetupContext) { 49 | onBeforeMount(() => { 50 | const instance = 51 | getCurrentInstance() as ComponentInternalInstanceWithSoftSkiaWASM; 52 | var root = instance as ComponentInternalInstanceWithSoftSkiaWASM; 53 | while (!root.ssw) { 54 | root = root.parent as ComponentInternalInstanceWithSoftSkiaWASM; 55 | } 56 | const core = root.ssw; 57 | 58 | let parent = instance.parent; 59 | 60 | while (!("_ssw_id" in parent)) { 61 | parent = parent.parent; 62 | } 63 | 64 | instance._ssw_id = ( 65 | parent as ComponentInternalInstanceWithSoftSkiaWASM 66 | )._ssw_id; 67 | instance._ssw_attached = true; 68 | 69 | instance._ssw_grouped = (child) => { 70 | core.setAttrBySerde(instance._ssw_id, { 71 | attr: { 72 | GC: { 73 | clip: child._ssw_id, 74 | }, 75 | }, 76 | }); 77 | }; 78 | }); 79 | 80 | return () => h(name, {}, slots.default?.()); 81 | }, 82 | }; 83 | } 84 | 85 | return { 86 | props: { 87 | config: { 88 | type: Object, 89 | default: function () { 90 | return {}; 91 | }, 92 | }, 93 | __useStrictMode: { 94 | type: Boolean, 95 | }, 96 | }, 97 | setup(_props: VNodeProps, { attrs, slots }: SetupContext) { 98 | 99 | onBeforeMount(() => { 100 | const instance = getCurrentInstance() as ComponentInternalInstanceWithSoftSkiaWASM; 101 | var root = instance as ComponentInternalInstanceWithSoftSkiaWASM; 102 | while (!root.ssw) { 103 | root = root.parent as ComponentInternalInstanceWithSoftSkiaWASM; 104 | } 105 | const core = root.ssw; 106 | instance._ssw_id = SelfIncreaseCount.count; 107 | instance._ssw_attached = true; 108 | var parent = instance.parent; 109 | while (!('_ssw_id' in parent)) { 110 | parent = parent.parent; 111 | } 112 | 113 | core.createChildAppendToContainer(instance._ssw_id, (parent as ComponentInternalInstanceWithSoftSkiaWASM)._ssw_id); 114 | updateInstance(core, name, instance, attrs); 115 | ( 116 | parent as ComponentInternalInstanceWithSoftSkiaWASM 117 | )._ssw_grouped?.(instance); 118 | root._ssw_batchDraw?.() 119 | }); 120 | 121 | onUpdated(() => { 122 | const instance = getCurrentInstance() as ComponentInternalInstanceWithSoftSkiaWASM; 123 | var root = instance as ComponentInternalInstanceWithSoftSkiaWASM; 124 | while (!root.ssw) { 125 | root = root.parent as ComponentInternalInstanceWithSoftSkiaWASM; 126 | } 127 | const core = root.ssw; 128 | updateInstance(core, name, instance, attrs); 129 | root._ssw_batchDraw?.() 130 | }); 131 | 132 | /** 133 | * updateInstance 134 | * @param name 135 | * @param instance 136 | * @param attrs 137 | */ 138 | function updateInstance(core: SoftSkiaWASM, name: string, instance: ComponentInternalInstanceWithSoftSkiaWASM, attrs: SetupContext['attrs']) { 139 | if (name === 'Rect') { 140 | core.setAttrBySerde(instance._ssw_id, { attr: { R: { x: attrs.x, y: attrs.y, width: attrs.width, height: attrs.height, color: attrs.color, style: attrs.style } } }) 141 | } 142 | if (name === 'Circle') { 143 | core.setAttrBySerde(instance._ssw_id, { attr: { C: { cx: attrs.cx, cy: attrs.cy, r: attrs.r, color: attrs.color, style: attrs.style } } }) 144 | } 145 | if (name === 'RoundRect') { 146 | core.setAttrBySerde(instance._ssw_id, { attr: { RR: { x: attrs.x, y: attrs.y, r: attrs.r, width: attrs.width, height: attrs.height, color: attrs.color, style: attrs.style } } }) 147 | } 148 | if (name === 'Line') { 149 | core.setAttrBySerde(instance._ssw_id, { attr: { L: { p1: attrs.p1, p2: attrs.p2, stroke_width: attrs.strokeWidth, color: attrs.color } } }) 150 | } 151 | if (name === 'Points') { 152 | core.setAttrBySerde(instance._ssw_id, { attr: { P: { points: attrs.points, stroke_width: attrs.strokeWidth, color: attrs.color, style: attrs.style } } }) 153 | } 154 | if (name === 'Group') { 155 | core.setAttrBySerde(instance._ssw_id, { 156 | attr: { 157 | G: { 158 | x: attrs.x, 159 | y: attrs.y, 160 | color: attrs.color, 161 | stroke_width: attrs.strokeWidth, 162 | style: attrs.style, 163 | invert_clip: attrs.invertClip, 164 | }, 165 | }, 166 | }); 167 | } 168 | if (name === "Image") { 169 | core.setAttrBySerde(instance._ssw_id, { 170 | attr: { 171 | I: { 172 | image: attrs.image, 173 | x: attrs.x, 174 | y: attrs.y, 175 | width: attrs.width, 176 | height: attrs.height, 177 | blur: attrs.blur, 178 | grayscale: attrs.grayscale, 179 | brighten: attrs.brighten, 180 | invert: attrs.invert, 181 | }, 182 | }, 183 | }); 184 | } 185 | if (name === "Text") { 186 | core.setAttrBySerde(instance._ssw_id, { 187 | attr: { 188 | T: { 189 | text: attrs.text, 190 | x: attrs.x, 191 | y: attrs.y, 192 | font_size: attrs.fontSize, 193 | color: attrs.color, 194 | max_width: attrs.maxWidth, 195 | }, 196 | }, 197 | }); 198 | } 199 | } 200 | 201 | onBeforeUnmount(() => { 202 | const instance = getCurrentInstance() as ComponentInternalInstanceWithSoftSkiaWASM; 203 | var root = instance as ComponentInternalInstanceWithSoftSkiaWASM; 204 | while (!root.ssw) { 205 | root = root.parent as ComponentInternalInstanceWithSoftSkiaWASM; 206 | } 207 | const core = root.ssw; 208 | const child_id = instance._ssw_id; 209 | var parent = instance.parent; 210 | while (!('_ssw_id' in parent)) { 211 | parent = parent.parent; 212 | } 213 | instance._ssw_attached = false; 214 | if ((parent as ComponentInternalInstanceWithSoftSkiaWASM)._ssw_attached && parent.isMounted) { 215 | core.removeChildFromContainer(child_id, (parent as ComponentInternalInstanceWithSoftSkiaWASM)._ssw_id) 216 | } 217 | }); 218 | 219 | return () => h(name, {}, slots.default?.()) 220 | } 221 | } 222 | } 223 | 224 | const VueSkiaPlugin = { 225 | install: (app: App) => { 226 | let prefixToUse = 'vSk'; 227 | WidgetList.forEach((name) => { 228 | app.component(`${prefixToUse}${name}`, VSKNode(name)); 229 | }); 230 | }, 231 | } as Plugin; 232 | 233 | export default VueSkiaPlugin; 234 | -------------------------------------------------------------------------------- /vue-skia-framework/surface/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | h, 3 | ref, 4 | onMounted, 5 | onBeforeUnmount, 6 | onUpdated, 7 | getCurrentInstance, 8 | VNodeProps, 9 | SetupContext 10 | } from 'vue'; 11 | import { ComponentInternalInstanceWithSoftSkiaWASM } from "../type"; 12 | import { SelfIncreaseCount } from "../common" 13 | 14 | export default { 15 | props: { 16 | config: { 17 | type: Object, 18 | default: function () { 19 | return {}; 20 | }, 21 | }, 22 | __useStrictMode: { 23 | type: Boolean, 24 | }, 25 | }, 26 | 27 | inheritAttrs: false, 28 | 29 | setup(_props: VNodeProps, { attrs, slots }: SetupContext) { 30 | 31 | const container = ref(null); 32 | const instance = getCurrentInstance() as ComponentInternalInstanceWithSoftSkiaWASM; 33 | const ssw = window.ssw; 34 | const rootID = SelfIncreaseCount.count; 35 | const core = new ssw.SoftSkiaWASM(rootID); 36 | 37 | let waitingForDraw = false; 38 | 39 | instance.ssw = core; // Save on component instance 40 | instance._ssw_id = rootID; 41 | core.setAttrBySerde(rootID, { attr: { R: { x: 0, y: 0, width: attrs.width, height: attrs.height, color: 'transparent', style: "fill" } } }) 42 | 43 | // batch draw func 44 | function batchDraw() { 45 | if (!waitingForDraw) { 46 | waitingForDraw = true; 47 | window.requestAnimationFrame(() => { 48 | const base64 = core.toBase64(); 49 | container.value.setAttribute("src", base64); 50 | waitingForDraw = false; 51 | }); 52 | } 53 | } 54 | instance._ssw_batchDraw = () => batchDraw(); 55 | 56 | onMounted(() => { 57 | batchDraw(); 58 | }); 59 | 60 | onUpdated(() => { 61 | batchDraw(); 62 | }); 63 | 64 | onBeforeUnmount(() => {}); 65 | 66 | 67 | return () => h('img', { ref: container }, slots.default?.()); 68 | } 69 | } -------------------------------------------------------------------------------- /vue-skia-framework/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "esnext", 4 | "moduleResolution": "node", 5 | "target": "esnext", 6 | "noImplicitAny": true, 7 | "removeComments": true, 8 | "preserveConstEnums": true, 9 | "outDir": "lib", 10 | "declaration": true, 11 | "declarationDir": "lib" 12 | }, 13 | "files": [ 14 | "plugin/index.ts", 15 | "surface/index.ts", 16 | "launch.ts", 17 | ] 18 | } -------------------------------------------------------------------------------- /vue-skia-framework/type.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ComponentInternalInstance, 3 | } from 'vue'; 4 | import { SoftSkiaWASM } from '../soft-skia-wasm/pkg/'; 5 | 6 | export type ComponentInternalInstanceWithSoftSkiaWASM = ComponentInternalInstance & { 7 | ssw: SoftSkiaWASM; 8 | _ssw_id: number; 9 | _ssw_attached: boolean; 10 | _ssw_grouped?: (instance: ComponentInternalInstanceWithSoftSkiaWASM) => void; 11 | _ssw_batchDraw?: () => void; 12 | } 13 | 14 | declare global { 15 | var ssw: { SoftSkiaWASM: typeof SoftSkiaWASM }; 16 | var core: SoftSkiaWASM; 17 | } --------------------------------------------------------------------------------