fix(fonts): pre-register macOS CJK fallback families in vendored i-slint-common

fontique's CoreText-based Han-script fallback fails to resolve a family on
modern macOS (the suggested PingFang is not always in the scanned family
map), so Japanese kanji rendered blank while kana worked. Vendor
i-slint-common 1.16.1 and pre-register Hiragino / PingFang / Apple SD
Gothic Neo / Arial Unicode MS in the fallback map at collection creation
(Japanese-biased default; the map takes priority over the CoreText query).
macOS-only cfg; Linux keeps its working fontconfig fallback. Type-checked
against aarch64-apple-darwin.

cc
This commit is contained in:
vicrodh committed 2026-07-03 10:00:31 -06:00
1 parent 058d38c8d2
commit fa3ee1e410
19 files changed
+3334 -2

No files matched your search

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "e9c1ca295f9356af71f1e251c287de18406b46f6"
},
"path_in_vcs": "internal/common"
}
+496
View File
@@ -0,0 +1,496 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bitflags"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]
name = "bytemuck"
version = "1.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "convert_case"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "derive_more"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"rustc_version",
"syn",
"unicode-xid",
]
[[package]]
name = "dlib"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
dependencies = [
"libloading",
]
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "font-types"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
dependencies = [
"bytemuck",
]
[[package]]
name = "fontique"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23358480a54a886d51b306718d5ca743fdfe238e5df38ef650f4e72f29c5d9e9"
dependencies = [
"hashbrown",
"linebender_resource_handle",
"memmap2",
"objc2",
"objc2-core-foundation",
"objc2-core-text",
"objc2-foundation",
"parlance",
"read-fonts",
"roxmltree",
"smallvec",
"windows",
"windows-core",
"yeslogic-fontconfig-sys",
]
[[package]]
name = "getopts"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
"unicode-width",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"foldhash",
]
[[package]]
name = "htmlparser"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144"
[[package]]
name = "i-slint-common"
version = "1.16.1"
dependencies = [
"derive_more",
"fontique",
"htmlparser",
"pulldown-cmark",
"skrifa",
]
[[package]]
name = "libc"
version = "0.2.185"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "memmap2"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3"
dependencies = [
"libc",
]
[[package]]
name = "objc2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags",
]
[[package]]
name = "objc2-core-text"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
dependencies = [
"bitflags",
"objc2-core-foundation",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "parlance"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b6937eda350acc1a5d05872c3cbf99fe78619c269096e2be3d4a350058639d5"
[[package]]
name = "pkg-config"
version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pulldown-cmark"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c3a14896dfa883796f1cb410461aef38810ea05f2b2c33c5aded3649095fdad"
dependencies = [
"bitflags",
"getopts",
"memchr",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "read-fonts"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b634fabf032fab15307ffd272149b622260f55974d9fad689292a5d33df02e5"
dependencies = [
"bytemuck",
"font-types",
]
[[package]]
name = "roxmltree"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
dependencies = [
"memchr",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "skrifa"
version = "0.40.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fbdfe3d2475fbd7ddd1f3e5cf8288a30eb3e5f95832829570cd88115a7434ac"
dependencies = [
"bytemuck",
"read-fonts",
]
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-segmentation"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"
[[package]]
name = "unicode-width"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
]
[[package]]
name = "yeslogic-fontconfig-sys"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "503a066b4c037c440169d995b869046827dbc71263f6e8f3be6d77d4f3229dbd"
dependencies = [
"dlib",
"once_cell",
"pkg-config",
]
+85
View File
@@ -0,0 +1,85 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.88"
name = "i-slint-common"
version = "1.16.1"
authors = ["Slint Developers <info@slint.dev>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Helper crate for sharing code & data structures between i-slint-core and slint-compiler"
homepage = "https://slint.dev"
documentation = "https://slint.dev/docs"
readme = "README.md"
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
repository = "https://github.com/slint-ui/slint"
[package.metadata.docs.rs]
rustdoc-args = ["--generate-link-to-definition"]
[features]
color-parsing = []
default = []
fontconfig-dlopen = ["fontique?/fontconfig-dlopen"]
markdown = [
"dep:pulldown-cmark",
"dep:htmlparser",
"dep:derive_more",
"color-parsing",
]
shared-fontique = [
"dep:fontique",
"dep:skrifa",
]
[lib]
name = "i_slint_common"
path = "lib.rs"
[dependencies.derive_more]
version = "2.0.0"
features = [
"deref",
"deref_mut",
"into",
"from",
"add",
"add_assign",
"mul",
"not",
"display",
"error",
"display",
]
optional = true
default-features = false
[dependencies.fontique]
version = "0.8.0"
optional = true
[dependencies.htmlparser]
version = "0.2.1"
optional = true
[dependencies.pulldown-cmark]
version = "0.13.0"
optional = true
[dependencies.skrifa]
version = "0.40"
optional = true
+34
View File
@@ -0,0 +1,34 @@
# Copyright © SixtyFPS GmbH <info@slint.dev>
# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
[package]
name = "i-slint-common"
description = "Helper crate for sharing code & data structures between i-slint-core and slint-compiler"
authors.workspace = true
documentation.workspace = true
edition = "2024"
homepage.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
[lib]
path = "lib.rs"
[features]
default = []
shared-fontique = ["dep:fontique", "dep:skrifa"]
color-parsing = []
fontconfig-dlopen = ["fontique?/fontconfig-dlopen"]
markdown = ["dep:pulldown-cmark", "dep:htmlparser", "dep:derive_more", "color-parsing"]
[dependencies]
fontique = { workspace = true, optional = true }
skrifa = { workspace = true, optional = true }
pulldown-cmark = { version = "0.13.0", optional = true }
htmlparser = { version = "0.2.1", optional = true }
derive_more = { workspace = true, optional = true, features = ["error", "display"] }
[package.metadata.docs.rs]
rustdoc-args = ["--generate-link-to-definition"]
@@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
@@ -0,0 +1,43 @@
# Slint Royalty-free Desktop, Mobile, and Web Applications License
Version 2.0
## Preamble
Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Royalty-free Desktop, Mobile, and Web Applications License** is suitable for those who develop desktop, mobile, or web applications and do not want to use open source components under copyleft licenses.
## 1. Grant of Rights
SixtyFPS hereby grants You a world-wide, royalty-free, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application.
A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system.
A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system.
A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser.
Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**.
## 2. License Conditions - Attribution
You may distribute the Software as part of an Application, modified or unmodified, provided that You do either of the following:
(a) Display the [`AboutSlint`](https://docs.slint.dev/latest/docs/slint/reference/std-widgets/misc/aboutslint/) widget in an "About" screen or dialog that is accessible from the top level menu of the Application. In the absence of such a screen or dialog, display the widget in the "Splash Screen" of the Application.
(b) Display the [Slint attribution badge](https://github.com/slint-ui/slint/tree/master/logo/MadeWithSlint-logo-whitebg.png) on a public webpage, preferably where the binaries of your Application can be downloaded from, in such a way that it can be easily found by any visitor to that page.
## 3. Limitations
The License does not permit to distribute or make the Software publicly available alone and without integration into an Application. For this purpose you may use the Software under the GNU General Public License, version 3.
The License does not permit the use of the Software within Embedded Systems. An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system.
The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software.
You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software.
## 4. Warranty and Liability
SixtyFPS is only liable for conflicting rights of third parties if SixtyFPS was aware of these rights without informing you. Unless required by applicable law or agreed to in writing, SixtyFPS provides the Software on an "as is" basis, without warranties or conditions of any kind, either express or implied, including, without limitation, any warranties or conditions of merchantability, or fitness for a particular purpose.
Unless required by law, SixtyFPS won't be liable for any direct, indirect, incidental, or consequential damages arising in any way out of the use of the Software.
@@ -0,0 +1,117 @@
# Slint Software License
Version 3.0.5
## Preamble
Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Software License** is suitable for those who do not want to use open source components under copyleft licenses.
## 1. Grant of Rights
SixtyFPS hereby grants You a world-wide, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application or as part of an Embedded System (each of which is defined below).
A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system.
A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system.
A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser.
An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system.
Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**.
## 2. License Conditions
The grant of rights in section 1 are conditional, provided that You do all of the following:
(a) You have purchased an appropriate **Paid License Plan** ([see Annex 1](#annex-1-paid-license-plans)) and the required amount of seats to cover all individual users of the Software associated with the designing, developing, or testing your Application or Embedded System. For clarity, each individual user is counted as one seat.
(b) In the case that You are distributing the Software as part of an Embedded System, You have purchased an appropriate quantity of **Royalties**, one Royalty for each Embedded System. Royalties become due and payable upon manufacture of the Embedded System, regardless of whether such is subsequently sold, shipped, returned, replaced under warranty, or recalled. Payment of royalties is non-refundable under any circumstances. Royalties are not necessary for non-commercial projects, personal projects, and open source projects.
## 3. Limitations
The License does not permit to distribute or make the Software publicly available alone and without integration into an Application or into an Embedded System. For this purpose you may use the Software under the GNU General Public License, version 3.
The License is limited to only the versions of Software that were made available to you under the Paid License Plan. For all other versions, you may use the Software under either the GNU General Public License, version 3 or the Slint Royalty-free Desktop, Mobile, and Web Applications License.
The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software.
You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software.
## 4. Audit Rights
SixtyFPS or an independent certified auditor on SixtyFPS's behalf, may, upon its reasonable request, with 30 (thirty) days written notice, and at its sole expense, examine your books and records solely with respect to your use of the Software. Any such audit shall be conducted during regular business hours at your facilities and shall not unreasonably interfere with your business activities. The auditor shall not remove, copy, or redistribute any electronic material during an audit. If an audit reveals that you are using the Software in a way that is in material violation of the terms of this License, then you shall pay SixtyFPS reasonable costs of conducting the audit. The auditor shall only be allowed to report violations of the terms of this License, with a copy to you. You shall be provided the right to provide comments to the report before it is finalized.
## 5. Termination
(a) SixtyFPS may terminate this License if You materially breach any obligation hereunder, provided You have been provided notice of such breach and an opportunity to cure such breach during a period of not less than sixty (60) days following such notice.
(b) You may terminate this License with or without cause upon no less than thirty (30) days advance written notice to SixtyFPS.
(c) Upon termination of this License, You will immediately cease using, reproducing, making available, modifying, displaying, performing, distributing the Software and pay immediately any unpaid Fees and contractual penalties.
(d) Sections 3 through 8 of this License will survive any termination of the License to the extent necessary to implement their objectives.
## 6. Assignment
You may assign this License, in whole or in part (whether by operation of law or otherwise), with prior consent from SixtyFPS, which shall not be unreasonably withheld or delayed. SixtyFPS may assign any of its rights or delegate any of its obligations hereunder with prior notice to You, provided that the successor maintains at least the same level of security, confidentiality, and data protection measures as in place at the time of assignment or delegation. Any attempt to assign this License other than in accordance with this Section 6 shall be null and void.
## 7. Severability
In the event that any provision of this License will, for any reason, be determined by any court of competent jurisdiction to be invalid, illegal or unenforceable in any respect, such invalidity, illegality or unenforceability will be interpreted as closely as possible so as not affect any other provision of this License, and such provision will further be modified by said court to permit its enforcement to the maximum extent permitted by law.
## 8. Governing Law
This Agreement shall be construed, interpreted, and governed by the laws of the Federal Republic of Germany.
## Annex 1: Paid License Plans
### Enterprise Plan
The following is included as part of the plan
(a) No restriction on the number of applications that are developed with Slint.
(b) Live Preview.
(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
(d) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
(e) GUI Test Framework.
### Small Enterprise Plan
This plan is limited to individual companies with a staff headcount between 10 and 50 and either a turnover or balance sheet total of 10 million EUR or less. If You are a Small Enterprise, You are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name).
The following is included as part of the plan
(a) No restriction on the number of applications that are developed with Slint.
(b) Live Preview.
(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
The following can be purchased as an Add-On
(a) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
(b) GUI Test Framework.
### Startup & Individual Plan
This plan is limited to individuals and individual companies with a staff headcount of less than 10 and either a turnover or balance sheet total of 2 million EUR or less. If You are a Startup, you are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name).
The following is included as part of the plan
(a) No restriction on the number of applications that are developed with Slint.
(b) Live Preview.
The following can be purchased as an Add-On
(a) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
(b) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
(c) GUI Test Framework.
+10
View File
@@ -0,0 +1,10 @@
This crate contains internal data structures and code that is shared between
the i-slint-core and the i-slint-compiler crates.
**NOTE**: This library is an **internal** crate of the [Slint project](https://slint.dev).
This crate should **not be used directly** by applications using Slint.
You should use the `slint` crate instead.
**WARNING**: This crate does not follow the semver convention for versioning and can
only be used with `version = "=x.y.z"` in Cargo.toml.
+220
View File
@@ -0,0 +1,220 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
//! This module contains all builtin structures exposed in the .slint language.
/// Call a macro with every builtin structures exposed in the .slint language
///
/// ## Example
/// ```rust
/// macro_rules! print_builtin_structs {
/// ($(
/// $(#[$struct_attr:meta])*
/// struct $Name:ident {
/// @name = $inner_name:expr,
/// export {
/// $( $(#[$pub_attr:meta])* $pub_field:ident : $pub_type:ty, )*
/// }
/// private {
/// $( $(#[$pri_attr:meta])* $pri_field:ident : $pri_type:ty, )*
/// }
/// }
/// )*) => {
/// $(println!("{} => export:[{}] private:[{}]", stringify!($Name), stringify!($($pub_field),*), stringify!($($pri_field),*));)*
/// };
/// }
/// i_slint_common::for_each_builtin_structs!(print_builtin_structs);
/// ```
#[macro_export]
macro_rules! for_each_builtin_structs {
($macro:ident) => {
$macro![
/// The `KeyboardModifiers` struct provides booleans to indicate possible modifier keys on a keyboard, such as Shift, Control, etc.
/// It is provided as part of `KeyEvent`'s `modifiers` field.
///
/// Keyboard shortcuts on Apple platforms typically use the Command key (⌘), such as Command+C for "Copy". On other platforms
/// the same shortcut is typically represented using Control+C. To make it easier to develop cross-platform applications, on macOS,
/// Slint maps the Command key to the control modifier, and the Control key to the meta modifier.
///
/// On Windows, the Windows key is mapped to the meta modifier.
#[non_exhaustive]
#[derive(Copy, Eq)]
struct KeyboardModifiers {
@name = BuiltinPublicStruct::KeyboardModifiers,
export {
/// Indicates the Alt key on a keyboard.
alt: bool,
/// Indicates the Control key on a keyboard, except on macOS, where it is the Command key (⌘).
control: bool,
/// Indicates the Shift key on a keyboard.
shift: bool,
/// Indicates the Control key on macos, and the Windows key on Windows.
meta: bool,
}
private {
}
}
/// Represents a Pointer event sent by the windowing system.
/// This structure is passed to the `pointer-event` callback of the `TouchArea` element.
struct PointerEvent {
@name = BuiltinPrivateStruct::PointerEvent,
export {
/// The button that was pressed or released
button: PointerEventButton,
/// The kind of the event
kind: PointerEventKind,
/// The keyboard modifiers pressed during the event
modifiers: KeyboardModifiers,
}
private {
/// The flag indicating whether the event was generated by a touch input
is_touch: bool,
}
}
/// Represents a Pointer scroll (or wheel) event sent by the windowing system.
/// This structure is passed to the `scroll-event` callback of the `TouchArea` element.
struct PointerScrollEvent {
@name = BuiltinPrivateStruct::PointerScrollEvent,
export {
/// The amount of pixel in the horizontal direction
delta_x: Coord,
/// The amount of pixel in the vertical direction
delta_y: Coord,
/// The keyboard modifiers pressed during the event
modifiers: KeyboardModifiers,
}
private {
}
}
/// This structure is generated and passed to the key press and release callbacks of the `FocusScope` element.
#[non_exhaustive]
struct KeyEvent {
@name = BuiltinPublicStruct::KeyEvent,
export {
/// The unicode representation of the key pressed.
text: SharedString,
/// The keyboard modifiers active at the time of the key press event.
modifiers: KeyboardModifiers,
/// This field is set to true for key press events that are repeated,
/// i.e. the key is held down. It's always false for key release events.
repeat: bool,
}
private {
}
}
/// This structure is passed to the callbacks of the `DropArea` element
struct DropEvent {
@name = BuiltinPrivateStruct::DropEvent,
export {
/// The mime type of the data being dragged
mime_type: SharedString,
/// The data being dragged
data: SharedString,
/// The current mouse position in coordinates of the `DropArea` element
position: LogicalPosition,
}
private {
}
}
/// Represents an item in a StandardListView and a StandardTableView.
#[non_exhaustive]
struct StandardListViewItem {
@name = BuiltinPublicStruct::StandardListViewItem,
export {
/// The text content of the item
text: SharedString,
}
private {
}
}
/// This is used to define the column and the column header of a TableView
#[non_exhaustive]
struct TableColumn {
@name = BuiltinPrivateStruct::TableColumn,
export {
/// The title of the column header
title: SharedString,
/// The minimum column width (logical length)
min_width: Coord,
/// The horizontal column stretch
horizontal_stretch: f32,
/// Sorts the column
sort_order: SortOrder,
/// the actual width of the column (logical length)
width: Coord,
}
private {
}
}
/// A structure to hold metrics of a font for a specified pixel size.
struct FontMetrics {
@name = BuiltinPrivateStruct::FontMetrics,
export {
/// The distance between the baseline and the top of the tallest glyph in the font.
ascent: Coord,
/// The distance between the baseline and the bottom of the tallest glyph in the font.
/// This is usually negative.
descent: Coord,
/// The distance between the baseline and the horizontal midpoint of the tallest glyph in the font,
/// or zero if not specified by the font.
x_height: Coord,
/// The distance between the baseline and the top of a regular upper-case glyph in the font,
/// or zero if not specified by the font.
cap_height: Coord,
}
private {
}
}
/// An item in the menu of a menu bar or context menu
struct MenuEntry {
@name = BuiltinPrivateStruct::MenuEntry,
export {
/// The text of the menu entry
title: SharedString,
/// the icon associated with the menu entry
icon: Image,
/// an opaque id that can be used to identify the menu entry
id: SharedString,
// keys: KeySequence,
/// whether the menu entry is enabled
enabled: bool,
/// whether the menu entry is checkable
checkable: bool,
/// whether the menu entry is checked
checked: bool,
/// Sub menu
has_sub_menu: bool,
/// The menu entry is a separator
is_separator: bool,
/// The shortcut keys
shortcut: Keys,
}
private {}
}
/// A structure representing the four edges of an axis-aligned rectangle
struct Edges {
@name = BuiltinPrivateStruct::Edges,
export {
/// The left edge value
left: Coord,
/// The top edge value
top: Coord,
/// The right edge value
right: Coord,
/// The bottom edge value
bottom: Coord,
}
private {}
}
];
};
}
+216
View File
@@ -0,0 +1,216 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
use std::collections::HashMap;
/// Returns `0xaarrggbb`
pub fn parse_color_literal(str: &str) -> Option<u32> {
if !str.starts_with('#') {
return None;
}
if !str.is_ascii() {
return None;
}
let str = &str[1..];
let (r, g, b, a) = match str.len() {
3 => (
u8::from_str_radix(&str[0..=0], 16).ok()? * 0x11,
u8::from_str_radix(&str[1..=1], 16).ok()? * 0x11,
u8::from_str_radix(&str[2..=2], 16).ok()? * 0x11,
255u8,
),
4 => (
u8::from_str_radix(&str[0..=0], 16).ok()? * 0x11,
u8::from_str_radix(&str[1..=1], 16).ok()? * 0x11,
u8::from_str_radix(&str[2..=2], 16).ok()? * 0x11,
u8::from_str_radix(&str[3..=3], 16).ok()? * 0x11,
),
6 => (
u8::from_str_radix(&str[0..2], 16).ok()?,
u8::from_str_radix(&str[2..4], 16).ok()?,
u8::from_str_radix(&str[4..6], 16).ok()?,
255u8,
),
8 => (
u8::from_str_radix(&str[0..2], 16).ok()?,
u8::from_str_radix(&str[2..4], 16).ok()?,
u8::from_str_radix(&str[4..6], 16).ok()?,
u8::from_str_radix(&str[6..8], 16).ok()?,
),
_ => return None,
};
Some((a as u32) << 24 | (r as u32) << 16 | (g as u32) << 8 | (b as u32))
}
#[test]
fn test_parse_color_literal() {
assert_eq!(parse_color_literal("#abc"), Some(0xffaabbcc));
assert_eq!(parse_color_literal("#ABC"), Some(0xffaabbcc));
assert_eq!(parse_color_literal("#AbC"), Some(0xffaabbcc));
assert_eq!(parse_color_literal("#AbCd"), Some(0xddaabbcc));
assert_eq!(parse_color_literal("#01234567"), Some(0x67012345));
assert_eq!(parse_color_literal("#012345"), Some(0xff012345));
assert_eq!(parse_color_literal("_01234567"), None);
assert_eq!(parse_color_literal("→↓←"), None);
assert_eq!(parse_color_literal("#→↓←"), None);
assert_eq!(parse_color_literal("#1234567890"), None);
}
static NAMED_COLORS: std::sync::OnceLock<HashMap<&'static str, u32>> = std::sync::OnceLock::new();
pub fn named_colors() -> &'static HashMap<&'static str, u32> {
// Colors from https://drafts.csswg.org/css-color/#named-colors plus "transparent"
NAMED_COLORS.get_or_init(|| {
HashMap::from([
("aliceblue", parse_color_literal("#F0F8FF").unwrap()),
("antiquewhite", parse_color_literal("#FAEBD7").unwrap()),
("aqua", parse_color_literal("#00FFFF").unwrap()),
("aquamarine", parse_color_literal("#7FFFD4").unwrap()),
("azure", parse_color_literal("#F0FFFF").unwrap()),
("beige", parse_color_literal("#F5F5DC").unwrap()),
("bisque", parse_color_literal("#FFE4C4").unwrap()),
("black", parse_color_literal("#000000").unwrap()),
("blanchedalmond", parse_color_literal("#FFEBCD").unwrap()),
("blue", parse_color_literal("#0000FF").unwrap()),
("blueviolet", parse_color_literal("#8A2BE2").unwrap()),
("brown", parse_color_literal("#A52A2A").unwrap()),
("burlywood", parse_color_literal("#DEB887").unwrap()),
("cadetblue", parse_color_literal("#5F9EA0").unwrap()),
("chartreuse", parse_color_literal("#7FFF00").unwrap()),
("chocolate", parse_color_literal("#D2691E").unwrap()),
("coral", parse_color_literal("#FF7F50").unwrap()),
("cornflowerblue", parse_color_literal("#6495ED").unwrap()),
("cornsilk", parse_color_literal("#FFF8DC").unwrap()),
("crimson", parse_color_literal("#DC143C").unwrap()),
("cyan", parse_color_literal("#00FFFF").unwrap()),
("darkblue", parse_color_literal("#00008B").unwrap()),
("darkcyan", parse_color_literal("#008B8B").unwrap()),
("darkgoldenrod", parse_color_literal("#B8860B").unwrap()),
("darkgray", parse_color_literal("#A9A9A9").unwrap()),
("darkgreen", parse_color_literal("#006400").unwrap()),
("darkgrey", parse_color_literal("#A9A9A9").unwrap()),
("darkkhaki", parse_color_literal("#BDB76B").unwrap()),
("darkmagenta", parse_color_literal("#8B008B").unwrap()),
("darkolivegreen", parse_color_literal("#556B2F").unwrap()),
("darkorange", parse_color_literal("#FF8C00").unwrap()),
("darkorchid", parse_color_literal("#9932CC").unwrap()),
("darkred", parse_color_literal("#8B0000").unwrap()),
("darksalmon", parse_color_literal("#E9967A").unwrap()),
("darkseagreen", parse_color_literal("#8FBC8F").unwrap()),
("darkslateblue", parse_color_literal("#483D8B").unwrap()),
("darkslategray", parse_color_literal("#2F4F4F").unwrap()),
("darkslategrey", parse_color_literal("#2F4F4F").unwrap()),
("darkturquoise", parse_color_literal("#00CED1").unwrap()),
("darkviolet", parse_color_literal("#9400D3").unwrap()),
("deeppink", parse_color_literal("#FF1493").unwrap()),
("deepskyblue", parse_color_literal("#00BFFF").unwrap()),
("dimgray", parse_color_literal("#696969").unwrap()),
("dimgrey", parse_color_literal("#696969").unwrap()),
("dodgerblue", parse_color_literal("#1E90FF").unwrap()),
("firebrick", parse_color_literal("#B22222").unwrap()),
("floralwhite", parse_color_literal("#FFFAF0").unwrap()),
("forestgreen", parse_color_literal("#228B22").unwrap()),
("fuchsia", parse_color_literal("#FF00FF").unwrap()),
("gainsboro", parse_color_literal("#DCDCDC").unwrap()),
("ghostwhite", parse_color_literal("#F8F8FF").unwrap()),
("gold", parse_color_literal("#FFD700").unwrap()),
("goldenrod", parse_color_literal("#DAA520").unwrap()),
("gray", parse_color_literal("#808080").unwrap()),
("green", parse_color_literal("#008000").unwrap()),
("greenyellow", parse_color_literal("#ADFF2F").unwrap()),
("grey", parse_color_literal("#808080").unwrap()),
("honeydew", parse_color_literal("#F0FFF0").unwrap()),
("hotpink", parse_color_literal("#FF69B4").unwrap()),
("indianred", parse_color_literal("#CD5C5C").unwrap()),
("indigo", parse_color_literal("#4B0082").unwrap()),
("ivory", parse_color_literal("#FFFFF0").unwrap()),
("khaki", parse_color_literal("#F0E68C").unwrap()),
("lavender", parse_color_literal("#E6E6FA").unwrap()),
("lavenderblush", parse_color_literal("#FFF0F5").unwrap()),
("lawngreen", parse_color_literal("#7CFC00").unwrap()),
("lemonchiffon", parse_color_literal("#FFFACD").unwrap()),
("lightblue", parse_color_literal("#ADD8E6").unwrap()),
("lightcoral", parse_color_literal("#F08080").unwrap()),
("lightcyan", parse_color_literal("#E0FFFF").unwrap()),
("lightgoldenrodyellow", parse_color_literal("#FAFAD2").unwrap()),
("lightgray", parse_color_literal("#D3D3D3").unwrap()),
("lightgreen", parse_color_literal("#90EE90").unwrap()),
("lightgrey", parse_color_literal("#D3D3D3").unwrap()),
("lightpink", parse_color_literal("#FFB6C1").unwrap()),
("lightsalmon", parse_color_literal("#FFA07A").unwrap()),
("lightseagreen", parse_color_literal("#20B2AA").unwrap()),
("lightskyblue", parse_color_literal("#87CEFA").unwrap()),
("lightslategray", parse_color_literal("#778899").unwrap()),
("lightslategrey", parse_color_literal("#778899").unwrap()),
("lightsteelblue", parse_color_literal("#B0C4DE").unwrap()),
("lightyellow", parse_color_literal("#FFFFE0").unwrap()),
("lime", parse_color_literal("#00FF00").unwrap()),
("limegreen", parse_color_literal("#32CD32").unwrap()),
("linen", parse_color_literal("#FAF0E6").unwrap()),
("magenta", parse_color_literal("#FF00FF").unwrap()),
("maroon", parse_color_literal("#800000").unwrap()),
("mediumaquamarine", parse_color_literal("#66CDAA").unwrap()),
("mediumblue", parse_color_literal("#0000CD").unwrap()),
("mediumorchid", parse_color_literal("#BA55D3").unwrap()),
("mediumpurple", parse_color_literal("#9370DB").unwrap()),
("mediumseagreen", parse_color_literal("#3CB371").unwrap()),
("mediumslateblue", parse_color_literal("#7B68EE").unwrap()),
("mediumspringgreen", parse_color_literal("#00FA9A").unwrap()),
("mediumturquoise", parse_color_literal("#48D1CC").unwrap()),
("mediumvioletred", parse_color_literal("#C71585").unwrap()),
("midnightblue", parse_color_literal("#191970").unwrap()),
("mintcream", parse_color_literal("#F5FFFA").unwrap()),
("mistyrose", parse_color_literal("#FFE4E1").unwrap()),
("moccasin", parse_color_literal("#FFE4B5").unwrap()),
("navajowhite", parse_color_literal("#FFDEAD").unwrap()),
("navy", parse_color_literal("#000080").unwrap()),
("oldlace", parse_color_literal("#FDF5E6").unwrap()),
("olive", parse_color_literal("#808000").unwrap()),
("olivedrab", parse_color_literal("#6B8E23").unwrap()),
("orange", parse_color_literal("#FFA500").unwrap()),
("orangered", parse_color_literal("#FF4500").unwrap()),
("orchid", parse_color_literal("#DA70D6").unwrap()),
("palegoldenrod", parse_color_literal("#EEE8AA").unwrap()),
("palegreen", parse_color_literal("#98FB98").unwrap()),
("paleturquoise", parse_color_literal("#AFEEEE").unwrap()),
("palevioletred", parse_color_literal("#DB7093").unwrap()),
("papayawhip", parse_color_literal("#FFEFD5").unwrap()),
("peachpuff", parse_color_literal("#FFDAB9").unwrap()),
("peru", parse_color_literal("#CD853F").unwrap()),
("pink", parse_color_literal("#FFC0CB").unwrap()),
("plum", parse_color_literal("#DDA0DD").unwrap()),
("powderblue", parse_color_literal("#B0E0E6").unwrap()),
("purple", parse_color_literal("#800080").unwrap()),
("rebeccapurple", parse_color_literal("#663399").unwrap()),
("red", parse_color_literal("#FF0000").unwrap()),
("rosybrown", parse_color_literal("#BC8F8F").unwrap()),
("royalblue", parse_color_literal("#4169E1").unwrap()),
("saddlebrown", parse_color_literal("#8B4513").unwrap()),
("salmon", parse_color_literal("#FA8072").unwrap()),
("sandybrown", parse_color_literal("#F4A460").unwrap()),
("seagreen", parse_color_literal("#2E8B57").unwrap()),
("seashell", parse_color_literal("#FFF5EE").unwrap()),
("sienna", parse_color_literal("#A0522D").unwrap()),
("silver", parse_color_literal("#C0C0C0").unwrap()),
("skyblue", parse_color_literal("#87CEEB").unwrap()),
("slateblue", parse_color_literal("#6A5ACD").unwrap()),
("slategray", parse_color_literal("#708090").unwrap()),
("slategrey", parse_color_literal("#708090").unwrap()),
("snow", parse_color_literal("#FFFAFA").unwrap()),
("springgreen", parse_color_literal("#00FF7F").unwrap()),
("steelblue", parse_color_literal("#4682B4").unwrap()),
("tan", parse_color_literal("#D2B48C").unwrap()),
("teal", parse_color_literal("#008080").unwrap()),
("thistle", parse_color_literal("#D8BFD8").unwrap()),
("tomato", parse_color_literal("#FF6347").unwrap()),
("transparent", parse_color_literal("#00000000").unwrap()),
("turquoise", parse_color_literal("#40E0D0").unwrap()),
("violet", parse_color_literal("#EE82EE").unwrap()),
("wheat", parse_color_literal("#F5DEB3").unwrap()),
("white", parse_color_literal("#FFFFFF").unwrap()),
("whitesmoke", parse_color_literal("#F5F5F5").unwrap()),
("yellow", parse_color_literal("#FFFF00").unwrap()),
("yellowgreen", parse_color_literal("#9ACD32").unwrap()),
])
})
}
+614
View File
@@ -0,0 +1,614 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
//! This module contains all enums exposed in the .slint language.
// cSpell: ignore evenodd grabbable horizontalbox horizontallayout nesw standardbutton standardtableview verticalbox verticallayout
/// Call a macro with every enum exposed in the .slint language
///
/// ## Example
/// ```rust
/// macro_rules! print_enums {
/// ($( $(#[$enum_doc:meta])* enum $Name:ident { $( $(#[$value_doc:meta])* $Value:ident,)* })*) => {
/// $(println!("{} => [{}]", stringify!($Name), stringify!($($Value),*));)*
/// }
/// }
/// i_slint_common::for_each_enums!(print_enums);
/// ```
#[macro_export]
macro_rules! for_each_enums {
($macro:ident) => {
$macro![
/// This enum describes the different types of alignment of text along the horizontal axis of a `Text` or `StyledText` element.
#[non_exhaustive]
enum TextHorizontalAlignment {
/// The text will be aligned with the start edge of the containing box.
/// This could be left or right depending on the direction of the text.
Start,
/// The text will be aligned with the end edge of the containing box.
/// This could be left or right depending on the direction of the text.
End,
/// The text will be aligned with the left edge of the containing box.
Left,
/// The text will be horizontally centered within the containing box.
Center,
/// The text will be aligned to the right of the containing box.
Right,
}
/// This enum describes the different types of alignment of text along the vertical axis of a `Text` or `StyledText` element.
#[non_exhaustive]
enum TextVerticalAlignment {
/// The text will be aligned to the top of the containing box.
Top,
/// The text will be vertically centered within the containing box.
Center,
/// The text will be aligned to the bottom of the containing box.
Bottom,
}
/// This enum describes the how the text wraps if it is too wide to fit in the width of a `Text` or `StyledText` element.
#[non_exhaustive]
enum TextWrap {
/// The text won't wrap, but instead will overflow.
NoWrap,
/// The text will be wrapped at word boundaries if possible, or at any location for very long words.
WordWrap,
/// The text will be wrapped at any character. Currently only supported by the Qt and Software renderers.
CharWrap,
}
/// This enum describes the how the text appears if it is too wide to fit in the width of a `Text` or `StyledText` element.
#[non_exhaustive]
enum TextOverflow {
/// The text will simply be clipped.
Clip,
/// The text will be elided with `…`.
Elide,
}
/// This enum describes the positioning of a text stroke relative to the border of the glyphs in a `Text` or `StyledText` element.
#[non_exhaustive]
enum TextStrokeStyle {
/// The inside edge of the stroke is at the outer edge of the text.
Outside,
/// The center line of the stroke is at the outer edge of the text, like in Adobe Illustrator.
Center,
}
/// This enum describes whether an event was rejected or accepted by an event handler.
#[non_exhaustive]
enum EventResult {
/// The event is rejected by this event handler and may then be handled by the parent item
Reject,
/// The event is accepted and won't be processed further
Accept,
}
/// This enum describes the different ways of deciding what the inside of a shape described by a path shall be.
#[non_exhaustive]
enum FillRule {
/// The ["nonzero" fill rule as defined in SVG](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule#nonzero).
Nonzero,
/// The ["evenodd" fill rule as defined in SVG](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule#evenodd)
Evenodd,
}
/// Use this enum to add standard buttons to a `Dialog`. The look and positioning
/// of these `StandardButton`s depends on the environment
/// (OS, UI environment, etc.) the application runs in.
#[non_exhaustive]
enum StandardButtonKind {
/// A "OK" button that accepts a `Dialog`, closing it when clicked.
Ok,
/// A "Cancel" button that rejects a `Dialog`, closing it when clicked.
Cancel,
/// A "Apply" button that should accept values from a
/// `Dialog` without closing it.
Apply,
/// A "Close" button, which should close a `Dialog` without looking at values.
Close,
/// A "Reset" button, which should reset the `Dialog` to its initial state.
Reset,
/// A "Help" button, which should bring up context related documentation when clicked.
Help,
/// A "Yes" button, used to confirm an action.
Yes,
/// A "No" button, used to deny an action.
No,
/// A "Abort" button, used to abort an action.
Abort,
/// A "Retry" button, used to retry a failed action.
Retry,
/// A "Ignore" button, used to ignore a failed action.
Ignore,
}
/// This enum represents the value of the `dialog-button-role` property which can be added to
/// any element within a `Dialog` to put that item in the button row, and its exact position
/// depends on the role and the platform.
#[non_exhaustive]
enum DialogButtonRole {
/// This isn't a button meant to go into the bottom row
None,
/// This is the role of the main button to click to accept the dialog. e.g. "Ok" or "Yes"
Accept,
/// This is the role of the main button to click to reject the dialog. e.g. "Cancel" or "No"
Reject,
/// This is the role of the "Apply" button
Apply,
/// This is the role of the "Reset" button
Reset,
/// This is the role of the "Help" button
Help,
/// This is the role of any other button that performs another action.
Action,
}
/// This enum describes the different reasons for a FocusEvent
#[non_exhaustive]
enum FocusReason {
/// A built-in function invocation caused the event (`.focus()`, `.clear-focus()`)
Programmatic,
/// Keyboard navigation caused the event (tabbing)
TabNavigation,
/// A mouse click caused the event
PointerClick,
/// A popup caused the event
PopupActivation,
/// The window manager changed the active window and caused the event
WindowActivation,
}
/// The enum reports what happened to the `PointerEventButton` in the event
#[non_exhaustive]
enum PointerEventKind {
/// The action was cancelled.
Cancel,
/// The button was pressed.
Down,
/// The button was released.
Up,
/// The pointer has moved,
Move,
}
/// This enum describes the different types of buttons for a pointer event,
/// typically on a mouse or a pencil.
#[non_exhaustive]
enum PointerEventButton {
/// A button that is none of left, right, middle, back or forward. For example,
/// this is used for the task button on a mouse with many buttons.
Other,
/// The left button.
Left,
/// The right button.
Right,
/// The center button.
Middle,
/// The back button.
Back,
/// The forward button.
Forward,
}
/// This enum represents different types of mouse cursors. It's a subset of the mouse cursors available in CSS.
/// For details and pictograms see the [MDN Documentation for cursor](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values).
/// Depending on the backend and used OS unidirectional resize cursors may be replaced with bidirectional ones.
#[non_exhaustive]
enum MouseCursor {
/// The systems default cursor.
Default,
/// No cursor is displayed.
None,
//context_menu,
/// A cursor indicating help information.
Help,
/// A pointing hand indicating a link.
Pointer,
/// The program is busy but can still be interacted with.
Progress,
/// The program is busy.
Wait,
//cell,
/// A crosshair.
Crosshair,
/// A cursor indicating selectable text.
Text,
//vertical_text,
/// An alias or shortcut is being created.
Alias,
/// A copy is being created.
Copy,
/// Something is to be moved.
Move,
/// Something can't be dropped here.
NoDrop,
/// An action isn't allowed
NotAllowed,
/// Something is grabbable.
Grab,
/// Something is being grabbed.
Grabbing,
//all_scroll,
/// Indicating that a column is resizable horizontally.
ColResize,
/// Indicating that a row is resizable vertically.
RowResize,
/// Unidirectional resize north.
NResize,
/// Unidirectional resize east.
EResize,
/// Unidirectional resize south.
SResize,
/// Unidirectional resize west.
WResize,
/// Unidirectional resize north-east.
NeResize,
/// Unidirectional resize north-west.
NwResize,
/// Unidirectional resize south-east.
SeResize,
/// Unidirectional resize south-west.
SwResize,
/// Bidirectional resize east-west.
EwResize,
/// Bidirectional resize north-south.
NsResize,
/// Bidirectional resize north-east-south-west.
NeswResize,
/// Bidirectional resize north-west-south-east.
NwseResize,
//zoom_in,
//zoom_out,
}
/// This enum defines how the source image or path shall fit into an `Image` or `Path` element.
#[non_exhaustive]
enum ImageFit {
/// Scales and stretches the source to fit the width and height of the element.
Fill,
/// The source is scaled to fit into the element's dimensions while preserving the aspect ratio.
Contain,
/// The source is scaled to cover the element's dimensions while preserving the aspect ratio.
/// If the aspect ratios don't match, the source will be clipped to fit.
Cover,
/// Preserves the size of the source in logical pixels.
/// The source will still be scaled by the scale factor that applies to all elements in the window.
/// Any extra space will be left blank.
Preserve,
}
/// This enum specifies the horizontal alignment of the source image.
#[non_exhaustive]
enum ImageHorizontalAlignment {
/// Aligns the source image at the center of the `Image` element.
Center,
/// Aligns the source image at the left of the `Image` element.
Left,
/// Aligns the source image at the right of the `Image` element.
Right,
}
/// This enum specifies the vertical alignment of the source image.
#[non_exhaustive]
enum ImageVerticalAlignment {
/// Aligns the source image at the center of the `Image` element.
Center,
/// Aligns the source image at the top of the `Image` element.
Top,
/// Aligns the source image at the bottom of the `Image` element.
Bottom,
}
/// This enum specifies how the source image will be scaled.
#[non_exhaustive]
enum ImageRendering {
/// The image is scaled with a linear interpolation algorithm.
Smooth,
/// The image is scaled with the nearest neighbor algorithm.
Pixelated,
}
/// This enum specifies how the source image will be tiled.
#[non_exhaustive]
enum ImageTiling {
/// The source image will not be tiled.
None,
/// The source image will be repeated to fill the `Image` element.
Repeat,
/// The source image will be repeated and scaled to fill the `Image` element, ensuring an integer number of repetitions.
Round,
}
/// This enum is used to define the type of the input field.
#[non_exhaustive]
enum InputType {
/// The default value. This will render all characters normally
Text,
/// This will render all characters with a character that defaults to "*"
Password,
/// This will only accept and render number characters (0-9)
Number,
/// This will accept and render characters if it's valid part of a decimal
Decimal,
}
/// Enum representing the `alignment` property of a
/// `HorizontalBox`, a `VerticalBox`,
/// a `HorizontalLayout`, or `VerticalLayout`.
#[non_exhaustive]
enum LayoutAlignment {
/// Use the minimum size of all elements in a layout, distribute remaining space
/// based on `*-stretch` among all elements.
Stretch,
/// Use the preferred size for all elements, distribute remaining space evenly before the
/// first and after the last element.
Center,
/// Use the preferred size for all elements, put remaining space after the last element.
Start,
/// Use the preferred size for all elements, put remaining space before the first
/// element.
End,
/// Use the preferred size for all elements, distribute remaining space evenly between
/// elements.
SpaceBetween,
/// Use the preferred size for all elements, distribute remaining space evenly
/// between the elements, and use half spaces at the start and end.
SpaceAround,
/// Use the preferred size for all elements, distribute remaining space evenly before the
/// first element, after the last element and between elements.
SpaceEvenly,
}
/// The direction in which flex items are placed in a flex container.
#[non_exhaustive]
enum FlexboxLayoutDirection {
/// Items are placed in a row, from left to right.
Row,
/// Items are placed in a row in reverse order, from right to left.
RowReverse,
/// Items are placed in a column, from top to bottom.
Column,
/// Items are placed in a column in reverse order, from bottom to top.
ColumnReverse,
}
/// Controls the distribution of flex lines along the cross axis in a flex container.
#[non_exhaustive]
enum FlexboxLayoutAlignContent {
/// Lines are stretched to fill the container along the cross axis.
Stretch,
/// Lines are placed at the start of the cross axis.
Start,
/// Lines are placed at the end of the cross axis.
End,
/// Lines are centered along the cross axis.
Center,
/// Equal gaps between lines, no gap at the edges.
SpaceBetween,
/// Equal gaps around each line (half-size at edges).
SpaceAround,
/// Equal gaps between lines and at the edges.
SpaceEvenly,
}
/// Controls the alignment of individual items along the cross axis within each flex line.
#[non_exhaustive]
enum FlexboxLayoutAlignItems {
/// Items are stretched to fill the line along the cross axis.
Stretch,
/// Items are placed at the start of the cross axis.
Start,
/// Items are placed at the end of the cross axis.
End,
/// Items are centered along the cross axis.
Center,
}
/// Overrides the container's `align-items` for a specific flex item.
#[non_exhaustive]
enum FlexboxLayoutAlignSelf {
/// Use the container's `align-items` value (default).
Auto,
/// The item is stretched to fill the line along the cross axis.
Stretch,
/// The item is placed at the start of the cross axis.
Start,
/// The item is placed at the end of the cross axis.
End,
/// The item is centered along the cross axis.
Center,
}
/// Controls whether flex items wrap onto multiple lines.
#[non_exhaustive]
enum FlexboxLayoutWrap {
/// Flex items wrap onto multiple lines, from top to bottom (for row direction) or left to right (for column direction).
Wrap,
/// All flex items are laid out on a single line (default for CSS, but Slint defaults to `wrap`).
NoWrap,
/// Flex items wrap onto multiple lines in the reverse direction.
WrapReverse,
}
/// PathEvent is a low-level data structure describing the composition of a path. Typically it is
/// generated at compile time from a higher-level description, such as SVG commands.
#[non_exhaustive]
enum PathEvent {
/// The beginning of the path.
Begin,
/// A straight line on the path.
Line,
/// A quadratic bezier curve on the path.
Quadratic,
/// A cubic bezier curve on the path.
Cubic,
/// The end of the path that remains open.
EndOpen,
/// The end of a path that is closed.
EndClosed,
}
/// This enum represents the different values for the `accessible-role` property, used to describe the
/// role of an element in the context of assistive technology such as screen readers.
#[non_exhaustive]
enum AccessibleRole {
/// The element isn't accessible.
None,
/// The element is a `Button` or behaves like one.
Button,
/// The element is a `CheckBox` or behaves like one.
Checkbox,
/// The element is a `ComboBox` or behaves like one.
Combobox,
/// The element is a `GroupBox` or behaves like one.
Groupbox,
/// The element is an `Image` or behaves like one. This is automatically applied to `Image` elements.
Image,
/// The element is a `ListView` or behaves like one.
List,
/// The element is a `Slider` or behaves like one.
Slider,
/// The element is a `SpinBox` or behaves like one.
Spinbox,
/// The element is a `Tab` or behaves like one.
Tab,
/// The element is similar to the tab bar in a `TabWidget`.
TabList,
/// The element is a container for tab content.
TabPanel,
/// The role for a `Text` element. This is automatically applied to `Text` elements.
Text,
/// The role for a `TableView` or behaves like one.
Table,
/// The role for a TreeView or behaves like one. (Not provided yet)
Tree,
/// The element is a `ProgressIndicator` or behaves like one.
ProgressIndicator,
/// The role for widget with editable text such as a `LineEdit` or a `TextEdit`.
/// This is automatically applied to `TextInput` elements.
TextInput,
/// The element is a `Switch` or behaves like one.
Switch,
/// The element is an item in a `ListView`.
ListItem,
/// The element is a `RadioButton` or behaves like one.
RadioButton,
}
/// This enum represents the different values of the `sort-order` property.
/// It's used to sort a `StandardTableView` by a column.
#[non_exhaustive]
enum SortOrder {
/// The column is unsorted.
Unsorted,
/// The column is sorted in ascending order.
Ascending,
/// The column is sorted in descending order.
Descending,
}
/// Represents the orientation of an element or widget such as the `Slider`.
// (on purpose not #[non_exhaustive])
enum Orientation {
/// Element is oriented horizontally.
Horizontal,
/// Element is oriented vertically.
Vertical,
}
/// This enum indicates the color scheme used by the widget style. Use this to explicitly switch
/// between dark and light schemes, or choose Unknown to fall back to the system default.
#[non_exhaustive]
enum ColorScheme {
/// The scheme is not known and a system wide setting configures this. This could mean that
/// the widgets are shown in a dark or light scheme, but it could also be a custom color scheme.
Unknown,
/// The style chooses light colors for the background and dark for the foreground.
Dark,
/// The style chooses dark colors for the background and light for the foreground.
Light,
}
/// This enum describes the direction of an animation.
#[non_exhaustive]
enum AnimationDirection {
/// The ["normal" direction as defined in CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction#normal).
Normal,
/// The ["reverse" direction as defined in CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction#reverse).
Reverse,
/// The ["alternate" direction as defined in CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction#alternate).
Alternate,
/// The ["alternate reverse" direction as defined in CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction#alternate-reverse).
AlternateReverse,
}
/// This enum describes the scrollbar visibility
#[non_exhaustive]
enum ScrollBarPolicy {
/// Scrollbar will be visible only when needed
AsNeeded,
/// Scrollbar never shown
AlwaysOff,
/// Scrollbar always visible
AlwaysOn,
}
// This enum describes the close behavior of `PopupWindow`
#[non_exhaustive]
enum PopupClosePolicy {
/// Closes the `PopupWindow` when user clicks or presses the escape key.
CloseOnClick,
/// Closes the `PopupWindow` when user clicks outside of the popup or presses the escape key.
CloseOnClickOutside,
/// Does not close the `PopupWindow` automatically when user clicks.
NoAutoClose,
}
/// This enum describes the appearance of the ends of stroked paths.
#[non_exhaustive]
enum LineCap {
/// The stroke ends with a flat edge that is perpendicular to the path.
Butt,
/// The stroke ends with a rounded edge.
Round,
/// The stroke ends with a square projection beyond the path.
Square,
}
/// This enum describes the appearance of the joins between segments of stroked paths.
#[non_exhaustive]
enum LineJoin {
/// The stroke joins with a sharp corner or a clipped corner, depending on the miter limit.
Miter,
/// The stroke joins with a smooth, rounded corner.
Round,
/// The stroke joins with a beveled (flattened) corner.
Bevel,
}
/// This enum describes the detected operating system types.
#[non_exhaustive]
enum OperatingSystemType {
/// This variant includes any version of Android running mobile phones, tablets, as well as embedded Android devices.
Android,
/// This variant covers iOS running on iPhones and iPads.
Ios,
/// This variant covers macOS running on Apple's Mac computers.
Macos,
/// This variant covers any version of Linux, except Android.
Linux,
/// This variant covers Microsoft Windows.
Windows,
/// This variant is reported when the operating system is none of the above.
Other,
}
];
};
}
+207
View File
@@ -0,0 +1,207 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
//! This module is meant to be included by different crates and each crate must define the macro
//! for_each_keys
//!
//! The key code comes from <https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/CORPCHAR.TXT>
//! the names for the special keys should match with <https://www.w3.org/TR/uievents-key/#named-key-attribute-values>,
//! and for normal keys with: <https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode>
//!
//! The format is a semicolon separated list of keys
//! `<char code> # Slint name # Shifted key => Muda accelerator code # Qt code # Winit code # xkb code`
//!
//! Note: The values after and including the => only exist for special keys. The Shifted key and
//! Muda accelerator code may both be empty.
//!
//! ## Example
//!
//! ```
//! macro_rules! do_something_with_keys {
//! ($($char:literal # $name:ident # $($shifted:ident)? $(=> $($muda:ident)? # $($qt:ident)|* # $($winit:ident $(($_pos:ident))?)|* # $($xkb:ident)|*)? ;)*) => {
//! //...
//! };
//! }
//! i_slint_common::for_each_keys!(do_something_with_keys);
//! ```
//!
// NOTE: Run `cargo xtask slintdocs` when changing/adding/removing keys, to keep the docs in sync!
#[macro_export]
macro_rules! for_each_keys {
($macro:ident) => {
$macro![
'\u{0008}' # Backspace # => Backspace # Qt_Key_Key_Backspace # Backspace # BackSpace ;
'\u{0009}' # Tab # => Tab # Qt_Key_Key_Tab # Tab # Tab ;
'\u{000a}' # Return # => Enter # Qt_Key_Key_Enter|Qt_Key_Key_Return # Enter # Return;
'\u{001b}' # Escape # => Escape # Qt_Key_Key_Escape # Escape # Escape ;
'\u{0019}' # Backtab # => # Qt_Key_Key_Backtab # # BackTab ;
'\u{007f}' # Delete # => Delete # Qt_Key_Key_Delete # Delete # Delete ;
// The modifier key codes comes from https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode.
'\u{0010}' # Shift # => # Qt_Key_Key_Shift # Shift(Left) # Shift_L ;
'\u{0011}' # Control # => # Qt_Key_Key_Control # Control(Left)# Control_L ;
'\u{0012}' # Alt # => # Qt_Key_Key_Alt # Alt # Alt_L ;
'\u{0013}' # AltGr # => # Qt_Key_Key_AltGr # AltGraph # Mode_switch;
'\u{0014}' # CapsLock # => # Qt_Key_Key_CapsLock # # Caps_Lock ;
'\u{0015}' # ShiftR # => # # Shift(Right) # Shift_R ;
'\u{0016}' # ControlR # => # # Control(Right)# Control_R ;
// Use custom codes instead of DOM_VK_META for meta, because the Mozilla defined code is a regular character (E0; LATIN SMALL LETTER A WITH GRAVE)
// which makes those keys appear as text.
'\u{0017}' # Meta # => # Qt_Key_Key_Meta # Super(Left) # Meta_L ;
'\u{0018}' # MetaR # => # # Super(Right) # Meta_R ;
'\u{0020}' # Space # => # Qt_Key_Key_Space # Space # space ;
'\u{F700}' # UpArrow # => ArrowUp # Qt_Key_Key_Up # ArrowUp # Up ;
'\u{F701}' # DownArrow # => ArrowDown # Qt_Key_Key_Down # ArrowDown # Down ;
'\u{F702}' # LeftArrow # => ArrowLeft # Qt_Key_Key_Left # ArrowLeft # Left ;
'\u{F703}' # RightArrow # => ArrowRight # Qt_Key_Key_Right # ArrowRight # Right ;
'\u{F704}' # F1 # => F1 # Qt_Key_Key_F1 # F1 # F1 ;
'\u{F705}' # F2 # => F2 # Qt_Key_Key_F2 # F2 # F2 ;
'\u{F706}' # F3 # => F3 # Qt_Key_Key_F3 # F3 # F3 ;
'\u{F707}' # F4 # => F4 # Qt_Key_Key_F4 # F4 # F4 ;
'\u{F708}' # F5 # => F5 # Qt_Key_Key_F5 # F5 # F5 ;
'\u{F709}' # F6 # => F6 # Qt_Key_Key_F6 # F6 # F6 ;
'\u{F70A}' # F7 # => F7 # Qt_Key_Key_F7 # F7 # F7 ;
'\u{F70B}' # F8 # => F8 # Qt_Key_Key_F8 # F8 # F8 ;
'\u{F70C}' # F9 # => F9 # Qt_Key_Key_F9 # F9 # F9 ;
'\u{F70D}' # F10 # => F10 # Qt_Key_Key_F10 # F10 # F10 ;
'\u{F70E}' # F11 # => F11 # Qt_Key_Key_F11 # F11 # F11 ;
'\u{F70F}' # F12 # => F12 # Qt_Key_Key_F12 # F12 # F12 ;
'\u{F710}' # F13 # => F13 # Qt_Key_Key_F13 # F13 # F13 ;
'\u{F711}' # F14 # => F14 # Qt_Key_Key_F14 # F14 # F14 ;
'\u{F712}' # F15 # => F15 # Qt_Key_Key_F15 # F15 # F15 ;
'\u{F713}' # F16 # => F16 # Qt_Key_Key_F16 # F16 # F16 ;
'\u{F714}' # F17 # => F17 # Qt_Key_Key_F17 # F17 # F17 ;
'\u{F715}' # F18 # => F18 # Qt_Key_Key_F18 # F18 # F18 ;
'\u{F716}' # F19 # => F19 # Qt_Key_Key_F19 # F19 # F19 ;
'\u{F717}' # F20 # => F20 # Qt_Key_Key_F20 # F20 # F20 ;
'\u{F718}' # F21 # => F21 # Qt_Key_Key_F21 # F21 # F21 ;
'\u{F719}' # F22 # => F22 # Qt_Key_Key_F22 # F22 # F22 ;
'\u{F71A}' # F23 # => F23 # Qt_Key_Key_F23 # F23 # F23 ;
'\u{F71B}' # F24 # => F24 # Qt_Key_Key_F24 # F24 # F24 ;
//'\u{F71C}' # F25 # # F25 => Qt_Key_Key_F25 # F25 # F25 ;
//'\u{F71D}' # F26 # # F26 => Qt_Key_Key_F26 # F26 # F26 ;
//'\u{F71E}' # F27 # # F27 => Qt_Key_Key_F27 # F27 # F27 ;
//'\u{F71F}' # F28 # # F28 => Qt_Key_Key_F28 # F28 # F28 ;
//'\u{F720}' # F29 # # F29 => Qt_Key_Key_F29 # F29 # F29 ;
//'\u{F721}' # F30 # # F30 => Qt_Key_Key_F30 # F30 # F30 ;
//'\u{F722}' # F31 # # F31 => Qt_Key_Key_F31 # F31 # F31 ;
//'\u{F723}' # F32 # # F32 => Qt_Key_Key_F32 # F32 # F32 ;
//'\u{F724}' # F33 # # F33 => Qt_Key_Key_F33 # F33 # F33 ;
//'\u{F725}' # F34 # # F34 => Qt_Key_Key_F34 # F34 # F34 ;
//'\u{F726}' # F35 # # F35 => Qt_Key_Key_F35 # F35 # F35 ;
'\u{F727}' # Insert # => Insert # Qt_Key_Key_Insert # Insert # Insert ;
//'\u{F728}' # Delete ; // already as a control code
'\u{F729}' # Home # => Home # Qt_Key_Key_Home # Home # Home ;
//'\u{F72A}' # Begin # => # # ;
'\u{F72B}' # End # => End # Qt_Key_Key_End # End # End ;
'\u{F72C}' # PageUp # => PageUp # Qt_Key_Key_PageUp # PageUp # Page_Up ;
'\u{F72D}' # PageDown # => PageDown # Qt_Key_Key_PageDown # PageDown # Page_Down ;
//'\u{F72E}' # PrintScreen # => # # Snapshot ;
'\u{F72F}' # ScrollLock # => ScrollLock # Qt_Key_Key_ScrollLock # ScrollLock # Scroll_Lock;
'\u{F730}' # Pause # => Pause # Qt_Key_Key_Pause # Pause # Pause ;
'\u{F731}' # SysReq # => PrintScreen # Qt_Key_Key_SysReq # PrintScreen # Sys_Req ;
//'\u{F732}' # Break # => # # ;
//'\u{F733}' # Reset # => # # ;
'\u{F734}' # Stop # => # Qt_Key_Key_Stop # # XF86_Stop ;
'\u{F735}' # Menu # => ContextMenu # Qt_Key_Key_Menu # ContextMenu # Menu ;
//'\u{F736}' # User # # => # ;
//'\u{F737}' # System # # => # ;
//'\u{F738}' # Print # # => Qt_Key_Key_Print # ;
//'\u{F739}' # ClearLine # # => # ;
//'\u{F73A}' # ClearDisplay# # => # ;
//'\u{F73B}' # InsertLine # # => # ;
//'\u{F73C}' # DeleteLine # # => # ;
//'\u{F73D}' # InsertChar # # => # ;
//'\u{F73E}' # DeleteChar # # => # ;
//'\u{F73F}' # Prev # # => # ;
//'\u{F740}' # Next # # => # ;
//'\u{F741}' # Select # # => Qt_Key_Key_Select # ;
//'\u{F742}' # Execute # # => Qt_Key_Key_Execute # ;
//'\u{F743}' # Undo # # => Qt_Key_Key_Undo # ;
//'\u{F744}' # Redo # # => Qt_Key_Key_Redo # ;
//'\u{F745}' # Find # # => Qt_Key_Key_Find # ;
//'\u{F746}' # Help # # => Qt_Key_Key_Help # ;
//'\u{F747}' # ModeSwitch # # => Qt_Key_Key_Mode_switch # ;
'\u{F748}' # Back # => # Qt_Key_Key_Back # # ;
// -------------------- NORMAL KEYS ------------------------------
// The names are based on: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
'a' # A # ;
'b' # B # ;
'c' # C # ;
'd' # D # ;
'e' # E # ;
'f' # F # ;
'g' # G # ;
'h' # H # ;
'i' # I # ;
'j' # J # ;
'k' # K # ;
'l' # L # ;
'm' # M # ;
'n' # N # ;
'o' # O # ;
'p' # P # ;
'q' # Q # ;
'r' # R # ;
's' # S # ;
't' # T # ;
'u' # U # ;
'v' # V # ;
'w' # W # ;
'x' # X # ;
'y' # Y # ;
'z' # Z # ;
'0' # Digit0 # CloseParen ;
'1' # Digit1 # Exclamation ;
'2' # Digit2 # At ;
'3' # Digit3 # Hash ;
'4' # Digit4 # Dollar ;
'5' # Digit5 # Percent ;
'6' # Digit6 # Circumflex ;
'7' # Digit7 # Ampersand ;
'8' # Digit8 # Asterisk ;
'9' # Digit9 # OpenParen ;
'^' # Circumflex # Digit6 ;
'!' # Exclamation # Digit1 ;
'"' # DoubleQuote # Quote ;
'#' # Hash # Digit3 ;
'$' # Dollar # Digit4 ;
'%' # Percent # Digit5 ;
'&' # Ampersand # Digit7 ;
'_' # Underscore # HyphenMinus ;
'(' # OpenParen # Digit9 ;
')' # CloseParen # Digit0 ;
'*' # Asterisk # Digit8 ;
'+' # Plus # Equals ;
'|' # Pipe # BackSlash ;
'-' # HyphenMinus # Underscore ;
'{' # OpenCurlyBracket # OpenBracket ;
'}' # CloseCurlyBracket # CloseBracket ;
'~' # Tilde # BackQuote ;
':' # Colon # Semicolon ;
';' # Semicolon # Colon ;
'<' # LessThan # Comma ;
'=' # Equals # Plus ;
'>' # GreaterThan # Period ;
'?' # QuestionMark # Slash ;
'@' # At # Digit2 ;
',' # Comma # LessThan ;
'.' # Period # GreaterThan ;
'/' # Slash # QuestionMark ;
'`' # BackQuote # Tilde ;
'[' # OpenBracket # OpenCurlyBracket ;
'\\'# BackSlash # Pipe ;
']' # CloseBracket # CloseCurlyBracket ;
'\''# Quote # DoubleQuote ;
];
};
}
+57
View File
@@ -0,0 +1,57 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
#![doc = include_str!("README.md")]
#![doc(html_logo_url = "https://slint.dev/logo/slint-logo-square-light.svg")]
#![cfg_attr(not(any(feature = "shared-fontique", feature = "color-parsing")), no_std)]
extern crate alloc;
pub mod builtin_structs;
#[cfg(feature = "color-parsing")]
pub mod color_parsing;
pub mod enums;
pub mod key_codes;
#[cfg(feature = "shared-fontique")]
pub mod sharedfontique;
pub mod styled_text;
/// Detect the native style depending on the platform
pub fn get_native_style(has_qt: bool, target: &str) -> &'static str {
// NOTE: duplicated in api/cpp/CMakeLists.txt
if target.contains("android") {
"material"
} else if target.contains("windows") {
"fluent"
} else if target.contains("apple") {
"cupertino"
} else if target.contains("wasm") {
"fluent"
} else if target.contains("linux") | target.contains("bsd") {
if has_qt { "qt" } else { "fluent" }
} else if cfg!(target_os = "android") {
"material"
} else if cfg!(target_os = "windows") {
"fluent"
} else if cfg!(target_os = "macos") {
"cupertino"
} else if cfg!(target_family = "wasm") {
"fluent"
} else if has_qt {
"qt"
} else {
"fluent"
}
}
/// MenuItem with this title are actually MenuSeparator
///
/// Use a private unicode character so we are sure it is not used in the user's code
pub const MENU_SEPARATOR_PLACEHOLDER_TITLE: &str = "\u{E001}⸺";
/// Internal "magic" value for row and col numbers, to mean "auto", in GridLayoutInputData
/// Use the value 65536, so it's outside u16 range and not as likely as -1
/// (we can catch it as a literal at compile time, but not if it's a runtime value)
pub const ROW_COL_AUTO: f32 = u16::MAX as f32 + 1.;
+234
View File
@@ -0,0 +1,234 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
pub use fontique;
pub use skrifa;
#[cfg(any(target_family = "wasm", target_os = "nto"))]
use fontique::ScriptExt;
use std::collections::HashMap;
use std::sync::Arc;
/// Create a new fontique Collection.
/// When `shared` is true, the collection uses `Arc`-based internal sharing,
/// so that clones share the underlying data and mutations are visible across clones.
pub fn create_collection(shared: bool) -> Collection {
let mut collection =
fontique::Collection::new(fontique::CollectionOptions { shared, system_fonts: true });
let mut source_cache =
if shared { fontique::SourceCache::new_shared() } else { fontique::SourceCache::default() };
let mut default_fonts: HashMap<std::path::PathBuf, fontique::QueryFont> = Default::default();
#[cfg(any(target_family = "wasm", target_os = "nto"))]
{
let data = include_bytes!("sharedfontique/Inter-VariableFont.ttf");
let fonts = collection.register_fonts(fontique::Blob::new(Arc::new(data)), None);
for script in fontique::Script::all_samples().iter().map(|(script, _)| *script) {
collection.append_fallbacks(
fontique::FallbackKey::new(script, None),
fonts.iter().map(|(family_id, _)| *family_id),
);
}
for generic_family in [
fontique::GenericFamily::SansSerif,
fontique::GenericFamily::SystemUi,
fontique::GenericFamily::UiSansSerif,
] {
collection.append_generic_families(
generic_family,
fonts.iter().map(|(family_id, _)| *family_id),
);
}
}
let mut add_font_from_path = |path: std::path::PathBuf| {
if let Ok(bytes) = std::fs::read(&path) {
let fonts = collection.register_fonts(bytes.into(), None);
for generic_family in [
fontique::GenericFamily::SansSerif,
fontique::GenericFamily::SystemUi,
fontique::GenericFamily::UiSansSerif,
] {
collection.set_generic_families(
generic_family,
fonts.iter().map(|(family_id, _)| *family_id),
);
}
// just use the first font of the first family in the file.
if let Some(font) = fonts.first().and_then(|(id, infos)| {
let info = infos.first()?;
get_font_for_info(&mut collection, &mut source_cache, *id, info)
}) {
default_fonts.insert(path, font);
}
}
};
if let Some(path) = std::env::var_os("SLINT_DEFAULT_FONT") {
let path = std::path::Path::new(&path);
if path.extension().is_some() {
add_font_from_path(path.to_owned());
} else if let Ok(dir) = std::fs::read_dir(path) {
for file in dir.flatten() {
add_font_from_path(file.path());
}
}
}
// On modern macOS the CoreText-based per-script fallback lookup can fail for
// Han-script text: the family CoreText suggests (typically PingFang) is not
// always resolvable in the scanned family map, which leaves CJK ideographs
// unrendered while kana still resolves through Hiragino. Pre-register the
// known system CJK families so the fallback map answers before the CoreText
// query runs (`Collection::fallback_families` consults the map first).
#[cfg(target_os = "macos")]
{
let find = |collection: &mut fontique::Collection,
names: &[&str]|
-> Vec<fontique::FamilyId> {
names.iter().filter_map(|name| collection.family_id(name)).collect()
};
let japanese = find(
&mut collection,
&["Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "Osaka"],
);
let chinese =
find(&mut collection, &["PingFang SC", "PingFang TC", "Heiti SC", "Songti SC"]);
let korean = find(&mut collection, &["Apple SD Gothic Neo", "AppleGothic"]);
let universal = find(&mut collection, &["Arial Unicode MS"]);
// Text reaches the fallback query without a locale (no lang tags in the
// UI), so every lookup lands on the language-agnostic default slot.
// Bias Han towards Japanese: correct for kana-mixed text, still
// readable for Chinese.
let han_default: Vec<fontique::FamilyId> =
japanese.iter().chain(&chinese).chain(&korean).chain(&universal).copied().collect();
if !han_default.is_empty() {
for script in ["Hani", "Hira", "Kana"] {
collection.append_fallbacks(
fontique::FallbackKey::new(
fontique::Script::from_str_unchecked(script),
None,
),
han_default.iter().copied(),
);
}
// Language-tagged lookups do not fall through to the default slot,
// so register the tracked languages as well in case a locale ever
// reaches the query.
for (lang, families) in [("ja", &japanese), ("zh", &chinese), ("ko", &korean)] {
collection.append_fallbacks(
(fontique::Script::from_str_unchecked("Hani"), lang),
families.iter().chain(&universal).copied(),
);
}
}
let hangul: Vec<fontique::FamilyId> =
korean.iter().chain(&universal).copied().collect();
if !hangul.is_empty() {
collection.append_fallbacks(
fontique::FallbackKey::new(fontique::Script::from_str_unchecked("Hang"), None),
hangul.iter().copied(),
);
}
}
Collection { inner: collection, source_cache, default_fonts: Arc::new(default_fonts) }
}
#[derive(Clone)]
pub struct Collection {
pub inner: fontique::Collection,
pub source_cache: fontique::SourceCache,
pub default_fonts: Arc<HashMap<std::path::PathBuf, fontique::QueryFont>>,
}
impl Collection {
pub fn query<'a>(&'a mut self) -> fontique::Query<'a> {
self.inner.query(&mut self.source_cache)
}
pub fn get_font_for_info(
&mut self,
family_id: fontique::FamilyId,
info: &fontique::FontInfo,
) -> Option<fontique::QueryFont> {
get_font_for_info(&mut self.inner, &mut self.source_cache, family_id, info)
}
}
fn get_font_for_info(
collection: &mut fontique::Collection,
source_cache: &mut fontique::SourceCache,
family_id: fontique::FamilyId,
info: &fontique::FontInfo,
) -> Option<fontique::QueryFont> {
let mut query = collection.query(source_cache);
query.set_families(std::iter::once(fontique::QueryFamily::from(family_id)));
query.set_attributes(fontique::Attributes {
weight: info.weight(),
style: info.style(),
width: info.width(),
});
let mut font = None;
query.matches_with(|queried_font| {
font = Some(queried_font.clone());
fontique::QueryStatus::Stop
});
font
}
impl std::ops::Deref for Collection {
type Target = fontique::Collection;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl std::ops::DerefMut for Collection {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
pub const FALLBACK_FAMILIES: [fontique::GenericFamily; 2] = [
// FemtoVG renderer needs SansSerif first, as it has difficulties rendering from SystemUi on macOS
fontique::GenericFamily::SansSerif,
fontique::GenericFamily::SystemUi,
];
/// Wraper around fontique::Blob to permit use of the blob as a key in the cache in the different renderers,
/// to map the blob to the native type face representation (skia_safe::Typeface, femtovg::FontId, QRawFont, etc.).
/// The use as key also ensures the blob remains strongly referenced, so that it doesn't vanish from the
/// shared SourceCache (parley prunes it).
#[derive(Clone)]
pub struct HashedBlob(fontique::Blob<u8>);
impl core::hash::Hash for HashedBlob {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.id().hash(state);
}
}
impl PartialEq for HashedBlob {
fn eq(&self, other: &Self) -> bool {
self.0.id() == other.0.id()
}
}
impl Eq for HashedBlob {}
impl From<fontique::Blob<u8>> for HashedBlob {
fn from(value: fontique::Blob<u8>) -> Self {
Self(value)
}
}
impl AsRef<fontique::Blob<u8>> for HashedBlob {
fn as_ref(&self) -> &fontique::Blob<u8> {
&self.0
}
}
@@ -0,0 +1,3 @@
SPDX-FileCopyrightText: Copyright 2020 The Inter Project Authors <https://fonts.google.com/specimen/Inter/license>
SPDX-License-Identifier: OFL-1.1-RFN
+752
View File
@@ -0,0 +1,752 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
#[derive(Clone, Debug, PartialEq)]
/// Styles that can be applied to text spans
#[allow(missing_docs, dead_code)]
pub enum Style {
Emphasis,
Strong,
Strikethrough,
Code,
Link,
Underline,
// ARGB encoded
Color(u32),
}
#[derive(Clone, Debug, PartialEq)]
/// A style and a text span
pub struct FormattedSpan {
/// Span of text to style
pub range: core::ops::Range<usize>,
/// The style to apply
pub style: Style,
}
#[cfg(feature = "markdown")]
#[derive(Clone, Debug)]
enum ListItemType {
Ordered(u64),
Unordered,
}
/// A section of styled text, split up by a linebreak
#[derive(Clone, Debug, PartialEq)]
pub struct StyledTextParagraph {
/// The raw paragraph text
pub text: alloc::string::String,
/// Formatting styles and spans
pub formatting: alloc::vec::Vec<FormattedSpan>,
/// Locations of clickable links within the paragraph
pub links: alloc::vec::Vec<(core::ops::Range<usize>, alloc::string::String)>,
}
/// Error type returned by `StyledText::parse`
#[cfg(feature = "markdown")]
#[derive(Debug, derive_more::Error, derive_more::Display, PartialEq)]
#[non_exhaustive]
pub enum StyledTextError<'a> {
/// Spans are unbalanced: stack already empty when popped
#[display("Spans are unbalanced: stack already empty when popped")]
Pop,
/// Spans are unbalanced: stack contained items at end of function
#[display("Spans are unbalanced: stack contained items at end of function")]
NotEmpty,
/// Paragraph not started
#[display("Paragraph not started")]
ParagraphNotStarted,
/// Unimplemented markdown tag
#[display("Unimplemented tag: {:?}", _0.to_end())]
UnimplementedTag(#[error(not(source))] pulldown_cmark::Tag<'a>),
/// Unimplemented markdown event
#[display("Unimplemented event: {_0:?}")]
UnimplementedEvent(#[error(not(source))] pulldown_cmark::Event<'a>),
/// Unimplemented html event
#[display("Unimplemented html: {_0}")]
UnimplementedHtmlEvent(#[error(not(source))] alloc::string::String),
/// Unimplemented html tag
#[display("Unimplemented html tag: {_0}")]
UnimplementedHtmlTag(#[error(not(source))] alloc::string::String),
/// Unimplemented html attribute
#[display("Unexpected {_0} attribute in html {_1}")]
UnexpectedAttribute(#[error(not(source))] alloc::string::String, alloc::string::String),
/// Missing color attribute in html
#[display("Missing color attribute in html {_0}")]
MissingColor(#[error(not(source))] alloc::string::String),
/// Closing html tag doesn't match the opening tag
#[display("Closing html tag doesn't match the opening tag. Expected {_0}, got {_1}")]
ClosingTagMismatch(#[error(not(source))] &'a str, alloc::string::String),
/// Argument index out of range
#[display("Argument index {_0} out of range: {_1} arguments provided")]
ArgumentOutOfRange(usize, usize),
/// Format string placeholders count mismatch
#[display("Format string contains {_0} placeholders, but {_1} arguments were provided")]
PlaceholderCountMismatch(usize, usize),
#[display("Interpolating multiple styled text paragraphs is not currently implemented")]
MultiParagraphInterpolation,
/// Invalid color value
#[display("Invalid color value '{_0}'")]
InvalidColor(#[error(not(source))] alloc::string::String),
}
#[cfg(feature = "markdown")]
pub fn paragraph_from_plain_text(text: alloc::string::String) -> StyledTextParagraph {
StyledTextParagraph { text, formatting: Default::default(), links: Default::default() }
}
#[cfg(feature = "markdown")]
/// This is the character for private use that is used to make interpolation possible in markdown.
pub const MARKDOWN_INTERPOLATION_PLACEHOLDER: char = '\u{e541}';
#[cfg(feature = "markdown")]
pub fn parse_interpolated<S: AsRef<[StyledTextParagraph]>>(
format_string: &str,
args: &[S],
) -> impl Iterator<Item = Result<StyledTextParagraph, StyledTextError<'static>>> {
let mut parser = pulldown_cmark::Parser::new_ext(
format_string,
pulldown_cmark::Options::ENABLE_STRIKETHROUGH,
);
let mut list_state_stack: alloc::vec::Vec<Option<u64>> = alloc::vec::Vec::new();
let mut style_stack = alloc::vec::Vec::new();
let mut current_url = None;
let mut arg_index = 0;
let begin_paragraph = |indentation: u32, list_item_type: Option<ListItemType>| {
let mut text = alloc::string::String::with_capacity(indentation as usize * 4);
for _ in 0..indentation {
text.push_str(" ");
}
match list_item_type {
Some(ListItemType::Unordered) => {
let remainder = indentation % 3;
if remainder == 0 {
text.push_str("• ")
} else if remainder == 1 {
text.push_str("◦ ")
} else {
text.push_str("▪ ")
}
}
Some(ListItemType::Ordered(num)) => text.push_str(&alloc::format!("{}. ", num)),
None => {}
};
StyledTextParagraph { text, formatting: Default::default(), links: Default::default() }
};
let mut current_paragraph = None;
std::iter::from_fn(move || {
let mut substitute = |paragraph: &mut StyledTextParagraph,
string: &str|
-> Result<(), StyledTextError<'static>> {
let mut pos = 0;
while let Some(mut p) = string[pos..].find(MARKDOWN_INTERPOLATION_PLACEHOLDER) {
p += pos;
paragraph.text.push_str(&string[pos..p]);
if let Some(arg) = args.get(arg_index) {
let arg_paragraphs = arg.as_ref();
match arg_paragraphs {
[arg_paragraph] => {
let offset = paragraph.text.len();
paragraph.text.push_str(&arg_paragraph.text);
paragraph.formatting.extend(
arg_paragraph.formatting.iter().cloned().map(|mut f| {
f.range.start += offset;
f.range.end += offset;
f
}),
);
paragraph.links.extend(arg_paragraph.links.iter().cloned().map(
|(mut range, link)| {
range.start += offset;
range.end += offset;
(range, link)
},
));
}
[] => {
// No paragraphs in the argument, so nothing to add
}
_ => {
return Err(StyledTextError::MultiParagraphInterpolation);
}
}
} else {
return Err(StyledTextError::ArgumentOutOfRange(arg_index, args.len()));
}
arg_index += 1;
p += MARKDOWN_INTERPOLATION_PLACEHOLDER.len_utf8();
pos = p;
}
paragraph.text.push_str(&string[pos..]);
Ok(())
};
for event in &mut parser {
let indentation = list_state_stack.len().saturating_sub(1) as _;
match event {
pulldown_cmark::Event::SoftBreak | pulldown_cmark::Event::HardBreak => {
if let Some(paragraph) =
current_paragraph.replace(begin_paragraph(indentation, None))
{
return Some(Ok(paragraph));
}
}
pulldown_cmark::Event::End(pulldown_cmark::TagEnd::List(_)) => {
if list_state_stack.pop().is_none() {
return Some(Err(StyledTextError::Pop));
}
}
pulldown_cmark::Event::End(
pulldown_cmark::TagEnd::Paragraph | pulldown_cmark::TagEnd::Item,
) => {}
pulldown_cmark::Event::Start(tag) => {
let style = match tag {
pulldown_cmark::Tag::Paragraph => {
if let Some(paragraph) =
current_paragraph.replace(begin_paragraph(indentation, None))
{
return Some(Ok(paragraph));
}
continue;
}
pulldown_cmark::Tag::Item => {
let old_paragraph = current_paragraph.replace(begin_paragraph(
indentation,
Some(match list_state_stack.last().copied() {
Some(Some(index)) => ListItemType::Ordered(index),
_ => ListItemType::Unordered,
}),
));
if let Some(state) = list_state_stack.last_mut() {
*state = state.map(|state| state + 1);
}
if let Some(paragraph) = old_paragraph {
return Some(Ok(paragraph));
}
continue;
}
pulldown_cmark::Tag::List(index) => {
list_state_stack.push(index);
continue;
}
pulldown_cmark::Tag::Strong => Style::Strong,
pulldown_cmark::Tag::Emphasis => Style::Emphasis,
pulldown_cmark::Tag::Strikethrough => Style::Strikethrough,
pulldown_cmark::Tag::Link { dest_url, .. } => {
current_url = Some(dest_url);
Style::Link
}
pulldown_cmark::Tag::Heading { .. }
| pulldown_cmark::Tag::Image { .. }
| pulldown_cmark::Tag::DefinitionList
| pulldown_cmark::Tag::DefinitionListTitle
| pulldown_cmark::Tag::DefinitionListDefinition
| pulldown_cmark::Tag::TableHead
| pulldown_cmark::Tag::TableRow
| pulldown_cmark::Tag::TableCell
| pulldown_cmark::Tag::HtmlBlock
| pulldown_cmark::Tag::Superscript
| pulldown_cmark::Tag::Subscript
| pulldown_cmark::Tag::Table(_)
| pulldown_cmark::Tag::MetadataBlock(_)
| pulldown_cmark::Tag::BlockQuote(_)
| pulldown_cmark::Tag::CodeBlock(_)
| pulldown_cmark::Tag::FootnoteDefinition(_) => {
return Some(Err(StyledTextError::UnimplementedTag(tag.into_static())));
}
};
let paragraph = match current_paragraph.as_mut() {
Some(paragraph) => paragraph,
None => return Some(Err(StyledTextError::ParagraphNotStarted)),
};
style_stack.push((style, paragraph.text.len()));
}
pulldown_cmark::Event::Text(text) => {
let paragraph = match current_paragraph.as_mut() {
Some(paragraph) => paragraph,
None => return Some(Err(StyledTextError::ParagraphNotStarted)),
};
if let Err(err) = substitute(paragraph, &text) {
return Some(Err(err));
};
}
pulldown_cmark::Event::End(_) => {
let (style, start) = if let Some(value) = style_stack.pop() {
value
} else {
return Some(Err(StyledTextError::Pop));
};
let paragraph = match current_paragraph.as_mut() {
Some(paragraph) => paragraph,
None => return Some(Err(StyledTextError::ParagraphNotStarted)),
};
let end = paragraph.text.len();
if let Some(url) = current_url.take() {
paragraph.links.push((start..end, url.into()));
}
paragraph.formatting.push(FormattedSpan { range: start..end, style });
}
pulldown_cmark::Event::Code(text) => {
let paragraph = match current_paragraph.as_mut() {
Some(paragraph) => paragraph,
None => return Some(Err(StyledTextError::ParagraphNotStarted)),
};
let start = paragraph.text.len();
if let Err(err) = substitute(paragraph, &text) {
return Some(Err(err));
}
paragraph.formatting.push(FormattedSpan {
range: start..paragraph.text.len(),
style: Style::Code,
});
}
pulldown_cmark::Event::InlineHtml(html) => {
if html.starts_with("</") {
let (style, start) = if let Some(value) = style_stack.pop() {
value
} else {
return Some(Err(StyledTextError::Pop));
};
let expected_tag = match &style {
Style::Color(_) => "</font>",
Style::Underline => "</u>",
other => std::unreachable!(
"Got unexpected closing style {:?} with html {}. This error should have been caught earlier.",
other,
html
),
};
if (&*html) != expected_tag {
return Some(Err(StyledTextError::ClosingTagMismatch(
expected_tag,
(&*html).into(),
)));
}
let paragraph = match current_paragraph.as_mut() {
Some(paragraph) => paragraph,
None => return Some(Err(StyledTextError::ParagraphNotStarted)),
};
let end = paragraph.text.len();
paragraph.formatting.push(FormattedSpan { range: start..end, style });
} else {
let mut expecting_color_attribute = false;
for token in htmlparser::Tokenizer::from(&*html) {
match token {
Ok(htmlparser::Token::ElementStart { local: tag_type, .. }) => {
match &*tag_type {
"u" => {
let paragraph = match current_paragraph.as_mut() {
Some(paragraph) => paragraph,
None => {
return Some(Err(
StyledTextError::ParagraphNotStarted,
));
}
};
style_stack
.push((Style::Underline, paragraph.text.len()));
}
"font" => {
expecting_color_attribute = true;
}
_ => {
return Some(Err(
StyledTextError::UnimplementedHtmlTag(
(&*tag_type).into(),
),
));
}
}
}
Ok(htmlparser::Token::Attribute {
local: key,
value: Some(value),
..
}) => match &*key {
"color" => {
if !expecting_color_attribute {
return Some(Err(
StyledTextError::UnexpectedAttribute(
(&*key).into(),
(&*html).into(),
),
));
}
expecting_color_attribute = false;
let value =
match crate::color_parsing::parse_color_literal(&value)
.or_else(|| {
crate::color_parsing::named_colors()
.get(&*value)
.copied()
}) {
Some(value) => value,
None => {
return Some(Err(
StyledTextError::InvalidColor(
value.to_string(),
),
));
}
};
let paragraph = match current_paragraph.as_mut() {
Some(paragraph) => paragraph,
None => {
return Some(Err(
StyledTextError::ParagraphNotStarted,
));
}
};
style_stack
.push((Style::Color(value), paragraph.text.len()));
}
_ => {
return Some(Err(StyledTextError::UnexpectedAttribute(
(&*key).into(),
(&*html).into(),
)));
}
},
Ok(htmlparser::Token::ElementEnd { .. }) => {}
_ => {
return Some(Err(StyledTextError::UnimplementedHtmlEvent(
alloc::format!("{:?}", token),
)));
}
}
}
if expecting_color_attribute {
return Some(Err(StyledTextError::MissingColor((&*html).into())));
}
}
}
pulldown_cmark::Event::Rule
| pulldown_cmark::Event::TaskListMarker(_)
| pulldown_cmark::Event::FootnoteReference(_)
| pulldown_cmark::Event::InlineMath(_)
| pulldown_cmark::Event::DisplayMath(_)
| pulldown_cmark::Event::Html(_) => {
return Some(Err(StyledTextError::UnimplementedEvent(event.into_static())));
}
}
}
if arg_index != args.len() {
return Some(Err(StyledTextError::PlaceholderCountMismatch(arg_index, args.len())));
}
if !style_stack.is_empty() {
return Some(Err(StyledTextError::NotEmpty));
}
current_paragraph.take().map(Ok)
})
}
#[cfg(feature = "markdown")]
#[test]
fn markdown_parsing() {
assert_eq!(
parse_interpolated::<&[_]>("hello *world*", &[]).collect::<Result<Vec<_>, _>>().unwrap(),
[StyledTextParagraph {
text: "hello world".into(),
formatting: alloc::vec![FormattedSpan { range: 6..11, style: Style::Emphasis }],
links: alloc::vec::Vec::new()
}]
);
assert_eq!(
parse_interpolated::<&[_]>(
"
- line 1
- line 2
",
&[]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[
StyledTextParagraph {
text: "• line 1".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
},
StyledTextParagraph {
text: "• line 2".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
}
]
);
assert_eq!(
parse_interpolated::<&[_]>(
"
1. a
2. b
4. c
",
&[]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[
StyledTextParagraph {
text: "1. a".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
},
StyledTextParagraph {
text: "2. b".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
},
StyledTextParagraph {
text: "3. c".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
}
]
);
assert_eq!(
parse_interpolated::<&[_]>(
"
Normal _italic_ **strong** ~~strikethrough~~ `code`
new *line*
",
&[]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[
StyledTextParagraph {
text: "Normal italic strong strikethrough code".into(),
formatting: alloc::vec![
FormattedSpan { range: 7..13, style: Style::Emphasis },
FormattedSpan { range: 14..20, style: Style::Strong },
FormattedSpan { range: 21..34, style: Style::Strikethrough },
FormattedSpan { range: 35..39, style: Style::Code }
],
links: alloc::vec::Vec::new()
},
StyledTextParagraph {
text: "new line".into(),
formatting: alloc::vec![FormattedSpan { range: 4..8, style: Style::Emphasis },],
links: alloc::vec::Vec::new()
}
]
);
assert_eq!(
parse_interpolated::<&[_]>(
"
- root
- child
- grandchild
- great grandchild
",
&[]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[
StyledTextParagraph {
text: "• root".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
},
StyledTextParagraph {
text: " ◦ child".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
},
StyledTextParagraph {
text: " ▪ grandchild".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
},
StyledTextParagraph {
text: " • great grandchild".into(),
formatting: alloc::vec::Vec::new(),
links: alloc::vec::Vec::new()
},
]
);
assert_eq!(
parse_interpolated::<&[_]>("hello [*world*](https://example.com)", &[])
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "hello world".into(),
formatting: alloc::vec![
FormattedSpan { range: 6..11, style: Style::Emphasis },
FormattedSpan { range: 6..11, style: Style::Link }
],
links: alloc::vec![(6..11, "https://example.com".into())]
}]
);
assert_eq!(
parse_interpolated::<&[_]>("<u>hello world</u>", &[])
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "hello world".into(),
formatting: alloc::vec![FormattedSpan { range: 0..11, style: Style::Underline },],
links: alloc::vec::Vec::new()
}]
);
assert_eq!(
parse_interpolated::<&[_]>(r#"<font color="blue">hello world</font>"#, &[])
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "hello world".into(),
formatting: alloc::vec![FormattedSpan {
range: 0..11,
style: Style::Color(0xff_00_00_ff)
},],
links: alloc::vec::Vec::new()
}]
);
assert_eq!(
parse_interpolated::<&[_]>(r#"<u><font color="red">hello world</font></u>"#, &[])
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "hello world".into(),
formatting: alloc::vec![
FormattedSpan { range: 0..11, style: Style::Color(0xff_ff_00_00) },
FormattedSpan { range: 0..11, style: Style::Underline },
],
links: alloc::vec::Vec::new()
}]
);
assert_eq!(
parse_interpolated::<&[_]>(r#"<u><font color="\#a">hello world</font></u>"#, &[])
.collect::<Result<Vec<_>, _>>()
.unwrap_err(),
StyledTextError::InvalidColor(r"\#a".into())
);
}
#[cfg(feature = "markdown")]
#[test]
fn markdown_parsing_interpolated() {
assert_eq!(
parse_interpolated(
&format!("Text: *{MARKDOWN_INTERPOLATION_PLACEHOLDER}*"),
&[&[paragraph_from_plain_text("italic".into())]]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "Text: italic".into(),
formatting: alloc::vec![FormattedSpan { range: 6..12, style: Style::Emphasis }],
links: alloc::vec![]
}]
);
assert_eq!(
parse_interpolated(
&format!("Escaped text: {MARKDOWN_INTERPOLATION_PLACEHOLDER}"),
&[&[paragraph_from_plain_text("*bold*".into())]]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "Escaped text: *bold*".into(),
formatting: alloc::vec![],
links: alloc::vec![]
}]
);
assert_eq!(
parse_interpolated(
&format!("Code block text: `{MARKDOWN_INTERPOLATION_PLACEHOLDER}`"),
&[&[paragraph_from_plain_text("*bold*".into())]]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "Code block text: *bold*".into(),
formatting: alloc::vec![FormattedSpan { range: 17..23, style: Style::Code }],
links: alloc::vec![]
}]
);
assert_eq!(
parse_interpolated(
&format!(
"**{MARKDOWN_INTERPOLATION_PLACEHOLDER}** {MARKDOWN_INTERPOLATION_PLACEHOLDER}"
),
&[
alloc::vec![paragraph_from_plain_text("Hello".into())],
parse_interpolated::<&[_]>("*World*", &[]).collect::<Result<_, _>>().unwrap()
]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "Hello World".into(),
formatting: alloc::vec![
FormattedSpan { range: 0..5, style: Style::Strong },
FormattedSpan { range: 6..11, style: Style::Emphasis }
],
links: alloc::vec![]
}]
);
assert_eq!(
parse_interpolated(
&format!("<u>{MARKDOWN_INTERPOLATION_PLACEHOLDER}</u>"),
&[parse_interpolated::<&[_]>("*underline_and_italic*", &[])
.collect::<Result<Vec<_>, _>>()
.unwrap()]
)
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph {
text: "underline_and_italic".into(),
formatting: alloc::vec![
FormattedSpan { range: 0..20, style: Style::Emphasis },
FormattedSpan { range: 0..20, style: Style::Underline },
],
links: alloc::vec![]
}]
);
// Empty paragraph list might be caused by a StyledText::default()
assert_eq!(
parse_interpolated(&format!("{MARKDOWN_INTERPOLATION_PLACEHOLDER}"), &[[]])
.collect::<Result<Vec<_>, _>>()
.unwrap(),
[StyledTextParagraph { text: "".into(), formatting: alloc::vec![], links: alloc::vec![] }]
)
}