Compare commits
70
Commits
b714024d2b
..
v0.1.7
No files matched your search
Generated
+157
-21
@@ -224,6 +224,21 @@ dependencies = [
|
||||
"equator",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
@@ -801,6 +816,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-padding"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -832,6 +856,16 @@ dependencies = [
|
||||
"piper",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.13.1"
|
||||
@@ -936,6 +970,15 @@ dependencies = [
|
||||
"cipher 0.4.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cbc"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cbindgen"
|
||||
version = "0.28.0"
|
||||
@@ -1002,6 +1045,17 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
@@ -1867,6 +1921,15 @@ version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "ecb"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.18.0"
|
||||
@@ -1875,7 +1938,7 @@ checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
|
||||
|
||||
[[package]]
|
||||
name = "ely-agent"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"ely-platform",
|
||||
"ely-ui",
|
||||
@@ -1884,7 +1947,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-doc"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"csv",
|
||||
@@ -1906,7 +1969,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-files"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"dunce",
|
||||
@@ -1923,7 +1986,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ely-gpui-component"
|
||||
version = "0.1.1"
|
||||
source = "git+https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components?rev=6df9ab0aa6cba99e6a79da80f79fc166f09890a8#6df9ab0aa6cba99e6a79da80f79fc166f09890a8"
|
||||
source = "git+https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components?rev=2e65b05a6592d8c3166a252261fc01bf6215c3c5#2e65b05a6592d8c3166a252261fc01bf6215c3c5"
|
||||
dependencies = [
|
||||
"alacritty_terminal",
|
||||
"anyhow",
|
||||
@@ -1969,14 +2032,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-ipc"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ely-lok"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"dunce",
|
||||
@@ -1997,7 +2060,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-mail"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"ely-platform",
|
||||
"ely-ui",
|
||||
@@ -2006,7 +2069,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-mark"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
@@ -2031,7 +2094,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-office"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"directories",
|
||||
@@ -2052,7 +2115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-pdf"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ely-files",
|
||||
@@ -2070,13 +2133,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-pdf-engine"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"ely-ipc",
|
||||
"ely-pdf-engine",
|
||||
"env_logger",
|
||||
"log",
|
||||
"lopdf",
|
||||
"objc2 0.6.4",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-pdf-kit",
|
||||
@@ -2086,7 +2150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-platform"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
@@ -2095,10 +2159,12 @@ dependencies = [
|
||||
"directories",
|
||||
"ely-ipc",
|
||||
"env_logger",
|
||||
"futures",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
"libc",
|
||||
"log",
|
||||
"lopdf",
|
||||
"metal",
|
||||
"objc2 0.6.4",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -2116,12 +2182,14 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"tempfile",
|
||||
"ureq",
|
||||
"windows 0.62.2",
|
||||
"windows-sys 0.60.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ely-show"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"ely-files",
|
||||
"ely-gpui-component",
|
||||
@@ -2141,7 +2209,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-table"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"ely-gpui-component",
|
||||
"ely-lok",
|
||||
@@ -2158,7 +2226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-tree"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ely-files",
|
||||
@@ -2178,7 +2246,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ely-ui"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"directories",
|
||||
@@ -2187,6 +2255,7 @@ dependencies = [
|
||||
"futures",
|
||||
"gpui-pre",
|
||||
"gpui-pre-platform",
|
||||
"gpui-pre-windows",
|
||||
"log",
|
||||
"notify",
|
||||
"semver",
|
||||
@@ -2832,7 +2901,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
|
||||
dependencies = [
|
||||
"color_quant",
|
||||
"weezl",
|
||||
"weezl 0.1.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2981,6 +3050,7 @@ dependencies = [
|
||||
"waker-fn",
|
||||
"web-time",
|
||||
"windows 0.62.2",
|
||||
"zed-font-kit",
|
||||
"zed-scap",
|
||||
]
|
||||
|
||||
@@ -3767,7 +3837,7 @@ version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"block-padding",
|
||||
"block-padding 0.3.3",
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
@@ -3777,6 +3847,7 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
|
||||
dependencies = [
|
||||
"block-padding 0.4.2",
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
@@ -4254,6 +4325,33 @@ dependencies = [
|
||||
"imgref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lopdf"
|
||||
version = "0.45.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3"
|
||||
dependencies = [
|
||||
"aes 0.9.3",
|
||||
"bitflags 2.13.2",
|
||||
"brotli-decompressor",
|
||||
"cbc 0.2.1",
|
||||
"ecb",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"indexmap",
|
||||
"itoa",
|
||||
"log",
|
||||
"md-5 0.11.0",
|
||||
"nom 8.0.0",
|
||||
"rand 0.10.3",
|
||||
"rangemap",
|
||||
"sha2 0.11.0",
|
||||
"stringprep",
|
||||
"thiserror 2.0.21",
|
||||
"weezl 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.18.5"
|
||||
@@ -4387,6 +4485,16 @@ dependencies = [
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -5236,7 +5344,7 @@ dependencies = [
|
||||
"async-io",
|
||||
"async-lock",
|
||||
"blocking",
|
||||
"cbc",
|
||||
"cbc 0.1.2",
|
||||
"cipher 0.4.4",
|
||||
"digest 0.10.7",
|
||||
"endi",
|
||||
@@ -5245,7 +5353,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"md-5",
|
||||
"md-5 0.10.6",
|
||||
"num",
|
||||
"num-bigint-dig",
|
||||
"pbkdf2",
|
||||
@@ -5870,6 +5978,17 @@ dependencies = [
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
|
||||
dependencies = [
|
||||
"chacha20",
|
||||
"getrandom 0.4.3",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
@@ -7071,6 +7190,17 @@ dependencies = [
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stringprep"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
|
||||
dependencies = [
|
||||
"unicode-bidi",
|
||||
"unicode-normalization",
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum"
|
||||
version = "0.27.2"
|
||||
@@ -7428,7 +7558,7 @@ dependencies = [
|
||||
"flate2",
|
||||
"half",
|
||||
"quick-error 2.0.1",
|
||||
"weezl",
|
||||
"weezl 0.1.12",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
@@ -8288,6 +8418,12 @@ version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2"
|
||||
|
||||
[[package]]
|
||||
name = "wgpu"
|
||||
version = "29.0.4"
|
||||
|
||||
+6
-3
@@ -5,10 +5,10 @@ members = ["apps/*", "crates/*"]
|
||||
exclude = ["engines", "reference"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
license = "AGPL-3.0-or-later"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
@@ -19,7 +19,7 @@ jiff = "0.2"
|
||||
anyhow = "1"
|
||||
directories = "6"
|
||||
dunce = "1"
|
||||
ely-gpui-component = { git = "https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components", rev = "6df9ab0aa6cba99e6a79da80f79fc166f09890a8" }
|
||||
ely-gpui-component = { git = "https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components", rev = "2e65b05a6592d8c3166a252261fc01bf6215c3c5" }
|
||||
env_logger = "0.11"
|
||||
gpui = { package = "gpui-pre", version = "=0.3.8", default-features = false, features = ["stacker"] }
|
||||
gpui_platform = { package = "gpui-pre-platform", version = "=0.3.8", features = ["font-kit", "wayland", "x11"] }
|
||||
@@ -43,6 +43,9 @@ sha2 = "0.10"
|
||||
tempfile = "3"
|
||||
ureq = "3"
|
||||
windows-sys = { version = "0.60", features = ["Win32_UI_WindowsAndMessaging", "Win32_Graphics_Gdi", "Win32_Globalization", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_Threading", "Win32_System_IO", "Win32_System_LibraryLoader", "Win32_System_Com", "Win32_UI_Shell", "Win32_Security_Authentication_Identity"] }
|
||||
windows = { version = "0.62", features = ["Data_Pdf", "Graphics_Imaging", "Storage_Streams", "Win32_Graphics_Gdi", "Win32_Graphics_Printing", "Win32_Storage_Xps", "Win32_System_Memory", "Win32_System_WinRT", "Win32_UI_Controls_Dialogs", "Win32_UI_Input_KeyboardAndMouse"] }
|
||||
lopdf = { version = "0.45", default-features = false }
|
||||
zbus = { version = "5", default-features = false, features = ["async-io"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["NSLocale", "NSPathUtilities", "NSString", "NSURL", "NSDictionary", "NSValue", "NSError", "NSRunLoop", "NSDate", "NSUserDefaults"] }
|
||||
objc2-av-foundation = { version = "0.3", default-features = false, features = ["std", "AVPlayer", "AVPlayerItem", "AVPlayerItemOutput", "AVAsset", "objc2-core-media", "objc2-core-video", "objc2-core-foundation"] }
|
||||
objc2-core-media = { version = "0.3", default-features = false, features = ["std", "CMTime"] }
|
||||
|
||||
@@ -1,661 +1,21 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 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 Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Yang Zhang
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -478,7 +478,7 @@ Git 托管、PR 审核平台、Issue 系统、CI 平台和远程开发环境不
|
||||
|
||||
参考 MarkText 的 Markdown 编辑行为、ColaMD 的本地文件同步和内容保留规则、Markion 的 GPUI 原生 Markdown 编辑,不复制其整个应用窗口。不用 Electron,不用 CEF 或其他网页内容宿主。[S17][S18]
|
||||
|
||||
解析、渲染、编辑命令与右键菜单以 Typora 1.14.10 的默认设置为对照,不输于它;可视模式仍是按下的块以原文编辑,不改为所见即所得的行内编辑(用户 2026-10-13 定)。[S25]
|
||||
解析、渲染、编辑命令与右键菜单以 Typora 1.14.10 的默认设置为对照,不输于它;可视模式仍是按下的块以原文编辑,不改为所见即所得的行内编辑(用户 2026-10-13 定)。Typora 是参照,不求一一相同:验收看每项功能可用,缺 Typora 的某项、次序或措辞不同不算缺陷(用户 2026-10-14 定)。[S25]
|
||||
|
||||
### 14.2 功能要求
|
||||
|
||||
@@ -756,7 +756,7 @@ Doc、Table、Show 的 PDF 输出由 LOK 完成,不要求安装 ElyPDF。ElyMa
|
||||
|
||||
### 21.1 自有代码默认许可
|
||||
|
||||
本 PRD 对新增应用代码采用 AGPL-3.0-or-later 作为发行默认,便于与 MuPDF 的开源使用路线保持一致。Ely GPUI Components 继续保留现有 MIT/Apache-2.0 许可,不因被应用使用而改写其许可证。[S1]
|
||||
本 PRD 对新增应用代码采用 MIT 作为发行默认(用户 2026-10-19 定,原为 AGPL-3.0-or-later)。MIT 只管 Ely 的自有代码:链接 MuPDF 的 ElyPDF 发行包整体仍须按 MuPDF 的 AGPL 条款提供对应源码。Ely GPUI Components 继续保留现有 MIT/Apache-2.0 许可,不因被应用使用而改写其许可证。[S1]
|
||||
|
||||
第三方代码保持原许可证。不得把 LibreOffice、Git 或其他依赖的版权声明统一替换成 Ely 的声明。最终发行须按实际链接、进程调用、修改和打包方式审查,进程隔离不作为免除许可义务的依据。
|
||||
|
||||
|
||||
@@ -43,4 +43,4 @@ Packages: `packaging/macos/release.sh` writes each app's `.app` and `.dmg`, the
|
||||
|
||||
## Licence
|
||||
|
||||
AGPL-3.0-or-later (`LICENSE`). Third-party components keep their own licences; see `docs/licenses.md`.
|
||||
MIT (`LICENSE`). Third-party components keep their own licences; see `docs/licenses.md`.
|
||||
@@ -40,7 +40,7 @@ site/ 官网(Vite 8、pnpm、TypeScript,无框架;等轴 SVG 积木
|
||||
|
||||
## 组件映射
|
||||
|
||||
依赖 `ely-gpui-component`(pin 6df9ab0,gpui 为 crates.io 的 `gpui-pre` =0.3.8)。名字取自 `reference/Ely-GPUI-Components/src`。gpui 用法规则见该仓库 `AGENTS.md`。`tests/scripts/agents_md.py` 核对下表每个名字都是组件库公开项。
|
||||
依赖 `ely-gpui-component`(pin 2e65b05,gpui 为 crates.io 的 `gpui-pre` =0.3.8)。名字取自 `reference/Ely-GPUI-Components/src`。gpui 用法规则见该仓库 `AGENTS.md`。`tests/scripts/agents_md.py` 核对下表每个名字都是组件库公开项。
|
||||
|
||||
| 需要 | 用 |
|
||||
| --- | --- |
|
||||
@@ -84,7 +84,7 @@ site/ 官网(Vite 8、pnpm、TypeScript,无框架;等轴 SVG 积木
|
||||
| `A11yChecker` 的 `audit` 与对照表是私有的;Omarchy 色板要照同一套规则 | `ely-ui` 的 `omarchy/palette.rs` 抄了对照表。上游待办:公开 `audit` |
|
||||
| 组件无 role/aria 语义:菜单、列表等控件在 AX 树仍不可见 | 上游已修核心控件(7380afb:Button、TextInput、Tabs、面板行、对话框等);其余上游待办。项目自绘控件已自带 |
|
||||
| gpui 无 aria-disabled API(`AriaProperties` 无 disabled 字段) | 组件 7380afb 起以本地化 aria_description 表达;上游待办:gpui 补 API |
|
||||
| 组件内部文案未接 i18n(Ely 用到的组件已接:提示、默认占位、补全空行、字号示例,6df9ab0,`i18n/tests/shipped.rs` 防回退;其余组件之外:欢迎页标题、菜单项、`SortBuilder` 与 `FilterBuilder` 等) | 面板族文案已接 i18n(7380afb,内建 en/zh-CN),`CommentSidebar` 与 `RelativeTime` 同(408f2b0);其余上游待办 |
|
||||
| 组件内部文案未接 i18n(Ely 用到的组件已接:提示、默认占位、补全空行、字号示例,6df9ab0;查找框、排序与筛选、密码开关,a4bf696;`i18n/tests/shipped.rs` 防回退;其余组件之外:欢迎页标题、菜单项等) | 面板族文案已接 i18n(7380afb,内建 en/zh-CN),`CommentSidebar` 与 `RelativeTime` 同(408f2b0);其余上游待办 |
|
||||
| LOK 的 `.uno:StyleApply` 状态给界面名(`Default Paragraph Style`),样式列表给程序名(`Standard`),两者对不上 | ElyDoc 属性栏:列表外的当前样式显示为占位文字;更新样式用状态里的界面名。上游待办:状态带程序名 |
|
||||
|
||||
## gpui 规则
|
||||
@@ -132,8 +132,9 @@ tests/scripts/linux-backends.sh Linux 构建带 Wayland 与 X11;Hyprland 上
|
||||
packaging/linux/container.sh 命令 在 Ubuntu 26.04 镜像里运行(引擎、应用、打包;目标在 target/ubuntu)
|
||||
tests/scripts/linux-glibc.sh Linux 的应用、worker 与引擎要求的 glibc 不高于 2.43
|
||||
packaging/linux/package.sh 应用 出该应用的 AppImage、deb、rpm 与 Arch 包到 dist/(在容器里运行)
|
||||
packaging/source.sh dist 本提交的源码包与随包的 copyleft 上游源码(打过补丁的 MuPDF、Git),文件名带提交号;工作区有未提交改动即拒绝(macOS 的 release.sh 与 CI 的 Windows、Linux 调用)
|
||||
packaging/source.sh dist 本提交的源码包与随包的 copyleft 上游源码(打过补丁的 MuPDF、Git),文件名带提交号;工作区有未提交改动即拒绝(macOS 的 release.sh 与 CI 的 Linux 调用,发布只上传 Linux 的;Windows 的检出把符号链接写成文件,不出源码包)
|
||||
tests/scripts/ci-share.sh ci.sh 只经指向 ELY_SHARE 的链接用共享引擎:自建目录、指向别处或目标带换行的链接即拒绝
|
||||
tests/scripts/ci-upload.sh ci.sh 的上传:macOS 建源码包而不上传,Linux 上传,重跑遇已有的同名文件即失败、什么也不传(假 curl)
|
||||
tests/scripts/linux-packages.sh deb、rpm、Arch 包在干净的 Ubuntu 26.04、Fedora 44、Arch 容器里装上,每个 ELF 都找得到库
|
||||
tests/scripts/linux-pins.sh Linux 打包工具(appimagetool、linuxdeploy、运行时、nfpm)的下载与钉的散列相符
|
||||
tests/scripts/linux-installed.sh installed|appimage Hyprland 上装好的六个应用或 AppImage:一个窗口、随 Omarchy(Catppuccin)、读出页面文字(PDF、Markdown 经各自引擎),ElyTree 随换主题到 Latte(grim 按窗口截取)
|
||||
@@ -141,7 +142,9 @@ tests/scripts/linux-distros.sh deb 在 Ubuntu 26.04、rpm 在 Fedora 44 容器
|
||||
cargo test -p ely-show --test compose 切换半程帧经 Metal 取像素(主线程,仅 macOS)
|
||||
tests/scripts/*.sh *.py 脚本测试(缺工具时报 SKIP)
|
||||
packaging/macos/bundle.sh ely-doc debug 出 dist/ElyDoc.app(带图标、文档类型与该应用的引擎)
|
||||
packaging/macos/release.sh [批次] 该批各应用的 release 包与 dmg;ELY_SIGN_IDENTITY 加 ELY_NOTARY_PROFILE 即公证
|
||||
packaging/macos/release.sh [批次] 该批各应用的 release 包与 dmg,另有装全部的 ElyOffice dmg;ELY_SIGN_IDENTITY 加 ELY_NOTARY_PROFILE 即公证
|
||||
packaging/windows/bundle.sh 由 dist 里各应用的安装程序出合集 ElyOffice 安装程序(先跑 installer.sh)
|
||||
packaging/windows/templates.sh 以本构建的内核重写 packaging/windows/new 的空白 DOCX、XLSX、PPTX(右键“新建”用)
|
||||
packaging/icons/masters.py 写出 assets/icons 的全部 SVG 母版(图标设计只改这里)
|
||||
packaging/icons/build.sh 由 assets/icons 的母版渲染 icns、png、ico(只在 macOS)
|
||||
tests/scripts/icons.sh 八个图标齐全、未过期,macOS 为 squircle,其余无底形
|
||||
@@ -169,7 +172,11 @@ tests/scripts/recovery.sh 真窗口 ElyDoc:恢复点、崩溃后副本、
|
||||
tests/scripts/pdf-recovery.sh 真窗口 ElyPDF:加锁文件的封存恢复点、空闲引擎退出后重开时再问密码(需辅助功能权限)
|
||||
tests/scripts/autosave.sh 真窗口 ElyDoc:自动保存开关、停手即写、外部改动不覆盖(需辅助功能权限)
|
||||
tests/scripts/print.sh 真窗口 ElyDoc:打印用文档自己的纸张,取消不动文档(需辅助功能权限)
|
||||
cargo test -p ely-platform --test print Windows 经“Microsoft Print to PDF”出作业,核对纸张、方向与页面位置;Linux 起私有会话总线与替身打印门户,核对页面设置、令牌与交出的字节、取消(缺 dbus-daemon 时 SKIP)
|
||||
tests/scripts/show-fullscreen.sh 真窗口 ElyShow:F5 放映的窗口盖住整块屏幕(菜单栏与程序坞之上,需辅助功能权限)
|
||||
tests/scripts/dock-macos.sh dist 里 ElyDoc、ElyTable、ElyShow 与包外的 target/debug/ely-doc 各启动数次:LOK worker 从未登记为程序坞应用,图块照出
|
||||
tests/scripts/windows-bundle.sh 合集安装程序逐个静默运行所选应用的安装程序;某个被拒即停下并报出其名与退出码(缺 makensis 时 SKIP)
|
||||
tests/scripts/windows-installer.sh 假应用的安装程序:所选目录原有的文件经两次安装与卸载都在,旧版按注册表清理,文件被占用或程序在运行时什么也不改,写不进时放回旧版(缺 makensis 时 SKIP)
|
||||
tests/scripts/types.sh packaging/types.tsv 的文件类型在 Linux 桌面项、Windows 安装程序与 macOS 文档类型里一致,从不设为默认
|
||||
tests/scripts/layout.sh 真窗口:六个应用在 640、800、1100 宽下无元素越出窗口左右,留截图(需辅助功能与屏幕录制权限)
|
||||
tests/scripts/ooxml.py <用例> <文件> 不经 LibreOffice 读 DOCX、XLSX、PPTX 并按自算的预期核对(往返用例调用)
|
||||
@@ -193,11 +200,11 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
|
||||
- 2026-10-01:macOS 的 LOK 用自建 LibreOffice 26.2.6.3 加 `patches/libreoffice/0001-lok-macos-tile-painting.patch`(已验证出图块)。2026-10-03 加 `0002-lok-dispatch-to-document-frame.patch`:`postUnoCommand` 原发往桌面的活动框架,另一文档关闭后命令落空或落到别的文档;改发本文档的框架。2026-10-04 加 `0003-lok-char-style-and-spacing-states.patch`:LOK 原不发当前字符样式与段前段后,属性栏无从同步;补发 `.uno:CharStyle`(界面名,无字符样式为空)与 `.uno:ULSpacing`(`上,下`,1/100 mm);混合选区的状态发 `{"commandName","dontcare":true}`,`ely_lok::MIXED` 表示,段落样式跨段不一致也算混合(原样报首段),字符样式带来的字体、字号、粗斜体等在选区内不一致也算混合(原样只看直接格式)。`.uno:ULSpacing` 缺的成员归零,故两值同发;属性栏记住已发未回显的两值状态(段距、页边距),连续编辑以它为底。同日加 `0004-lok-panel-states.patch`:补发页面尺寸、页面项(横向、版式、页码格式)、页边距、分栏、页眉页脚开关与版式、四种锚点与六种环绕(真假或禁用)、标题行重复;页面项缺的成员同样归零,故转向时页面项与尺寸都发。`0005-jsdialog-skip-disposed-dialogs.patch`:对话框守卫关闭对话框后,JSDialog 空闲任务仍为它生成整窗更新,读已释放窗口崩溃(实测崩溃报告),补丁让已释放的对话框不再生成消息。`0006-page-size-takes-the-page-item.patch`:`.uno:AttributePageSize` 也收页面项,转向是一次改动、一步撤销。`0007-lok-aqua-anyinput-without-peeking.patch`:worker 的请求经主 GCD 队列派发,而 Aqua 的 `AnyInput` 用 `nextEventMatchingMask` 窥探时会转动 run loop、在内核空闲任务中途执行请求(实测:表格删列与排版空闲任务交错,`SwLayIdle::DoIdleJob_` 段错误,约三成全量测试复现);补丁让 LOK 下的 `AnyInput` 改问客户端,worker 以 `registerAnyInputCallback` 报告是否有待处理请求,请求只在顶层让出时执行(补丁后连续十次全绿)。`0008-lok-toc-caption-formula-without-dialogs.patch`:目录、题注、公式在内核只有对话框入口;补丁给 `.uno:InsertMultiIndex` 加 `Title`(默认目录)、`.uno:InsertCaptionDialog` 加 `Category`(程序名)与 `Text`(照内核题注对话框的选项)、`.uno:InsertObjectStarMath` 加 `Formula`(文字转公式,选中公式时整体替换,一步撤销),并加 `getCommandValues(".uno:Formula")` 读选中公式。插入目录后光标落在目录内(内核原样)。`0009-lok-word-count-values.patch`:`getCommandValues(".uno:WordCount")` 给文档与选区的字数、字符数;内核的 `.uno:StateWordCount` 状态是英文串,只作重读的信号。构建加 `--with-myspell-dicts`,随包词典取自 LibreOffice 的 dictionaries 子模块(core 钉的 9925407,来源与许可见各目录 README 与 license),装在 `Resources/extensions`。构建后只留 `dict-en`(25 MB,英语拼写、断词、同义词):界面语言是英文与简体中文,中文无 Hunspell 词典;全部 65 个(473 MB)时 LOK 首启 5.4 秒、再启 2.3 秒,只留英文为 1.1 秒与 0.7 秒(PERF-01 要求 3 秒内可操作)。词典语种已由用户定:英文。`0010-lok-outline-values.patch`:`getCommandValues(".uno:Outline")` 给各标题的文字、级别、位置(twips)与是否当前(光标所在处按文档顺序之前最近的标题,`GetOutlinePos`;分栏时位置比不出先后),`.uno:Bookmarks` 的每项加位置(版面不显示的书签无位置);导航栏的跳转都按位置。`0011-lok-font-lists-present-when-a-member-is-used.patch`:LOK 把以 `;` 连写的字体列表整串当作字体名,列表中有字体已用上也报缺失(实测报出界面字体的回退列表);补丁让列表中任一成员用上即不算缺失,文档里写的列表全缺时照报。`0012-lok-calc-cursor-references-merge.patch`:Calc 在回调注册后补发单元格光标;`.uno:SheetReferences?sheet=N` 给引用某表的公式格数、命名区域数、第一个公式格,以及用 INDIRECT 的公式与名称数(这类引用运行时才知指向,删除说明里单独列出);合并带 `MoveContents` 时不弹对话框,并修上游“多个数据格的 API 合并什么也不做”。worker 以 `SAL_LOK_OPTIONS=sc_print_twips_msgs`(另加 `unipoll`)运行,Calc 的光标、选区与 `.uno:SheetGeometryData` 同为文档 twips;视图把可见区经 `setClientVisibleArea` 报给内核。`0013-lok-author-option.patch`:`lo_setOption("author", 名)` 设内核用户全名,新批注与修订以此署名。`0014-lok-calc-formula-entry-and-names.patch`:公式语法错误不弹询问、补全不切走编辑、提交清引用标记、名称的可撤销定义删Line truncated
|
||||
- 2026-10-04:LOK 命令与对话框。界面只经 `ely_lok::commands::COMMANDS` 发 UNO 命令,worker 拒绝表外命令;内核弹出的对话框(`LOK_CALLBACK_WINDOW` created 或 JSDialog)在回调里即刻关闭并经 `LokError` 报给应用,需要的对话框由 Ely 自建。起因:Calc 的 Backspace 弹同步模态“删除内容”,曾卡死 worker。
|
||||
- 2026-10-04:ElyDoc 查找替换、拼写、比较、邮件合并(DOC-12 至 14)。查找经 `.uno:ExecuteSearch`:查全部计数并高亮,下一处按全部的矩形定当前序号;替换一处后重新计数,无当前项时“替换”先选下一处。拼写建议来自右键时内核给的上下文菜单,只取拼写部分,`ContextMenu::manual` 在插入点下打开。比较把当前文档存成工作副本、开成新标签、对它发 `.uno:CompareDocuments`,两个源文件都不动。邮件合并的字段在正文里写成 `«列名»`(同 Word 的显示,已定),预览与生成都是对模板副本整体替换;生成逐行写 DOCX 或 PDF 到所选文件夹,任一目标已存在即整体拒绝,从不发邮件。
|
||||
- 2026-10-04:ElyDoc 输出与导航(DOC-15、16)。导出 PDF 经 worker 的 `EXPORT_PDF` 请求,滤镜选项为 JSON(页码范围、批注印在页边、标出修订);打印先导出同一 PDF,macOS 用 PDFKit 的 `NSPrintOperation` 弹系统打印面板(`ely_platform::print`),其他平台报错,未实现。加密文档经 LOK 的 `DOCUMENT_PASSWORD` 回调询问密码,错的密码再问一次,取消即不打开。左栏导航默认打开(大纲、页面、书签),跳转前记下所在处,“返回”逐级回到原处;上一跳的输入未落到内核、或落下后光标尚未移动时,以其目标为所在处,连续跳转不丢位置;落下之后即按实际光标。当前标题取内核的标记,当前页按光标所在页。导出 PDF 与另存为的目标按文件身份(符号链接与硬链接)比对打开着的文档:导出遇之即拒绝,另存为遇本文件时只许原格式。缺字体时页面上方给出提示条。QA-10 与 Microsoft Office 互开未验证:本机无 Office。
|
||||
- 2026-10-04:ElyDoc 输出与导航(DOC-15、16)。导出 PDF 经 worker 的 `EXPORT_PDF` 请求,滤镜选项为 JSON(页码范围、批注印在页边、标出修订);打印先导出同一 PDF,交系统打印面板(`ely_platform::print`,三端见 R7.6)。加密文档经 LOK 的 `DOCUMENT_PASSWORD` 回调询问密码,错的密码再问一次,取消即不打开。左栏导航默认打开(大纲、页面、书签),跳转前记下所在处,“返回”逐级回到原处;上一跳的输入未落到内核、或落下后光标尚未移动时,以其目标为所在处,连续跳转不丢位置;落下之后即按实际光标。当前标题取内核的标记,当前页按光标所在页。导出 PDF 与另存为的目标按文件身份(符号链接与硬链接)比对打开着的文档:导出遇之即拒绝,另存为遇本文件时只许原格式。缺字体时页面上方给出提示条。QA-10 与 Microsoft Office 互开未验证:本机无 Office。
|
||||
- 2026-10-04:ElyDoc 的标签、会话、打开、保存、另存为(按文件身份比对)、关闭询问、冲突、密码与标签条移入 `crates/ely-office`:应用实现 `Host`(格式表 `Kind`、每标签附加数据、内核回报钩子),共用逻辑以扩展 trait 提供(`use ely_office::prelude::*`)。ElyTable 用同一外壳。共用文案在 `office.*`。
|
||||
- 2026-10-04:ElyTable(C09.1)。新建为空白 XLSX(首个工作表名随界面语言),保存保留 xlsx/ods/xls/fods,另存为 XLSX(默认)或 ODS,xlsm/xltm 进风险模式。上方名称框与公式栏(回车分别发 `.uno:GoToCell` 与 `.uno:EnterString`,Esc 交回网格),中间行列表头按内核几何自绘(点选整行整列,拖边改尺寸),下方工作表标签(右键与“工作表”菜单:插入、重命名、复制、左右移、隐藏、显示、删除;删除前列出引用该表的公式数与命名区域数)与状态栏(保存状态、内核给的选区统计)。“单元格”菜单:插删行列与单元格、合并拆分(多个数据格时先问移入或保留隐藏)、行高列宽(厘米)与最适、隐藏显示行列、冻结。填充柄拖到目标格发 `.uno:AutoFill`。选区统计文字由内核给出,当前为英文(内核界面语言未随 Ely 切换),待处理。
|
||||
- 2026-10-04:ElyTable 公式、计算、名称(C09.2,TABLE-03 至 06)。公式语法为 Excel A1(用户定):`Sheet2!A1`、逗号分隔参数,由安装层 `packaging/libreoffice/ely.xcd` 设定;载入选项 `Language=en-US,DeviceFormFactor=desktop`,内核界面与数字区域都是 en-US(小数点、月/日/年输入)。单元格内编辑由内核完成:键入时内核给出匹配的函数(`editor::CompletionMenu` 显示在单元格下,上下键选,Tab 补全,经 `completeFunction` 入有序队列),参数提示(`editor::SignatureHelp`,取内核的用法文字),点选单元格插入引用并按内核颜色画框;内核只为点选的引用与再次编辑(F2)的已有公式画框,新键入的引用不画(同桌面版)。第一下 Esc 关提示,第二下取消(同内核)。语法错误的公式照原样输入,状态栏按界面语言解释当前格的错误(内核英文错误串换成界面文案,同统计);循环引用同此提示。“公式”菜单:自动计算开关(关时状态栏显示手动计算)、重新计算、全部重新计算、定义名称(名称、引用位置默认为所选区域的绝对引用、范围为工作簿或某表;名称先经内核判定)、名称列表(改引用、转到所命名的绝对区域、删除,失效引用标出;内核给出每个名称的区域,`.uno:SelectedRange` 给所选区域)、追踪错误、追踪引用与从属单元格、移去箭头。名称框可直接输入名称跳转,跳转后显示该名称。手动计算在 ods、xlsx、xls、fods 存后重开都保持。
|
||||
- 2026-10-04:ElyTable 格式、数据整理、规则(C09.3,TABLE-07 至 09)。补丁 `0016-lok-calc-formats-and-conditions.patch`(数字格式、条件格式、两处 sdi 参数)、`0017-lok-calc-filter-validation-columns.patch`(筛选、验证、分列)、`0018-lok-calc-reads-requests-search.patch`(读值、请求、查找全部):数字格式按代码设(`.uno:NumberFormat` 的 `FormatCode`),`.uno:NumberFormatCode` 读当前格代码与类别(常规按区域块首判定)或校验代码;标准筛选收 JSON 条件(`.uno:DataFilterStandardFilter` 的 `Query`,含按列取值),`.uno:AutoFilterValues` 照内核自己的筛选菜单给出条目、他列隐藏与本列勾选;数据验证收 JSON 规则(`.uno:Validation` 的 `Rule`),`.uno:Validation` 读当前格规则,`.uno:DataSelectValues` 给序列;条件格式收 JSON(单元格规则配内核单元格样式、色阶、数据条、按键删除,`cellsh.sdi` 的同名槽也加参数),`.uno:ConditionalFormats` 列出本表;分列收 `Options`(ScAsciiOptions 串);`.uno:SelectedRange` 另给所选区域内数据区的四角、首行文字与内核的标题判定。LOK 下内核不再弹自己的筛选菜单与序列下拉,改发 `LOK_CALLBACK_TOOLTIP`(`autofilter`、`datalist`,带列行),无效输入发 `validityerror`(标题、内容、样式、是否接受;接受与否取内核对话框的默认:信息接受,警告与停止拒绝),Ely 以 `ely_lok::Request` 接收后自建菜单与提示。查找全部按格报矩形(内核原把相邻命中并成一块,计数偏少)。查找替换移入 `ely-office`(`Finding`,ElyDoc 与 ElyTable 共用,`Host::search_leaves` 供 ElyDoc 记返回位置)。“粘贴为值/公式”只在系统剪贴板仍是本视图上次的复制时进行(内核自己的单元格剪贴板;Ely 复制的 HTML 末尾带一个进程内唯一的标记注释,以标记而不是文字识别,同样文字的外来复制不算);其他内容(含别的工作簿复制的单元格)明确拒绝并提示改用粘贴:内核无法从外来内容单取值或公式。排序最多三个关键字(内核限制)。右侧格式面板(数字、对齐、边框、填充)、“数据”菜单(排序、筛选、删除重复项、分列、查找替换、粘贴为值或公式、数据验证)、“格式”菜单(格式面板开关、条件格式)。组件库 `SortBuilder`、`FilterBuilder` 的文案未接 i18n,中文界面下仍为英文(上游待办)。
|
||||
- 2026-10-04:ElyTable 格式、数据整理、规则(C09.3,TABLE-07 至 09)。补丁 `0016-lok-calc-formats-and-conditions.patch`(数字格式、条件格式、两处 sdi 参数)、`0017-lok-calc-filter-validation-columns.patch`(筛选、验证、分列)、`0018-lok-calc-reads-requests-search.patch`(读值、请求、查找全部):数字格式按代码设(`.uno:NumberFormat` 的 `FormatCode`),`.uno:NumberFormatCode` 读当前格代码与类别(常规按区域块首判定)或校验代码;标准筛选收 JSON 条件(`.uno:DataFilterStandardFilter` 的 `Query`,含按列取值),`.uno:AutoFilterValues` 照内核自己的筛选菜单给出条目、他列隐藏与本列勾选;数据验证收 JSON 规则(`.uno:Validation` 的 `Rule`),`.uno:Validation` 读当前格规则,`.uno:DataSelectValues` 给序列;条件格式收 JSON(单元格规则配内核单元格样式、色阶、数据条、按键删除,`cellsh.sdi` 的同名槽也加参数),`.uno:ConditionalFormats` 列出本表;分列收 `Options`(ScAsciiOptions 串);`.uno:SelectedRange` 另给所选区域内数据区的四角、首行文字与内核的标题判定。LOK 下内核不再弹自己的筛选菜单与序列下拉,改发 `LOK_CALLBACK_TOOLTIP`(`autofilter`、`datalist`,带列行),无效输入发 `validityerror`(标题、内容、样式、是否接受;接受与否取内核对话框的默认:信息接受,警告与停止拒绝),Ely 以 `ely_lok::Request` 接收后自建菜单与提示。查找全部按格报矩形(内核原把相邻命中并成一块,计数偏少)。查找替换移入 `ely-office`(`Finding`,ElyDoc 与 ElyTable 共用,`Host::search_leaves` 供 ElyDoc 记返回位置)。“粘贴为值/公式”只在系统剪贴板仍是本视图上次的复制时进行(内核自己的单元格剪贴板;Ely 复制的 HTML 末尾带一个进程内唯一的标记注释,以标记而不是文字识别,同样文字的外来复制不算);其他内容(含别的工作簿复制的单元格)明确拒绝并提示改用粘贴:内核无法从外来内容单取值或公式。排序最多三个关键字(内核限制)。右侧格式面板(数字、对齐、边框、填充)、“数据”菜单(排序、筛选、删除重复项、分列、查找替换、粘贴为值或公式、数据验证)、“格式”菜单(格式面板开关、条件格式)。组件库 `SortBuilder`、`FilterBuilder` 的文案 a4bf696 起接 i18n(原为英文)。
|
||||
- 2026-10-04:右侧属性栏宽取 `theme.sheet_size()`(380),左栏仍是 `sidebar_width`。`PropertyGrid` 名称列固定 120,240 宽时编辑器只剩约 76。颜色经色块弹出 `ColorPalette`,一次点击一条命令。
|
||||
- 2026-10-01:MailCore 2 的子模块 libetpan 过旧,改钉 libetpan master `4d47862`。
|
||||
- 2026-10-01:每个应用的全部数据在 `<本机数据目录>/ElyOffice/<slug>/`,路径由 `ely_platform::data_dir` 给出。卸载只动这里,且先问。用户文档永不碰。
|
||||
@@ -225,7 +232,7 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
|
||||
- 2026-10-07:ElyTree 恢复与清理、外部工具、操作规则(C13.6,TREE-13、14,§13.3,QA-19、20)。仓库页第二行:在终端中打开(macOS `open -a Terminal`,其他平台报未构建)、在访达中显示(`reveal_path`)、清理未跟踪的文件…;页底“引用日志”列出 HEAD 最近 200 次移动(`reflog show -z`,位置、Git 写的原因、时间),选中即中间显示该提交(同提交详情,`Whose::Reflog`),上方“在此新建分支…”(找回删掉的分支)与“把当前分支移到此…”:有已暂存的改动即拒绝(`reset --keep` 会丢掉它们,请先提交或取消暂存);否则在后台算出离开该分支的提交,对话框写明分支、从哪到哪、离开的提交(引用日志仍可找回)与“工作区改动保留”,确认后 `reset --keep`(Git 在改动冲突时拒绝;没有任何按钮做硬重置),执行前在写队列里核对 HEAD 仍在预览时的分支(完整引用名,或仍游离)与提交、仍无暂存,任一变了即什么也不做。引用日志的时间是该次移动的时间(`--date=unix` 下的 `%gd`),不是提交时间;选中按事件本身(提交、原因、时间与它在全部引用日志中自最早起的序号,后者新移动不改,同一秒同原因的两次也分得开),同一提交的多条不会一起选中;之后有新的移动时该事件的位置后移,选中与详情跟着它,事件已不在引用日志里即不显示。清理:对话框先由 `git clean -n -d`(勾“包括被忽略的文件”另加 `-x`)得出 Git 会删除的路径(`core.quotePath=false`,其余 C 引号照 Git 规则还原),其中的文件夹当场展开为其中的文件(`ls-files --others`,同一忽略规则,另一仓库不入),对话框逐个列出文件与文件夹;确认后先逐段查每个所列路径:仍在仓库里、途中没有符号链接、文件仍是文件、文件夹仍是文件夹(任一变了即整体拒绝,什么也不删),再以 `git clean -f [-x] -- 所列文件` 删去(只给文件,Git 不递归;此后被跟踪了的文件 Git 留下,也不穿过链接),最后自深而浅删去所列文件夹中已空的(预览后在其中新出现的文件不动,文件夹随之留下),每次都问。文件标题栏多出“在编辑器中打开”(用户在“仓库›选择编辑器…”选的程序,存在数据目录 `tools.json`,字段类型不对与读不出同样报错且不覆盖;macOS 的 .app 经 `open -a`,在后台等它结束,失败即显示其原话;未选时先问)与 Markdown 的“在 ElyMark 中打开”(`ely_platform::apps::open`:按安装布局找同级的应用,macOS 的 `名称.app/Contents/MacOS`,Windows 的 `Ely Office\名称`,开发构建的同一目录;找不到即报错)。锁(§13.3):任何写操作因 Git 的锁文件失败(`….lock': File exists`,或配置文件的 `could not lock config file …: File exists`)时,对话框说明另一个 Git 正在工作、Ely 从不删除锁文件,“重试”把同一写操作重新排队。QA-19:测试都以独立的 Git 命令核对索引、提交、引用与工作区。QA-20:冲突、钩子失败、凭据被拒(本机 401 服务器,显示 Git 的 “terminal prompts disabled” 原话)、锁、变基中断后中止、取消(停止取回)都有窗口测试,结束时仓库状态以 Git 读回核对。切换到系统 Git 目前经 `ELY_GIT`(设置页随 C18.1)。真窗口(macOS):仓库页工具行、清理预览对话框、文件标题栏的编辑器与 ElyMark 按钮,按下后同级的 ely-mark 以该文件启动。未验证:Windows 与 Linux 的终端;ElyMark 打开文件的内容(C14)。
|
||||
- 2026-10-07:ElyTree 储藏、远程、工作树、子模块、LFS(C13.5,TREE-10 至 12,§13.3)。左栏第四页“仓库”:上方取回(`fetch --progress --all`)、拉取(`pull --progress`,照用户的 pull 设置)、推送、强制推送…;储藏(`stash list -z`,新的在前;“储藏改动…”问说明与是否包括未跟踪的文件,`stash push`),远程(名称与地址,`remote` 加 `config --get-regexp` 读出取回与推送地址),工作树(`worktree list --porcelain -z`,行名为文件夹名,有失效的可“清理”即 `worktree prune`),子模块(索引里的 gitlink 与文件夹自身 `.git` 的 HEAD:未检出、在记录的提交上、在别的提交上、冲突),LFS 文件(`git lfs ls-files --long --json`:工作树里是内容、对象在本机而工作树是指针、只有指针而对象不在本机);没有子模块或 LFS 文件时不列。各列表分别读出,一个读不出只在该处显示 Git 原话;切到此页时读,此后每次状态重读时重读,只取最新一次。选中一项,中间显示:储藏为提交详情的同一套(`hist::Picked`,历史与储藏共用读取与面板):改动的文件(对第一个父提交)与储藏的未跟踪文件(第三个父提交,各自对空树),选文件看差异,上方应用、弹出、删除…;远程为地址与推送地址,取回、修改…(改名 `remote rename`、改地址 `remote set-url`)、移除…(先问);工作树为路径与分支或提交、锁定与失效原因,打开(作为标签)、移除…(先问,主工作树与当前的不给);子模块为记录的与检出的提交,“检出记录的提交”(`submodule update --init`,经远程运行)与打开。用户输入的名称、地址、路径前一律加 `--`(推送的远程名同样)。表单与选择对话框(新建分支、标签、改名、身份、储藏、远程、工作树、选远程与上游)记下打开时的仓库,提交时写进那个仓库,不随当前标签变;储藏列表按每条三个字段读(说明可为空)。储藏的应用、弹出、删除按 `stash@{n}` 执行,执行前在写队列里核对它仍是所见的那个储藏(另有储藏插入即拒绝,什么也不做);弹出遇冲突时 Git 保留储藏,对话框显示 Git 原话。删除储藏、移除远程与工作树每次都问。分支页的本地分支多出“设置上游…”(列出远程分支,`branch --set-upstream-to=refs/remotes/名`)与“取消上游”。推送:有上游即 `push --progress`;没有上游时后台读出远程,问推到哪个远程(`push --set-upstream -- 远程 refs/heads/分支:refs/heads/分支`),没有远程或 HEAD 游离即说明。强制推送(§13.3):后台读出当前分支、上游的远程与远端分支、上次取回时远端的提交(租约)、此刻 HEAD 的提交(源)与远端有而源没有的提交,对话框写明远程、分支与将被覆盖的提交(或写明没有),确认后推送的就是所示的源提交(`push --force-with-lease=远端分支:租约提交 -- 远程 源提交:远端分支`),确认前本地分支再动也不改变推送内容;远端自上次取回后变了即被拒绝;没有上游或游离即说明不能。远程命令(取回、拉取、推送、子模块更新)是写队列里的一种(`Write::Remote`),经 `running::Running` 运行:Git 在自己的会话里(`setsid`,SSH 找不到终端,不会挂在终端提示上;凭据照用 credential helper 与 ssh-agent),进度逐行显示在中间上方的提示条,可停止(向整个进程组发 SIGTERM,Git 自行清理;已结束的不再发);用户停止时提示“已停止”、清掉其后的排队写,不当作失败;失败时对话框显示 Git 的 stdout 与 stderr(以回车结尾的进度行被下一行改写,只留最后一次;以换行结尾的行全部保留,钩子的每一行都在);拉取遇冲突照合并类命令判定为停下。关窗与退出时停下所有远程命令与克隆。克隆改用同一运行器。真窗口(macOS):仓库页五类列表、储藏详情与文件、工作树详情、分支行。未验证:Windows 与 Linux(停止远程命令在非 Unix 上报未构建);真实网络与 HTTPS、SSH 凭据;LFS 对象的下载(只显示状态)。
|
||||
- 2026-10-07(用户定):跟随组件库最新的 main。组件库 K01 把 gpui 从 zed 仓库的提交换成 crates.io 的 `gpui-pre` =0.3.8(`gpui-pre-platform` 同版本),K02 让 Tab 绑在 FocusScope 的 ElyFocus 上下文下、更深的上下文先得;本项目工作区的 `gpui`、`gpui_platform` 随之改为这两个包(以 `package =` 保留原名,源码不变),组件库 pin 到 dabc1eb(其上加本项目一个提交:树与树行的无障碍角色)。升级后全工作区编译无改动。
|
||||
- 2026-10-08:首版打包(R1.1)。图标(用户定:logo-design 技能出方案,选 C“实心几何”;macOS 标准 squircle,Linux 与 Windows 无底形,八个同一套设计):母版在 `assets/icons`(我按圆角矩形、圆与 30°/45° 斜线在 256 网格上画;每个颜色对白与 `#1E1E1E` 都不低于 3:1,ElyMark 原定的石板灰在深色上 1.75:1,改为琥珀 `#B87A00`;ElyTable 在 48 像素以下用简化的一版),`packaging/icons/build.sh` 以 AppKit 渲染出 icns(macOS)、512 像素 png(Linux 的 AppImage 与桌面文件)、16 至 256 像素 ico(Windows 安装程序、开始菜单快捷方式与卸载项);生成物入库,Linux 与 Windows 构建不需要 macOS。系统交给应用的文件:`ely_ui::run` 收下启动参数与 `on_open_urls`(访达的打开请求,启动前到达的也在内),应用先取 `launch_files`(有则不开空白文档;ElyMark 有则不恢复上次的标签),再以 `on_open` 处理运行中的请求;六个应用都走这一条(ElyDoc、ElyTable、ElyShow 原先不收启动参数)。macOS 包:LOK 应用只带内核,按 LibreOffice 自己的布局并入本应用:内核的库进 `Contents/Frameworks`(合并库构建留下的“invalid - merged lib”占位文件不拷,其余非代码文件即报错),内核的资料进 `Contents/Resources`,另有 `MacOS/ely-lok-worker`;`install_dir` 先找包内(`Frameworks/libmergedlo.dylib`)。不带 `LibreOffice.app` 本身:原先整份嵌入时,其快速查看与聚焦插件、`soffice` 等启动程序与文档类型被系统登记,系统设置里出现“LibreOffice 扩展”(用户发现;已注销本机七处登记);测试也不再运行 LibreOffice 应用(样本改为 `tests/fixtures/office` 的固定文件,运行开发构建的 `soffice` 会让系统重新登记它)。ElyPDF 带 `MacOS/ely-pdf-worker` 与 `Resources/tessdata`(三种语言),OCR 数据先找应用旁再找包内;ElyTree 带 `Resources/git`,其中每个 Mach-O 先签(Git 以 `INSTALL_SYMLINKS` 构建,内建命令是指向同一程序的相对链接;原先是硬链接,拷进包后变成约 150 份副本、689 MB;以 `MACOSX_DEPLOYMENT_TARGET=14.0` 构建,原先随本机 SDK 要求 macOS 27);ElyMark 用同级 ElyTree 包里的 Git。文档类型(`packaging/macos/documents.sh`)一律 `Alternate`,不抢系统默认:Doc 为 docx、odt、doc、rtf;Table 为 xlsx、ods、xls、csv、tsv;Show 为 pptx、odp、ppt;PDF;Markdown;Tree 为文件夹(查看者)。worker、内核、OCR 数据的所在路径都写日志,`tests/scripts/release-macos.sh` 据此核对都在包内。许可(§21.2、§21.3):每个包的 `Resources/Licenses` 有 Ely 的 AGPL 全文(仓库根 `LICENSE`)、`rust-crates.txt`(`packaging/crates.py`:本机目标下链进各二进制的全部 crate 与其许可文件,无许可文件的取 `packaging/licenses` 里该表达式的标准文本并写明作者,都没有即失败)与所带引擎的许可:LibreOffice 的 LICENSE、NOTICE、CREDITS;MuPDF 的 COPYING 与其编进去的每个第三方及每组内嵌字体(按构建实际嵌入的)的许可、OpenSSL、tessdata(Apache-2.0,按提交与散列取)、Great Vibes 的 OFL;Git 的 COPYING 与 LGPL-2.1、git-lfs 的 LICENSE.md(发布包里没有,按标签与散列取);ElyMark 带 RaTeX 嵌入的 KaTeX 字体的 OFL 与说明;缺任何一份即打包失败(`packaging/licenses.sh`)。`release.sh` 另出 `ElyOffice-<版本>-source.tar.gz`:自有源码、锁文件、上游补丁与构建脚本(上游各自钉在提交,取得方式即其中的 fetch 脚本)。ElyTable 同时收到多个文本文件(访达一次交来多份 CSV)时,读完的导入排队,没有对话框开着才逐个询问(原先后到的一份替换前一份,前一份静默丢失)。`packaging/macos/release.sh` 按 `apps.tsv` 的批次出各应用的 dmg;本机只有 Apple Development 证书,无 Developer ID,未公证。未验证:Intel 包(只建了 arm64)、公证、Linux 与 Windows 的包(本机不能建)。
|
||||
- 2026-10-08:首版打包(R1.1)。图标(用户定:logo-design 技能出方案,选 C“实心几何”;macOS 标准 squircle,Linux 与 Windows 无底形,八个同一套设计):母版在 `assets/icons`(我按圆角矩形、圆与 30°/45° 斜线在 256 网格上画;每个颜色对白与 `#1E1E1E` 都不低于 3:1,ElyMark 原定的石板灰在深色上 1.75:1,改为琥珀 `#B87A00`;ElyTable 在 48 像素以下用简化的一版),`packaging/icons/build.sh` 以 AppKit 渲染出 icns(macOS)、512 像素 png(Linux 的 AppImage 与桌面文件)、16 至 256 像素 ico(Windows 安装程序、开始菜单快捷方式与卸载项);生成物入库,Linux 与 Windows 构建不需要 macOS。系统交给应用的文件:`ely_ui::run` 收下启动参数与 `on_open_urls`(访达的打开请求,启动前到达的也在内),应用先取 `launch_files`(有则不开空白文档;ElyMark 有则不恢复上次的标签),再以 `on_open` 处理运行中的请求;六个应用都走这一条(ElyDoc、ElyTable、ElyShow 原先不收启动参数)。macOS 包:LOK 应用只带内核,按 LibreOffice 自己的布局并入本应用:内核的库进 `Contents/Frameworks`(合并库构建留下的“invalid - merged lib”占位文件不拷,其余非代码文件即报错),内核的资料进 `Contents/Resources`,另有 `MacOS/ely-lok-worker`;`install_dir` 先找包内(`Frameworks/libmergedlo.dylib`)。不带 `LibreOffice.app` 本身:原先整份嵌入时,其快速查看与聚焦插件、`soffice` 等启动程序与文档类型被系统登记,系统设置里出现“LibreOffice 扩展”(用户发现;已注销本机七处登记);测试也不再运行 LibreOffice 应用(样本改为 `tests/fixtures/office` 的固定文件,运行开发构建的 `soffice` 会让系统重新登记它)。ElyPDF 带 `MacOS/ely-pdf-worker` 与 `Resources/tessdata`(三种语言),OCR 数据先找应用旁再找包内;ElyTree 带 `Resources/git`,其中每个 Mach-O 先签(Git 以 `INSTALL_SYMLINKS` 构建,内建命令是指向同一程序的相对链接;原先是硬链接,拷进包后变成约 150 份副本、689 MB;以 `MACOSX_DEPLOYMENT_TARGET=14.0` 构建,原先随本机 SDK 要求 macOS 27);ElyMark 用同级 ElyTree 包里的 Git(2026-10-15 起 Windows 同此:`git::own` 先找本应用旁的,再按 `apps` 的同级查找与 macOS 的登记找 ElyTree 旁的,都没有即 `git::NoGit`,ElyMark 的 Git 项写明要装 ElyTree;Windows 的 ElyMark 原随带一份,用户问起后去掉。Linux 的 ElyMark 照带:AppImage 自成一体,找不到别的映像里的 Git,deb、rpm、Arch 包与它同一 AppDir,R6.6)。Windows 安装程序只动自己装下的:装好后写下所装的每个文件与文件夹(`.ely-installed`,由 `packaging/windows/files.sh` 按分装目录生成),升级与卸载只移去其中的文件,文件夹空了才删;清单之前的版本只在注册表记下的安装目录里按旧的通配名与其文件夹里的全部文件移去;先查每个文件能否写(运行中或被占用即不能,文件夹里的也查),再逐个挪进 `.ely-old`(按清单次序编号,备份路径不随原路径变长,近 260 字的路径照样升级与卸载),任一项挪不动即放回、什么也不改、退出码 2;卸载时清单本身也先查、删不掉即放回全部;新文件的位置已有不属于本应用的文件即拒绝、什么也不改、退出码 2;写到一半失败即删去本次写下的、放回旧版;升级后不留旧的 `git` 与 CEF 文件(R6.11,`tests/scripts/windows-installer.sh`)。文档类型(`packaging/macos/documents.sh`)一律 `Alternate`,不抢系统默认:Doc 为 docx、odt、doc、rtf;Table 为 xlsx、ods、xls、csv、tsv;Show 为 pptx、odp、ppt;PDF;Markdown;Tree 为文件夹(查看者)。worker、内核、OCR 数据的所在路径都写日志,`tests/scripts/release-macos.sh` 据此核对都在包内。许可(§21.2、§21.3):每个包的 `Resources/Licenses` 有 Ely 的 AGPL 全文(仓库根 `LICENSE`)、`rust-crates.txt`(`packaging/crates.py`:本机目标下链进各二进制的全部 crate 与其许可文件,无许可文件的取 `packaging/licenses` 里该表达式的标准文本并写明作者,都没有即失败)与所带引擎的许可:LibreOffice 的 LICENSE、NOTICE、CREDITS;MuPDF 的 COPYING 与其编进去的每个第三方及每组内嵌字体(按构建实际嵌入的)的许可、OpenSSL、tessdata(Apache-2.0,按提交与散列取)、Great Vibes 的 OFL;Git 的 COPYING 与 LGPL-2.1、git-lfs 的 LICENSE.md(发布包里没有,按标签与散列取);ElyMark 带 RaTeX 嵌入的 KaTeX 字体的 OFL 与说明;缺任何一份即打包失败(`packaging/licenses.sh`)。`release.sh` 另出 `ElyOffice-<版本>-source.tar.gz`:自有源码、锁文件、Line truncated
|
||||
- 2026-10-08(用户定):深色主题不用纯黑或近黑,底色取柔和的灰 `#252525`。组件库 fd0efc7:深色色板 bg `#252525`、surface `#2c2c2c`、sunken `#202020`、overlay `#323232`、hover `#383838`、active 与 border `#3f3f3f`、border_strong `#555555`;为让说明文字在较亮的 hover 与 active 上仍有 4.5:1,muted 提到 `#c4c2c0`、subtle 与代码注释提到 `#acaaa8`;色盲友好图表的紫与橙改为 `#9d8dec`、`#ffd93d`(3:1 且各色两两分得开)。`ely.xcd` 的深色方案随之:页面 `#2c2c2c`、页外 `#252525`、边界与网格 `#555555`、域底纹 `#3f3f3f`。跨应用同步外观、设置里的浅色/深色/跟随系统、Omarchy 下随 Omarchy 主题,本来已有(共用 `settings.json` 加文件监视;`settings.sh` 核对 ElyPDF 选深色后 ElyTree 即刻变深);Omarchy 的读法与 OmaPhoto 相同(`~/.local/state/omarchy/current/theme/colors.toml`、`mode` 与具名颜色)。
|
||||
- 2026-10-08:图像的显存与内存(C20.2 长时测试查出)。GPUI 把每张画过的 `RenderImage` 留在窗口的图集里,直到调 `window.drop_image`;LOK 的图块、PDF 的图块与缩略图、演示的缩略图、动画预览与放映图层原先都不释放,ElyDoc 编辑保存 60 轮后应用进程涨到约 2 GB(内核不涨)。组件库 `primitives::Retired`:不再画的图先交给它,下一次绘制时释放(`release` 只放别处已不持有的,`release_all` 给自知不再画的属主,`append` 接过关闭者的);LokView、PdfView 在替换、挤出、清空图块时交出旧图,绘制前释放;ElyShow 每个标签一份,关闭的标签与结束的预览交给 Deck;放映按窗口各一份(观众屏、演讲者视图),离场中的幻灯片还在画时其图层等它结束。修后同样 100 轮在 340 至 440 MB 之间起落。
|
||||
- 2026-10-08:性能基准(C20.1,§20.1)。`tests/perf/bench.py` 在发行构建上测 PERF-01 至 08(每项 30 次,P50、P95,含全部子进程的内存),样本由 `tests/perf/samples.py` 按固定种子生成到 `engines/bench`,记录写到 `docs/perf/<日期>-<机型>.md`(格式见其 README);`ELY_STALLS=1` 开主线程忙碌记录(只供测量,空闲的应用照样不做事)。实测改动:Doc、Table、Show 原先要等内核启动完(约 2.5 至 3.9 秒)才开窗口,ElyDoc 日常启动 P95 3.9 秒不达标;现 `Worker::launch` 只起进程,内核的版本与图块核对在第一个请求前做(`Worker::ready`,任何请求都先过它,未核对的 worker 收不到请求),`ely_office::start` 在后台核对并设作者名,失败即 `startup::fail`;窗口约 0.15 秒可操作,空白文档在内核首次载入后出现(中位约 2.7 秒,其中约 2.2 秒是内核首次载入文档)。启动参数改为按当前目录取绝对路径(原相对路径成了 `file://相对` 而打不开)。补丁 `0039-skia-macos-no-unused-font-manager.patch`:macOS Skia 首次画字时以全部系统字体再建一个无人使用的 `SkFontMgr`(约 370 个字体枚举加排序,主线程约 175 毫秒),新文档的第一个字与打开文档的首块带字图块因此迟到;去掉后 PERF-03 的 10 次对比 P95 由 2.6 秒降到 1.5 秒。PERF-02 的计时原以输入落地时的代际为基准,内核的作废事件先于落地回报到达时,该次编辑的图块不计,钟一直走到下一次按键(记下的是按键间隔约 250 毫秒);现按编辑的修订认定(`view/clock.rs`:修订不低于该编辑的批次所升的代际,其图块即为所求),实测中位 2 毫秒、P95 5 毫秒。PERF-08:关闭的标签原把其图块留在 GPUI 的图集里(每个文档约 20 MB 显存,40 次新建关闭后应用涨约 250 MB);`Engine::retire` 交出关闭视图的全部图像(LOK 图块、PDF 图块与缩略图、ElyMark 页面的画面),外壳在窗口的下一帧释放,修后 40 次在 454 至 462 MB 之间。历史首屏改为从按下“历史”计(原从进程启动计,含打开仓库)。R1 后基准更严:PERF-03、04 到视图收下的第一块图块(`lok: tile (x, y) shown`),其间有图块画失败即整次作废;DOCX 样本原以单独一段的分页符分页,内核只排出 60 余页(`Heading1` 段上的 `pageBreakBefore` 同样丢页),改为分页符放在标题段内,PERF-03 之前先核对恰为 100 页(视图记录页数);PERF-02 每键须有自己的计时,缺即失败;PERF-08 循环前记基线,记内核中的文档数(worker 每次载入关闭写 `N documents open`),文档数须回到基线,文件数自第一次之后不变(第一次打开模板对话框时进程一次性载入两个系统字体与两个 AppKit 本地化表)。worker 的启动核对失败后保持失败,此后一切请求被拒(原核对失败的状态与成功相同,第二次即放行)。空白文档就绪由约 2.5 秒降到约 1.0 秒,发生在本次重建内核之后,与 0039 无关(对比实测),原因未查明。
|
||||
@@ -268,7 +275,7 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
|
||||
- 2026-10-09:每个应用只跑一份(缺陷清单 X-03)。`ely_ui::run` 在写日志之前取应用数据目录的 `instance.lock`(`ely_platform::instance::hold`;Unix 为 fcntl 记录锁,进程结束即放,被拒时以 `F_GETLK` 向系统问出持锁的进程号,不另存进程号文件,同时启动的几份也报得准;Windows 为 LockFileEx,不报进程号);原先第二份启动即清空第一份的工作目录、把它的恢复点当作干净结束删掉、改写崩溃锁。2026-10-14 起(用户报:已开着时再打开文件弹“已在运行”而不是新标签,各应用同此)第二份把文件交给运行中的那份后退出:持锁的那份在 127.0.0.1 开一个门(`instance::Door`,随机端口),端口、进程号与 32 字节随机令牌写在数据目录的 `instance.door`(先写临时文件再改名,Unix 为 0600);第二份先按当前目录把启动参数变成绝对路径,连上后先发令牌,门答“开”或“拒”之后才发各路径(`ely-ipc` 的帧,Unix 为原字节,Windows 为 UTF-16),收到回执即以 0 退出、不弹框;门未开、连不上、令牌被拒(旧的门文件)或答“开”之前断开时 10 秒内重试,路径发出后不重试(不会开两次),仍不成即照旧报“已在运行……未收下文件”及原因。门为每个来者各开一个线程,一个来者从连上到答完共 5 秒(零星补字不续期),令牌前的帧至多 64 字节、路径帧至多 128 KiB(`ely_ipc::read_capped`,超出即在分配前拒绝)。Windows 上第二份先 `AllowSetForegroundWindow` 让持锁的那份能到前台。每个应用的启动(`ely_ui::run`,`blank` 的 ElyMail、ElyAgent 同)在主窗口开出后装上交接的接收者(`opening::home`):先把主窗口带到前台(最小化的先复原),再把文件放进 `ely_ui::on_open` 的同一队列(各应用不改),然后才回执;主窗口已不在即不回执,第二份照报未收下。不带文件的再次启动只带到前台。主窗口关闭即退出应用(只剩设置窗口时进程原会一直持锁,却开不了文件)。macOS 经访达打开文件本就交给运行中的那份。`instance` 的单测以两个进程核对交接与伪造令牌被拒;`tests/scripts/one-instance.sh`(macOS)核对第二份 ElyDoc 交出文件、第一份开出它且工作目录不动,本次未在 macOS 上跑;Windows 上以真窗口的 ElyMark 核对(第二份 132 毫秒退出,第一份多一个标签)。
|
||||
- 2026-10-10:ElyMark 的链接(M-05,我定,同常见编辑器):可视模式单击链接是编辑,Cmd 单击(Windows、Linux 为 Ctrl)交应用;预览单击即交应用;应用照 ElyPDF:http、https、mailto 交系统打开,其余提示拒绝。
|
||||
- 2026-10-10:Windows 与 Linux 的构建环境(E-01)。Windows:MSVC(VS 2022,v143);MuPDF 由 `build-mupdf.sh` 以 MSBuild 编上游 `platform/win32` 的 `libmupdf`(静态运行库 /MT,同 Rust 的 `crt-static`;`HAVE_LIBCRYPTO`,`libmupdf.lib` 内含第三方、Tesseract 与 PKCS#7);静态 OpenSSL 取自钉在 2026.07.29 的 vcpkg(`engines/vcpkg`,`openssl:x64-windows-static`);Git 为 Git for Windows 的 MinGit 2.56.0(钉散列,`engines/git/cmd/git.exe`,LFS 在 `ucrt64/libexec/git-core`);`%TEMP%` 下的程序被系统的应用控制拦下,构建与探针都不放那里;cmake 与 ninja 须在 PATH;LibreOffice 的 configure 只认 VS 自带的 CMake(组件 `VC.CMake.Project`)。仓库与 `reference/` 一律 LF(`core.autocrlf false`、`core.eol lf`;`fetch-references.sh` 对每个上游照设)。Linux:WSL 的 Ubuntu 26.04;静态 libcrypto 另需其 pkg-config 列出的库(jitterentropy、zstd、z)。LibreOffice 在 Linux 照 Collabora 的 LOKit 配置构建(无图形后端、cairo RGBA、自带各库)。
|
||||
- 2026-10-10:Windows 与 Linux 的内核与 worker(W-01、K-01,用户定:0.1.3 先三端发布)。内核只认合并库(`ffi::KERNEL`:`libmergedlo.dylib`、`libmergedlo.so`、`mergedlo.dll`;`sofficeapp` 在合并构建里是文本占位);Windows 载入时一并搜索该 DLL 所在的 `program/`。查找次序照旧,Windows 与 Linux 的包内位置是应用旁的 `libreoffice/program`,开发构建为 `engines/lo-src/instdir/program`。worker 的主循环:macOS 照旧以 GCD;Linux 以 unipoll,`runLoop` 的轮询回调里每次答一个请求,内核的唤醒回调往同一队列放信号(`worker/unipoll.rs`;回调的数据指针须非空,VCL 见空即不调用);Windows 也以 unipoll:LOK 不另起主线程,worker 的主线程跑 `runLoop`(Windows 的消息循环),请求经只收消息的窗口投到这条线程上执行(`worker/messages.rs`),同 macOS 的 GCD;原先 LOK 自起主线程、worker 在另一线程作答,载入表格即死锁。Windows 的循环不调轮询回调,但须传非空的回调,`isUnipoll` 只看它。补丁 `0043-lok-callbacks-flush-inline-everywhere.patch`:回调队列在各平台都即时冲出(原只 macOS),否则请求里等的命令结果与状态要等下一轮主循环才到。`0042-svx-boost-json-needs-no-library.patch`:svxcore 与 sd 定义 `BOOST_ALL_NO_LIB`,MSVC 不再按 Boost 的自动链接索要 `libboost_json`、`libboost_container`。Linux 的内核以 cairo 画图块(worker 设 `SAL_DISABLESKIA`;构建去掉 `--enable-cairo-rgba`,自带的 cairo 要清掉重建),字节为 BGRA,同 macOS 与 Windows;`getTileMode` 只看 cairo 开关,不可信。worker 启动核对在三端都画一段红字,按 BGRA 找不到红色即拒绝。`scripts/apply-lo-patches.sh` 的临时库设 `core.autocrlf false`(Windows 默认转换使任何前缀都对不上)。Windows 的 LibreOffice 在 Cygwin 下构建(`build-libreoffice.sh` 的 CYGWIN 分支:去掉 Unix 专用开关,加 VS 2022,用 `/opt/lo/bin` 的 make,清掉 Git Bash 带进来的 `MSYSTEM`);构建目录与 Cygwin 排除在 Defender 扫描之外(否则并行 configure 删不掉 `conftest.dir`)。英文词典扩展里的 Lightproof(Python 写的语法检查)在构建后删去:macOS 与 Linux 的内核不带 Python,它本不生效;Windows 必带内置 Python(Cygwin 下 configure 不许去掉),第二次用同一配置启动时初始化它,worker 挂起。worker 以 `SAL_NOLOCK_PROFILE` 运行,`ely.xcd` 关掉 LibreOffice 的文档锁(`Common/Misc/UseLocking`):被强杀的 worker 留下的锁会让下次启动或载入弹出交互而挂起;每个应用只有一个 worker 用自己的配置,冲突由 Ely 自己核对。三端发布(CI-01):`.gitea/workflows/release.yml` 在打标签时于三台运行器上执行 `scripts/ci.sh`:macOS 在 Mac mini 的常驻克隆里借用开发克隆 `~/Documents/GitHub/ElyOfficeSuite` 的引擎(`ELY_SHARE`;2026-10-11 起:从零构建 LibreOffice 超过 act_runner 默认的 3 小时,v0.1.3 的 Mac 任务被杀、无 dmg),Windows 在本机运行器上把 `engines` 与 `reference` 接到开发克隆,Linux 由同一台 Windows 运行器经 WSL 构建(服务器上的 Linux 运行器是一次性容器,建不了内核);各自打包后上传到该标签的发布。Windows 为 NSIS 安装程序,Linux 为 AppImage、deb、rpm 与 Arch 包(引擎构建与打包都经 `packaging/linux/container.sh` 进 Ubuntu 26.04 容器,WSL 里须有 docker;`ELY_SHARE` 的目录一并挂进容器),都由 `packaging/stage.sh` 分装引擎;每个平台都上传本提交的源码包(`packaging/source.sh`);更新清单只含 macOS(Windows 与 Linux 的自动安装未做)。
|
||||
- 2026-10-10:Windows 与 Linux 的内核与 worker(W-01、K-01,用户定:0.1.3 先三端发布)。内核只认合并库(`ffi::KERNEL`:`libmergedlo.dylib`、`libmergedlo.so`、`mergedlo.dll`;`sofficeapp` 在合并构建里是文本占位);Windows 载入时一并搜索该 DLL 所在的 `program/`。查找次序照旧,Windows 与 Linux 的包内位置是应用旁的 `libreoffice/program`,开发构建为 `engines/lo-src/instdir/program`。worker 的主循环:macOS 照旧以 GCD;Linux 以 unipoll,`runLoop` 的轮询回调里每次答一个请求,内核的唤醒回调往同一队列放信号(`worker/unipoll.rs`;回调的数据指针须非空,VCL 见空即不调用);Windows 也以 unipoll:LOK 不另起主线程,worker 的主线程跑 `runLoop`(Windows 的消息循环),请求经只收消息的窗口投到这条线程上执行(`worker/messages.rs`),同 macOS 的 GCD;原先 LOK 自起主线程、worker 在另一线程作答,载入表格即死锁。Windows 的循环不调轮询回调,但须传非空的回调,`isUnipoll` 只看它。补丁 `0043-lok-callbacks-flush-inline-everywhere.patch`:回调队列在各平台都即时冲出(原只 macOS),否则请求里等的命令结果与状态要等下一轮主循环才到。`0042-svx-boost-json-needs-no-library.patch`:svxcore 与 sd 定义 `BOOST_ALL_NO_LIB`,MSVC 不再按 Boost 的自动链接索要 `libboost_json`、`libboost_container`。Linux 的内核以 cairo 画图块(worker 设 `SAL_DISABLESKIA`;构建去掉 `--enable-cairo-rgba`,自带的 cairo 要清掉重建),字节为 BGRA,同 macOS 与 Windows;`getTileMode` 只看 cairo 开关,不可信。worker 启动核对在三端都画一段红字,按 BGRA 找不到红色即拒绝。`scripts/apply-lo-patches.sh` 的临时库设 `core.autocrlf false`(Windows 默认转换使任何前缀都对不上)。Windows 的 LibreOffice 在 Cygwin 下构建(`build-libreoffice.sh` 的 CYGWIN 分支:去掉 Unix 专用开关,加 VS 2022,用 `/opt/lo/bin` 的 make,清掉 Git Bash 带进来的 `MSYSTEM`);构建目录与 Cygwin 排除在 Defender 扫描之外(否则并行 configure 删不掉 `conftest.dir`)。英文词典扩展里的 Lightproof(Python 写的语法检查)在构建后删去:macOS 与 Linux 的内核不带 Python,它本不生效;Windows 必带内置 Python(Cygwin 下 configure 不许去掉),第二次用同一配置启动时初始化它,worker 挂起。worker 以 `SAL_NOLOCK_PROFILE` 运行,`ely.xcd` 关掉 LibreOffice 的文档锁(`Common/Misc/UseLocking`):被强杀的 worker 留下的锁会让下次启动或载入弹出交互而挂起;每个应用只有一个 worker 用自己的配置,冲突由 Ely 自己核对。三端发布(CI-01):`.gitea/workflows/release.yml` 在打标签时于三台运行器上执行 `scripts/ci.sh`:macOS 在 Mac mini 的常驻克隆里借用开发克隆 `~/Documents/GitHub/ElyOfficeSuite` 的引擎(`ELY_SHARE`;2026-10-11 起:从零构建 LibreOffice 超过 act_runner 默认的 3 小时,v0.1.3 的 Mac 任务被杀、无 dmg),Windows 在本机运行器上把 `engines` 与 `reference` 接到开发克隆,Linux 由同一台 Windows 运行器经 WSL 构建(服务器上的 Linux 运行器是一次性容器,建不了内核);各自打包后上传到该标签的发布。Windows 为 NSIS 安装程序,Linux 为 AppImage、deb、rpm 与 Arch 包(引擎构建与打包都经 `packaging/linux/container.sh` 进 Ubuntu 26.04 容器,WSL 里须有 docker;`ELY_SHARE` 的目录一并挂进容器),都由 `packaging/stage.sh` 分装引擎;本提交的源码包只由 Linux 上传(`packaging/source.sh`;macOS 照建供 `release-macos.sh` 核对,不上传,两端并行时不重复;Windows 的检出把符号链接写成文件,不出);重跑时所传文件有任一同名的已在发布里即失败、什么也不传,写明须先删去哪些(重建的字节不同,更新清单的散列会对不上已在的 dmg);更新清单只含 macOS(Windows 与 Linux 的自动安装未做)。
|
||||
- 2026-10-11:gpui 的 Windows 窗口关闭(W-03 冒烟查出)。`gpui-pre-windows` 0.3.8 在窗口关闭时报三条错:系统已销毁窗口(ElyTree 的关窗交给系统)后 Drop 仍对旧句柄 `RevokeDragDrop` 与 `DestroyWindow`(拖放处理器因此不释放,连带窗口状态);销毁时的失活回报排在异步任务里,执行时窗口已移除(“window not found”);退出后后台任务向已销毁的平台窗口投递(`Invalid window handle`)。修复在 `vendor/gpui-pre-windows`:`WM_DESTROY` 时记下已销毁、在句柄仍有效时撤销拖放、去掉失活回调,Drop 见已销毁即不再动句柄;平台窗口已不在时投递失败只记 debug(应用已退出),其余投递失败照报。三个应用关窗与退出的日志无错。
|
||||
- 2026-10-11(用户报:Windows 启动带黑色命令行窗口、“打开方式”里无图标、点 X 不退出、表格全黑无网格线):四处根因。命令行窗口:应用是控制台子系统;发行构建改为 `windows_subsystem = "windows"`(开发构建照旧有控制台看日志),子进程(两个 worker、Git、`cmd start`)一律经 `ely_ipc::windowless` 以 `CREATE_NO_WINDOW` 启动。图标:exe 里只有 gpui 的清单资源;各应用共用构建脚本 `packaging/windows/icon.rs`,把 `assets/icons/<应用>.ico` 编成资源 1(gpui 的窗口图标也取资源 1)。点 X 不退出:窗口其实弹了“保存更改”询问。`ely.xcd` 深色方案的 `CalcNotesBackground` 与浅色不同,Calc 在配色变化时改写批注样式并记一步撤销(`ScDetectiveFunc::UpdateAllComments`),未动的表格切到深色即算已修改;两套方案的批注底色改为同一值(LibreOffice 默认的浅黄),切换主题不再改文档,三端同此(`sheet.rs` 的 `a_theme_switch_is_no_edit`)。全黑:Win32 的虚拟设备没有 `SetSizeUsingBuffer`(基类默认返回假,断言在发行构建里不在),给客户缓冲区的设备停在 1×1 像素,Calc 图块只画了一个像素,放映图层同空;补丁 `0044-lok-win32-paints-then-copies.patch` 让 Windows 走 macOS 的路:按全尺寸画进设备,再拷进客户缓冲区(`doc_paintTile` 与 `SlideshowLayerRenderer`)。Writer 自设设备尺寸,原本不受影响。`tests/scripts/lo-patches.sh` 的临时库也设 `core.autocrlf false`(原先在 Windows 上恒失败)。
|
||||
- 2026-10-11(用户报:Windows 上标题栏的最小化、最大化、关闭三个按钮都按不动):gpui 回答系统的命中测试(`WM_NCHITTEST`)时按绘制次序取第一个含指针的窗口控制区,标题栏的拖动区先于其中的按钮画出,按钮上一律答“标题栏”,系统把按下当作拖动窗口的开始,点击到不了按钮。修复在 `vendor/gpui-pre`(原样一个提交,其后是修复):按命中测试的次序取最上层的控制区,且只看未被遮挡的部分(同 `is_hovered`,盖在标题栏上的对话框挡住其下的按钮)。实测(发行构建,DPI 感知的探针移动真实指针):自右向左依次答关闭、最大化、最小化、拖动;按下最小化即最小化,最大化即最大化,关闭即退出、worker 随之结束;v0.1.3 的安装版同一探针处处答拖动。该回调只有 Windows 平台调用。
|
||||
@@ -283,7 +290,7 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
|
||||
- 2026-10-11:Linux 包的实测(L1.6)。本机(Omarchy,Hyprland 0.56)装上六个 Arch 包与六个 AppImage,`linux-installed.sh` 两种都过;deb、rpm、Arch 包在 Ubuntu 26.04、Fedora 44、Arch 容器里装上、全部 ELF 找得到库;deb 与 rpm 的六个应用在各自容器的 Xvfb 下画出窗口(`linux-distros.sh`)。截图按窗口(`grim -T` 加 Hyprland 的 `stableId`):按区域截时用户切换工作区或别的窗口盖住即截错。ElyMark 的文件监视略去读取后不会自激:重读前先比指纹(长度与修改时间),不打开文件。
|
||||
- 2026-10-11(用户定:替换 v0.1.3 的 Linux 包):v0.1.3 发布里原有的六个 AppImage(无头,打不开窗口)已删去,换成本机容器里建出的六个应用各四种包(共 24 个),出自 L1.7 的提交(晚于该标签);上传后逐个核对大小,ElyTree 的 AppImage 下载回来散列相同。`package.sh` 把每个 RUNPATH 按所在 ELF 解析(`$ORIGIN` 或 `${ORIGIN}` 开头,规范化后须在 AppDir 内),否则拒绝(如未修正的 cairo):CI 用的是别处建好的引擎,旧构建会在这里报错而不是带进包里。替换的 Linux 包对应的源码随之上传到同一发布(`source.sh`,文件名带构建提交号),发布说明写明 Linux 包出自哪个提交。
|
||||
- 2026-10-11:`ci.sh` 用 `ELY_SHARE` 时,CI 克隆里的 `engines`、`reference` 须是指向共享克隆的链接(Windows 为目录联接,不查);是本克隆自建的目录或指向别处即报错,不混用。`.gitignore` 的 `/engines`、`/reference` 不带斜杠,链接也被忽略(`source.sh` 要求工作区干净)。
|
||||
- 2026-10-11(用户定:ElyMark 不用 CEF,不用 Electron):ElyMark 改为原生。界面用组件库的 Markdown 组件(`documents::MarkdownEditor` 一族,缺的在组件库补并推到 Gitea),解析用 markdown-rs(`markdown` 1.0.0),公式用 RaTeX,Mermaid 用 mermaid-rs-renderer,PDF 用 MuPDF Story;CEF 随之删去,ElyMail 的正文也不用 CEF 与 Electron。进度在 `tasks/TASKS.md` 的 C14。组件库 fcad0ff 与 508cc55:`MarkdownRenderer`、`MarkdownEditor`、Markdown 着色、块范围与链接查找改读 markdown-rs 的语法树(GitHub 风格加公式),引用式链接与图片按定义解析,图片把所在段落分开,单行 `$$…$$` 为块公式,软换行(LF、CRLF、CR)读作空格,嵌套在引用与列表里的定义同样解析,强调与链接里的图片仍是图片(链接里的图片可按);`BlockEditor` 的导入导出不属 ElyMark,仍用 pulldown-cmark。markdown-rs 读嵌套图片时只留外层的说明。组件库 d5ecc5a:块公式经 `typography::Latex` 由 RaTeX 排出(字形为轮廓,按窗口缩放画),```` ```mermaid ```` 块经 `documents::Diagram` 由 mermaid-rs-renderer 画出(Mermaid 自己的深浅主题,底色与字色取 Ely 色板),都作为 gpui 资源在后台排版,RaTeX 或 Mermaid 对已解析的输入 panic 时显示为错误;`MarkdownRenderer::base` 给出文档所在文件夹,相对与 file 地址的图片从中读取并按自身大小、不超过栏宽显示,`data:` 地址解码,网络图片不载入(写明)。组件库 ab9a14c:每个公式、图与图片元素经 `primitives::held` 持有其资源,按资源计数持有者(8b9820b;画出的图存在共享的记录里,9036c92 起由最后离开的持有者释放,哪怕它自己还没收到图),最后一个持有者换了内容或离开窗口才从 gpui 资源缓存移除、在本帧之后从图集释放,共用同一内容的元素(含 gpui 缓存的视图)不受影响;公式按字形实际范围取画框,字形不被裁;公式失败显示原因、RaTeX 给的位置与原文,日志不含公式;`file:` 地址去掉查询与片段,`localhost` 为本机,Windows 上别的主机为共享路径,他处拒绝;Mermaid 的节点与饼图文字取 Ely 的前景色。组件库 2b6f551:`documents::MarkdownDocument` 是文件级的 Markdown 文档:全文与撤销在一个 `CodeEditor` 里(`CodeEditor::highlighter` 以 `markdown_highlights` 着色,无行号);可视以 gpui `list` 逐块画出文件的顶层块(链接定义、HTML、front matter 照原文显示,每个字节都在块里或块间),按下的块开成源码(`TextInput`),其键入即刻算作文档的文字,写回为一步撤销,上下键越过块边进入相邻块,Esc 写回;Cmd(他处 Ctrl)按下交给链接;预览只读;源码为编辑器本身;128 KiB 以内当场解析,更长的在后台解析,解析中按下块不打开(日志);新解析保留两端相同的块,滚动不跳。`CodeEditor` 的撤销历史最多留 64 MiB 文字,超出先丢最旧的步;`CodeEditor::reset` 换文字且撤销重新开始;`MarkdownMode` 加 `Preview`。组件库 fc181b4:一个插入点通用于各模式(编辑器的选区,写回的块移动它);`set_caret` 与 `set_top_line` 分别设插入点与视图,换模式保持顶行;按下的块在前一块写回后仍是所按的块(按偏移换算,结构变了即不开并记日志);块是 Tab 停靠点,Enter 或空格打开;预览不收按下、撤销与重做;撤销与重做每次记录、输入法组字、撤销、重做后都限在 64 MiB 内(先丢最旧的撤销,再丢最远的重做)。组件库 433c38f:只有对当下文字的解析才能打开块(解析的文字与编辑器相同),否则拒绝;要求的顶行在其文字解析后才落定:先到所在块,下一帧按块高的比例到块内位置,再有新的要求即接着放下一个;源码与列表之间切换保持顶行,可视与预览共用一个列表,切换不动滚动。组件库 abac8b4:顶行的要求带编号,迟到的帧回调只完成自己的那个;文字一换即按新文字重新放,放时按当下文字的行数夹住;`reveal` 是同样的要求(插入点设在该行,该行放到顶上),新文字解析后才落定。组件库 f59c9f7:文字超过读取上限(2 MiB)即丢掉旧的读取,大纲与块为空。ElyMark(C14.4):视图即一个 `MarkdownDocument`,文本即文件原文(BOM 与 CRLF 照 `text.rs` 存回),新建、打开、保存、另存、重命名经外壳照旧;视图在建成后的下一轮更新向外壳报一次载入(文档在 `new` 里当场解析,外壳此时还未订阅);文字超过 2 MiB 即只用源码并转去源码(随当前文字,不只看打开时);网页实现的查找替换、表格、附件、书写视图的应用、导出与打印Line truncated
|
||||
- 2026-10-11(用户定:ElyMark 不用 CEF,不用 Electron):ElyMark 改为原生。界面用组件库的 Markdown 组件(`documents::MarkdownEditor` 一族,缺的在组件库补并推到 Gitea),解析用 markdown-rs(`markdown` 1.0.0),公式用 RaTeX,Mermaid 用 mermaid-rs-renderer,PDF 用 MuPDF Story;CEF 随之删去,ElyMail 的正文也不用 CEF 与 Electron。进度在 `tasks/TASKS.md` 的 C14。组件库 fcad0ff 与 508cc55:`MarkdownRenderer`、`MarkdownEditor`、Markdown 着色、块范围与链接查找改读 markdown-rs 的语法树(GitHub 风格加公式),引用式链接与图片按定义解析,图片把所在段落分开,单行 `$$…$$` 为块公式,软换行(LF、CRLF、CR)读作空格(2026-10-15 起屏上读作换行,见下),嵌套在引用与列表里的定义同样解析,强调与链接里的图片仍是图片(链接里的图片可按);`BlockEditor` 的导入导出不属 ElyMark,仍用 pulldown-cmark。markdown-rs 读嵌套图片时只留外层的说明。组件库 d5ecc5a:块公式经 `typography::Latex` 由 RaTeX 排出(字形为轮廓,按窗口缩放画),```` ```mermaid ```` 块经 `documents::Diagram` 由 mermaid-rs-renderer 画出(Mermaid 自己的深浅主题,底色与字色取 Ely 色板),都作为 gpui 资源在后台排版,RaTeX 或 Mermaid 对已解析的输入 panic 时显示为错误;`MarkdownRenderer::base` 给出文档所在文件夹,相对与 file 地址的图片从中读取并按自身大小、不超过栏宽显示,`data:` 地址解码,网络图片不载入(写明)。组件库 ab9a14c:每个公式、图与图片元素经 `primitives::held` 持有其资源,按资源计数持有者(8b9820b;画出的图存在共享的记录里,9036c92 起由最后离开的持有者释放,哪怕它自己还没收到图),最后一个持有者换了内容或离开窗口才从 gpui 资源缓存移除、在本帧之后从图集释放,共用同一内容的元素(含 gpui 缓存的视图)不受影响;公式按字形实际范围取画框,字形不被裁;公式失败显示原因、RaTeX 给的位置与原文,日志不含公式;`file:` 地址去掉查询与片段,`localhost` 为本机,Windows 上别的主机为共享路径,他处拒绝;Mermaid 的节点与饼图文字取 Ely 的前景色。组件库 2b6f551:`documents::MarkdownDocument` 是文件级的 Markdown 文档:全文与撤销在一个 `CodeEditor` 里(`CodeEditor::highlighter` 以 `markdown_highlights` 着色,无行号);可视以 gpui `list` 逐块画出文件的顶层块(链接定义、HTML、front matter 照原文显示,每个字节都在块里或块间),按下的块开成源码(`TextInput`),其键入即刻算作文档的文字,写回为一步撤销,上下键越过块边进入相邻块,Esc 写回;Cmd(他处 Ctrl)按下交给链接;预览只读;源码为编辑器本身;128 KiB 以内当场解析,更长的在后台解析,解析中按下块不打开(日志);新解析保留两端相同的块,滚动不跳。`CodeEditor` 的撤销历史最多留 64 MiB 文字,超出先丢最旧的步;`CodeEditor::reset` 换文字且撤销重新开始;`MarkdownMode` 加 `Preview`。组件库 fc181b4:一个插入点通用于各模式(编辑器的选区,写回的块移动它);`set_caret` 与 `set_top_line` 分别设插入点与视图,换模式保持顶行;按下的块在前一块写回后仍是所按的块(按偏移换算,结构变了即不开并记日志);块是 Tab 停靠点,Enter 或空格打开;预览不收按下、撤销与重做;撤销与重做每次记录、输入法组字、撤销、重做后都限在 64 MiB 内(先丢最旧的撤销,再丢最远的重做)。组件库 433c38f:只有对当下文字的解析才能打开块(解析的文字与编辑器相同),否则拒绝;要求的顶行在其文字解析后才落定:先到所在块,下一帧按块高的比例到块内位置,再有新的要求即接着放下一个;源码与列表之间切换保持顶行,可视与预览共用一个列表,切换不动滚动。组件库 abac8b4:顶行的要求带编号,迟到的帧回调只完成自己的那个;文字一换即按新文字重新放,放时按当下文字的行数夹住;`reveal` 是同样的要求(插入点设在该行,该行放到顶上),新文字解析后才落定。组件库 f59c9f7:文字超过读取上限(2 MiB)即丢掉旧的读取,大纲与块为空。ElyMark(C14.4):视图即一个 `MarkdownDocument`,文本即文件原文(BOM 与 CRLF 照 `text.rs` 存回),新建、打开、保存、另存、重命名经外壳照旧;视图在建成后的下一轮更新向外壳报一次载入(文档在 `new` 里当场解析,外壳此时还未订阅);文字超过 2 MiB 即只用源码并转去源码(随当前文字,不只看打开时);网页实现的查找替换、表格、Line truncated
|
||||
- 2026-10-12(用户报:Windows 上 ElyMark 的最近列表显示 `\\?\C:\…`):凡取真实路径一律 `dunce::canonicalize`(ely-files 的会话登记、ely-lok 的内核目录与配置目录、ElyMark 的文件夹、最近列表、会话与标签比对;ElyTree 原已如此):Windows 上能写成普通路径即普通路径,他处同 `std::fs::canonicalize`。只供读写的路径照旧保留 `\\?\`(`ely_files::save` 的落盘与同文件判定:在 250 字的文件夹里,普通写法的暂存文件名越过 260 而写不进),保存后交给会话与 `Saved` 的路径以 `dunce::simplified` 整体判定后为普通写法;ely-office 另存的目标先以完整路径求出,再以 `dunce::simplified` 整体判定能否写成普通路径(先简化文件夹再接文件名时,结尾带空格的名字会被 Windows 削成另一个已打开的文件)。`ely_files::recent` 读入时以 `dunce::simplified` 去掉旧版写下的 `\\?\` 并去重,下次写入即为普通路径。
|
||||
- 2026-10-12(用户报:ElyTable 的网格上一直是文字指针):`LokView` 原把指针写死为文字指针。现不按键的鼠标移动也交内核(悬停,不算编辑、不加修订),内核以 `LOK_CALLBACK_MOUSE_POINTER` 回报 CSS 指针名(`vcl` 的 `gaLOKPointerMap`),随事件批次到视图,换成 gpui 的指针:单元格上为箭头,编辑单元格或文字时为文字指针,链接为手;未知的名字记警告并用箭头。
|
||||
- 2026-10-13(用户定):ElyMark 以 Typora 1.14.10 为对照(R4;安装包与解包放在 `TyporaRef`,不入库):可视模式仍是按下的块以原文编辑;语法照 Typora 默认(`:表情:`、行内与块级 HTML 的常用标签、GitHub 提示块、`[toc]`、front matter 框;`==`、`^`、单个 `~` 照 GFM);快捷键照 Typora(Ctrl+1–6 标题、Ctrl+0 段落、Ctrl+/ 源码、Ctrl+Shift+=/-/0 字号、F8 专注、F9 打字机);右键菜单照 Typora 的布局,剪贴板与格式为图标行(组件库 `Menu` 新增)。Typora 与 GitHub 读同一份文件不同时随 GitHub(GFM,§14.3):表情名取 GitHub 现行的 gemoji(`emojis` 库,`:cricket:` 为蟋蟀),转义与字符引用之后照样是表情,自动链接与 `<code>` 里不是,同一 DOM 文字节点里第一个 `:名:` 前为空白或空格才全部转、否则全不转(`x:smile: :smile:` 原样,过滤标签不分节点),HTML 标签与强调交叉时照浏览器修复 CommonMark 输出,`</br>` 照 HTML5 也是换行,GFM 标签过滤的九种(`script`、`style` 等)照原文显示,提示块的标记读解析后的纯文字;Typora 只决定哪些扩展显示。导出、纯文本与富文本复制经组件 `MarkdownReader` 照可视读每个段落、标题、单元格与 HTML 块(各自一套新栈,块尾关闭未闭合的标签):脚注在原处、写作 `[号]`,链接不带标题(可视不显示),取代 C14.14 的页末脚注与 HTML 一律转义。审查改用 gpt-6-astra,effort max,fast。
|
||||
@@ -292,7 +299,22 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
|
||||
- 2026-10-14(用户要求核对 ElyTable 与 ElyShow):ElyTable 的右键(R5.5)。菜单机制移入 `ely_office::menu`(取内核这次给的菜单、开在所点之处、剪贴板图标行、子菜单可否随其中各项),ElyDoc 与 ElyTable 共用;`ely_lok::menu` 的目标另有单元格(有 `.uno:InsertCell`)与 Writer 之外的绘图对象(有 `.uno:ArrangeMenu`)。网格照 Excel:插入 ▸、删除 ▸、清除内容(`.uno:ClearContents`,同 Delete 键,不弹内核的删除内容对话框)、合并、拆分、设置单元格格式(打开格式面板);对象为置于顶层、置于底层;编辑单元格时只有剪贴板行。行列表头由 Ely 自画,内核不给菜单:右键先选中该行或列(已选的整行整列含它即不动,同 Excel)。选中对象或正编辑图形里的文字时,绘图外壳取代了单元格外壳,`.uno:SelectRow`/`.uno:SelectColumn` 原无处执行而被丢弃;补丁 `0046-lok-calc-headers-leave-drawings.patch` 让 LOK 下视图外壳接下这两条:先结束图形编辑(键入的文字留下)并取消选中,再选行列,同 Calc 自己的表头(`DrawDeselectAll`),菜单为插入、删除、清除内容、行高或列宽、隐藏、显示。ElyTable 每一项的可否都取自内核对它所发的那条命令此刻的状态(内核的菜单只定目标):补丁 `0045-lok-command-states.patch` 加 `getCommandValues(".uno:CommandStates?commands=…")`,先冲出调度器、再逐条问调度器(同菜单栏),未知的命令即报错(`ely_lok::menu::runs`);LOK 推送的状态只有固定的一组,且在空闲时才更新。因此受保护而许插入行列的工作表照样可插;行高、列宽只在文档只读时禁用(内核的规则),受保护时由内核拒绝并报出其错误。ElyTable 无批注界面,不列批注。
|
||||
- 2026-10-14:ElyShow 的右键(R5.6)。画布右键照 PowerPoint 按目标出 Ely 的菜单(`apps/ely-show/src/menu.rs`,共用 `ely_office::menu`);`ely_lok::menu` 的目标另有幻灯片(有 `.uno:SlideLayoutMenu`)与 Writer 之外的图片(有 `.uno:ChangePicture`)。幻灯片为版式 ▸、新建批注;编辑文字为项目符号、编号、新建批注;图形与文本框为组合 ▸、置于顶层 ▸、置于底层 ▸、新建批注;图片另有替换…、裁剪;表格为插入 ▸、删除 ▸、合并单元格、新建批注;剪贴板同为图标行。每项可否取自内核对其命令此刻的状态(补丁 0045):整表选中时可插入行列,删除与合并要光标进单元格(内核的规则)。Impress 的 `LOK_CALLBACK_TABLE_SELECTED` 由 boost 属性树写出,数值与真假都是文字,空列表是空串,`table::read` 照收;拖动表格边线走 R5.3 的同一路径(`.uno:TableChangeCurrentBorderPosition`,偏移为 twips,内核换算)。补丁 `0047-lok-impress-table-edges.patch`:Impress 原只给内侧边线的上下限,行的下限是布局器写死的 600(上游待办),参考线与落点不符;补丁让两轴都带首尾边线的上下限(`leftMin`、`leftMax`、`rightMin`、`rightMax`,列只限从左到右),内侧行线取行自身的最小高度,`table::Lines::ends` 收下,有则按它夹住(内侧线也直接用内核的上限),Writer 不给时照旧留 40 twips;已在界外的线从不逆着拖动方向移动,原地按下松开不发命令;最左列边线原什么也不做却记一步撤销(上游待办),LOK 下改为改首列宽并随边线移动表格,同一步撤销,桌面的拖动手柄不变。正编辑的单元格按编辑器量最小高度,略大于内核真正允许的(约 2 像素),新表的行因此不能再缩,参考线与落点仍一致。正编辑表格单元格时在幻灯片空白处右键,内核只结束编辑、不给菜单,再按一次才有(BUGS P3-11)。
|
||||
- 2026-10-14(Gitea #1,Linux Wayland 报):ElyShow 左侧缩略图条滚轮不滚。根因:列表包在 `ContextMenu` 宿主里,宿主无尺寸,列表随内容长高、从不溢出,滚轮无处可滚(右栏正常);宿主改为 `size_full`(同 ElyPDF 的三处),`tests/strip.rs` 以 24 张幻灯片核对滚轮滚到最后一张。各应用其余 `ContextMenu` 宿主已核:ElyPDF 三处本有尺寸,ElyTable 的工作表标签条与下拉选项不是滚动列表。
|
||||
- 2026-10-14:ElyMark 的菜单与快捷键(R4.9,MARK-15)。项与键取自 Typora 1.14.10 主进程字节码的字符串表(`.work/typora-main-menus.txt`)与其 `zh-Hans.lproj/Menu.json`;实际大小在字节码里有 Ctrl+Shift+9 与 Ctrl+Shift+0 两串,照用户所定用 Ctrl+Shift+0,R4.11 在真窗口核对。表格是“段落”的子菜单(照 Typora),顶层不再有“表格”。原 Ctrl+1/2/3 切模式、Ctrl+=/-/0 字号、Ctrl+Shift+F 专注让给 Typora 的键;可视、源码、预览留在“视图”菜单,无键。Ctrl+/ 另绑在 `ElyEditor` 上(gpui 同深度后绑者胜),盖过代码编辑器的 `//` 注释切换(Markdown 没有这种注释);`MarkdownDocument` 的键上下文只在可视模式有。带 Shift 的标点:Windows 写键名(`ctrl-shift-[`),macOS 与 Linux 写字符(`cmd-{`),见 `blocks::shifted`。Ctrl+Enter 在打开的块里原是输入框的 Submit(文档不处理),改绑为下方插入行。拒绝一律成信息提示:当场的由 `Desk::edit` 说,后台读出的经 `DocumentEvent::EditRefused`、`view::Refused` 到宿主。菜单打开时,打开的块把焦点借给菜单,块与选区都留着,菜单命令照样作用于所选(组件 6d90351)。复制为 Markdown 与粘贴为纯文本只作用于文档:焦点在文档外的输入框(查找框、对话框)时交给该框自己的复制、粘贴。表格子菜单末项为删除表格(组件 `TableEdit::Delete`,一步撤销,插入点不在表格里即拒绝;在打开的块里删除后焦点回到文档,撤销键照用,组件 6c2d28c)。Typora 有而组件库暂缺的不进菜单:行内公式、上下标、注释、提示块子菜单、任务状态、列表缩进 Ctrl+[/]、代码工具。
|
||||
- 2026-10-14:ElyMark 的右键菜单(R4.10)。项、次序与显隐规则取自 Typora 1.14.10 的 `resources/window.html`(`#context-menu` 与其子菜单)与 `frame.js` 的显隐函数,记在 `.work/R4.10/typora-context-menu.txt`。菜单在 `view/menu.rs`,`MarkView` 自持(`ely_office::menu::Offer` 与 `ContextMenu::manual`):可视模式由组件的 `DocumentEvent::Pointed` 开在指针处,源码与预览由视图自己的右键开。剪切、复制、粘贴、删除所选范围为图标行,按下即把其键交回菜单打开前的焦点(`dispatch_keystroke`),与键盘同一路径;无选区时剪切、复制、删除灰显。其余项经各自的动作,显示所绑的键。组件 013f142、1b5fb07:文本框与代码编辑器右键落在选区里时保留选区,否则把插入点移到所点处;可视模式打开的块右键不写回、不关闭,目标在后台按全文读出(块外的引用定义照样解析);`MarkdownDocument::delete_image`(删除图片,一步撤销,无图片即 `EditRefusal::NoImage`);可视无块时 Ctrl+V 粘贴文字(原只收图片,文字被丢弃)。复制为 HTML 代码的图片照原地址(`Pictures::Written`,同 Typora),复制为富文本照旧内嵌。“编辑”菜单的复制项照 Typora 次序:纯文本、Markdown、HTML 代码、富文本。Typora 有而不做的:缩进与减少缩进行(可视只在打开的块里有)、复制表格、代码自动缩进、图片上传、缩放、移动与语法切换、拼写、表情复制、检查元素。gpui 的测试只发按下,菜单在 Enter 松开时选中,测试另发松开(`blocks/context.rs` 的 `choose`)。
|
||||
- 2026-10-14(用户报:整个软件中文显示问题很多):中文显示(R4.13)。Windows 上 gpui 以用户区域(本机为 en-US)排版全部文字,DirectWrite 按日文为汉字选回退字体,日文字体缺的简体字再落到另一字体,同一个词里字形与粗细不一(ElyTree 的“打开仓库”:“打开”粗、“仓库”细)。`vendor/gpui-pre-windows` 的 `text_locale`:用户区域不是中日韩时,改用 Windows 语言列表(WinRT `GlobalizationPreferences::Languages`,Win32 的界面语言只给 en-US)里第一个中日韩语言排版(日志 `text: laid out as …`);在 Windows 上打中文须把中文加进该列表,所以它就是用户读的汉字。只换排版的区域,字体族名与字体列表仍按用户区域。读不出语言列表即记警告、照用户区域。组件库 6df9ab0:Ely 用到的组件里写死的英文(下拉的“Choose…”、清除、关闭、移除、取消固定的提示,公式补全的“No suggestions”,设置里字号的重置提示与示例句)改走内建中英目录。仍为英文的是内核的文字(LibreOffice 界面语言固定英文:幻灯片占位“Click to add Title”、母版“Default”、配色名、数字格式代码“General”、函数名),以及启动失败对话框(出现在读入语言之前,中英并列)。
|
||||
- 2026-10-14(用户定:dmg 不再显示未公证):macOS 发布以 Developer ID Application 证书签名、经 `notarytool` 公证并钉票。证书与公证凭据(`xcrun notarytool store-credentials`,App 专用密码只在钥匙串里)装在构建用的 Mac 上;发布流程的 macOS 任务从仓库变量 `ELY_SIGN_IDENTITY`(证书全名)与 `ELY_NOTARY_PROFILE`(凭据名)取得,`ci.sh` 在 macOS 上缺任一即失败,不出未公证的包。本机手动出包同样设这两个变量再跑 `packaging/macos/release.sh`。
|
||||
- 2026-10-14:ElyMark 的菜单与快捷键(R4.9,MARK-15)。项与键取自 Typora 1.14.10 主进程字节码的字符串表(`.work/typora-main-menus.txt`)与其 `zh-Hans.lproj/Menu.json`;实际大小在字节码里有 Ctrl+Shift+9 与 Ctrl+Shift+0 两串,照用户所定用 Ctrl+Shift+0;R4.11 真窗口查出 Windows 的中文输入法把 Ctrl+Shift+0 留作热键(注册表 `HKCU\Control Panel\Input Method\Hot Keys\00000104`),应用收不到,Windows 另绑 Ctrl+Shift+9(菜单显示它)。表格是“段落”的子菜单(照 Typora),顶层不再有“表格”。原 Ctrl+1/2/3 切模式、Ctrl+=/-/0 字号、Ctrl+Shift+F 专注让给 Typora 的键;可视、源码、预览留在“视图”菜单,无键。Ctrl+/ 另绑在 `ElyEditor` 上(gpui 同深度后绑者胜),盖过代码编辑器的 `//` 注释切换(Markdown 没有这种注释);`MarkdownDocument` 的键上下文只在可视模式有。带 Shift 的标点与数字一律写所出的字符(`secondary-{`、`secondary-+`、`alt-%`):三端的 gpui 都把 Shift 加该键报成字符并去掉 Shift(Windows 见 `gpui-pre-windows` 的 `get_keystroke_key`);R4.9 原在 Windows 写键名,真键盘按不出(R4.11 真窗口查出)。Ctrl+Enter 在打开的块里原是输入框的 Submit(文档不处理),改绑为下方插入行。拒绝一律成信息提示:当场的由 `Desk::edit` 说,后台读出的经 `DocumentEvent::EditRefused`、`view::Refused` 到宿主。菜单打开时,打开的块把焦点借给菜单,块与选区都留着,菜单命令照样作用于所选(组件 6d90351)。复制为 Markdown 与粘贴为纯文本只作用于文档:焦点在文档外的输入框(查找框、对话框)时交给该框自己的复制、粘贴。表格子菜单末项为删除表格(组件 `TableEdit::Delete`,一步撤销,插入点不在表格里即拒绝;在打开的块里删除后焦点回到文档,撤销键照用,组件 6c2d28c)。Typora 有而组件库暂缺的不进菜单:行内公式、上下标、注释、提示块子菜单、任务状态、列表缩进 Ctrl+[/]、代码工具。
|
||||
- 2026-10-14:ElyMark 的右键菜单(R4.10)。项、次序与显隐规则取自 Typora 1.14.10 的 `resources/window.html`(`#context-menu` 与其子菜单)与 `frame.js` 的显隐函数,记在 `.work/R4.10/typora-context-menu.txt`。菜单在 `view/menu.rs`,`MarkView` 自持(`ely_office::menu::Offer` 与 `ContextMenu::manual`):可视模式由组件的 `DocumentEvent::Pointed` 开在指针处,源码与预览由视图自己的右键开。剪切、复制、粘贴、删除所选范围为图标行,按下即把其键交回菜单打开前的焦点(`dispatch_keystroke`),与键盘同一路径;无选区时剪切、复制、删除灰显。其余项经各自的动作,显示所绑的键。组件 013f142、1b5fb07:文本框与代码编辑器右键落在选区里时保留选区,否则把插入点移到所点处;可视模式打开的块右键不写回、不关闭,目标在后台按全文读出(块外的引用定义照样解析);`MarkdownDocument::delete_image`(删除图片,一步撤销,无图片即 `EditRefusal::NoImage`);可视无块时 Ctrl+V 粘贴文字(原只收图片,文字被丢弃)。复制为 HTML 代码的图片照原地址(`Pictures::Written`,同 Typora),复制为富文本照旧内嵌。“编辑”菜单的复制项照 Typora 次序:纯文本、Markdown、HTML 代码、富文本。Typora 有而不做的:缩进与减少缩进行(可视只在打开的块里有)、复制表格、代码自动缩进、图片上传、缩放、移动与语法切换、拼写、表情复制、检查元素。gpui 的测试只发按下,菜单在 Enter 松开时选中,测试另发松开(`blocks/context.rs` 的 `choose`)。第 1 轮后:右键的目标按所点的字节读(组件 79e94f7),保留的选区只供剪贴板,删除图片删所点的那张;三种“复制为”在后台转换,界面线程只写剪贴板,新的复制取代未完成的旧复制(`Desk::copying`);`ely_office::menu::Offer` 只在首次绘制时把请求交给宿主(宿主按元素存的“已开”记录随标签切走而丢,切回会重开),ElyDoc、ElyTable、ElyShow 同受其益。第 2 轮后:转换完成时剪贴板已不是开始时的内容(此后有任何复制,含编辑器自己的 Ctrl+C)即丢弃这次结果,同内容的再次写入分不出;打开的块里只认最后一次右键(组件 2b8bd9f),所点字节对回所画字节的读法逐段只对齐一次(原逐字重读,8000 字的段落要近 2 秒)。第 3 轮后:剪贴板的比对另含其 HTML(gpui 读剪贴板不含 HTML,纯文字相同而富文本不同的后来复制原被盖掉;`ely_platform::clipboard::html`);组件的计时测试改用 `web_time::Instant`(组件 e07fd34)。
|
||||
- 2026-10-14(用户报:整个软件中文显示问题很多):中文显示(R4.13)。Windows 上 gpui 以用户区域(本机为 en-US)排版全部文字,DirectWrite 按日文为汉字选回退字体,日文字体缺的简体字再落到另一字体,同一个词里字形与粗细不一(ElyTree 的“打开仓库”:“打开”粗、“仓库”细)。`vendor/gpui-pre-windows` 的 `text_locale`:用户区域不是中日韩时,改用 Windows 语言列表(WinRT `GlobalizationPreferences::Languages`,Win32 的界面语言只给 en-US)里第一个中日韩语言排版(日志 `text: laid out as …`);在 Windows 上打中文须把中文加进该列表,所以它就是用户读的汉字。只换排版的区域,字体族名与字体列表仍按用户区域。读不出语言列表即记警告、照用户区域。Ely 的界面语言是中文时(设置或 `ELY_LOCALE`),`ely_ui::i18n::install_as` 经 `gpui_windows::set_text_language` 让排版随它,不论 Windows 区域(日文区域下“打开仓库”原为 Yu Gothic UI 600 与 Microsoft JhengHei UI 700 两种字);语言下次启动生效,故启动时设一次。组件库 6df9ab0:Ely 用到的组件里写死的英文(下拉的“Choose…”、清除、关闭、移除、取消固定的提示,公式补全的“No suggestions”,设置里字号的重置提示与示例句)改走内建中英目录。a4bf696:查找框(计数、三个选项与上下一处的提示、替换与全部替换)、排序与筛选(添加规则、满足全部或任一、条件、升降序、添加排序)、密码框的显示与隐藏提示同此;筛选条件以目录键为值(`Test::key`);ElyMark 的删除图片按右键所点的字节(`delete_image(at)`)。仍为英文的是内核的文字(LibreOffice 界面语言固定英文:幻灯片占位“Click to add Title”、母版“Default”、配色名、数字格式代码“General”、函数名),以及启动失败对话框(出现在读入语言之前,中英并列)。
|
||||
- 2026-10-14(用户定:dmg 不再显示未公证):macOS 发布以 Developer ID Application 证书签名、经 `notarytool` 公证并钉票。证书与公证凭据(`xcrun notarytool store-credentials`,App 专用密码只在钥匙串里)装在构建用的 Mac 上;发布流程的 macOS 任务从仓库变量 `ELY_SIGN_IDENTITY`(证书全名)与 `ELY_NOTARY_PROFILE`(凭据名)取得,`ci.sh` 在 macOS 上缺任一即失败,不出未公证的包。本机手动出包同样设这两个变量再跑 `packaging/macos/release.sh`。强化运行时下 LibreOffice 的 UNO 桥以 `MAP_JIT` 映射虚表,`ely-lok-worker` 须带 `com.apple.security.cs.allow-jit`(`packaging/macos/lok-worker.entitlements`,同 LibreOffice 自己的 `hardened_runtime.xcent`;其余几项不需要,实测);0.1.5 首发的三个 LOK 应用缺它,worker 在首个请求时中止(R6.5)。
|
||||
- 2026-10-15(用户报:ElyMark 点表格整个表格变成源码,应在格内编辑;用户定:格内显示该格原文):表格单元格编辑(R6.1)。组件库 2594b3f:可视模式按下表格只打开所按的那一格,在格内原位以单行输入框显示该格的 Markdown 原文(`**粗体**` 带记号),表格其余照常画出;按在格内文字上即落在所按的字,按在格内空白落在格末;以表格边缘、键盘或上下键从邻块进入的表格块打开其首格或末格;Tab、Shift+Tab 到下一格、上一格(跨行),上下键到上下一格,越出表格即到邻块;回车与 Esc 写回,写回为一步撤销;格内键入的 `|` 写回时转义为 `\|`(表格编辑读到的也是转义后的文字);格开着时做表格编辑(插删行列、整理等)先写回该格再执行,格随之关闭。列表、引用里的表格同此。表格绘制移入组件 `render/table.rs`,按格的空白处也带出所按的格(`Place::Cell`)。第 1 轮后(组件库 6a3f348):开着的格里的按下只给其输入框,插入点落在所按处、仍是一步撤销;格末单数的反斜杠写回时补成一对,不吞下一格的竖线;查找在可视模式里打开匹配所在的格并选中,跨格的匹配转到其行;格开着时右键所按的字节随格内键入的竖线换算;在未开的格的空白处右键,目标为该格末尾。第 2 轮后(组件库 2b6bd1d):格末的反斜杠只在紧接竖线时补成一对(`| a\ |` 的反斜杠后是空格,原样写回,只打开不键入不改一个字节);改首格后仍认得所在表格(无外侧竖线的表格首格始于块首,原被当作写掉了块),Tab 与按邻格照常;开着的格的空白处左键把插入点移到格末、右键以格末为目标,都不写回,仍是一步撤销。第 3 轮后(组件库 f1771b3,最后一轮,修完不再审查):无外侧竖线的行里清空首格或末格时写回一个竖线(`| | beta`、`alpha | |`),列数不变;插入点照写回的转义文字报出(键入竖线后不再落在多字节字中间);改过一格后右键邻格照常给出目标;长文(后台解析)里改格后 Tab 等到解析完成再打开下一格。
|
||||
- 2026-10-15(用户报:二级菜单选不到,往子菜单移动时经过下面的项会弹出它们的子菜单,七个应用都如此;用户定照桌面系统的悬停意图做:安全三角加打开与关闭的延时):级联菜单(R6.2,组件库 d4fdb69,`ContextMenu`、`DropdownMenu`、`MenuBar` 共用的面板)。菜单面板挡住其下的元素(原先子菜单被挤回、盖在父菜单上时,被盖住的父菜单行照收悬停);子菜单右侧放不下且左侧放得下即开在所在行的左侧,从右滑入,不盖父菜单的行(两侧都放不下时贴窗口边,仍被面板挡住);指针停在有子菜单的行上 150 毫秒才打开;子菜单开着时,指针落在“上一位置与子菜单近侧上下两角”构成的三角形里的另一行,等 300 毫秒,指针仍在该行才切换,其间到达子菜单即作废;三角形外的行即刻标记。键盘与按下照旧即刻打开。实现在组件 `menus::aim`。第 1 轮后(组件库 5a53c08):指针离开一行(到边距、分隔线、禁用的行或菜单外)即作废其延时,回到该行重新计时;菜单在别处重开即忘掉旧的悬停;图标按钮行同样受三角形保护。
|
||||
- 2026-10-15(用户报:ElyMark 的最近列表清不掉):侧栏“清除最近文件”(R6.3,98692cb)写空 `recent.json`(`ely_files::recent::clear`),失败即提示。会话恢复的标签不把文件加回列表(`Desk::remembered` 预先记下),清空在重启后照旧;显式打开照样加入,已开着的文件(按文件身份,含硬链接,`Sessions::is_open`)只切到该标签,也加入列表。
|
||||
- 2026-10-15(用户报:ElyMark 代码块后的“你好↵测试”离开输入框后成了“你好 测试”):单个换行照 Typora 的默认(编辑时保留,导出与打印不保留):组件库 93efa7f 起 `MarkdownReader::new`(屏上:可视、预览、右键与命令的读法)把软换行读作换行,`MarkdownReader::joined`(输出)照 GFM 读作空格;标题的大纲与目录文字照旧一行。ElyMark 的 HTML、PDF、富文本复制与纯文本导出用 `joined`(R6.7)。组件库 c31d092 与 26af4be:画出成一个换行的 CRLF 对回其起点(原先按在 CRLF 行末键入落在 CR 与 LF 之间),行内代码照留两字则逐字对回。
|
||||
- 2026-10-15(用户报:ElyMark 源码模式“测”后的插入点画在“测”的中间):组件库 `CodeEditor` 原按“列 × m 的宽”放插入点、选区、按下处与输入法框,中日韩字与表情约宽两格。组件库 9fb607b 起按 gpui 排好的这一行定位(`editor::measure`,含着色带来的字重),块状与下划线插入点取所在字的宽;标尺与缩进参考线仍按列(R6.8)。上下移动仍按字数记目标列。cd61653:按下处取最近的字首或行末(gpui 的 `closest_index_for_x` 越过末字字首即给行末);上次绘制得出的括号与配对位置只属当时的文字(`Buffer` 每次改动换一个戳),输入法改字后、下次绘制前的测量不用它们(原先把新字切进不同字体段,DirectWrite 崩溃)。
|
||||
- 2026-10-15(用户报:ElyMark 三、四级标题不显眼):组件库 5954132 起标题字号随正文按 Typora 的倍数(一至六级 2.25、1.75、1.5、1.25、1、1),一律加粗,六级为次要色,行高为字号的 1.3 倍(原为固定的 24、20、16、14 像素,正文 13,三、四级只是中等字重)(R6.9)。90bd37b:粗体与标题同一字重(原粗体为半粗,标题里的粗体反而更细,正文粗体随之由半粗改为粗,同 Typora);标题行高按自身字号取 1.3 倍。Windows 真窗口核对(`.work/r69`):可视模式各级标题分明、“你好↵测试”两行,源码模式“测”后的插入点落在两字之间。
|
||||
- 2026-10-15(用户报:macOS 打开一个文档,程序坞里有两个同样的图标):LOK worker 在应用包的 `Contents/MacOS` 里启动 AppKit,系统按包的 Info.plist 把它也登记为常规应用(`lsappinfo` 里应用与 worker 都是 Foreground),程序坞多一个图标;内核自己从不设激活策略。worker 在内核启动 AppKit 之前(`Lok::hook` 打开内核之后、调钩子之前)把本进程主包信息里的 `LSUIElement` 设为真,AppKit 登记时即为辅助应用(无程序坞图标、无菜单栏,仍可建屏外窗口);钩子之后核对激活策略是辅助,不是即报错、不启动(`ffi/accessory.rs`);包外的 worker(`cargo run`、单测)无包可登记,策略为禁止,此时改设辅助(R6.12 第 2 轮)。原先在登记之后才改策略,审查实测 15 次启动有 11 次先登记为 Foreground 约 30 毫秒(R6.12 第 1 轮)。`tests/scripts/dock-macos.sh` 连续启动三个应用与包外的开发构建,从 worker 启动起采样其类型到首块图块,见 Foreground 即失败(R6.12)。
|
||||
- 2026-10-15(用户报:ElyShow 编辑区滚轮与上下键不换页,三端):内核在未选中对象时把上下键当作滚动窗口(`fupoor.cxx`),Ely 的画布整页适合、无处可滚,滚轮同样。`LokView::turn_parts`(ElyShow 首次适合时调用)之后:整页可见时滚轮换页(`view/turn.rs`):滚轮的行按本平台每格的行数(`ely_lok::notch`:macOS 1,Windows 取系统设置,X11 与 Wayland 为 3)折成格,整格的行每格一页(快速连滚与一次多格都照格数);一串行里出现不足一格的(X11、Windows 的触控板)即为平滑滚动,此后到停顿前不再换页,像素(macOS、Wayland 的触控板)同按手势:一次手势换一页(满一格或 50 像素),惯性不算;有起止的手势(macOS)只到结束才算完,没有起止的停 200 毫秒即为下一次。X11 的滚轮与触控板同为行、gpui 不分,以整格开头的触控板滑动在出现小数之前会按格换页(已知限制)。未选中对象、未编辑文字时上下键换页。换页一律经有序输入队列交 worker(`TURN`):worker 按之前各输入回报后的状态判定,有选区、选中对象或插入点即把方向键照常交内核,否则当场切页(到首末页即停,同缩略图条的 `setPart`),视图在落地时换上 worker 所示的页,其后排队的键与点按都落在新页上(Tab 后紧接的 Down 移动所选对象;Down、Tab、Down 是换页后在新页上选中并移动);ElyShow 后台读回的当前页只在视图已无待落地输入时采用(R6.13)。
|
||||
- 2026-10-16(用户定):合集安装包(R7.1)。macOS 一个公证的 `ElyOffice-<版本>-<架构>.dmg`,装首批六个已签名的 .app 与“应用程序”替身,用户拖入所要的(`release.sh` 的 `dmg` 与单个应用共用);无 Developer ID Installer 证书,不出 .pkg。Windows 一个 `ElyOffice-<版本>-windows-x86_64-setup.exe`(`packaging/windows/bundle.nsi`),组件页勾选应用,所选的各自的安装程序以 `/S` 运行,所以装法、位置、升级、卸载项与单装完全相同;某个退出码非零即停下并写明其名与退出码(2 为文件被占用或位置被占),之前装上的照旧。Linux 不出合集。单个应用的包、更新清单照旧。
|
||||
- 2026-10-16(Gitea #6):设置窗口多出一行应用菜单(R7.2)。设置窗口沿用主窗口的外壳 `Shell`,Windows 与 Linux 上随之画出菜单栏(macOS 菜单在系统菜单栏,不受影响)与更新横幅。菜单栏与更新横幅只属主窗口:`Shell::secondary` 去掉两者,设置窗口用它;`settings/tests.rs` 量内容起点距标题栏底:只装菜单时主窗口大于零(macOS 为零),再有待下载的新版时更大,设置窗口为零。
|
||||
- 2026-10-16(Gitea #4):装了宋体仍报缺少(R7.3)。内核按名找字体时比较 `GetEnglishSearchFontName`(小写 ASCII、去空格、中日韩本地名译为英文名,`宋体` 即 `simsun`),所以文档的 `宋体` 找到并用上 SimSun;缺字检查却比较原名与所用字体名,报为缺失。Linux 上内核以界面语言(英文)为 fontconfig 字体取名,文档里的本地名一律报缺。补丁 `0048-lok-fonts-missing-by-search-name.patch`:缺字检查同样比较检索名。实测(2026-10-16):Arch 容器装 ElyDoc 0.1.5 的 Arch 包与 simsun.ttc,40 行宋体五号、文档网格的 docx 报缺宋体,正文实为 SimSun(无此字体时为方框),与 Windows 同为一页;换上打过 0048 的内核后同一容器不再报缺、仍为一页。用户所说一页变两页未能复现,需其文件:十种宋体版式(44 与 45 行的文档网格、无网格、折行两端对齐、字符网格、粗体、小四、固定行距、1.5 倍行距)在 Windows 与 Linux 内核上页数、断行、分页逐行相同(`.work/r7/pages`),网格下每页 44 行、每行约 39 字,同 Word 的 A4 默认;差别若在,是该文件里 LibreOffice 与 Word 的排版不同,与平台无关。缺字检查测试:`navigate/tests.rs` 以随包的 DejaVu Sans 写作 `DEJAVU SANS`,只报真缺的字体。另见:Linux 上属性栏的字体框为空(字体列表只有 SimSun,文档写宋体),未改。
|
||||
- 2026-10-16(Gitea #5):每个 PDF 打开即报已损坏(R7.4)。C11.8 把画图块与导出时 MuPDF 的任何警告都算作损坏;读页面时载入未嵌入的字体也发警告(中文文件里写名而不嵌入的宋体等:`non-embedded font using identity encoding`),合法的文件因此转为修复副本、保存一律另存。现在警告监视(`keep_warning`,打开时的扫描、画图块、导出与 Markdown 的 PDF 共用)只略去这一句与紧随其后的 MuPDF 重复计数(`... repeated N times...`);其余照算损坏,含内容的语法错误、无字体写字、坏的嵌入字体与图片流。读文字与搜索也受监视(坏图片读过即被缓存,之后画图块、导出与检查都不再报警告):其间遇到的损坏记入报告与该文档,下一次画图块或检查图片报出,报出之前导出图片与文字一律拒绝。监视开始时,MuPDF 尚未报出的重复计数(来自其余未受监视的读取)按它所重复的那句归类(`ctx->warn.message`):字体提示的重复略去,其余照算。`tests/output.rs` 核对:两个同名未嵌入字体的文件先读文字再画图块、导出图片与文字都不算损坏;无字体写字与 `BT ] ET` 的图块为损坏;`[/FlateDecode /ASCIIHexDecode]` 下校验和错的图片使两种导出都被拒、图块为损坏。先读文字或搜索后,这样的两张图片、颜色键掩码无效的一张图片、以及它在两个未嵌入字体之前或之后画出,画图块、导出与检查图片仍报损坏。
|
||||
- 2026-10-16(Gitea #3):Windows 与 Linux 打印(R7.6)。`print_pdf` 改为异步:对话框在应用线程上,读页与出作业在自己的线程上(`print::off`),应用不卡。Windows:系统打印对话框(`PrintDlgEx`,Windows 11 显示为新式对话框),打开前把默认打印机的设置改成文档的纸张与方向(按打印机自己的纸型匹配(纸型须装得下页面,至多大 2 毫米,Linux 的 PWG 名同此);没有即自定义尺寸),设置须连同打印机名(`DEVNAMES`)一起交给对话框,否则对话框改用打印机自己的偏好(实测:Letter 文档印成 A4);所选页码范围照办,份数交驱动;勾“打印到文件”时文档输出为 `FILE:`,由打印子系统问文件名。驱动不支持所设纸张时会换成别的(实测“Microsoft Print to PDF”没有自定义尺寸,1000×600 点的页面换成 A4),所以出作业之前(`StartDoc` 之前)按打印机实际的纸张核对每一页:超出纸张半点以上(纸张尺寸至多舍入到整点,`print::ROUNDING`)、转过来也超出即报错,什么也不印(实测:600×842 点的页面原在 A4 上印出、右缘被裁)。页面由 Windows 自带的 PDF 渲染(`Windows.Data.Pdf`)按打印机分辨率分条画出,按原大从纸张的角上放(扣去不可打印的偏移),只在转过来才放得下时左转 90 度;渲染器的尺寸按 DIP 算、乘显示缩放,每次作业先试画一次量出倍数。`ELY_PRINT_TO` 时不弹对话框,经“Microsoft Print to PDF”写成文件(测试用)。`GlobalFree` 成功时返回空,windows-rs 读成错误码 0 的错误,须当作成功(否则打印报“操作成功完成”)。Linux:经 xdg 桌面门户的 `org.freedesktop.portal.Print`(`PreparePrint` 后带其令牌 `Print`,交出 PDF 的文件描述符),页面设置为文档纸张(标准纸型给 PWG 名,否则自定义毫米尺寸),边距为零,只许输出 PDF(`supported_output_file_formats`,否则对话框可选 PostScript,写出的却是 PDF);门户照原样交出所给的字节,对话框的选择由应用排定(`print/linux/sheets.rs`):GTK 设置里的页码范围(从零起)、奇偶页、倒序、份数与逐份、缩放、每张页数与排列,排到对话框所选纸张与方向上,每页为一个表单对象(带可打印批注的外观;带 NoRotate 的批注在转过的页面上绕其左上角转回、保持正立,同 MuPDF;外观的资源名避开页面已有的;可打印却没有外观的批注即报错,链接与弹出说明本无外观),单页按原大乘缩放从纸张左上角放,超出半点以上而转过来放得下即左转,否则报错;方向照 GTK 的写法(`reverse-portrait`,门户文档的页面设置同此);奇偶页只在 GTK 的文件与 lpr 后端时由 Ely 排(设置里有 `output-uri` 或 `lpr-commandline`),CUPS 后端自己把它交给 CUPS(`cups-page-set`,GTK 3.24.52 实测),Ely 再排一次即丢页;份数、每张页数等 GTK 留给应用,Ely 照排;裁剪框超出媒体框的部分不印(取两者的交);页码范围的开放终点 GTK 写作 -1(`1--1`),倒着的范围即报错;多页按格居中,再交内存文件(`memfd`);直接用 zbus:ashpd 0.13.13 的 `PageSetup`、`Settings` 缺任一字段即解析失败,真门户的回复常不带 `PPDName`。页面尺寸由 lopdf 读(CropBox,否则 MediaBox,继承、`/Rotate` 与页面自己的 `/UserUnit`)。打印不再按平台禁用(原 `print::BUILT` 与“此平台尚未构建”删去)。替身门户的测试核对选页、缩放、倒序与份数后交出的页面与位置,与只许 PDF。ElyPDF 的打印副本(`ely_print_copy`)按打印的规则画:可打印(不隐藏)的批注与表单控件,外观画进页面内容(位置照 MuPDF 自己的 `pdf_annot_transform`,与屏上一致;无外观的先由 MuPDF 生成,MuPDF 原只在显示时放在本地表里、不存入文件),其余批注与表单去掉,只留链接;系统的渲染器按屏幕规则画(不打印的照画,“打印但不显示”的不画,实测 Windows),画进内容后各渲染器都只见要打印的;仍画不出的即报错;`tests/output.rs` 渲染副本核对。真窗口(Windows):ElyDoc 的 Ctrl+P、Ely 的打印对话框、系统对话框、“Microsoft Print to PDF”的另存为,印出的 PDF 为文档的 Letter;系统对话框取消时不打印、不报错(`.work/r76/print.ps1`)。未验证:Linux 真桌面上的门户(只对替身门户核对);实体打印机。
|
||||
- 2026-10-16(用户定):Windows 资源管理器的右键“新建”可建 DOCX、XLSX、PPTX 与 Markdown 文件(R7.9)。空白文件在 `packaging/windows/new`(`templates.sh` 以本构建的内核把空文件转存而得,无作者与日期;Markdown 为空文件),随所属的应用装在安装目录(列在 `.ely-installed` 里),`HKCU\…\.<扩展名>\ShellNew` 的 `FileName` 指向它。资源管理器只在扩展名有默认 ProgID 时列出新建项(实测:只有 `ShellNew`、或只在 `OpenWithProgids` 下时都不列);所以只在该类型没有任何程序处理时(HKCR 下无默认值,或默认值所指的类不存在:本机 Windows 11 的 `.md` 指向不存在的 `Markdown Document`)把默认值设为本应用的 ProgID(写在 HKCU,用户自己的 `UserChoice` 不动),已有的从不改动(装着 Office、WPS 时新建菜单用它们自己的项);没有处理程序的这四种类型从此由 Ely 打开。卸载只删仍是本安装写下的 `ShellNew` 与默认值。ProgID 的名称为“<应用> Document”(新建菜单与类型列显示它)。`tests/scripts/types.sh` 核对四种都有新建项,默认值只在判空之后写。
|
||||
- 2026-10-16(用户定):ElyMark 打开的块保持原样(R7.5)。组件库 bff7ebc 起,可视模式里按下的块以原文显示在它合上时的框里(同样的边距与透明边框),字号、行高与颜色同合上时:段落、列表、引用等为正文,标题按其级数的字号、1.3 倍行高、加粗(六级为次要色),照原文写出的块(链接定义等)为等宽次要色;不再加深色底板与另一套边距,按下前后不挪位置。代码块、块公式与 front matter 仍有自己的底板(代码与 front matter 为等宽小号,front matter 为次要色,同合上时)。输入框的着色(源码模式同用)给标题与粗体同一字重(原为半粗,压过所设的加粗),六级标题里的字照为次要色(行内代码照为正文色,2e65b05),front matter 照 front matter 读(原读成分隔线加标题,键名变亮变粗)(1ff993d、962964e)。表格单元格照旧。打字机模式的居中另按两端余量判定(原只按块高与视图高,打开前后同高时首块不再居中)。同批带入组件库 cdc5ce8(标题栏拖动区里的控件按下归控件,Windows)。Windows 真窗口核对(`.work/r75`):段落、三级标题、代码块打开前后位置相同。
|
||||
@@ -332,3 +332,39 @@ fn an_outline_click_goes_where_its_row_was_drawn() {
|
||||
});
|
||||
assert_eq!(target(vcx), Some((0, 300, 10, 10)), "the click goes where its row was");
|
||||
}
|
||||
|
||||
/// A bundled font spelled otherwise, and one nowhere.
|
||||
const SPELLED: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
|
||||
<office:font-face-decls>
|
||||
<style:font-face style:name="DEJAVU SANS" svg:font-family="'DEJAVU SANS'"/>
|
||||
<style:font-face style:name="Nowhere Sans" svg:font-family="'Nowhere Sans'"/>
|
||||
</office:font-face-decls>
|
||||
<office:automatic-styles>
|
||||
<style:style style:name="T1" style:family="text"><style:text-properties style:font-name="DEJAVU SANS"/></style:style>
|
||||
<style:style style:name="T2" style:family="text"><style:text-properties style:font-name="Nowhere Sans"/></style:style>
|
||||
</office:automatic-styles>
|
||||
<office:body><office:text>
|
||||
<text:p><text:span text:style-name="T1">found</text:span> <text:span text:style-name="T2">lost</text:span></text:p>
|
||||
</office:text></office:body>
|
||||
</office:document>"#;
|
||||
|
||||
#[test]
|
||||
fn a_font_found_by_its_search_name_is_not_missing() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let mut cx = TestAppContext::single();
|
||||
let Some(docs) = docs(&mut cx, dir.path()) else {
|
||||
eprintln!("SKIP: no LOK build");
|
||||
return;
|
||||
};
|
||||
open_text(&mut cx, &docs, &dir.path().join("spelled.fodt"), SPELLED);
|
||||
settle(&cx, |app| {
|
||||
let tab = docs.read(app).active_tab().expect("a tab");
|
||||
!tab.view.read(app).missing_fonts().is_empty()
|
||||
});
|
||||
let missing = cx.update(|app| {
|
||||
let tab = docs.read(app).active_tab().expect("a tab");
|
||||
tab.view.read(app).missing_fonts().to_vec()
|
||||
});
|
||||
assert_eq!(missing, ["Nowhere Sans"], "the lookup found DejaVu Sans");
|
||||
}
|
||||
@@ -46,19 +46,10 @@ actions!(
|
||||
Hyperlink,
|
||||
InsertImage,
|
||||
ClearFormat,
|
||||
DeleteBlock,
|
||||
DeleteImage
|
||||
DeleteBlock
|
||||
]
|
||||
);
|
||||
|
||||
/// Shift with punctuation: Windows names the key, others the character.
|
||||
pub(crate) fn shifted(mods: &str, key: char, typed: char) -> String {
|
||||
match cfg!(target_os = "windows") {
|
||||
true => format!("{mods}-shift-{key}"),
|
||||
false => format!("{mods}-{typed}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bind(cx: &mut App) {
|
||||
let at = Some(commands::CONTEXT);
|
||||
cx.bind_keys([
|
||||
@@ -74,14 +65,14 @@ pub fn bind(cx: &mut App) {
|
||||
KeyBinding::new("secondary-shift-m", MathBlock, at),
|
||||
KeyBinding::new("secondary-shift-k", CodeFences, at),
|
||||
KeyBinding::new("secondary-shift-q", Quote, at),
|
||||
KeyBinding::new(&shifted("secondary", '[', '{'), OrderedList, at),
|
||||
KeyBinding::new(&shifted("secondary", ']', '}'), BulletList, at),
|
||||
KeyBinding::new("secondary-{", OrderedList, at),
|
||||
KeyBinding::new("secondary-}", BulletList, at),
|
||||
KeyBinding::new("secondary-shift-x", TaskList, at),
|
||||
KeyBinding::new("secondary-b", Strong, at),
|
||||
KeyBinding::new("secondary-i", Emphasis, at),
|
||||
KeyBinding::new("secondary-u", Underline, at),
|
||||
KeyBinding::new(&shifted("secondary", '`', '~'), InlineCode, at),
|
||||
KeyBinding::new(&shifted("alt", '5', '%'), Strike, at),
|
||||
KeyBinding::new("secondary-~", InlineCode, at),
|
||||
KeyBinding::new("alt-%", Strike, at),
|
||||
KeyBinding::new("secondary-k", Hyperlink, at),
|
||||
KeyBinding::new("secondary-shift-i", InsertImage, at),
|
||||
KeyBinding::new("secondary-\\", ClearFormat, at),
|
||||
@@ -230,7 +221,6 @@ impl Desk {
|
||||
InsertImage => |d, cx| d.format(F::Image, cx),
|
||||
ClearFormat => |d, cx| d.format(F::Clear, cx),
|
||||
DeleteBlock => |d, cx| d.block(B::Delete, cx),
|
||||
DeleteImage => |d, cx| d.delete_image(cx),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,3 +161,91 @@ fn html_code_keeps_picture_addresses(cx: &mut TestAppContext) {
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn copies_convert_off_the_window_thread(cx: &mut TestAppContext) {
|
||||
let (_desk, cx, _files) = opened("alpha *it*\n", cx);
|
||||
cx.write_to_clipboard(gpui::ClipboardItem::new_string("before".into()));
|
||||
// The context's dispatch parks; this one does not.
|
||||
cx.update(|window, cx| window.dispatch_action(Box::new(crate::export::CopyHtml), cx));
|
||||
assert_eq!(
|
||||
clipboard(cx).as_deref(),
|
||||
Some("before"),
|
||||
"not on the window thread"
|
||||
);
|
||||
cx.update(|window, cx| window.dispatch_action(Box::new(crate::export::CopyPlain), cx));
|
||||
cx.run_until_parked();
|
||||
assert_eq!(clipboard(cx).as_deref(), Some("alpha it\n"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_later_markdown_copy_outlives_a_pending_conversion(cx: &mut TestAppContext) {
|
||||
let (_desk, cx, _files) = opened("alpha *it*\n", cx);
|
||||
cx.update(|window, cx| window.dispatch_action(Box::new(crate::export::CopyHtml), cx));
|
||||
cx.update(|window, cx| window.dispatch_action(Box::new(crate::clip::CopyMarkdown), cx));
|
||||
cx.run_until_parked();
|
||||
assert_eq!(clipboard(cx).as_deref(), Some("alpha *it*\n"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_later_editor_copy_outlives_a_pending_conversion(cx: &mut TestAppContext) {
|
||||
use gpui::Focusable as _;
|
||||
let (desk, cx, _files) = opened("alpha *it*\n", cx);
|
||||
switch(&desk, Mode::Source, cx);
|
||||
let editor = document(&desk, cx).read_with(cx, |document, _| document.editor().clone());
|
||||
editor.update(cx, |editor, cx| editor.select(std::iter::once(0..5), cx));
|
||||
let focus = editor.read_with(cx, |editor, cx| editor.focus_handle(cx));
|
||||
cx.update(|window, cx| window.focus(&focus, cx));
|
||||
cx.run_until_parked();
|
||||
cx.update(|window, cx| window.dispatch_action(Box::new(crate::export::CopyHtml), cx));
|
||||
let copy = gpui::Keystroke::parse("secondary-c").expect("key");
|
||||
cx.update(|window, cx| window.dispatch_keystroke(copy, cx));
|
||||
cx.run_until_parked();
|
||||
assert_eq!(clipboard(cx).as_deref(), Some("alpha"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_later_rich_copy_with_the_same_text_outlives_a_pending_conversion(cx: &mut TestAppContext) {
|
||||
use ely_platform::clipboard::{self, Clip};
|
||||
if std::env::var_os("ELY_CLIPBOARD_TEST").is_none() {
|
||||
eprintln!("SKIP: set ELY_CLIPBOARD_TEST=1; this replaces the clipboard");
|
||||
return;
|
||||
}
|
||||
let rich = |html: &str| Clip::Html {
|
||||
html: html.into(),
|
||||
text: "x".into(),
|
||||
};
|
||||
let (_desk, cx, _files) = opened("alpha *it*\n", cx);
|
||||
clipboard::write(&rich("<b>x</b>")).expect("writes");
|
||||
cx.write_to_clipboard(gpui::ClipboardItem::new_string("x".into()));
|
||||
cx.update(|window, cx| window.dispatch_action(Box::new(crate::export::CopyHtml), cx));
|
||||
clipboard::write(&rich("<i>x</i>")).expect("writes");
|
||||
cx.run_until_parked();
|
||||
let html = clipboard::html().expect("reads");
|
||||
assert_eq!(
|
||||
clipboard(cx).as_deref(),
|
||||
Some("x"),
|
||||
"the conversion is dropped"
|
||||
);
|
||||
assert!(html.is_some_and(|html| html.contains("<i>x</i>")));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_shut_menu_stays_shut_when_its_tab_returns(cx: &mut TestAppContext) {
|
||||
let (desk, cx, files) = opened("alpha\n", cx);
|
||||
right_on(0, 1, cx);
|
||||
assert!(cx.debug_bounds("menu-button-0-0").is_some(), "opened");
|
||||
cx.simulate_keystrokes("escape");
|
||||
cx.run_until_parked();
|
||||
assert!(cx.debug_bounds("menu-button-0-0").is_none(), "shut");
|
||||
let other = files[1].path().join("b.md");
|
||||
std::fs::write(&other, "beta\n").expect("b");
|
||||
crate::desk::tests::open(&desk, &other, cx);
|
||||
let first = desk.read_with(cx, |desk, _| desk.core.tabs[0].id);
|
||||
desk.update(cx, |desk, cx| {
|
||||
desk.core.active = Some(first);
|
||||
cx.notify();
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert!(cx.debug_bounds("menu-button-0-0").is_none(), "not replayed");
|
||||
}
|
||||
@@ -6,7 +6,6 @@ use gpui::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
blocks::shifted,
|
||||
desk::{
|
||||
Desk,
|
||||
tests::{open, start},
|
||||
@@ -83,9 +82,9 @@ fn paragraph_keys_retype_the_caret_block(cx: &mut TestAppContext) {
|
||||
assert_eq!(current(&desk, cx), "# Intro\n");
|
||||
press("secondary-0", cx);
|
||||
assert_eq!(current(&desk, cx), "Intro\n");
|
||||
press(&shifted("secondary", '[', '{'), cx);
|
||||
press("secondary-{", cx);
|
||||
assert_eq!(current(&desk, cx), "1. Intro\n");
|
||||
press(&shifted("secondary", ']', '}'), cx);
|
||||
press("secondary-}", cx);
|
||||
assert_eq!(current(&desk, cx), "- Intro\n");
|
||||
press("secondary-shift-q", cx);
|
||||
assert_eq!(
|
||||
@@ -102,7 +101,7 @@ fn format_keys_wrap_the_caret_word(cx: &mut TestAppContext) {
|
||||
assert_eq!(current(&desk, cx), "**word**\n");
|
||||
press("secondary-\\", cx);
|
||||
assert_eq!(current(&desk, cx), "word\n");
|
||||
press(&shifted("alt", '5', '%'), cx);
|
||||
press("alt-%", cx);
|
||||
assert_eq!(current(&desk, cx), "~~word~~\n");
|
||||
}
|
||||
|
||||
@@ -144,10 +143,10 @@ fn alt_arrows_move_a_table_row(cx: &mut TestAppContext) {
|
||||
#[gpui::test]
|
||||
fn view_keys_follow_typora(cx: &mut TestAppContext) {
|
||||
let (desk, cx, _files) = opened("a\n", cx);
|
||||
press(&format!("f8 f9 {}", shifted("secondary", '=', '+')), cx);
|
||||
press("f8 f9 secondary-+", cx);
|
||||
let look = desk.read_with(cx, |desk, _| desk.look.clone());
|
||||
assert!(look.focus && look.typewriter && look.size > 100, "{look:?}");
|
||||
press(&shifted("secondary", '0', ')'), cx);
|
||||
press("secondary-)", cx);
|
||||
assert_eq!(desk.read_with(cx, |desk, _| desk.look.size), 100);
|
||||
}
|
||||
|
||||
@@ -284,14 +283,14 @@ fn every_command_takes_typoras_windows_key(cx: &mut TestAppContext) {
|
||||
(&MathBlock, "ctrl-shift-m"),
|
||||
(&CodeFences, "ctrl-shift-k"),
|
||||
(&Quote, "ctrl-shift-q"),
|
||||
(&OrderedList, "ctrl-shift-["),
|
||||
(&BulletList, "ctrl-shift-]"),
|
||||
(&OrderedList, "ctrl-{"),
|
||||
(&BulletList, "ctrl-}"),
|
||||
(&TaskList, "ctrl-shift-x"),
|
||||
(&Strong, "ctrl-b"),
|
||||
(&Emphasis, "ctrl-i"),
|
||||
(&Underline, "ctrl-u"),
|
||||
(&InlineCode, "ctrl-shift-`"),
|
||||
(&Strike, "alt-shift-5"),
|
||||
(&InlineCode, "ctrl-~"),
|
||||
(&Strike, "alt-%"),
|
||||
(&Hyperlink, "ctrl-k"),
|
||||
(&InsertImage, "ctrl-shift-i"),
|
||||
(&ClearFormat, "ctrl-\\"),
|
||||
@@ -305,9 +304,9 @@ fn every_command_takes_typoras_windows_key(cx: &mut TestAppContext) {
|
||||
(&ToggleSource, "ctrl-/"),
|
||||
(&look::FocusMode, "f8"),
|
||||
(&look::Typewriter, "f9"),
|
||||
(&look::Larger, "ctrl-shift-="),
|
||||
(&look::Smaller, "ctrl-shift--"),
|
||||
(&look::ActualSize, "ctrl-shift-0"),
|
||||
(&look::Larger, "ctrl-+"),
|
||||
(&look::Smaller, "ctrl-_"),
|
||||
(&look::ActualSize, "ctrl-("),
|
||||
(&CopyMarkdown, "ctrl-shift-c"),
|
||||
(&PastePlain, "ctrl-shift-v"),
|
||||
];
|
||||
|
||||
@@ -56,6 +56,8 @@ pub struct Desk {
|
||||
asked_print: Option<ely_files::Fingerprint>,
|
||||
/// The find box, while open.
|
||||
pub(crate) finding: Option<crate::finding::Find>,
|
||||
/// The copy being converted; a newer one drops it.
|
||||
pub(crate) copying: Option<gpui::Task<()>>,
|
||||
}
|
||||
|
||||
impl Host for Desk {
|
||||
@@ -205,6 +207,7 @@ pub(crate) fn open_in(
|
||||
asked: None,
|
||||
asked_print: None,
|
||||
finding: None,
|
||||
copying: None,
|
||||
}
|
||||
});
|
||||
let menus = crate::keys::menus(&look, cx);
|
||||
@@ -224,7 +227,12 @@ pub(crate) fn open_in(
|
||||
// Launch files stand alone; unsaved text still returns.
|
||||
if asked.is_empty() {
|
||||
for path in kept {
|
||||
// A restored tab does not rejoin the recent list.
|
||||
let (id, real) = (desk.core.next, dunce::canonicalize(&path).ok());
|
||||
desk.open_path(path, cx);
|
||||
if let Some(real) = real.filter(|_| desk.core.next > id) {
|
||||
desk.remembered.insert(id, real);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (at, name) in desk.keeping.untitled() {
|
||||
|
||||
@@ -82,6 +82,26 @@ fn a_file_opens_with_its_outline_and_joins_the_recent_list(cx: &mut TestAppConte
|
||||
assert!(!kept.contains(r"\\\\?\\"), "plain paths only: {kept}");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_recent_list_clears_from_its_button(cx: &mut TestAppContext) {
|
||||
let (data, files) = (
|
||||
tempfile::tempdir().expect("data"),
|
||||
tempfile::tempdir().expect("files"),
|
||||
);
|
||||
let path = files.path().join("a.md");
|
||||
std::fs::write(&path, "Text.\n").expect("a file");
|
||||
let (desk, cx) = start(cx, data.path());
|
||||
open(&desk, &path, cx);
|
||||
assert!(desk.read_with(cx, |desk, _| !desk.recent.is_empty()));
|
||||
let button = cx.debug_bounds("mark-clear-recent").expect("the button");
|
||||
cx.simulate_click(button.center(), gpui::Modifiers::none());
|
||||
cx.run_until_parked();
|
||||
assert!(desk.read_with(cx, |desk, _| desk.recent.is_empty()));
|
||||
let kept = std::fs::read_to_string(data.path().join("recent.json")).expect("the list");
|
||||
assert_eq!(kept, "[]");
|
||||
assert!(cx.debug_bounds("mark-clear-recent").is_none(), "nothing left to clear");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_outline_follows_typing(cx: &mut TestAppContext) {
|
||||
let (data, files) = (
|
||||
|
||||
@@ -9,15 +9,30 @@ use ely_ui::i18n::text;
|
||||
use gpui::{ClipboardItem, Context, Div, InteractiveElement as _, actions};
|
||||
|
||||
use crate::desk::Desk;
|
||||
use crate::output::{self, Pictures};
|
||||
use crate::output::{self, Page, Pictures};
|
||||
|
||||
actions!(mark, [CopyRich, CopyHtml, CopyPlain]);
|
||||
|
||||
/// What a copy turns the Markdown into.
|
||||
#[derive(Clone, Copy)]
|
||||
enum As {
|
||||
Rich,
|
||||
Html,
|
||||
Plain,
|
||||
}
|
||||
|
||||
/// A converted copy, ready for the clipboard.
|
||||
enum Copied {
|
||||
Rich(Clip, Page),
|
||||
Html(String, Page),
|
||||
Plain(String),
|
||||
}
|
||||
|
||||
impl Desk {
|
||||
pub(super) fn copy_actions(root: Div, cx: &mut Context<Self>) -> Div {
|
||||
root.on_action(cx.listener(|desk, _: &CopyRich, _, cx| desk.copy_rich(cx)))
|
||||
.on_action(cx.listener(|desk, _: &CopyHtml, _, cx| desk.copy_html(cx)))
|
||||
.on_action(cx.listener(|desk, _: &CopyPlain, _, cx| desk.copy_plain(cx)))
|
||||
root.on_action(cx.listener(|desk, _: &CopyRich, _, cx| desk.copy(As::Rich, cx)))
|
||||
.on_action(cx.listener(|desk, _: &CopyHtml, _, cx| desk.copy(As::Html, cx)))
|
||||
.on_action(cx.listener(|desk, _: &CopyPlain, _, cx| desk.copy(As::Plain, cx)))
|
||||
}
|
||||
|
||||
/// The selection or whole text, and the file's folder.
|
||||
@@ -44,52 +59,78 @@ impl Desk {
|
||||
self.toast(said, Severity::Danger, cx);
|
||||
}
|
||||
|
||||
/// HTML for pasting, the Markdown beside it.
|
||||
fn copy_rich(&mut self, cx: &mut Context<Self>) {
|
||||
/// Converts in the background, then writes the clipboard.
|
||||
fn copy(&mut self, kind: As, cx: &mut Context<Self>) {
|
||||
let Some((markdown, beside)) = self.copied_text(cx) else {
|
||||
return;
|
||||
};
|
||||
let copied =
|
||||
output::body(&markdown, beside.as_deref(), &Pictures::Inline).and_then(|mut page| {
|
||||
let clip = Clip::Html {
|
||||
html: std::mem::take(&mut page.html),
|
||||
text: markdown,
|
||||
};
|
||||
clipboard::write(&clip)
|
||||
.map(|()| page)
|
||||
.map_err(|error| std::io::Error::other(format!("{error:#}")))
|
||||
let before = witness(cx);
|
||||
self.copying = Some(cx.spawn(async move |desk, cx| {
|
||||
let converted = cx
|
||||
.background_executor()
|
||||
.spawn(async move { convert(kind, markdown, beside) })
|
||||
.await;
|
||||
let landed = desk.update(cx, |desk, cx| {
|
||||
desk.copying = None;
|
||||
// A later copy, here or elsewhere, wins.
|
||||
if witness(cx) != before {
|
||||
return log::info!("mark: the clipboard changed first; a copy is dropped");
|
||||
}
|
||||
desk.copied(converted, cx);
|
||||
});
|
||||
match copied {
|
||||
Ok(page) => self.left_out(&page, cx),
|
||||
Err(error) => self.copy_failed(&error, cx),
|
||||
}
|
||||
}
|
||||
|
||||
/// The HTML as text; pictures keep their addresses.
|
||||
fn copy_html(&mut self, cx: &mut Context<Self>) {
|
||||
let Some((markdown, beside)) = self.copied_text(cx) else {
|
||||
return;
|
||||
};
|
||||
match output::body(&markdown, beside.as_deref(), &Pictures::Written) {
|
||||
Ok(mut page) => {
|
||||
log::info!("mark: {} bytes copied as HTML code", page.html.len());
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(std::mem::take(&mut page.html)));
|
||||
self.left_out(&page, cx);
|
||||
if landed.is_err() {
|
||||
log::warn!("mark: a copy finished after its window closed");
|
||||
}
|
||||
Err(error) => self.copy_failed(&error, cx),
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
fn copy_plain(&mut self, cx: &mut Context<Self>) {
|
||||
let Some((markdown, _)) = self.copied_text(cx) else {
|
||||
return;
|
||||
};
|
||||
match output::plain(&markdown) {
|
||||
Ok(plain) => {
|
||||
fn copied(&mut self, converted: std::io::Result<Copied>, cx: &mut Context<Self>) {
|
||||
let written = converted.and_then(|copied| match copied {
|
||||
Copied::Rich(clip, page) => clipboard::write(&clip)
|
||||
.map(|()| Some(page))
|
||||
.map_err(|error| std::io::Error::other(format!("{error:#}"))),
|
||||
Copied::Html(html, page) => {
|
||||
log::info!("mark: {} bytes copied as HTML code", html.len());
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(html));
|
||||
Ok(Some(page))
|
||||
}
|
||||
Copied::Plain(plain) => {
|
||||
log::info!("mark: {} bytes copied as plain text", plain.len());
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(plain));
|
||||
Ok(None)
|
||||
}
|
||||
});
|
||||
match written {
|
||||
Ok(Some(page)) => self.left_out(&page, cx),
|
||||
Ok(None) => {}
|
||||
Err(error) => self.copy_failed(&error, cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the clipboard holds, its HTML included.
|
||||
fn witness(cx: &mut Context<Desk>) -> (Option<ClipboardItem>, Result<Option<String>, String>) {
|
||||
let html = clipboard::html().map_err(|error| {
|
||||
log::warn!("mark: the clipboard's HTML did not read: {error:#}");
|
||||
format!("{error:#}")
|
||||
});
|
||||
(cx.read_from_clipboard(), html)
|
||||
}
|
||||
|
||||
/// The copy as `kind`, converted off the window thread.
|
||||
fn convert(kind: As, markdown: String, beside: Option<PathBuf>) -> std::io::Result<Copied> {
|
||||
let beside = beside.as_deref();
|
||||
match kind {
|
||||
As::Rich => output::body(&markdown, beside, &Pictures::Inline).map(|mut page| {
|
||||
let html = std::mem::take(&mut page.html);
|
||||
let clip = Clip::Html {
|
||||
html,
|
||||
text: markdown,
|
||||
};
|
||||
Copied::Rich(clip, page)
|
||||
}),
|
||||
As::Html => output::body(&markdown, beside, &Pictures::Written)
|
||||
.map(|mut page| Copied::Html(std::mem::take(&mut page.html), page)),
|
||||
As::Plain => output::plain(&markdown).map(Copied::Plain),
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,7 @@ fn rich_copy_takes_the_selection_as_html(cx: &mut TestAppContext) {
|
||||
.update(cx, |editor, cx| editor.select(std::iter::once(8..22), cx))
|
||||
});
|
||||
cx.dispatch_action(crate::export::CopyRich);
|
||||
cx.run_until_parked();
|
||||
let clip = ely_platform::clipboard::read()
|
||||
.expect("reads")
|
||||
.expect("a clip");
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use ely_ui::{commands, i18n::text};
|
||||
use gpui::{Action, App, Context, InteractiveElement as _, KeyBinding, Menu, MenuItem, actions};
|
||||
|
||||
use crate::{blocks::shifted, desk::Desk, view::Mode};
|
||||
use crate::{desk::Desk, view::Mode};
|
||||
|
||||
actions!(
|
||||
mark,
|
||||
@@ -18,11 +18,14 @@ pub fn bind(cx: &mut App) {
|
||||
KeyBinding::new("secondary-/", ToggleSource, Some("ElyEditor")),
|
||||
KeyBinding::new("f8", crate::look::FocusMode, at),
|
||||
KeyBinding::new("f9", crate::look::Typewriter, at),
|
||||
KeyBinding::new(&shifted("secondary", '=', '+'), crate::look::Larger, at),
|
||||
KeyBinding::new(&shifted("secondary", '-', '_'), crate::look::Smaller, at),
|
||||
KeyBinding::new(&shifted("secondary", '0', ')'), crate::look::ActualSize, at),
|
||||
KeyBinding::new("secondary-+", crate::look::Larger, at),
|
||||
KeyBinding::new("secondary-_", crate::look::Smaller, at),
|
||||
KeyBinding::new("secondary-)", crate::look::ActualSize, at),
|
||||
KeyBinding::new("secondary-f", ely_office::FindReplace, at),
|
||||
]);
|
||||
// Windows' Chinese input keeps Ctrl+Shift+0 for itself.
|
||||
#[cfg(target_os = "windows")]
|
||||
cx.bind_keys([KeyBinding::new("ctrl-(", crate::look::ActualSize, at)]);
|
||||
crate::blocks::bind(cx);
|
||||
crate::tools::bind(cx);
|
||||
crate::clip::bind(cx);
|
||||
|
||||
@@ -28,7 +28,7 @@ pub(super) fn write(
|
||||
placed,
|
||||
page,
|
||||
source,
|
||||
reader: MarkdownReader::new(source, tree),
|
||||
reader: MarkdownReader::joined(source, tree),
|
||||
anchored: HashSet::new(),
|
||||
};
|
||||
writer.root(tree)
|
||||
|
||||
@@ -11,7 +11,7 @@ use markdown::mdast::Node;
|
||||
pub fn plain(text: &str) -> io::Result<String> {
|
||||
let tree = markdown::to_mdast(text, &markdown_options())
|
||||
.map_err(|error| io::Error::other(error.to_string()))?;
|
||||
let reader = MarkdownReader::new(text, &tree);
|
||||
let reader = MarkdownReader::joined(text, &tree);
|
||||
let mut blocks = Vec::new();
|
||||
// Alerts and `[toc]` live only at the root.
|
||||
for child in tree.children().into_iter().flatten() {
|
||||
|
||||
@@ -230,3 +230,10 @@ fn a_copied_fragment_carries_its_look() {
|
||||
"the look needs no page style: {page}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soft_break_joins_in_exports_as_typora_exports_it() {
|
||||
let page = html("你好\n测试 \nend\n");
|
||||
assert!(page.contains("<p>你好 测试<br>end</p>"), "{page}");
|
||||
assert_eq!(text("你好\n测试\n"), "你好 测试\n");
|
||||
}
|
||||
@@ -13,9 +13,14 @@ use crate::folder::{Folder, markdown_under};
|
||||
impl Desk {
|
||||
/// A folder lists beside; a file opens in a tab.
|
||||
pub fn open_path(&mut self, path: PathBuf, cx: &mut Context<Self>) {
|
||||
match path.is_dir() {
|
||||
true => self.open_folder(path, cx),
|
||||
false => self.open_file(path, cx),
|
||||
if path.is_dir() {
|
||||
return self.open_folder(path, cx);
|
||||
}
|
||||
// A shown file only takes focus; the list still learns.
|
||||
let shown = self.core.sessions.is_open(&path).unwrap_or(false);
|
||||
self.open_file(path.clone(), cx);
|
||||
if shown {
|
||||
self.remember(&path, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +113,22 @@ impl Desk {
|
||||
}
|
||||
}
|
||||
|
||||
/// Empties the recent list.
|
||||
pub fn clear_recent(&mut self, cx: &mut Context<Self>) {
|
||||
match ely_files::recent::clear(&self.recent_file) {
|
||||
Ok(()) => {
|
||||
log::info!("mark: the recent list is cleared");
|
||||
self.recent.clear();
|
||||
cx.notify();
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("mark: the recent list did not clear: {error}");
|
||||
let said = text(cx, "office.error.engine", &[("error", &error.to_string())]);
|
||||
self.toast(said, Severity::Danger, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Line and column `at` in a tab or file.
|
||||
pub fn open_at(
|
||||
&mut self,
|
||||
|
||||
@@ -441,4 +441,50 @@ mod window {
|
||||
"the session"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_cleared_recent_list_stays_cleared_with_tabs_restored(
|
||||
first: &mut TestAppContext,
|
||||
second: &mut TestAppContext,
|
||||
) {
|
||||
let (data, files) = (
|
||||
tempfile::tempdir().expect("data"),
|
||||
tempfile::tempdir().expect("files"),
|
||||
);
|
||||
let (a, b) = (files.path().join("a.md"), files.path().join("b.md"));
|
||||
std::fs::write(&a, "A
|
||||
").expect("a");
|
||||
std::fs::write(&b, "B
|
||||
").expect("b");
|
||||
let (desk, cx) = start(first, data.path());
|
||||
open(&desk, &a, cx);
|
||||
let button = cx.debug_bounds("mark-clear-recent").expect("the button");
|
||||
cx.simulate_click(button.center(), gpui::Modifiers::none());
|
||||
cx.run_until_parked();
|
||||
desk.update(cx, |desk, cx| {
|
||||
desk.leave(cx);
|
||||
desk.keeping.close();
|
||||
});
|
||||
cx.run_until_parked();
|
||||
|
||||
let (desk, cx) = start(second, data.path());
|
||||
assert_eq!(names(&desk, cx), ["a.md"]);
|
||||
assert!(desk.read_with(cx, |desk, _| desk.recent.is_empty()));
|
||||
let list = data.path().join("recent.json");
|
||||
assert_eq!(std::fs::read_to_string(&list).expect("the list"), "[]");
|
||||
// Explicit opens still join it: the restored file, a link.
|
||||
let alias = files.path().join("alias.md");
|
||||
std::fs::hard_link(&a, &alias).expect("a hard link");
|
||||
open(&desk, &a, cx);
|
||||
open(&desk, &alias, cx);
|
||||
open(&desk, &b, cx);
|
||||
assert_eq!(names(&desk, cx), ["a.md", "b.md"]);
|
||||
let real = |path: &std::path::Path| dunce::canonicalize(path).expect("real");
|
||||
let want = [real(&b), real(&alias), real(&a)];
|
||||
assert_eq!(desk.read_with(cx, |desk, _| desk.recent.clone()), want);
|
||||
let kept: Vec<std::path::PathBuf> =
|
||||
serde_json::from_str(&std::fs::read_to_string(&list).expect("the list"))
|
||||
.expect("a list");
|
||||
assert_eq!(kept, want);
|
||||
}
|
||||
}
|
||||
+27
-10
@@ -200,7 +200,7 @@ impl Side {
|
||||
.action(open)
|
||||
.into_any_element();
|
||||
}
|
||||
let opener = desk.downgrade();
|
||||
let (opener, clearer) = (desk.downgrade(), desk.downgrade());
|
||||
let rows = read.recent.iter().map(|path| {
|
||||
let name = path
|
||||
.file_name()
|
||||
@@ -214,15 +214,32 @@ impl Side {
|
||||
);
|
||||
(key, item)
|
||||
});
|
||||
rows.fold(
|
||||
SelectableList::new("mark-recent").label(text(cx, "mark.recent", &[])),
|
||||
|list, (key, item)| list.row(key, item),
|
||||
)
|
||||
.on_activate(move |key, _, cx| {
|
||||
let path = PathBuf::from(key.as_ref());
|
||||
opener.update(cx, |desk, cx| desk.open_path(path, cx)).ok();
|
||||
})
|
||||
.into_any_element()
|
||||
let list = rows
|
||||
.fold(
|
||||
SelectableList::new("mark-recent").label(text(cx, "mark.recent", &[])),
|
||||
|list, (key, item)| list.row(key, item),
|
||||
)
|
||||
.on_activate(move |key, _, cx| {
|
||||
let path = PathBuf::from(key.as_ref());
|
||||
opener.update(cx, |desk, cx| desk.open_path(path, cx)).ok();
|
||||
});
|
||||
let clear = Button::new("mark-clear-recent", text(cx, "mark.recent.clear", &[]))
|
||||
.size(ControlSize::Sm)
|
||||
.on_click(move |_, _, cx| {
|
||||
clearer.update(cx, |desk, cx| desk.clear_recent(cx)).ok();
|
||||
});
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_2()
|
||||
.size_full()
|
||||
.child(div().flex_1().min_h_0().child(list))
|
||||
.child(
|
||||
div()
|
||||
.debug_selector(|| "mark-clear-recent".into())
|
||||
.child(clear),
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn outline(&self, desk: &Entity<Desk>, cx: &mut Context<Self>) -> AnyElement {
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::{io, path::Path};
|
||||
|
||||
use ely_gpui_component::{primitives::Severity, shell::StatusBarItem};
|
||||
use ely_office::prelude::*;
|
||||
use ely_platform::AppId;
|
||||
use ely_platform::{AppId, git::NoGit};
|
||||
use ely_ui::i18n::text;
|
||||
use gpui::Context;
|
||||
|
||||
@@ -20,15 +20,22 @@ pub enum Tracked {
|
||||
Untracked,
|
||||
Ignored,
|
||||
Conflicted,
|
||||
/// Ely's Git sits beside ElyTree, which is not installed.
|
||||
NoGit,
|
||||
/// Git could not answer; why.
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
/// Git's word on `file`: in a repository, then its status.
|
||||
pub fn ask(file: &Path) -> Tracked {
|
||||
match status(file) {
|
||||
Ok(tracked) => tracked,
|
||||
Err(error) => Tracked::Unknown(error.to_string()),
|
||||
status(file).unwrap_or_else(failed)
|
||||
}
|
||||
|
||||
/// A failure: no Git at all, else why.
|
||||
fn failed(error: io::Error) -> Tracked {
|
||||
match error.get_ref().is_some_and(|inner| inner.is::<NoGit>()) {
|
||||
true => Tracked::NoGit,
|
||||
false => Tracked::Unknown(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,6 +126,16 @@ impl Desk {
|
||||
Tracked::Untracked => "mark.git.untracked",
|
||||
Tracked::Ignored => "mark.git.ignored",
|
||||
Tracked::Conflicted => "mark.git.conflicted",
|
||||
Tracked::NoGit => {
|
||||
let this = cx.entity();
|
||||
let item = StatusBarItem::new("mark-git")
|
||||
.label(text(cx, "mark.git.none", &[]))
|
||||
.tooltip(text(cx, "mark.git.needs", &[]));
|
||||
return Some(item.on_click(move |_, _, cx| {
|
||||
let said = text(cx, "mark.git.needs", &[]);
|
||||
this.update(cx, |desk, cx| desk.toast(said, Severity::Warning, cx));
|
||||
}));
|
||||
}
|
||||
Tracked::Unknown(why) => {
|
||||
let label = text(cx, "mark.git.unknown", &[]);
|
||||
return Some(
|
||||
@@ -172,6 +189,14 @@ mod tests {
|
||||
assert!(done.expect("git runs").status.success(), "git {args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_git_asks_for_elytree_and_other_failures_say_why() {
|
||||
let missing = io::Error::new(io::ErrorKind::NotFound, NoGit);
|
||||
assert_eq!(failed(missing), Tracked::NoGit);
|
||||
let other = io::Error::new(io::ErrorKind::NotFound, "gone");
|
||||
assert_eq!(failed(other), Tracked::Unknown("gone".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaces_stay_and_broken_repositories_say_why() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
|
||||
@@ -90,16 +90,14 @@ impl MarkView {
|
||||
true => "mark.image.browser",
|
||||
false => "mark.image.location",
|
||||
};
|
||||
let view = view.clone();
|
||||
let (shown, dropped, at) = (view.clone(), view.clone(), target.at);
|
||||
rows =
|
||||
rows.row(MenuItem::new(said(key, cx)).on_click(move |_, cx| {
|
||||
view.update(cx, |view, cx| view.show_picture(&url, cx))
|
||||
shown.update(cx, |view, cx| view.show_picture(&url, cx))
|
||||
}))
|
||||
.row(MenuItem::new(said("mark.image.delete", cx)).on_click(move |_, cx| {
|
||||
dropped.update(cx, |view, cx| view.delete_image(at, cx))
|
||||
}))
|
||||
.row(run(
|
||||
said("mark.image.delete", cx),
|
||||
Box::new(b::DeleteImage),
|
||||
window,
|
||||
))
|
||||
.line();
|
||||
}
|
||||
if let Some(url) = &target.link {
|
||||
@@ -162,6 +160,14 @@ impl MarkView {
|
||||
rows.menu()
|
||||
}
|
||||
|
||||
/// Deletes the picture at byte `at`, or says why not.
|
||||
fn delete_image(&mut self, at: usize, cx: &mut Context<Self>) {
|
||||
let deleted = (self.document).update(cx, |document, cx| document.delete_image(at, cx));
|
||||
if let Err(why) = deleted {
|
||||
cx.emit(super::Refused(why));
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a local picture's file, or opens a web one.
|
||||
fn show_picture(&mut self, url: &str, cx: &mut Context<Self>) {
|
||||
if web(url) {
|
||||
|
||||
@@ -95,7 +95,10 @@ impl Host for Deck {
|
||||
&& !tab.extra.fitted
|
||||
{
|
||||
tab.extra.fitted = true;
|
||||
view.update(cx, |view, cx| view.fit_page(cx));
|
||||
view.update(cx, |view, cx| {
|
||||
view.fit_page(cx);
|
||||
view.turn_parts();
|
||||
});
|
||||
}
|
||||
// Pictures follow the kernel's light or dark scheme.
|
||||
let dark = view.read(cx).dark();
|
||||
@@ -263,7 +266,12 @@ impl Deck {
|
||||
Ok(((slides, at), (design, objects, notes, remarks, (motion, media)), size, history)) => {
|
||||
tab.extra.read_at = Some(at);
|
||||
log::info!("show: tab {id} has {} parts", slides.list.len());
|
||||
view.update(cx, |view, _| view.set_part(slides.current));
|
||||
// A queued turn or part outranks an earlier read.
|
||||
view.update(cx, |view, _| {
|
||||
if view.settled() {
|
||||
view.set_part(slides.current)
|
||||
}
|
||||
});
|
||||
let names: HashSet<&String> =
|
||||
slides.list.iter().map(|slide| &slide.name).collect();
|
||||
tab.extra.keep_pictures(&names);
|
||||
|
||||
@@ -19,6 +19,7 @@ mod play_time;
|
||||
mod review;
|
||||
mod slides;
|
||||
mod strip;
|
||||
mod turn;
|
||||
|
||||
/// An unrendered Deck over a fresh worker, if LOK exists.
|
||||
pub(super) fn deck(cx: &mut TestAppContext, dir: &Path) -> Option<Entity<Deck>> {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
use ely_lok::LokView;
|
||||
use ely_office::prelude::*;
|
||||
use gpui::{Entity, ScrollDelta, ScrollWheelEvent, TestAppContext, VisualTestContext, point};
|
||||
|
||||
use super::objects::{blank, selection};
|
||||
use super::{counts, quiet, settle, update};
|
||||
use crate::deck::Deck;
|
||||
|
||||
/// The slide canvas alone in a window.
|
||||
struct Host(Entity<LokView>);
|
||||
|
||||
impl gpui::Render for Host {
|
||||
fn render(&mut self, _: &mut gpui::Window, _: &mut gpui::Context<Self>) -> impl gpui::IntoElement {
|
||||
use gpui::{ParentElement as _, Styled as _};
|
||||
gpui::div().size_full().child(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// The current slide once every turn landed.
|
||||
fn current(shown: &mut VisualTestContext, deck: &Entity<Deck>) -> usize {
|
||||
quiet(shown, deck);
|
||||
shown.update(|_, app| deck.read(app).active_tab().map(|tab| tab.extra.slides.current).expect("a tab"))
|
||||
}
|
||||
|
||||
/// Whole notches, in this platform's lines.
|
||||
fn wheel(shown: &mut VisualTestContext, notches: f32) {
|
||||
let middle = shown.update(|window, _| window.viewport_size()).center();
|
||||
let delta = ScrollDelta::Lines(point(0.0, notches * ely_lok::notch()));
|
||||
shown.simulate_event(ScrollWheelEvent { position: middle.into(), delta, ..Default::default() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wheel_and_up_down_turn_slides() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let mut cx = TestAppContext::single();
|
||||
let Some(deck) = blank(&mut cx, dir.path()) else {
|
||||
return eprintln!("SKIP: no LOK build");
|
||||
};
|
||||
for n in 2..=3 {
|
||||
update(&mut cx, &deck, |deck, cx| deck.object_command("slide.insert", &[], cx));
|
||||
settle(&cx, |app| counts(app, &deck).0 == n);
|
||||
}
|
||||
let view = cx.update(|app| deck.read(app).active_tab().expect("a tab").view.clone());
|
||||
cx.update(|app| view.update(app, |view, _| view.show_part(0)));
|
||||
let window = cx.add_window(|_, _| Host(view.clone()));
|
||||
let mut shown = VisualTestContext::from_window(window.into(), &cx);
|
||||
shown.run_until_parked();
|
||||
assert_eq!(current(&mut shown, &deck), 0);
|
||||
wheel(&mut shown, -2.0);
|
||||
assert_eq!(current(&mut shown, &deck), 2, "two notches in one event turn two");
|
||||
wheel(&mut shown, 1.0);
|
||||
wheel(&mut shown, 1.0);
|
||||
assert_eq!(current(&mut shown, &deck), 0, "rapid notches each turn");
|
||||
wheel(&mut shown, -1.0);
|
||||
assert_eq!(current(&mut shown, &deck), 1, "the wheel turns down");
|
||||
shown.update(|window, app| {
|
||||
let focus = view.read(app).focus_handle().clone();
|
||||
window.focus(&focus, app)
|
||||
});
|
||||
shown.simulate_keystrokes("down");
|
||||
assert_eq!(current(&mut shown, &deck), 2, "Down turns");
|
||||
shown.simulate_keystrokes("down");
|
||||
assert_eq!(current(&mut shown, &deck), 2, "the last slide stays");
|
||||
shown.simulate_keystrokes("up");
|
||||
assert_eq!(current(&mut shown, &deck), 1, "Up turns back");
|
||||
wheel(&mut shown, 1.0);
|
||||
assert_eq!(current(&mut shown, &deck), 0, "the wheel turns up");
|
||||
// Down queued behind Tab moves the object Tab picks.
|
||||
shown.simulate_keystrokes("tab down");
|
||||
assert_eq!(current(&mut shown, &deck), 0, "Down after Tab moves, not turns");
|
||||
assert!(shown.update(|_, app| selection(app, &deck)).is_some(), "Tab picked an object");
|
||||
// A turn lands before the keys queued after it.
|
||||
shown.simulate_keystrokes("escape down tab down");
|
||||
assert_eq!(current(&mut shown, &deck), 1, "Down turns, then moves");
|
||||
assert!(shown.update(|_, app| selection(app, &deck)).is_some(), "Tab picked on the new slide");
|
||||
}
|
||||
@@ -64,7 +64,9 @@ fn a_failed_print_says_printing_failed() {
|
||||
.expect("the window");
|
||||
let gone = dir.path().join("gone.pdf");
|
||||
update(&mut cx, &book, |_, cx| ely_office::print_later(gone, cx));
|
||||
cx.run_until_parked();
|
||||
let (toasts, prefix) = cx.update(|app| (root.read(app).toasts(app), ely_office::text(app, "office.print.failed", &[("error", "")])));
|
||||
assert!(toasts.iter().any(|(text, severity)| *severity == Some(Severity::Danger) && text.starts_with(prefix.as_ref())), "{toasts:?}");
|
||||
// The file is read on its own thread.
|
||||
settle(&cx, |app| {
|
||||
let prefix = ely_office::text(app, "office.print.failed", &[("error", "")]);
|
||||
root.read(app).toasts(app).iter().any(|(text, severity)| *severity == Some(Severity::Danger) && text.starts_with(prefix.as_ref()))
|
||||
});
|
||||
}
|
||||
@@ -39,6 +39,14 @@ pub fn forget(file: &Path, root: &Path) -> io::Result<()> {
|
||||
.map(drop)
|
||||
}
|
||||
|
||||
/// Empties the list.
|
||||
pub fn clear(file: &Path) -> io::Result<()> {
|
||||
if let Some(dir) = file.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
crate::save_atomic(file, b"[]", 0).map(drop)
|
||||
}
|
||||
|
||||
/// Puts `root` first in the list and writes it.
|
||||
pub fn remember(file: &Path, root: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let mut list = recent(file)?;
|
||||
@@ -60,7 +68,7 @@ pub fn remember(file: &Path, root: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{forget, recent, remember};
|
||||
use super::{clear, forget, recent, remember};
|
||||
|
||||
#[test]
|
||||
fn the_list_puts_the_newest_first_and_keeps_twenty() {
|
||||
@@ -82,6 +90,8 @@ mod tests {
|
||||
let plain = [PathBuf::from(r"C:\r\old"), PathBuf::from(r"C:\r\new")];
|
||||
assert_eq!(recent(&file).expect("reads"), plain);
|
||||
}
|
||||
clear(&file).expect("clears");
|
||||
assert!(recent(&file).expect("reads").is_empty());
|
||||
std::fs::write(&file, "not json").expect("writes");
|
||||
assert!(
|
||||
remember(&file, Path::new("/r/1")).is_err(),
|
||||
|
||||
@@ -237,6 +237,15 @@ impl Worker {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turns `step` parts, or posts `key` if something is picked.
|
||||
pub fn turn(&mut self, doc: &Doc, step: i32, key: Option<(u32, i32)>) -> io::Result<Option<usize>> {
|
||||
let (char_code, key_code) = key.unwrap_or_default();
|
||||
let doc_id = self.doc_id(doc)?;
|
||||
let payload = Pack::new().u64(doc_id).i64(step.into()).i64(char_code.into()).i64(key_code.into()).bytes();
|
||||
let shown = Unpack::new(&self.request(tag::TURN, &payload)?).i64()?;
|
||||
Ok(usize::try_from(shown).ok())
|
||||
}
|
||||
|
||||
/// Drags a selected object's handle, start then end.
|
||||
pub fn drag_graphic(&mut self, doc: &Doc, from: (i32, i32), to: (i32, i32)) -> io::Result<()> {
|
||||
for (kind, (x, y)) in [(0, from), (1, to)] {
|
||||
|
||||
@@ -362,11 +362,14 @@ pub fn stop_all(docs: &HashMap<u64, Document>) {
|
||||
|
||||
/// The current generation of `id`.
|
||||
pub fn generation(id: u64) -> u64 {
|
||||
slots()
|
||||
.lock()
|
||||
.expect("the events lock")
|
||||
.get(&id)
|
||||
.map_or(0, |slot| slot.batch.generation)
|
||||
slots().lock().expect("the events lock").get(&id).map_or(0, |slot| slot.batch.generation)
|
||||
}
|
||||
|
||||
/// Whether `id` shows a selection, object or caret.
|
||||
pub fn picked(id: u64) -> bool {
|
||||
let slots = slots().lock().expect("the events lock");
|
||||
let Some(batch) = slots.get(&id).map(|slot| &slot.batch) else { return false };
|
||||
batch.graphic.is_some() || !batch.selection.is_empty() || batch.cursor_visible && batch.cursor.is_some()
|
||||
}
|
||||
|
||||
/// Blocks until documents have unpushed events.
|
||||
@@ -399,12 +402,7 @@ pub fn clear_result(id: u64) {
|
||||
|
||||
/// The completion the last dispatch reported.
|
||||
pub fn take_result(id: u64) -> Option<(String, bool)> {
|
||||
slots()
|
||||
.lock()
|
||||
.expect("the events lock")
|
||||
.get_mut(&id)?
|
||||
.result
|
||||
.take()
|
||||
slots().lock().expect("the events lock").get_mut(&id)?.result.take()
|
||||
}
|
||||
|
||||
/// The bridged a11y text now.
|
||||
|
||||
@@ -60,6 +60,8 @@ macro_rules! call {
|
||||
}};
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod accessory;
|
||||
mod document;
|
||||
mod slideshow;
|
||||
pub use document::{Raw, close_window};
|
||||
@@ -80,6 +82,9 @@ impl Lok {
|
||||
let install_c = cstring(&install_str)?;
|
||||
let profile_c = cstring(profile_url)?;
|
||||
let lib = Library::open(install)?;
|
||||
// Before the kit starts, so no Dock icon shows.
|
||||
#[cfg(target_os = "macos")]
|
||||
accessory::hide()?;
|
||||
let hook: Hook2 = unsafe {
|
||||
lib.symbol(b"libreofficekit_hook_2\0")
|
||||
.or_else(|_| lib.symbol(b"libreofficekit_hook\0"))
|
||||
@@ -97,6 +102,8 @@ impl Lok {
|
||||
"lok hook failed for {install_str}"
|
||||
)));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
accessory::check()?;
|
||||
log::info!("lok: hooked {}", install_str);
|
||||
Ok(Self { kit, _lib: lib })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! The worker stays out of the Dock (macOS).
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
use std::io;
|
||||
|
||||
#[link(name = "Foundation", kind = "framework")]
|
||||
#[link(name = "objc")]
|
||||
unsafe extern "C" {
|
||||
fn objc_getClass(name: *const c_char) -> *mut c_void;
|
||||
fn sel_registerName(name: *const c_char) -> *mut c_void;
|
||||
fn objc_msgSend();
|
||||
}
|
||||
|
||||
/// NSApplicationActivationPolicyAccessory: no Dock icon, no menu bar.
|
||||
const ACCESSORY: isize = 1;
|
||||
/// NSApplicationActivationPolicyProhibited: an unbundled worker starts so.
|
||||
const PROHIBITED: isize = 2;
|
||||
|
||||
type Id = *mut c_void;
|
||||
|
||||
fn send() -> unsafe extern "C" fn() {
|
||||
objc_msgSend as unsafe extern "C" fn()
|
||||
}
|
||||
|
||||
fn class(name: &std::ffi::CStr) -> io::Result<Id> {
|
||||
let class = unsafe { objc_getClass(name.as_ptr()) };
|
||||
if class.is_null() {
|
||||
return Err(io::Error::other(format!("no {} class", name.to_string_lossy())));
|
||||
}
|
||||
Ok(class)
|
||||
}
|
||||
|
||||
fn get(object: Id, selector: &std::ffi::CStr) -> io::Result<Id> {
|
||||
type F = unsafe extern "C" fn(Id, Id) -> Id;
|
||||
let f: F = unsafe { std::mem::transmute(send()) };
|
||||
let result = unsafe { f(object, sel_registerName(selector.as_ptr())) };
|
||||
if result.is_null() {
|
||||
return Err(io::Error::other(format!("{} gave nothing", selector.to_string_lossy())));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Marks the process a UI element before registration.
|
||||
pub fn hide() -> io::Result<()> {
|
||||
// The kit reads the bundle's LSUIElement when it registers.
|
||||
let info = get(get(class(c"NSBundle")?, c"mainBundle")?, c"infoDictionary")?;
|
||||
type Text = unsafe extern "C" fn(Id, Id, *const c_char) -> Id;
|
||||
type Flag = unsafe extern "C" fn(Id, Id, i8) -> Id;
|
||||
type Set = unsafe extern "C" fn(Id, Id, Id, Id);
|
||||
let text: Text = unsafe { std::mem::transmute(send()) };
|
||||
let flag: Flag = unsafe { std::mem::transmute(send()) };
|
||||
let set: Set = unsafe { std::mem::transmute(send()) };
|
||||
unsafe {
|
||||
let key = text(class(c"NSString")?, sel_registerName(c"stringWithUTF8String:".as_ptr()), c"LSUIElement".as_ptr());
|
||||
let yes = flag(class(c"NSNumber")?, sel_registerName(c"numberWithBool:".as_ptr()), 1);
|
||||
set(info, sel_registerName(c"setObject:forKey:".as_ptr()), yes, key);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fails unless the kernel's application came up an accessory.
|
||||
pub fn check() -> io::Result<()> {
|
||||
type Policy = unsafe extern "C" fn(Id, Id) -> isize;
|
||||
type SetPolicy = unsafe extern "C" fn(Id, Id, isize) -> i8;
|
||||
let policy: Policy = unsafe { std::mem::transmute(send()) };
|
||||
let set: SetPolicy = unsafe { std::mem::transmute(send()) };
|
||||
let app = get(class(c"NSApplication")?, c"sharedApplication")?;
|
||||
let read = || unsafe { policy(app, sel_registerName(c"activationPolicy".as_ptr())) };
|
||||
let mut found = read();
|
||||
if found == PROHIBITED {
|
||||
// Outside a bundle nothing registers; accessory lets it draw.
|
||||
let done = unsafe { set(app, sel_registerName(c"setActivationPolicy:".as_ptr()), ACCESSORY) };
|
||||
found = read();
|
||||
log::info!("lok: the unbundled worker asked for accessory ({done})");
|
||||
}
|
||||
if found != ACCESSORY {
|
||||
return Err(io::Error::other(format!("the worker's activation policy is {found}, not accessory")));
|
||||
}
|
||||
log::info!("lok: the worker is an accessory app");
|
||||
Ok(())
|
||||
}
|
||||
@@ -88,6 +88,8 @@ pub mod tag {
|
||||
pub const REVISION: u8 = 34;
|
||||
/// One layer's pixels from the last `SLIDE_LAYERS`.
|
||||
pub const SLIDE_LAYER: u8 = 35;
|
||||
/// Turns parts; an arrow with something picked goes in.
|
||||
pub const TURN: u8 = 36;
|
||||
pub const OK: u8 = 100;
|
||||
pub const ERR: u8 = 101;
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use client::{
|
||||
};
|
||||
#[cfg(feature = "view")]
|
||||
pub use view::{
|
||||
CONTEXT, Copy, Cut, Geom, Layout, LokError, LokView, Paste, Reported, ZOOM_STEPS,
|
||||
CONTEXT, Copy, Cut, Geom, Layout, LokError, LokView, Paste, Reported, ZOOM_STEPS, notch,
|
||||
Zoomed, init, layout, paper, read_off, scheme,
|
||||
};
|
||||
#[cfg(feature = "view")]
|
||||
|
||||
@@ -32,7 +32,9 @@ mod scroll;
|
||||
mod sheet;
|
||||
pub use input::{CONTEXT, Copy, Cut, Paste, init};
|
||||
pub use off::read_off;
|
||||
pub use render::scheme;
|
||||
pub use render::{paper, scheme};
|
||||
mod turn;
|
||||
pub use turn::notch;
|
||||
|
||||
pub(crate) use crate::{TILE_TWIPS, TWIPS_PER_PIXEL};
|
||||
|
||||
@@ -125,6 +127,8 @@ pub struct LokView {
|
||||
dark: Option<bool>,
|
||||
/// The zoom follows the viewport so a page fits.
|
||||
fit: bool,
|
||||
/// Set when the wheel and Up, Down turn parts.
|
||||
turning: Option<turn::Turning>,
|
||||
/// The sheet shown, and the offered function chosen.
|
||||
part: usize,
|
||||
picked: usize,
|
||||
@@ -150,17 +154,6 @@ pub type Layout = ((i64, i64), Vec<Rect>);
|
||||
|
||||
use sheet::{Measured, measure};
|
||||
|
||||
/// A page's colour; the kernel's Ely schemes share it.
|
||||
pub fn paper(cx: &gpui::App) -> gpui::Hsla {
|
||||
use ely_gpui_component::theme::ActiveTheme as _;
|
||||
let theme = cx.theme();
|
||||
if theme.is_dark() {
|
||||
theme.colors.surface
|
||||
} else {
|
||||
theme.colors.paper
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `doc`'s size and page frames.
|
||||
pub fn layout(worker: &mut Worker, doc: &Doc) -> io::Result<Layout> {
|
||||
Ok((doc.size(worker)?, doc.pages(worker)?))
|
||||
@@ -227,6 +220,7 @@ impl LokView {
|
||||
cell: crate::Cell::default(),
|
||||
dark: None,
|
||||
fit: false,
|
||||
turning: None,
|
||||
part: 0,
|
||||
picked: 0,
|
||||
marked: None,
|
||||
|
||||
@@ -64,6 +64,14 @@ pub(super) enum Input {
|
||||
Visible(Rect, (u32, i32)),
|
||||
/// Shows sheet or slide `part`, from 0.
|
||||
Part(usize),
|
||||
/// Turns `step` parts; a picked object takes the arrow `key`.
|
||||
Turn { step: i32, key: Option<(u32, i32)> },
|
||||
}
|
||||
|
||||
/// What an input gives back.
|
||||
pub(super) enum Back {
|
||||
Copied(String),
|
||||
Shown(usize),
|
||||
}
|
||||
|
||||
impl Input {
|
||||
@@ -73,6 +81,7 @@ impl Input {
|
||||
// Arrows, Home, End, Page keys, Escape.
|
||||
Input::Key { key_code, .. } => !matches!(key_code & 0x0FFF, 1024..=1031 | 1281),
|
||||
Input::Mouse(_)
|
||||
| Input::Turn { .. }
|
||||
| Input::Copy { cut: false }
|
||||
| Input::Visible(..)
|
||||
| Input::Part(_)
|
||||
@@ -169,7 +178,7 @@ fn lok_button(button: MouseButton) -> Option<i32> {
|
||||
}
|
||||
|
||||
/// Runs one input; gives a copy's mark and the revision.
|
||||
pub(super) fn run(worker: &Mutex<Worker>, doc: &Doc, input: Input) -> (io::Result<Option<String>>, Option<u64>) {
|
||||
pub(super) fn run(worker: &Mutex<Worker>, doc: &Doc, input: Input) -> (io::Result<Option<Back>>, Option<u64>) {
|
||||
let mut worker = worker.lock().expect("the worker lock");
|
||||
let counts = !matches!(input, Input::Visible(..));
|
||||
let copied = apply(&mut worker, doc, input);
|
||||
@@ -181,12 +190,13 @@ pub(super) fn run(worker: &Mutex<Worker>, doc: &Doc, input: Input) -> (io::Resul
|
||||
(copied, now)
|
||||
}
|
||||
|
||||
fn apply(worker: &mut Worker, doc: &Doc, input: Input) -> io::Result<Option<String>> {
|
||||
fn apply(worker: &mut Worker, doc: &Doc, input: Input) -> io::Result<Option<Back>> {
|
||||
let done = match input {
|
||||
Input::Key {
|
||||
char_code,
|
||||
key_code,
|
||||
} => worker.post_key(doc, char_code, key_code),
|
||||
Input::Turn { step, key } => return Ok(worker.turn(doc, step, key)?.map(Back::Shown)),
|
||||
Input::Mouse(event) => worker.post_mouse(doc, event),
|
||||
Input::Drag { from, to } => worker.drag_graphic(doc, from, to),
|
||||
Input::Visible(area, scale) => doc.visible_area(worker, area, scale),
|
||||
@@ -195,9 +205,8 @@ fn apply(worker: &mut Worker, doc: &Doc, input: Input) -> io::Result<Option<Stri
|
||||
Input::Theme(scheme) => worker.run(doc, "view.theme", &[scheme]),
|
||||
Input::Text { commit, text } => worker.post_text(doc, commit, &text),
|
||||
Input::Copy { cut } => {
|
||||
return clip::copy_out(worker, doc, cut, |clip| {
|
||||
clipboard::write(clip).map_err(io::Error::other)
|
||||
});
|
||||
let copied = clip::copy_out(worker, doc, cut, |clip| clipboard::write(clip).map_err(io::Error::other));
|
||||
return copied.map(|copied| copied.map(Back::Copied));
|
||||
}
|
||||
Input::Run { commands, at } => {
|
||||
let values: Vec<Vec<&str>> =
|
||||
@@ -298,7 +307,10 @@ impl LokView {
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.walk(&event.keystroke, cx) || self.key_down(&event.keystroke) {
|
||||
if self.walk(&event.keystroke, cx)
|
||||
|| self.turn_key(&event.keystroke)
|
||||
|| self.key_down(&event.keystroke)
|
||||
{
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,8 @@ use std::{
|
||||
use futures::{StreamExt, channel::mpsc, select_biased};
|
||||
use gpui::Context;
|
||||
|
||||
use super::{Geom, LokError, LokView, Reported, TILE_TWIPS, input::Input};
|
||||
use super::input::{Back, Input};
|
||||
use super::{Geom, LokError, LokView, Reported, TILE_TWIPS};
|
||||
use crate::{Doc, Tile, Worker};
|
||||
|
||||
/// An input slower than this is logged as a warning.
|
||||
@@ -24,7 +25,7 @@ pub(super) struct Job {
|
||||
/// What came back from the lane.
|
||||
enum Landed {
|
||||
/// Sequence, whether it edits, whether it switched part, outcome.
|
||||
Input(u64, bool, bool, (io::Result<Option<String>>, Option<u64>)),
|
||||
Input(u64, bool, bool, (io::Result<Option<Back>>, Option<u64>)),
|
||||
Tile(Job, io::Result<Tile>),
|
||||
}
|
||||
|
||||
@@ -111,7 +112,13 @@ impl LokView {
|
||||
}
|
||||
self.seen_revision(now.unwrap_or(0));
|
||||
match outcome {
|
||||
Ok(Some(copied)) => self.copied = Some(copied),
|
||||
Ok(Some(Back::Copied(copied))) => self.copied = Some(copied),
|
||||
Ok(Some(Back::Shown(part))) if part != self.part => {
|
||||
// The worker turned in order.
|
||||
self.part = part;
|
||||
self.invalidate(cx);
|
||||
}
|
||||
Ok(Some(Back::Shown(_))) => {}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
log::error!("lok: input failed ({:?})", error.kind());
|
||||
|
||||
@@ -24,6 +24,16 @@ pub fn scheme(dark: bool) -> &'static str {
|
||||
if dark { DARK } else { LIGHT }
|
||||
}
|
||||
|
||||
/// A page's colour; the kernel's Ely schemes share it.
|
||||
pub fn paper(cx: &gpui::App) -> gpui::Hsla {
|
||||
let theme = cx.theme();
|
||||
if theme.is_dark() {
|
||||
theme.colors.surface
|
||||
} else {
|
||||
theme.colors.paper
|
||||
}
|
||||
}
|
||||
|
||||
impl LokView {
|
||||
/// Paints with the app's light or dark scheme.
|
||||
pub(super) fn follow_theme(&mut self, dark: bool) {
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
//! The wheel and Up, Down turn slides (SHOW-01).
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gpui::{Keystroke, Modifiers, ScrollDelta, ScrollWheelEvent, TouchPhase};
|
||||
|
||||
use super::LokView;
|
||||
use super::input::{Input, vcl_key};
|
||||
|
||||
/// Trackpad pixels one turn takes.
|
||||
const SWIPE: f32 = 50.0;
|
||||
/// A pause this long ends a gesture without phases.
|
||||
const PAUSE: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Lines one wheel notch scrolls on this platform.
|
||||
pub fn notch() -> f32 {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{SPI_GETWHEELSCROLLLINES, SystemParametersInfoW};
|
||||
let mut lines = 3u32;
|
||||
// Same setting gpui scales the wheel by.
|
||||
unsafe { SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, (&raw mut lines).cast(), 0) };
|
||||
lines as f32
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
1.0
|
||||
}
|
||||
// gpui's X11 and Wayland scroll three lines a notch.
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
{
|
||||
3.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The wheel's progress towards a turn.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Turning {
|
||||
/// This gesture's travel, in turns.
|
||||
travel: f32,
|
||||
/// This gesture already turned.
|
||||
spent: bool,
|
||||
/// The platform began a gesture it has not ended.
|
||||
held: bool,
|
||||
/// Fractional lines in this run: a touchpad, not a wheel.
|
||||
smooth: bool,
|
||||
last: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Turning {
|
||||
/// The turn a wheel event makes; 0 for none.
|
||||
pub(super) fn wheel(&mut self, delta: ScrollDelta, phase: TouchPhase, now: Instant, notch: f32) -> i32 {
|
||||
let paused = self.last.is_none_or(|last| now.duration_since(last) >= PAUSE);
|
||||
self.last = Some(now);
|
||||
// X11 lines mix wheels and touchpads; they carry no phase.
|
||||
let (travel, phase) = match delta {
|
||||
ScrollDelta::Lines(_) if notch <= 0.0 => return 0,
|
||||
ScrollDelta::Lines(lines) => (lines.y / notch, None),
|
||||
ScrollDelta::Pixels(pixels) => (f32::from(pixels.y) / SWIPE, Some(phase)),
|
||||
};
|
||||
// Phases bound a gesture; without them, a pause does.
|
||||
if phase == Some(TouchPhase::Started) || paused && !self.held {
|
||||
(self.travel, self.spent, self.smooth) = (0.0, false, false);
|
||||
}
|
||||
let whole = travel.round();
|
||||
if phase.is_none() && (whole == 0.0 || (travel - whole).abs() >= 1e-3) {
|
||||
self.smooth = true;
|
||||
}
|
||||
// Whole wheel notches each turn, until fractions show a touchpad.
|
||||
if phase.is_none() && !self.smooth {
|
||||
(self.travel, self.spent, self.held) = (0.0, true, false);
|
||||
return -(whole as i32);
|
||||
}
|
||||
self.held = match phase {
|
||||
Some(TouchPhase::Started) => true,
|
||||
Some(TouchPhase::Moved) => self.held,
|
||||
Some(TouchPhase::Ended | TouchPhase::Cancelled) | None => false,
|
||||
};
|
||||
// One gesture turns once, momentum included.
|
||||
if self.spent {
|
||||
return 0;
|
||||
}
|
||||
self.travel += travel;
|
||||
if self.travel.abs() < 1.0 - 1e-3 {
|
||||
return 0;
|
||||
}
|
||||
self.spent = true;
|
||||
// Content moving down shows the part before.
|
||||
-(self.travel.signum() as i32)
|
||||
}
|
||||
}
|
||||
|
||||
impl LokView {
|
||||
/// The wheel and Up, Down turn parts from now on.
|
||||
pub fn turn_parts(&mut self) {
|
||||
self.turning.get_or_insert_default();
|
||||
}
|
||||
|
||||
/// Queues Up, Down; the worker turns if nothing is picked.
|
||||
pub(super) fn turn_key(&mut self, keystroke: &Keystroke) -> bool {
|
||||
if self.turning.is_none() || keystroke.modifiers != Modifiers::none() {
|
||||
return false;
|
||||
}
|
||||
let step = match keystroke.key.as_str() {
|
||||
"down" => 1,
|
||||
"up" => -1,
|
||||
_ => return false,
|
||||
};
|
||||
let Some(key) = vcl_key(keystroke) else {
|
||||
return false;
|
||||
};
|
||||
self.send(Input::Turn { step, key: Some(key) });
|
||||
true
|
||||
}
|
||||
|
||||
/// The wheel turns while the whole page shows.
|
||||
pub(super) fn turn_wheel(&mut self, event: &ScrollWheelEvent) -> bool {
|
||||
let (width, height) = self.extent();
|
||||
// A pixel of slack for rounding.
|
||||
let whole = self.geom.px_of(width) <= self.viewport.0 + 1.0
|
||||
&& self.geom.px_of(height) <= self.viewport.1 + 1.0;
|
||||
let Some(turning) = self.turning.as_mut().filter(|_| whole) else {
|
||||
return false;
|
||||
};
|
||||
let step = turning.wheel(event.delta, event.touch_phase, Instant::now(), notch());
|
||||
if step != 0 {
|
||||
// In order with the input around it.
|
||||
self.send(Input::Turn { step, key: None });
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::{ScrollDelta, TouchPhase, point, px};
|
||||
|
||||
use super::{PAUSE, Turning};
|
||||
|
||||
const NOTCH: f32 = 3.0;
|
||||
|
||||
fn lines(y: f32) -> ScrollDelta {
|
||||
ScrollDelta::Lines(point(0.0, y))
|
||||
}
|
||||
|
||||
fn pixels(y: f32) -> ScrollDelta {
|
||||
ScrollDelta::Pixels(point(px(0.0), px(y)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_notch_with_a_pause_turns_once() {
|
||||
let (mut turning, now) = (Turning::default(), std::time::Instant::now());
|
||||
let mut wheel = |y, at| turning.wheel(lines(y), TouchPhase::Moved, at, NOTCH);
|
||||
assert_eq!(wheel(-3.0, now), 1, "Windows and Linux scroll three lines a notch");
|
||||
assert_eq!(wheel(-3.0, now + PAUSE), 1);
|
||||
assert_eq!(wheel(3.0, now + PAUSE * 2), -1);
|
||||
assert_eq!(wheel(-6.0, now + PAUSE * 3), 2, "two notches in one event");
|
||||
assert_eq!(wheel(-3.0, now + PAUSE * 3), 1, "rapid notches each turn");
|
||||
assert_eq!(wheel(-3.0, now + PAUSE * 3), 1);
|
||||
assert_eq!(wheel(-1.0, now + PAUSE * 4), 0, "a third of a notch");
|
||||
let mut mac = Turning::default();
|
||||
assert_eq!(mac.wheel(lines(-1.0), TouchPhase::Moved, now, 1.0), 1, "macOS scrolls a line a notch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_of_lines_turns_once() {
|
||||
let (mut turning, now) = (Turning::default(), std::time::Instant::now());
|
||||
// A whole step, then fractions: no more turns once smooth.
|
||||
let stream = [-3.0, -0.4, -0.4, -0.4, -0.4, -0.4, -0.4, -0.4, -0.4, -3.0];
|
||||
let turned: i32 = stream.iter().map(|&y| turning.wheel(lines(y), TouchPhase::Moved, now, NOTCH)).sum();
|
||||
assert_eq!(turned, 1, "one swipe turns once");
|
||||
let mut turning = Turning::default();
|
||||
let turned: i32 = (0..30).map(|_| turning.wheel(lines(-0.4), TouchPhase::Moved, now, NOTCH)).sum();
|
||||
assert_eq!(turned, 1, "fractions add up once");
|
||||
assert_eq!(turning.wheel(lines(-3.0), TouchPhase::Moved, now + PAUSE, NOTCH), 1, "a pause ends it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swipe_turns_once_until_the_next() {
|
||||
let (mut turning, now) = (Turning::default(), std::time::Instant::now());
|
||||
let mut swipe = |y, phase, at| turning.wheel(pixels(y), phase, at, NOTCH);
|
||||
assert_eq!(swipe(-30.0, TouchPhase::Started, now), 0);
|
||||
assert_eq!(swipe(-30.0, TouchPhase::Moved, now), 1);
|
||||
// A pause with fingers down is the same gesture.
|
||||
assert_eq!(swipe(-60.0, TouchPhase::Moved, now + PAUSE * 2), 0);
|
||||
assert_eq!(swipe(0.0, TouchPhase::Ended, now + PAUSE * 2), 0);
|
||||
// Momentum after the turn turns nothing more.
|
||||
for _ in 0..20 {
|
||||
assert_eq!(swipe(-80.0, TouchPhase::Moved, now + PAUSE * 2), 0);
|
||||
}
|
||||
assert_eq!(swipe(60.0, TouchPhase::Started, now + PAUSE * 2), -1);
|
||||
assert_eq!(swipe(0.0, TouchPhase::Ended, now + PAUSE * 2), 0);
|
||||
// Without phases a pause ends a gesture (Wayland).
|
||||
let later = now + PAUSE * 4;
|
||||
assert_eq!(swipe(60.0, TouchPhase::Moved, later), -1);
|
||||
assert_eq!(swipe(60.0, TouchPhase::Moved, later), 0);
|
||||
assert_eq!(swipe(60.0, TouchPhase::Moved, later + PAUSE), -1);
|
||||
}
|
||||
}
|
||||
@@ -65,9 +65,9 @@ impl LokView {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Ctrl (macOS: Cmd) and the wheel zoom; else scroll.
|
||||
/// Ctrl (macOS: Cmd) wheel zooms; else it turns or scrolls.
|
||||
pub(super) fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if !self.wheel_zoom(event, cx) {
|
||||
if !self.wheel_zoom(event, cx) && !self.turn_wheel(event) {
|
||||
self.on_scroll(event, window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +218,7 @@ fn answer(lok: &Lok, tag: u8, id: u64, payload: &[u8]) {
|
||||
}
|
||||
}),
|
||||
tag::POST_KEY => input::key(unpack),
|
||||
tag::TURN => input::turn(unpack),
|
||||
tag::POST_MOUSE => input::mouse(unpack),
|
||||
tag::GRAPHIC => input::graphic(unpack),
|
||||
tag::POST_TEXT => input::text(unpack),
|
||||
|
||||
@@ -99,6 +99,28 @@ pub(super) fn key(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Turns `step` parts in order, or posts the arrow (-1).
|
||||
pub(super) fn turn(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let (id, step, char_code, key_code) = (unpack.u64()?, unpack.i64()?, unpack.i64()?, unpack.i64()?);
|
||||
// Earlier input's callbacks already landed here.
|
||||
if key_code != 0 && crate::events::picked(id) {
|
||||
with_doc(id, |doc| {
|
||||
doc.post_key(0, char_code as i32, key_code as i32);
|
||||
doc.post_key(1, char_code as i32, key_code as i32);
|
||||
})?;
|
||||
return Ok(Pack::new().i64(-1).bytes());
|
||||
}
|
||||
let shown = with_doc(id, |doc| {
|
||||
let (part, last) = (i64::from(doc.part()), i64::from(doc.parts()) - 1);
|
||||
let next = (part + step).clamp(0, last.max(0));
|
||||
if next != part {
|
||||
doc.set_part(next as i32);
|
||||
}
|
||||
next
|
||||
})?;
|
||||
Ok(Pack::new().i64(shown).bytes())
|
||||
}
|
||||
|
||||
/// One mouse event: kind, x, y, count, buttons, modifiers.
|
||||
pub(super) fn mouse(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let id = unpack.u64()?;
|
||||
|
||||
@@ -51,7 +51,7 @@ pub fn expect(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
pub fn bump(request: u8, payload: &[u8]) {
|
||||
let changes = matches!(
|
||||
request,
|
||||
tag::POST_KEY | tag::POST_MOUSE | tag::GRAPHIC | tag::POST_TEXT | tag::POST_UNO | tag::PASTE | tag::CUT | tag::COMPLETE_FUNCTION
|
||||
tag::POST_KEY | tag::TURN | tag::POST_MOUSE | tag::GRAPHIC | tag::POST_TEXT | tag::POST_UNO | tag::PASTE | tag::CUT | tag::COMPLETE_FUNCTION
|
||||
);
|
||||
let mut unpack = Unpack::new(payload);
|
||||
let Ok(id) = unpack.u64() else {
|
||||
|
||||
@@ -246,7 +246,7 @@ pub fn in_window<H: Host, R>(
|
||||
pub fn print_later<H: Tabs>(pdf: std::path::PathBuf, cx: &mut Context<H>) {
|
||||
// The panel's modal loop calls back into GPUI.
|
||||
cx.spawn(async move |this, cx| {
|
||||
let printed = ely_platform::print::print_pdf(&pdf);
|
||||
let printed = ely_platform::print::print_pdf(&pdf).await;
|
||||
// The copy may hold what a password guarded.
|
||||
if let Err(error) = std::fs::remove_file(&pdf) {
|
||||
log::error!("office: the print copy {} stays: {error}", pdf.display());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Ely's right-click menus, gated by the kernel's (DOC-02).
|
||||
|
||||
use std::io;
|
||||
use std::{cell::Cell, io};
|
||||
|
||||
use ely_gpui_component::{
|
||||
menus::{ContextMenu, Menu, MenuItem},
|
||||
@@ -15,18 +15,21 @@ pub struct Offer<W> {
|
||||
pub what: W,
|
||||
/// Bumps for each menu, so each opens once.
|
||||
request: (u64, Point<Pixels>),
|
||||
/// Handed to a host; a remounted host must not reopen.
|
||||
served: Cell<bool>,
|
||||
}
|
||||
|
||||
impl<W> Offer<W> {
|
||||
/// The next menu after `last`.
|
||||
pub fn new(last: Option<&Offer<W>>, tab: u64, what: W, at: Point<Pixels>) -> Self {
|
||||
let number = last.map_or(1, |last| last.request.0 + 1);
|
||||
Offer { tab, what, request: (number, at) }
|
||||
Offer { tab, what, request: (number, at), served: Cell::new(false) }
|
||||
}
|
||||
|
||||
/// Its host, opened at the point.
|
||||
/// Its host; only the first render opens it.
|
||||
pub fn host(&self, id: &'static str, menu: Menu) -> ContextMenu {
|
||||
ContextMenu::new(id, menu).manual(Some(self.request))
|
||||
let request = (!self.served.replace(true)).then_some(self.request);
|
||||
ContextMenu::new(id, menu).manual(request)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ cc = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
ely-pdf-engine = { path = ".", features = ["test-support"] }
|
||||
lopdf.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -56,10 +56,21 @@ typedef struct
|
||||
void *user;
|
||||
} passing;
|
||||
|
||||
/* MuPDF draws an unembedded font with another. */
|
||||
static const char notice[] = "non-embedded font using identity encoding:";
|
||||
|
||||
/* 1 while the last warning was that notice. */
|
||||
static int substituted;
|
||||
|
||||
static void keep_warning(void *user, const char *message)
|
||||
{
|
||||
passing *p = user;
|
||||
if (strlen(warned) + strlen(message) + 2 < sizeof warned)
|
||||
/* An unembedded font drawn by another is no damage. */
|
||||
if (!strncmp(message, notice, sizeof notice - 1))
|
||||
substituted = 1;
|
||||
else if (strncmp(message, "... repeated ", 13))
|
||||
substituted = 0;
|
||||
if (!substituted && strlen(warned) + strlen(message) + 2 < sizeof warned)
|
||||
{
|
||||
fz_strlcat(warned, message, sizeof warned);
|
||||
fz_strlcat(warned, "\n", sizeof warned);
|
||||
@@ -74,6 +85,8 @@ static int watched;
|
||||
/* Collects MuPDF's warnings until `ely_watch_end`. */
|
||||
void ely_watch_begin(fz_context *ctx)
|
||||
{
|
||||
/* A pending repeat is of MuPDF's last warning. */
|
||||
substituted = !strncmp(ctx->warn.message, notice, sizeof notice - 1);
|
||||
watching.next = fz_warning_callback(ctx, &watching.user);
|
||||
warned[0] = 0;
|
||||
watched = 1;
|
||||
|
||||
@@ -143,6 +143,143 @@ int ely_write_repaired(fz_context *ctx, fz_document *doc, const char *path)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Marked for print and not hidden. */
|
||||
static int prints(fz_context *ctx, pdf_annot *annot)
|
||||
{
|
||||
int flags = pdf_annot_flags(ctx, annot);
|
||||
return (flags & PDF_ANNOT_IS_PRINT) && !(flags & (PDF_ANNOT_IS_HIDDEN | PDF_ANNOT_IS_INVISIBLE));
|
||||
}
|
||||
|
||||
/* Asks MuPDF to make and keep a printable annotation's look. */
|
||||
static void ask_look(fz_context *ctx, pdf_annot *annot)
|
||||
{
|
||||
if (prints(ctx, annot))
|
||||
pdf_annot_request_synthesis(ctx, annot);
|
||||
}
|
||||
|
||||
/* Draws a printable look into `buf`, named in `xobj`. */
|
||||
static void draw_look(fz_context *ctx, pdf_annot *annot, int page, pdf_obj *xobj, fz_buffer *buf)
|
||||
{
|
||||
pdf_obj *type = pdf_dict_get(ctx, pdf_annot_obj(ctx, annot), PDF_NAME(Subtype));
|
||||
pdf_obj *ap;
|
||||
fz_matrix m;
|
||||
char name[32];
|
||||
int n = 0;
|
||||
/* Links and popups have no look of their own. */
|
||||
if (!prints(ctx, annot) || type == PDF_NAME(Link) || type == PDF_NAME(Popup))
|
||||
return;
|
||||
if (!pdf_dict_getp(ctx, pdf_annot_obj(ctx, annot), "AP/N"))
|
||||
fz_throw(ctx, FZ_ERROR_FORMAT, "a %s annotation on page %d cannot be drawn", pdf_to_name(ctx, type), page + 1);
|
||||
/* A state with no look of its own draws nothing. */
|
||||
ap = pdf_annot_ap(ctx, annot);
|
||||
if (!ap)
|
||||
return;
|
||||
do
|
||||
fz_snprintf(name, sizeof name, "ElyAnnot%d", n++);
|
||||
while (pdf_dict_gets(ctx, xobj, name));
|
||||
pdf_dict_puts(ctx, xobj, name, ap);
|
||||
pdf_dict_put(ctx, ap, PDF_NAME(Type), PDF_NAME(XObject));
|
||||
pdf_dict_put(ctx, ap, PDF_NAME(Subtype), PDF_NAME(Form));
|
||||
m = pdf_annot_transform(ctx, annot);
|
||||
fz_append_printf(ctx, buf, "q %g %g %g %g %g %g cm /%s Do Q\n", m.a, m.b, m.c, m.d, m.e, m.f, name);
|
||||
}
|
||||
|
||||
/* Draws the printable looks in; drops all but links. */
|
||||
static void flatten(fz_context *ctx, pdf_document *pdf, pdf_page *page, int number)
|
||||
{
|
||||
pdf_obj *annots = pdf_dict_get(ctx, page->obj, PDF_NAME(Annots));
|
||||
pdf_obj *res, *xobj, *contents, *links = NULL, *prologue = NULL;
|
||||
fz_buffer *buf = NULL;
|
||||
pdf_annot *annot;
|
||||
int prepend, append, i;
|
||||
if (pdf_array_len(ctx, annots) == 0)
|
||||
return;
|
||||
res = pdf_dict_get(ctx, page->obj, PDF_NAME(Resources));
|
||||
if (!res)
|
||||
{
|
||||
res = pdf_dict_get_inheritable(ctx, page->obj, PDF_NAME(Resources));
|
||||
if (res)
|
||||
pdf_dict_put(ctx, page->obj, PDF_NAME(Resources), res);
|
||||
else
|
||||
res = pdf_dict_put_dict(ctx, page->obj, PDF_NAME(Resources), 4);
|
||||
}
|
||||
xobj = pdf_dict_get(ctx, res, PDF_NAME(XObject));
|
||||
if (!xobj)
|
||||
xobj = pdf_dict_put_dict(ctx, res, PDF_NAME(XObject), 8);
|
||||
fz_var(buf);
|
||||
fz_var(links);
|
||||
fz_var(prologue);
|
||||
fz_try(ctx)
|
||||
{
|
||||
/* The page's own state is closed before the looks. */
|
||||
contents = pdf_dict_get(ctx, page->obj, PDF_NAME(Contents));
|
||||
pdf_count_q_balance(ctx, pdf, res, contents, &prepend, &append);
|
||||
buf = fz_new_buffer(ctx, 1024);
|
||||
while (prepend-- > 0)
|
||||
fz_append_string(ctx, buf, "q\n");
|
||||
prologue = pdf_add_stream(ctx, pdf, buf, NULL, 0);
|
||||
fz_clear_buffer(ctx, buf);
|
||||
while (append-- > 0)
|
||||
fz_append_string(ctx, buf, "Q\n");
|
||||
for (annot = pdf_first_annot(ctx, page); annot; annot = pdf_next_annot(ctx, annot))
|
||||
draw_look(ctx, annot, number, xobj, buf);
|
||||
for (annot = pdf_first_widget(ctx, page); annot; annot = pdf_next_widget(ctx, annot))
|
||||
draw_look(ctx, annot, number, xobj, buf);
|
||||
links = pdf_new_array(ctx, pdf, 4);
|
||||
for (i = 0; i < pdf_array_len(ctx, annots); i++)
|
||||
if (pdf_dict_get(ctx, pdf_array_get(ctx, annots, i), PDF_NAME(Subtype)) == PDF_NAME(Link))
|
||||
pdf_array_push(ctx, links, pdf_array_get(ctx, annots, i));
|
||||
pdf_dict_put(ctx, page->obj, PDF_NAME(Annots), links);
|
||||
if (!pdf_is_array(ctx, contents))
|
||||
{
|
||||
pdf_obj *all = pdf_dict_put_array(ctx, page->obj, PDF_NAME(Contents), 3);
|
||||
if (contents)
|
||||
pdf_array_push(ctx, all, contents);
|
||||
contents = all;
|
||||
}
|
||||
pdf_array_insert(ctx, contents, prologue, 0);
|
||||
pdf_array_push_drop(ctx, contents, pdf_add_stream(ctx, pdf, buf, NULL, 0));
|
||||
}
|
||||
fz_always(ctx)
|
||||
{
|
||||
fz_drop_buffer(ctx, buf);
|
||||
pdf_drop_obj(ctx, links);
|
||||
pdf_drop_obj(ctx, prologue);
|
||||
}
|
||||
fz_catch(ctx)
|
||||
fz_rethrow(ctx);
|
||||
}
|
||||
|
||||
/* Every page as it prints; no form is left. */
|
||||
static void flatten_all(fz_context *ctx, fz_document *copy, void *arg)
|
||||
{
|
||||
pdf_document *pdf = ely_pdf_of(ctx, copy);
|
||||
pdf_page *page = NULL;
|
||||
pdf_annot *annot;
|
||||
int i, n = pdf_count_pages(ctx, pdf);
|
||||
fz_var(page);
|
||||
fz_try(ctx)
|
||||
{
|
||||
for (i = 0; i < n; i++)
|
||||
{
|
||||
page = pdf_load_page(ctx, pdf, i);
|
||||
for (annot = pdf_first_annot(ctx, page); annot; annot = pdf_next_annot(ctx, annot))
|
||||
ask_look(ctx, annot);
|
||||
for (annot = pdf_first_widget(ctx, page); annot; annot = pdf_next_widget(ctx, annot))
|
||||
ask_look(ctx, annot);
|
||||
pdf_update_page(ctx, page);
|
||||
flatten(ctx, pdf, page, i);
|
||||
fz_drop_page(ctx, &page->super);
|
||||
page = NULL;
|
||||
}
|
||||
pdf_dict_del(ctx, pdf_dict_get(ctx, pdf_trailer(ctx, pdf), PDF_NAME(Root)), PDF_NAME(AcroForm));
|
||||
}
|
||||
fz_always(ctx)
|
||||
fz_drop_page(ctx, (fz_page *)page);
|
||||
fz_catch(ctx)
|
||||
fz_rethrow(ctx);
|
||||
}
|
||||
|
||||
/* Leave to print was checked; the printer gets no lock. */
|
||||
int ely_print_copy(fz_context *ctx, fz_document *doc, const char *raw, const char *out, const char *password)
|
||||
{
|
||||
@@ -150,7 +287,7 @@ int ely_print_copy(fz_context *ctx, fz_document *doc, const char *raw, const cha
|
||||
{
|
||||
pdf_write_options opts = pdf_default_write_options;
|
||||
opts.do_encrypt = PDF_ENCRYPT_NONE;
|
||||
ely_save_copy(ctx, ely_pdf_of(ctx, doc), raw, out, password, &opts, NULL, NULL);
|
||||
ely_save_copy(ctx, ely_pdf_of(ctx, doc), raw, out, password, &opts, flatten_all, NULL);
|
||||
}
|
||||
fz_catch(ctx)
|
||||
return ely_fail(ctx);
|
||||
|
||||
@@ -31,6 +31,8 @@ struct Doc {
|
||||
/// What MuPDF warned at open; kept as the repair report.
|
||||
warnings: String,
|
||||
repair: Option<String>,
|
||||
/// Damage a read met that no draw has told yet.
|
||||
found: bool,
|
||||
/// The repaired copy standing in; removed on close.
|
||||
copy: Option<std::path::PathBuf>,
|
||||
/// MuPDF's steps: an edit's id, or none for a save.
|
||||
@@ -359,7 +361,7 @@ impl Worker {
|
||||
let id = self.next;
|
||||
self.next += 1;
|
||||
let warnings = output::open_warnings();
|
||||
let doc = Doc { open, password: String::new(), owner, warnings, repair: None, copy: None, steps: Vec::new(), at: 0 };
|
||||
let doc = Doc { open, password: String::new(), owner, warnings, repair: None, found: false, copy: None, steps: Vec::new(), at: 0 };
|
||||
self.docs.insert(id, doc);
|
||||
if !locked && let Err(error) = self.repair(id) {
|
||||
self.forget(id)?;
|
||||
@@ -405,13 +407,12 @@ impl Worker {
|
||||
self.drawn(id, page, (scale, rotate), tile, dark)
|
||||
}
|
||||
tag::TEXT => {
|
||||
let doc = self.doc(ask.u64()?)?;
|
||||
self.mupdf.text(doc, ask.u64()? as usize)
|
||||
let (id, page) = (ask.u64()?, ask.u64()? as usize);
|
||||
self.read(id, |mupdf, doc| mupdf.text(doc, page))
|
||||
}
|
||||
tag::SEARCH => {
|
||||
let doc = self.doc(ask.u64()?)?;
|
||||
let page = ask.u64()? as usize;
|
||||
self.mupdf.search(doc, page, &ask.str()?)
|
||||
let (id, page, needle) = (ask.u64()?, ask.u64()? as usize, ask.str()?);
|
||||
self.read(id, |mupdf, doc| mupdf.search(doc, page, &needle))
|
||||
}
|
||||
tag::OUTLINE => self.mupdf.outline(self.doc(ask.u64()?)?),
|
||||
tag::HELLO => Ok(Pack::new().str(ely_pdf_engine::proto::BUILD).bytes()),
|
||||
|
||||
@@ -82,6 +82,24 @@ impl crate::Worker {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A text read; damage it meets waits for a draw.
|
||||
pub(crate) fn read(&mut self, id: u64, read: impl FnOnce(&Mupdf, &Open) -> io::Result<Vec<u8>>) -> io::Result<Vec<u8>> {
|
||||
let doc = self.doc(id)?;
|
||||
unsafe { ely_watch_begin(self.mupdf.ctx) };
|
||||
let answer = read(&self.mupdf, doc);
|
||||
if unsafe { ely_watch_end(self.mupdf.ctx) } != 0 {
|
||||
self.note_damage(id)?;
|
||||
self.docs.get_mut(&id).expect("just read").found = true;
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
/// Takes damage a read found; the caller tells it.
|
||||
fn found(&mut self, id: u64) -> io::Result<bool> {
|
||||
let doc = self.docs.get_mut(&id).ok_or_else(|| io::Error::other(format!("no document {id}")))?;
|
||||
Ok(std::mem::take(&mut doc.found))
|
||||
}
|
||||
|
||||
/// A tile, and whether drawing it met damage.
|
||||
pub(crate) fn drawn(&mut self, id: u64, page: usize, view: (f32, i32), tile: [i32; 4], dark: bool) -> io::Result<Vec<u8>> {
|
||||
unsafe { ely_watch_begin(self.mupdf.ctx) };
|
||||
@@ -90,7 +108,9 @@ impl crate::Worker {
|
||||
if warned {
|
||||
self.note_damage(id)?;
|
||||
}
|
||||
Ok(Pack::new().u64(u64::from(warned)).blob(&pixels?).bytes())
|
||||
let pixels = pixels?;
|
||||
let damaged = warned | self.found(id)?;
|
||||
Ok(Pack::new().u64(u64::from(damaged)).blob(&pixels).bytes())
|
||||
}
|
||||
|
||||
/// Every picture decoded before an overwrite; true if any failed.
|
||||
@@ -99,6 +119,7 @@ impl crate::Worker {
|
||||
if failed {
|
||||
self.note_damage(id)?;
|
||||
}
|
||||
let failed = failed | self.found(id)?;
|
||||
Ok(Pack::new().u64(u64::from(failed)).bytes())
|
||||
}
|
||||
|
||||
@@ -153,6 +174,12 @@ impl crate::Worker {
|
||||
pub(crate) fn output(&mut self, kind: u8, id: u64, ask: &mut Unpack) -> io::Result<Vec<u8>> {
|
||||
let has = self.allowed(id)?;
|
||||
let doc = self.record(id)?;
|
||||
// What a read found is no whole export.
|
||||
if matches!(kind, tag::EXPORT_IMAGE | tag::EXPORT_TEXT) && doc.found {
|
||||
refuse(may::COPY, has)?;
|
||||
let report = doc.repair.as_deref().expect("noted with the damage");
|
||||
return Err(io::Error::other(format!("the document did not read whole: {report}")));
|
||||
}
|
||||
match kind {
|
||||
tag::EXPORT_IMAGE => {
|
||||
refuse(may::COPY, has)?;
|
||||
|
||||
@@ -148,6 +148,7 @@ fn a_broken_stream_under_a_sound_table_is_damage_and_fails_exports() {
|
||||
let report = worker.repair_report(doc).expect("asks").expect("damage is reported");
|
||||
assert!(!report.trim().is_empty());
|
||||
assert!(worker.export_text(doc, &dir.path().join("doc.txt")).is_err(), "partial text is no export");
|
||||
assert!(worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).is_err(), "nor a partial page");
|
||||
worker.rotate_pages(doc, &[0], 90).expect("edits the copy");
|
||||
doc = worker.now(doc).expect("the state");
|
||||
worker.save(doc, &dir.path().join("fixed.pdf")).expect("saves the copy");
|
||||
@@ -170,6 +171,45 @@ fn a_print_copy_carries_no_lock() {
|
||||
assert_eq!(third.pages(opened.doc).expect("pages"), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_copy_shows_what_prints_to_any_screen_renderer() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
// No looks of their own: MuPDF makes them.
|
||||
let square = |flags: u8, rect: &str, color: &str| format!("<< /Type /Annot /Subtype /Square /F {flags} /Rect [{rect}] /C [{color}] /IC [{color}] >>");
|
||||
let annots = [
|
||||
square(4, "50 100 150 180", "1 0 0"),
|
||||
square(0, "200 100 300 180", "0 1 0"),
|
||||
// Print and NoView: printed, never shown.
|
||||
square(36, "350 100 450 180", "0 0 1"),
|
||||
// Print and Hidden: neither.
|
||||
square(6, "50 300 150 380", "0 1 0"),
|
||||
"<< /Type /Annot /Subtype /Link /F 4 /Rect [200 300 300 380] /A << /S /URI /URI (https://example.com) >> >>".to_string(),
|
||||
];
|
||||
let path = dir.path().join("doc.pdf");
|
||||
std::fs::write(&path, one_page("", " /Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R]", "", &annots)).expect("writes");
|
||||
let (mut worker, doc) = opened(&path);
|
||||
let print = dir.path().join("print.pdf");
|
||||
worker.print_copy(doc, &print).expect("writes");
|
||||
// Only the link stays an annotation.
|
||||
let copy = lopdf::Document::load(&print).expect("a PDF");
|
||||
let left = copy.get_dictionary(copy.get_pages()[&1]).and_then(|page| page.get(b"Annots")).and_then(lopdf::Object::as_array).expect("annotations");
|
||||
let kinds: Vec<&[u8]> = left.iter().map(|annot| copy.dereference(annot).and_then(|(_, a)| a.as_dict()?.get(b"Subtype")?.as_name()).expect("a kind")).collect();
|
||||
assert_eq!(kinds, [b"Link".as_slice()]);
|
||||
assert!(copy.catalog().expect("a catalog").get(b"AcroForm").is_err(), "no form left");
|
||||
// MuPDF draws by screen rules, as Windows' renderer does.
|
||||
let mut third = self::worker();
|
||||
let printed = third.open(&print).expect("opens").doc;
|
||||
let bgra = third.render(printed, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws").bgra;
|
||||
let at = |x: usize, y: usize| -> [u8; 3] {
|
||||
let p = &bgra[((792 - y) * 612 + x) * 4..][..3];
|
||||
[p[2], p[1], p[0]]
|
||||
};
|
||||
assert_eq!(at(100, 140), [255, 0, 0], "printable");
|
||||
assert_eq!(at(250, 140), [255, 255, 255], "not for print");
|
||||
assert_eq!(at(400, 140), [0, 0, 255], "print, not view");
|
||||
assert_eq!(at(100, 340), [255, 255, 255], "hidden");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_picture_shows_when_drawn_or_checked() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
@@ -186,3 +226,131 @@ fn a_broken_picture_shows_when_drawn_or_checked() {
|
||||
assert!(other.check_pictures(again).expect("checks"), "the check finds it undrawn");
|
||||
assert_eq!(std::fs::read(&path).expect("reads"), bytes);
|
||||
}
|
||||
|
||||
/// As many Chinese files name their fonts.
|
||||
const SIMSUN: &str = "<< /Type /Font /Subtype /Type0 /BaseFont /SimSun /Encoding /Identity-H /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /SimSun /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 2 >> /FontDescriptor << /Type /FontDescriptor /FontName /SimSun /Flags 6 /FontBBox [0 -141 996 855] /ItalicAngle 0 /Ascent 859 /Descent -141 /CapHeight 859 /StemV 91 >> >>] >>";
|
||||
|
||||
/// Two runs, each in its own unembedded font.
|
||||
const TWO_RUNS: &str = "BT /F1 24 Tf 72 700 Td <00410042> Tj /F2 24 Tf <0043> Tj ET";
|
||||
|
||||
#[test]
|
||||
fn an_unembedded_font_is_no_damage() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let path = dir.path().join("doc.pdf");
|
||||
// Two fonts, one notice: a repeat is no damage either.
|
||||
let fonts = " /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >>";
|
||||
let bytes = one_page("", fonts, TWO_RUNS, &[SIMSUN.to_string(), SIMSUN.to_string()]);
|
||||
std::fs::write(&path, &bytes).expect("writes");
|
||||
// Each on a fresh worker: no font loaded before.
|
||||
let (mut worker, doc) = opened(&path);
|
||||
worker.export_text(doc, &dir.path().join("doc.txt")).expect("the text exports");
|
||||
let (mut worker, doc) = opened(&path);
|
||||
worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).expect("the page exports");
|
||||
let (mut worker, doc) = opened(&path);
|
||||
// Read unwatched first: its repeat is pending.
|
||||
worker.text(doc, 0).expect("reads");
|
||||
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
|
||||
assert!(!tile.damaged, "a substituted font draws whole");
|
||||
assert_eq!(worker.repair_report(doc).expect("asks"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_content_still_draws_as_damage() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
// Text with no font; a stray bracket.
|
||||
for content in ["BT 72 700 Td (Missing text) Tj ET", "BT ] ET"] {
|
||||
let path = dir.path().join("doc.pdf");
|
||||
std::fs::write(&path, one_page("", "", content, &[])).expect("writes");
|
||||
let (mut worker, doc) = opened(&path);
|
||||
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
|
||||
assert!(tile.damaged, "{content} draws as damage");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two pictures whose zlib checksums are wrong.
|
||||
fn broken_pictures(dir: &Path) -> std::path::PathBuf {
|
||||
let hex = format!("{}>", "ff0000".repeat(16));
|
||||
// One stored deflate block, its checksum wrong.
|
||||
let mut zlib = vec![0x78, 0x01, 0x01];
|
||||
zlib.extend_from_slice(&(hex.len() as u16).to_le_bytes());
|
||||
zlib.extend_from_slice(&(!(hex.len() as u16)).to_le_bytes());
|
||||
zlib.extend_from_slice(hex.as_bytes());
|
||||
zlib.extend_from_slice(&[0, 0, 0, 0]);
|
||||
let slot = "#".repeat(zlib.len());
|
||||
let image = format!("<< /Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter [/FlateDecode /ASCIIHexDecode] /Length {} >>
|
||||
stream
|
||||
{slot}
|
||||
endstream", zlib.len());
|
||||
let names = " /Resources << /XObject << /Im1 5 0 R /Im2 6 0 R >> >>";
|
||||
let mut bytes = one_page("", names, "q 100 0 0 100 72 600 cm /Im1 Do Q q 100 0 0 100 72 400 cm /Im2 Do Q", &[image.clone(), image]);
|
||||
for _ in 0..2 {
|
||||
let at = bytes.windows(slot.len()).position(|w| w == slot.as_bytes()).expect("the slot");
|
||||
bytes[at..at + zlib.len()].copy_from_slice(&zlib);
|
||||
}
|
||||
let path = dir.join("doc.pdf");
|
||||
std::fs::write(&path, &bytes).expect("writes");
|
||||
path
|
||||
}
|
||||
|
||||
/// A picture whose colour key mask is invalid.
|
||||
fn masked() -> String {
|
||||
let hex = format!("{}>", "ff0000".repeat(16));
|
||||
format!("<< /Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Mask [null null null null null null] /Filter /ASCIIHexDecode /Length {} >>
|
||||
stream
|
||||
{hex}
|
||||
endstream", hex.len())
|
||||
}
|
||||
|
||||
/// The bad mask, alone or drawn beside two font notices.
|
||||
fn bad_mask(dir: &Path, fonts: Option<bool>) -> std::path::PathBuf {
|
||||
let picture = "q 100 0 0 100 72 600 cm /Im1 Do Q";
|
||||
let (resources, content, objects) = match fonts {
|
||||
None => (String::new(), picture.to_string(), vec![masked()]),
|
||||
Some(first) => (
|
||||
" /Font << /F1 6 0 R /F2 7 0 R >>".to_string(),
|
||||
if first { format!("{picture} {TWO_RUNS}") } else { format!("{TWO_RUNS} {picture}") },
|
||||
vec![masked(), SIMSUN.to_string(), SIMSUN.to_string()],
|
||||
),
|
||||
};
|
||||
let names = format!(" /Resources << /XObject << /Im1 5 0 R >>{resources} >>");
|
||||
let path = dir.join(format!("mask-{fonts:?}.pdf"));
|
||||
std::fs::write(&path, one_page("", &names, &content, &objects)).expect("writes");
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_picture_under_two_filters_fails_exports() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let path = broken_pictures(dir.path());
|
||||
let (mut worker, doc) = opened(&path);
|
||||
assert!(worker.export_text(doc, &dir.path().join("doc.txt")).is_err(), "its text read whole");
|
||||
let (mut worker, doc) = opened(&path);
|
||||
assert!(worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).is_err(), "its page read whole");
|
||||
let (mut worker, doc) = opened(&path);
|
||||
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
|
||||
assert!(tile.damaged, "the picture draws as damage");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_picture_read_before_is_still_damage() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let files = [broken_pictures(dir.path()), bad_mask(dir.path(), None), bad_mask(dir.path(), Some(true)), bad_mask(dir.path(), Some(false))];
|
||||
// Reading caches the pictures; their repeat waits.
|
||||
let read: [fn(&mut Worker, Doc); 2] = [|w, d| drop(w.text(d, 0).expect("reads")), |w, d| drop(w.search(d, 0, "x").expect("searches"))];
|
||||
for (path, first) in files.iter().flat_map(|p| read.map(|r| (p, r))) {
|
||||
let (mut worker, doc) = opened(path);
|
||||
first(&mut worker, doc);
|
||||
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
|
||||
assert!(tile.damaged, "the picture draws as damage");
|
||||
assert!(worker.repair_report(doc).expect("asks").is_some());
|
||||
let (mut worker, doc) = opened(path);
|
||||
first(&mut worker, doc);
|
||||
assert!(worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).is_err(), "its page read whole");
|
||||
let (mut worker, doc) = opened(path);
|
||||
first(&mut worker, doc);
|
||||
assert!(worker.export_text(doc, &dir.path().join("doc.txt")).is_err(), "its text read whole");
|
||||
let (mut worker, doc) = opened(path);
|
||||
first(&mut worker, doc);
|
||||
assert!(worker.check_pictures(doc).expect("checks"), "the check finds it");
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ arboard.workspace = true
|
||||
directories.workspace = true
|
||||
ely-ipc.workspace = true
|
||||
env_logger.workspace = true
|
||||
futures.workspace = true
|
||||
getrandom.workspace = true
|
||||
image.workspace = true
|
||||
log.workspace = true
|
||||
@@ -38,17 +39,21 @@ security-framework.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys.workspace = true
|
||||
windows.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
lopdf.workspace = true
|
||||
zbus.workspace = true
|
||||
rfd = { workspace = true, features = ["xdg-portal"] }
|
||||
|
||||
[target.'cfg(not(target_os = "linux"))'.dependencies]
|
||||
rfd.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
lopdf.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
@@ -60,3 +65,7 @@ workspace = true
|
||||
[[test]]
|
||||
name = "media"
|
||||
harness = false
|
||||
|
||||
[[test]]
|
||||
name = "print"
|
||||
harness = false
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
use crate::AppId;
|
||||
|
||||
/// Where `app` sits for an install laid out like `exe`'s.
|
||||
fn beside(exe: &Path, app: AppId) -> Vec<PathBuf> {
|
||||
pub(crate) fn beside(exe: &Path, app: AppId) -> Vec<PathBuf> {
|
||||
let file = format!("{}{}", app.slug(), std::env::consts::EXE_SUFFIX);
|
||||
let Some(dir) = exe.parent() else {
|
||||
return Vec::new();
|
||||
@@ -40,7 +40,7 @@ fn find(app: AppId) -> io::Result<Option<PathBuf>> {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn registered(app: AppId) -> Option<PathBuf> {
|
||||
pub(crate) fn registered(app: AppId) -> Option<PathBuf> {
|
||||
use objc2_app_kit::NSWorkspace;
|
||||
use objc2_foundation::NSString;
|
||||
let id = NSString::from_str(&app.bundle_id());
|
||||
@@ -51,7 +51,7 @@ fn registered(app: AppId) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn registered(_: AppId) -> Option<PathBuf> {
|
||||
pub(crate) fn registered(_: AppId) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
|
||||
@@ -74,6 +74,11 @@ pub fn read() -> Result<Option<Clip>> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The clipboard's HTML, if any; gpui's reads omit it.
|
||||
pub fn html() -> Result<Option<String>> {
|
||||
with_board(|board| absent_ok(board.get().html()))
|
||||
}
|
||||
|
||||
/// Empty or other-format clipboards read as None.
|
||||
fn absent_ok<T>(outcome: Result<T, Error>) -> Result<Option<T>> {
|
||||
match outcome {
|
||||
|
||||
@@ -32,8 +32,7 @@ pub fn locate() -> io::Result<(PathBuf, bool)> {
|
||||
Some(serde_json::Value::String(path)) => return Ok((PathBuf::from(path), false)),
|
||||
Some(other) => return Err(io::Error::new(io::ErrorKind::InvalidData, format!("settings: git cannot be {other}"))),
|
||||
}
|
||||
let exe = std::env::current_exe()?;
|
||||
Ok((own(exe.parent().unwrap_or(Path::new("."))), true))
|
||||
Ok((own(&std::env::current_exe()?)?, true))
|
||||
}
|
||||
|
||||
/// `git version 2.56.0…` as (2, 56); None for anything else.
|
||||
@@ -65,19 +64,36 @@ pub fn system_version(path: &Path) -> io::Result<String> {
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
/// Beside `dir`, in its bundle, in ElyTree's, or built.
|
||||
fn own(dir: &Path) -> PathBuf {
|
||||
/// No Git beside the app nor beside ElyTree.
|
||||
#[derive(Debug)]
|
||||
pub struct NoGit;
|
||||
|
||||
impl std::fmt::Display for NoGit {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("Ely's Git is missing: ElyTree carries it")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for NoGit {}
|
||||
|
||||
/// The app at `exe`'s own Git, else ElyTree's, else built.
|
||||
fn own(exe: &Path) -> io::Result<PathBuf> {
|
||||
// ElyTree carries Git; the other apps use its copy.
|
||||
let tree = format!("../../../{}.app/Contents/Resources/git", AppId::Tree.name());
|
||||
let trees = crate::apps::beside(exe, AppId::Tree).into_iter().chain(crate::apps::registered(AppId::Tree));
|
||||
let built = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../engines/git").join(GIT);
|
||||
[
|
||||
dir.join("git").join(GIT),
|
||||
dir.join("../Resources/git").join(GIT),
|
||||
dir.join(tree).join(GIT),
|
||||
]
|
||||
.into_iter()
|
||||
.find(|path| path.is_file())
|
||||
.unwrap_or(built)
|
||||
find(exe, trees, built)
|
||||
}
|
||||
|
||||
/// The first Git beside `exe`, beside a tree, or built.
|
||||
fn find(exe: &Path, trees: impl IntoIterator<Item = PathBuf>, built: PathBuf) -> io::Result<PathBuf> {
|
||||
exe.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.into_iter()
|
||||
.chain(trees.into_iter().filter_map(|tree| tree.parent().map(Path::to_path_buf)))
|
||||
.flat_map(|dir| [dir.join("git").join(GIT), dir.join("../Resources/git").join(GIT)])
|
||||
.chain([built])
|
||||
.find(|path| path.is_file())
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, NoGit))
|
||||
}
|
||||
|
||||
/// Git at `git` in `dir`, as Ely runs it.
|
||||
@@ -119,7 +135,18 @@ mod tests {
|
||||
assert_eq!(super::parse_version("hello"), None);
|
||||
}
|
||||
|
||||
use super::{GIT, own};
|
||||
use super::{GIT, NoGit, find};
|
||||
use crate::{AppId, apps::beside};
|
||||
use std::path::Path;
|
||||
|
||||
/// `find` with only temp folders: no installed or built Git.
|
||||
fn found(exe: &Path, root: &Path) -> std::io::Result<std::path::PathBuf> {
|
||||
find(exe, beside(exe, AppId::Tree), root.join("built").join(GIT))
|
||||
}
|
||||
|
||||
fn same(found: std::path::PathBuf, git: &Path) {
|
||||
assert_eq!(std::fs::canonicalize(found).expect("found"), std::fs::canonicalize(git).expect("git"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apps_beside_elytree_use_its_git() {
|
||||
@@ -127,9 +154,34 @@ mod tests {
|
||||
let mark = apps.path().join("ElyMark.app/Contents/MacOS");
|
||||
let git = apps.path().join("ElyTree.app/Contents/Resources/git").join(GIT);
|
||||
std::fs::create_dir_all(&mark).expect("ElyMark");
|
||||
assert!(own(&mark).ends_with(std::path::Path::new("engines/git").join(GIT)));
|
||||
std::fs::create_dir_all(apps.path().join("ElyTree.app/Contents/MacOS")).expect("ElyTree");
|
||||
let exe = mark.join("ely-mark");
|
||||
let missing = found(&exe, apps.path()).expect_err("no Git yet");
|
||||
assert!(missing.get_ref().is_some_and(|error| error.is::<NoGit>()), "{missing}");
|
||||
std::fs::create_dir_all(git.parent().expect("a folder")).expect("ElyTree's Git");
|
||||
std::fs::write(&git, "").expect("git");
|
||||
assert_eq!(own(&mark), mark.join("../../../ElyTree.app/Contents/Resources/git").join(GIT));
|
||||
same(found(&exe, apps.path()).expect("ElyTree's Git"), &git);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_install_uses_elytrees_git() {
|
||||
let root = tempfile::tempdir().expect("a temp dir");
|
||||
let exe = root.path().join("Ely Office/ElyMark/ely-mark");
|
||||
let git = root.path().join("Ely Office/ElyTree/git").join(GIT);
|
||||
std::fs::create_dir_all(exe.parent().expect("a folder")).expect("ElyMark");
|
||||
assert!(found(&exe, root.path()).is_err(), "no Git yet");
|
||||
std::fs::create_dir_all(git.parent().expect("a folder")).expect("ElyTree's Git");
|
||||
std::fs::write(&git, "").expect("git");
|
||||
same(found(&exe, root.path()).expect("ElyTree's Git"), &git);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_built_git_comes_last() {
|
||||
let root = tempfile::tempdir().expect("a temp dir");
|
||||
let exe = root.path().join("app/ely-mark");
|
||||
let built = root.path().join("built").join(GIT);
|
||||
std::fs::create_dir_all(built.parent().expect("a folder")).expect("built");
|
||||
std::fs::write(&built, "").expect("git");
|
||||
same(found(&exe, root.path()).expect("the built Git"), &built);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +1,32 @@
|
||||
//! Prints a PDF through the system print panel.
|
||||
//! Prints a PDF through the system print dialog.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// This build has a system print panel.
|
||||
pub const BUILT: bool = cfg!(target_os = "macos");
|
||||
|
||||
/// Shows the print panel for `pdf`; false when cancelled.
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn print_pdf(pdf: &Path) -> anyhow::Result<bool> {
|
||||
use objc2::{AllocAnyThread, MainThreadMarker};
|
||||
use objc2_app_kit::{NSPaperOrientation, NSPrintInfo, NSPrintJobSavingURL, NSPrintSaveJob};
|
||||
use objc2_foundation::{NSCopying, NSSize, NSString, NSURL};
|
||||
use objc2_pdf_kit::{PDFDisplayBox, PDFDocument, PDFPrintScalingMode};
|
||||
mod mac;
|
||||
#[cfg(windows)]
|
||||
mod win;
|
||||
|
||||
let mtm =
|
||||
MainThreadMarker::new().ok_or_else(|| anyhow::anyhow!("printing needs the main thread"))?;
|
||||
let url = NSURL::fileURLWithPath(&NSString::from_str(&pdf.to_string_lossy()));
|
||||
let document = unsafe { PDFDocument::initWithURL(PDFDocument::alloc(), &url) }
|
||||
.ok_or_else(|| anyhow::anyhow!("{} is no readable PDF", pdf.display()))?;
|
||||
let sizes: Vec<(f64, f64)> = (0..unsafe { document.pageCount() })
|
||||
.filter_map(|n| unsafe { document.pageAtIndex(n) })
|
||||
.map(|page| {
|
||||
let size = unsafe { page.boundsForBox(PDFDisplayBox::MediaBox) }.size;
|
||||
// A page turned a quarter shows its other side up.
|
||||
match unsafe { page.rotation() }.rem_euclid(180) == 90 {
|
||||
true => (size.height, size.width),
|
||||
false => (size.width, size.height),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let (width, height) = paper_for(&sizes).ok_or_else(|| anyhow::anyhow!("{} has no pages", pdf.display()))?;
|
||||
let paper = NSSize::new(width, height);
|
||||
if let Some(scale) = crate::env::value("ELY_PRINT_SHARED_SCALE") {
|
||||
// Tests start from a shared scale the copy must undo.
|
||||
NSPrintInfo::sharedPrintInfo().setScalingFactor(scale.parse()?);
|
||||
}
|
||||
// The PDF already holds the document's paper, margins and scale.
|
||||
let info = NSPrintInfo::sharedPrintInfo().copy();
|
||||
info.setScalingFactor(1.0);
|
||||
info.setOrientation(match paper.width > paper.height {
|
||||
true => NSPaperOrientation::Landscape,
|
||||
false => NSPaperOrientation::Portrait,
|
||||
});
|
||||
info.setPaperSize(paper);
|
||||
info.setTopMargin(0.0);
|
||||
info.setBottomMargin(0.0);
|
||||
info.setLeftMargin(0.0);
|
||||
info.setRightMargin(0.0);
|
||||
log::info!("print: paper {}x{} points", paper.width, paper.height);
|
||||
let operation = unsafe {
|
||||
document.printOperationForPrintInfo_scalingMode_autoRotate(
|
||||
Some(&info),
|
||||
PDFPrintScalingMode::PageScaleNone,
|
||||
true,
|
||||
mtm,
|
||||
)
|
||||
}
|
||||
.ok_or_else(|| anyhow::anyhow!("no print operation for {}", pdf.display()))?;
|
||||
// Tests read the real job: saved to a file.
|
||||
let saved = crate::env::value("ELY_PRINT_TO");
|
||||
if let Some(to) = &saved {
|
||||
let info = operation.printInfo();
|
||||
info.setJobDisposition(unsafe { NSPrintSaveJob });
|
||||
let to = NSURL::fileURLWithPath(&NSString::from_str(to));
|
||||
unsafe { info.dictionary().insert(NSPrintJobSavingURL, &to) };
|
||||
}
|
||||
operation.setShowsPrintPanel(saved.is_none());
|
||||
operation.setShowsProgressPanel(saved.is_none());
|
||||
let printed = operation.runOperation();
|
||||
log::info!("print: the panel closed, printed {printed}");
|
||||
Ok(printed)
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use linux::print_pdf;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use mac::print_pdf;
|
||||
#[cfg(windows)]
|
||||
pub use win::print_pdf;
|
||||
|
||||
/// Paper sizes round to whole points at worst.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
const ROUNDING: f64 = 0.5;
|
||||
|
||||
/// Whether a named paper, short side first, holds a page.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn holds((across, down): (f64, f64), (short, long): (f64, f64)) -> bool {
|
||||
// A named paper may run 2 mm over, never under.
|
||||
let suits = |paper: f64, page: f64| paper >= page - ROUNDING && paper - page <= 2.0 * 72.0 / 25.4;
|
||||
suits(across, short) && suits(down, long)
|
||||
}
|
||||
|
||||
/// One paper holding every page, turned as needed.
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn paper_for(sizes: &[(f64, f64)]) -> Option<(f64, f64)> {
|
||||
let long = sizes.iter().map(|(w, h)| w.max(*h)).fold(None, |most: Option<f64>, side| Some(most.map_or(side, |m| m.max(side))))?;
|
||||
let short = sizes.iter().map(|(w, h)| w.min(*h)).fold(0.0, f64::max);
|
||||
@@ -87,10 +40,16 @@ fn paper_for(sizes: &[(f64, f64)]) -> Option<(f64, f64)> {
|
||||
Some(if wide { (long, short) } else { (short, long) })
|
||||
}
|
||||
|
||||
/// Printing needs a system panel this platform build lacks.
|
||||
/// Runs `work` on its own thread, off the app's.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn print_pdf(_: &Path) -> anyhow::Result<bool> {
|
||||
anyhow::bail!("printing is not built on this platform")
|
||||
async fn off<T: Send + 'static>(work: impl FnOnce() -> anyhow::Result<T> + Send + 'static) -> anyhow::Result<T> {
|
||||
let (sender, answer) = futures::channel::oneshot::channel();
|
||||
std::thread::Builder::new().name("ely-print".into()).spawn(move || {
|
||||
if sender.send(work()).is_err() {
|
||||
log::warn!("print: the job ended after its caller left");
|
||||
}
|
||||
})?;
|
||||
answer.await.map_err(|_| anyhow::anyhow!("the print thread ended without an answer"))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Linux: the desktop portal's print dialog, over D-Bus.
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
io::{Seek as _, Write as _},
|
||||
os::fd::{AsFd, FromRawFd as _},
|
||||
path::Path,
|
||||
sync::atomic::{AtomicU32, Ordering},
|
||||
};
|
||||
|
||||
use anyhow::{Context as _, anyhow, bail};
|
||||
use futures::StreamExt as _;
|
||||
use lopdf::Document;
|
||||
use serde::Serialize;
|
||||
use zbus::{
|
||||
Connection, Proxy,
|
||||
zvariant::{DynamicType, Fd, OwnedObjectPath, OwnedValue, Value},
|
||||
};
|
||||
|
||||
const TITLE: &str = "Ely Office";
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
const PORTAL: &str = "/org/freedesktop/portal/desktop";
|
||||
/// Standard papers: name, label, width and height in millimetres.
|
||||
const FORMS: [(&str, &str, f64, f64); 6] = [
|
||||
("iso_a3", "A3", 297.0, 420.0),
|
||||
("iso_a4", "A4", 210.0, 297.0),
|
||||
("iso_a5", "A5", 148.0, 210.0),
|
||||
("iso_b5", "B5", 176.0, 250.0),
|
||||
("na_letter", "US Letter", 215.9, 279.4),
|
||||
("na_legal", "US Legal", 215.9, 355.6),
|
||||
];
|
||||
|
||||
type Options = HashMap<&'static str, Value<'static>>;
|
||||
|
||||
mod choices;
|
||||
mod sheets;
|
||||
|
||||
/// Shows the portal's print dialog for `pdf`; false when cancelled.
|
||||
pub async fn print_pdf(pdf: &Path) -> anyhow::Result<bool> {
|
||||
let sizes = {
|
||||
let pdf = pdf.to_owned();
|
||||
super::off(move || sizes(&pdf)).await?
|
||||
};
|
||||
let paper = super::paper_for(&sizes).ok_or_else(|| anyhow!("{} has no pages", pdf.display()))?;
|
||||
log::info!("print: paper {}x{} points", paper.0, paper.1);
|
||||
let bus = Connection::session().await.context("no session bus for the print portal")?;
|
||||
let portal = Proxy::new(&bus, DESKTOP, PORTAL, "org.freedesktop.portal.Print").await?;
|
||||
let settings = Options::new();
|
||||
let prepared = request(&bus, &portal, "PreparePrint", |mut options| {
|
||||
// We hand over PDF; the dialog must not offer others.
|
||||
options.insert("supported_output_file_formats", Value::from(vec!["pdf"]));
|
||||
("", TITLE, settings, page_setup(paper), options)
|
||||
})
|
||||
.await?;
|
||||
let Some(mut prepared) = prepared else {
|
||||
log::info!("print: the dialog was cancelled");
|
||||
return Ok(false);
|
||||
};
|
||||
let token = prepared.get("token").context("the portal gave no print token")?.downcast_ref::<u32>()?;
|
||||
let mut part = |key: &str| -> anyhow::Result<HashMap<String, OwnedValue>> {
|
||||
Ok(prepared.remove(key).with_context(|| format!("the portal gave no {key}"))?.try_into()?)
|
||||
};
|
||||
let choices = choices::chosen(&part("settings")?, &part("page-setup")?)?;
|
||||
log::info!("print: {} copies, {}%, {} up", choices.copies, choices.scale * 100.0, choices.up);
|
||||
// The portal prints our bytes as given: we lay out.
|
||||
let laid = {
|
||||
let pdf = pdf.to_owned();
|
||||
super::off(move || sheets::compose(&pdf, &choices)).await?
|
||||
};
|
||||
let file = in_memory(&laid)?;
|
||||
let fd = Fd::from(file.as_fd());
|
||||
let printed = request(&bus, &portal, "Print", |mut options| {
|
||||
options.insert("token", Value::from(token));
|
||||
("", TITLE, fd, options)
|
||||
})
|
||||
.await?;
|
||||
log::info!("print: the portal took the job, printed {}", printed.is_some());
|
||||
Ok(printed.is_some())
|
||||
}
|
||||
|
||||
/// Calls `method`, awaits its answer; None when cancelled.
|
||||
async fn request<B: Serialize + DynamicType>(
|
||||
bus: &Connection,
|
||||
portal: &Proxy<'_>,
|
||||
method: &str,
|
||||
body: impl FnOnce(Options) -> B,
|
||||
) -> anyhow::Result<Option<HashMap<String, OwnedValue>>> {
|
||||
static NEXT: AtomicU32 = AtomicU32::new(0);
|
||||
let token = format!("ely{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
|
||||
let sender = bus.unique_name().context("the bus gave no name")?.trim_start_matches(':').replace('.', "_");
|
||||
let path = format!("{PORTAL}/request/{sender}/{token}");
|
||||
// Listen before asking: the answer may come first.
|
||||
let request = Proxy::new(bus, DESKTOP, path.as_str(), "org.freedesktop.portal.Request").await?;
|
||||
let mut answers = request.receive_signal("Response").await?;
|
||||
let handle: OwnedObjectPath = portal.call(method, &body(Options::from([("handle_token", Value::from(token.clone()))]))).await?;
|
||||
if handle.as_str() != path {
|
||||
bail!("the portal answers at {handle}, not {path}");
|
||||
}
|
||||
let answer = answers.next().await.context("the portal closed the request")?;
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = answer.body().deserialize()?;
|
||||
match code {
|
||||
0 => Ok(Some(results)),
|
||||
1 => Ok(None),
|
||||
_ => bail!("the portal ended {method} ({code})"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The portal's page setup for a paper, margins zero.
|
||||
fn page_setup((width, height): (f64, f64)) -> Options {
|
||||
let millimetres = |points: f64| points * 25.4 / 72.0;
|
||||
let (short, long) = (millimetres(width.min(height)), millimetres(width.max(height)));
|
||||
let points = |mm: f64| mm * 72.0 / 25.4;
|
||||
let page = (width.min(height), width.max(height));
|
||||
let (name, label) = match FORMS.iter().find(|(.., across, down)| super::holds((points(*across), points(*down)), page)) {
|
||||
Some((name, label, ..)) => (name.to_string(), label.to_string()),
|
||||
None => (format!("custom_{short:.0}x{long:.0}mm"), format!("{short:.0} × {long:.0} mm")),
|
||||
};
|
||||
let orientation = if width > height { "landscape" } else { "portrait" };
|
||||
Options::from([
|
||||
("Name", Value::from(name)),
|
||||
("DisplayName", Value::from(label)),
|
||||
("Width", Value::from(short)),
|
||||
("Height", Value::from(long)),
|
||||
("MarginTop", Value::from(0.0)),
|
||||
("MarginBottom", Value::from(0.0)),
|
||||
("MarginLeft", Value::from(0.0)),
|
||||
("MarginRight", Value::from(0.0)),
|
||||
("Orientation", Value::from(orientation)),
|
||||
])
|
||||
}
|
||||
|
||||
/// Each page's size in points, as it shows.
|
||||
fn sizes(pdf: &Path) -> anyhow::Result<Vec<(f64, f64)>> {
|
||||
let document = Document::load(pdf)?;
|
||||
document.get_pages().into_values().map(|page| Ok(sheets::Shown::of(&document, page)?.size())).collect()
|
||||
}
|
||||
|
||||
/// `bytes` in an unnamed file, read from its start.
|
||||
fn in_memory(bytes: &[u8]) -> anyhow::Result<File> {
|
||||
let fd = unsafe { libc::memfd_create(c"ely-print".as_ptr(), libc::MFD_CLOEXEC) };
|
||||
if fd < 0 {
|
||||
bail!("no file for the print job: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
let mut file = unsafe { File::from_raw_fd(fd) };
|
||||
file.write_all(bytes)?;
|
||||
file.rewind()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{page_setup, sizes};
|
||||
|
||||
#[test]
|
||||
fn a_known_paper_goes_by_its_name() {
|
||||
let setup = page_setup((842.0, 595.0));
|
||||
let text = |key: &str| setup[key].downcast_ref::<&str>().expect("text");
|
||||
let number = |key: &str| setup[key].downcast_ref::<f64>().expect("a number").round();
|
||||
assert_eq!((text("Name"), text("Orientation")), ("iso_a4", "landscape"));
|
||||
assert_eq!((number("Width"), number("Height"), number("MarginLeft")), (210.0, 297.0, 0.0));
|
||||
let custom = page_setup((283.5, 425.2));
|
||||
assert_eq!(custom["Name"].downcast_ref::<&str>().expect("text"), "custom_100x150mm");
|
||||
assert_eq!(custom["Orientation"].downcast_ref::<&str>().expect("text"), "portrait");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_sizes_inherit_turn_and_scale() {
|
||||
use lopdf::{Document, Object, dictionary};
|
||||
|
||||
let mut document = Document::with_version("1.7");
|
||||
let tree = document.new_object_id();
|
||||
let media: Vec<Object> = vec![0.into(), 0.into(), 595.into(), 842.into()];
|
||||
let upright = document.add_object(dictionary! { "Type" => "Page", "Parent" => tree });
|
||||
let turned = document.add_object(dictionary! { "Type" => "Page", "Parent" => tree, "Rotate" => 90 });
|
||||
let cropped = document.add_object(dictionary! { "Type" => "Page", "Parent" => tree, "CropBox" => vec![10.into(), 10.into(), 110.into(), 60.into()] });
|
||||
let large = document.add_object(dictionary! { "Type" => "Page", "Parent" => tree, "UserUnit" => 2 });
|
||||
let kids: Vec<Object> = vec![upright.into(), turned.into(), cropped.into(), large.into()];
|
||||
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => 4, "MediaBox" => media }.into());
|
||||
let catalog = document.add_object(dictionary! { "Type" => "Catalog", "Pages" => tree });
|
||||
document.trailer.set("Root", catalog);
|
||||
let folder = tempfile::tempdir().expect("a folder");
|
||||
let pdf = folder.path().join("pages.pdf");
|
||||
document.save(&pdf).expect("saves");
|
||||
assert_eq!(sizes(&pdf).expect("reads"), [(595.0, 842.0), (842.0, 595.0), (100.0, 50.0), (1190.0, 1684.0)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! What the portal's dialog chose: its settings and page setup.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::{Context as _, bail};
|
||||
use zbus::zvariant::OwnedValue;
|
||||
|
||||
type Map = HashMap<String, OwnedValue>;
|
||||
|
||||
/// Which sheets print, counting from one.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum Set {
|
||||
All,
|
||||
Even,
|
||||
Odd,
|
||||
}
|
||||
|
||||
/// How several pages fill one sheet.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct Order {
|
||||
pub across_first: bool,
|
||||
pub leftward: bool,
|
||||
pub upward: bool,
|
||||
}
|
||||
|
||||
/// The dialog's choices; the app applies every one.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct Choices {
|
||||
/// Pages from zero, both ends kept; None is every page.
|
||||
pub ranges: Option<Vec<(u32, u32)>>,
|
||||
pub set: Set,
|
||||
pub reverse: bool,
|
||||
pub copies: u32,
|
||||
pub collate: bool,
|
||||
pub scale: f64,
|
||||
pub up: u32,
|
||||
pub order: Order,
|
||||
/// The sheet as it lies, in points.
|
||||
pub sheet: (f64, f64),
|
||||
pub upside_down: bool,
|
||||
}
|
||||
|
||||
/// GTK's settings and page setup, as the portal passes them.
|
||||
pub(super) fn chosen(settings: &Map, setup: &Map) -> anyhow::Result<Choices> {
|
||||
let ranges = match text(settings, "print-pages")?.unwrap_or("all") {
|
||||
"all" => None,
|
||||
"ranges" => Some(ranges(text(settings, "page-ranges")?.context("the print dialog gave no page ranges")?)?),
|
||||
other => bail!("the print dialog chose the {other} pages; Ely offers none"),
|
||||
};
|
||||
let set = match text(settings, "page-set")?.unwrap_or("all") {
|
||||
"all" => Set::All,
|
||||
"even" => Set::Even,
|
||||
"odd" => Set::Odd,
|
||||
other => bail!("the print dialog chose the page set {other}"),
|
||||
};
|
||||
// GTK's CUPS backend sends even or odd to CUPS.
|
||||
let set = match settings.contains_key("output-uri") || settings.contains_key("lpr-commandline") {
|
||||
true => set,
|
||||
false => Set::All,
|
||||
};
|
||||
let scale = number(settings, "scale", 100.0)? / 100.0;
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
bail!("the print dialog chose a scale of {}%", scale * 100.0);
|
||||
}
|
||||
let order = order(text(settings, "number-up-layout")?.unwrap_or("lrtb"))?;
|
||||
let millimetres = |key: &str| -> anyhow::Result<f64> {
|
||||
let value = setup.get(key).with_context(|| format!("the page setup gives no {key}"))?;
|
||||
Ok(value.downcast_ref::<f64>().with_context(|| format!("the page setup's {key} is no number"))? * 72.0 / 25.4)
|
||||
};
|
||||
let (width, height) = (millimetres("Width")?, millimetres("Height")?);
|
||||
let way = setup.get("Orientation").context("the page setup gives no orientation")?;
|
||||
let (sheet, upside_down) = match way.downcast_ref::<&str>().context("the page setup's orientation is no text")? {
|
||||
"portrait" => ((width, height), false),
|
||||
"landscape" => ((height, width), false),
|
||||
"reverse-portrait" => ((width, height), true),
|
||||
"reverse-landscape" => ((height, width), true),
|
||||
other => bail!("the page setup's orientation is {other}"),
|
||||
};
|
||||
Ok(Choices {
|
||||
ranges,
|
||||
set,
|
||||
reverse: flag(settings, "reverse", false)?,
|
||||
copies: count(settings, "n-copies")?,
|
||||
collate: flag(settings, "collate", true)?,
|
||||
scale,
|
||||
up: count(settings, "number-up")?,
|
||||
order,
|
||||
sheet,
|
||||
upside_down,
|
||||
})
|
||||
}
|
||||
|
||||
/// GTK's ranges, "0-2,4" from zero; end -1 runs on.
|
||||
fn ranges(text: &str) -> anyhow::Result<Vec<(u32, u32)>> {
|
||||
let page = |part: &str| part.trim().parse::<u32>().with_context(|| format!("the page range {text} is unreadable"));
|
||||
let ranges = text
|
||||
.split(',')
|
||||
.filter(|part| !part.trim().is_empty())
|
||||
.map(|part| {
|
||||
let (from, to) = match part.split_once('-') {
|
||||
Some((from, to)) if to.trim() == "-1" => (page(from)?, u32::MAX),
|
||||
Some((from, to)) => (page(from)?, page(to)?),
|
||||
None => (page(part)?, page(part)?),
|
||||
};
|
||||
if from > to {
|
||||
bail!("the page range {text} runs backwards");
|
||||
}
|
||||
Ok((from, to))
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
if ranges.is_empty() {
|
||||
bail!("the page ranges are empty");
|
||||
}
|
||||
Ok(ranges)
|
||||
}
|
||||
|
||||
/// GTK's n-up nick, such as "lrtb": first way, then next.
|
||||
fn order(nick: &str) -> anyhow::Result<Order> {
|
||||
let (first, then) = nick.split_at_checked(2).with_context(|| format!("the n-up layout {nick} is unknown"))?;
|
||||
let across = |way: &str| matches!(way, "lr" | "rl");
|
||||
let down = |way: &str| matches!(way, "tb" | "bt");
|
||||
if !(across(first) && down(then) || down(first) && across(then)) {
|
||||
bail!("the n-up layout {nick} is unknown");
|
||||
}
|
||||
Ok(Order { across_first: across(first), leftward: nick.contains("rl"), upward: nick.contains("bt") })
|
||||
}
|
||||
|
||||
fn text<'a>(settings: &'a Map, key: &str) -> anyhow::Result<Option<&'a str>> {
|
||||
let value = settings.get(key).map(|value| value.downcast_ref::<&str>());
|
||||
value.transpose().with_context(|| format!("the print setting {key} is no text"))
|
||||
}
|
||||
|
||||
fn number(settings: &Map, key: &str, unset: f64) -> anyhow::Result<f64> {
|
||||
match text(settings, key)? {
|
||||
Some(text) => text.trim().parse().with_context(|| format!("the print setting {key} is {text}")),
|
||||
None => Ok(unset),
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole number, at least one; one when unset.
|
||||
fn count(settings: &Map, key: &str) -> anyhow::Result<u32> {
|
||||
let count = match text(settings, key)? {
|
||||
Some(text) => text.trim().parse().with_context(|| format!("the print setting {key} is {text}"))?,
|
||||
None => 1,
|
||||
};
|
||||
if count == 0 {
|
||||
bail!("the print setting {key} is zero");
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn flag(settings: &Map, key: &str, unset: bool) -> anyhow::Result<bool> {
|
||||
match text(settings, key)? {
|
||||
None => Ok(unset),
|
||||
Some("true") => Ok(true),
|
||||
Some("false") => Ok(false),
|
||||
Some(other) => bail!("the print setting {key} is {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use zbus::zvariant::{OwnedValue, Value};
|
||||
|
||||
use super::{Choices, Map, Order, Set, chosen};
|
||||
|
||||
fn map(pairs: &[(&str, Value<'static>)]) -> Map {
|
||||
pairs.iter().map(|(key, value)| (key.to_string(), OwnedValue::try_from(value.clone()).expect("owned"))).collect()
|
||||
}
|
||||
|
||||
fn a4(orientation: &'static str) -> Map {
|
||||
map(&[("Width", Value::from(210.0)), ("Height", Value::from(297.0)), ("Orientation", Value::from(orientation))])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unset_settings_print_everything_once() {
|
||||
let choices = chosen(&Map::new(), &a4("portrait")).expect("reads");
|
||||
let order = Order { across_first: true, leftward: false, upward: false };
|
||||
let (width, height) = (210.0 * 72.0 / 25.4, 297.0 * 72.0 / 25.4);
|
||||
assert_eq!(
|
||||
choices,
|
||||
Choices {
|
||||
ranges: None,
|
||||
set: Set::All,
|
||||
reverse: false,
|
||||
copies: 1,
|
||||
collate: true,
|
||||
scale: 1.0,
|
||||
up: 1,
|
||||
order,
|
||||
sheet: (width, height),
|
||||
upside_down: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gtk_settings_read_as_given() {
|
||||
let settings = map(&[
|
||||
("print-pages", Value::from("ranges")),
|
||||
("page-ranges", Value::from("0-1, 4,7--1")),
|
||||
("page-set", Value::from("even")),
|
||||
("reverse", Value::from("true")),
|
||||
("n-copies", Value::from("3")),
|
||||
("collate", Value::from("false")),
|
||||
("scale", Value::from("50")),
|
||||
("number-up", Value::from("4")),
|
||||
("number-up-layout", Value::from("btrl")),
|
||||
("output-uri", Value::from("file:///tmp/out.pdf")),
|
||||
]);
|
||||
let choices = chosen(&settings, &a4("reverse-landscape")).expect("reads");
|
||||
assert_eq!(choices.ranges, Some(vec![(0, 1), (4, 4), (7, u32::MAX)]));
|
||||
assert_eq!((choices.set, choices.reverse, choices.copies, choices.collate), (Set::Even, true, 3, false));
|
||||
assert_eq!((choices.scale, choices.up), (0.5, 4));
|
||||
assert_eq!(choices.order, Order { across_first: false, leftward: true, upward: true });
|
||||
assert_eq!((choices.sheet.0.round(), choices.sheet.1.round(), choices.upside_down), (842.0, 595.0, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_pages_are_ours_only_where_cups_leaves_them() {
|
||||
let set = |backend: &[(&str, Value<'static>)]| {
|
||||
let mut pairs = vec![("page-set", Value::from("even"))];
|
||||
pairs.extend_from_slice(backend);
|
||||
chosen(&map(&pairs), &a4("portrait")).expect("reads").set
|
||||
};
|
||||
// GTK's CUPS backend sends cups-page-set itself.
|
||||
assert_eq!(set(&[("printer", Value::from("Office"))]), Set::All);
|
||||
assert_eq!(set(&[("output-uri", Value::from("file:///tmp/out.pdf"))]), Set::Even);
|
||||
assert_eq!(set(&[("lpr-commandline", Value::from("lpr"))]), Set::Even);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_cannot_be_honoured_fails() {
|
||||
let bad = |pairs: &[(&str, Value<'static>)]| chosen(&map(pairs), &a4("portrait")).is_err();
|
||||
assert!(bad(&[("print-pages", Value::from("selection"))]));
|
||||
assert!(bad(&[("print-pages", Value::from("ranges")), ("page-ranges", Value::from("two"))]));
|
||||
assert!(bad(&[("print-pages", Value::from("ranges")), ("page-ranges", Value::from("3-1"))]));
|
||||
assert!(chosen(&Map::new(), &a4("reverse_portrait")).is_err(), "GTK writes reverse-portrait");
|
||||
assert!(bad(&[("scale", Value::from("0"))]));
|
||||
assert!(bad(&[("n-copies", Value::from("0"))]));
|
||||
assert!(bad(&[("number-up-layout", Value::from("lrrl"))]));
|
||||
assert!(bad(&[("reverse", Value::from(1u32))]));
|
||||
assert!(chosen(&Map::new(), &map(&[("Width", Value::from(210.0))])).is_err(), "no height");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! The chosen pages laid on the chosen sheets, as PDF.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use anyhow::{Context as _, anyhow, bail};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary};
|
||||
|
||||
use super::choices::{Choices, Set};
|
||||
use crate::print::ROUNDING;
|
||||
|
||||
/// Catalog entries that name pages no longer there.
|
||||
const STALE: [&str; 4] = ["Outlines", "OpenAction", "AcroForm", "PageLabels"];
|
||||
|
||||
/// A PDF matrix, `[a b c d e f]`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct Matrix(pub [f64; 6]);
|
||||
|
||||
impl Matrix {
|
||||
/// This, then `next`.
|
||||
fn then(self, next: Matrix) -> Matrix {
|
||||
let ([a, b, c, d, e, f], [g, h, i, j, k, l]) = (self.0, next.0);
|
||||
Matrix([a * g + b * i, a * h + b * j, c * g + d * i, c * h + d * j, e * g + f * i + k, e * h + f * j + l])
|
||||
}
|
||||
|
||||
pub(super) fn apply(self, (x, y): (f64, f64)) -> (f64, f64) {
|
||||
let [a, b, c, d, e, f] = self.0;
|
||||
(a * x + c * y + e, b * x + d * y + f)
|
||||
}
|
||||
}
|
||||
|
||||
/// A page's box, unit and turn.
|
||||
pub(super) struct Shown {
|
||||
corners: [f64; 4],
|
||||
unit: f64,
|
||||
turn: i64,
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
pub(super) fn of(document: &Document, page: ObjectId) -> anyhow::Result<Self> {
|
||||
let corners = |bounds: &Object| -> anyhow::Result<[f64; 4]> {
|
||||
let numbers = bounds.as_array()?.iter().map(|n| Ok(f64::from(n.as_float()?))).collect::<anyhow::Result<Vec<_>>>()?;
|
||||
let [x0, y0, x1, y1] = numbers[..] else {
|
||||
bail!("a page box has {} numbers", numbers.len());
|
||||
};
|
||||
Ok([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
|
||||
};
|
||||
let media = corners(inherited(document, page, b"MediaBox")?.ok_or_else(|| anyhow!("a page has no media box"))?)?;
|
||||
// A crop box is cut to the media box.
|
||||
let [x0, y0, x1, y1] = match inherited(document, page, b"CropBox")? {
|
||||
Some(crop) => {
|
||||
let crop = corners(crop)?;
|
||||
[crop[0].max(media[0]), crop[1].max(media[1]), crop[2].min(media[2]), crop[3].min(media[3])]
|
||||
}
|
||||
None => media,
|
||||
};
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
bail!("a page's crop box lies outside its media box");
|
||||
}
|
||||
// UserUnit is the page's own, never inherited.
|
||||
let unit = match document.get_dictionary(page)?.get(b"UserUnit") {
|
||||
Ok(unit) => f64::from(document.dereference(unit)?.1.as_float()?),
|
||||
Err(_) => 1.0,
|
||||
};
|
||||
let turn = inherited(document, page, b"Rotate")?.map_or(Ok(0), Object::as_i64)?.rem_euclid(360);
|
||||
if !(unit > 0.0 && turn % 90 == 0) {
|
||||
bail!("a page has a unit of {unit} or a turn of {turn}");
|
||||
}
|
||||
Ok(Self { corners: [x0, y0, x1, y1], unit, turn })
|
||||
}
|
||||
|
||||
/// Width and height in points, as it shows.
|
||||
pub(super) fn size(&self) -> (f64, f64) {
|
||||
let [x0, y0, x1, y1] = self.corners;
|
||||
let (width, height) = ((x1 - x0) * self.unit, (y1 - y0) * self.unit);
|
||||
// A page turned a quarter shows its other side up.
|
||||
if self.turn % 180 == 90 { (height, width) } else { (width, height) }
|
||||
}
|
||||
|
||||
/// From the page's own space to its shown points.
|
||||
fn matrix(&self) -> Matrix {
|
||||
let [x0, y0, x1, y1] = self.corners;
|
||||
let (w, h) = ((x1 - x0) * self.unit, (y1 - y0) * self.unit);
|
||||
let unit = Matrix([self.unit, 0.0, 0.0, self.unit, -x0 * self.unit, -y0 * self.unit]);
|
||||
// Rotate turns the page clockwise as shown.
|
||||
unit.then(Matrix(match self.turn {
|
||||
90 => [0.0, -1.0, 1.0, 0.0, 0.0, w],
|
||||
180 => [-1.0, 0.0, 0.0, -1.0, w, h],
|
||||
270 => [0.0, 1.0, -1.0, 0.0, h, 0.0],
|
||||
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// `key` on the page or its nearest tree node.
|
||||
pub(super) fn inherited<'a>(document: &'a Document, page: ObjectId, key: &[u8]) -> anyhow::Result<Option<&'a Object>> {
|
||||
let mut node = document.get_dictionary(page)?;
|
||||
// A loop in the tree must not hang.
|
||||
for _ in 0..64 {
|
||||
if let Ok(value) = node.get(key) {
|
||||
return Ok(Some(document.dereference(value)?.1));
|
||||
}
|
||||
let Ok(parent) = node.get(b"Parent") else {
|
||||
return Ok(None);
|
||||
};
|
||||
node = document.dereference(parent)?.1.as_dict()?;
|
||||
}
|
||||
bail!("the page tree is deeper than 64")
|
||||
}
|
||||
|
||||
/// The PDF at `pdf`, laid out as `choices` asks.
|
||||
pub(super) fn compose(pdf: &std::path::Path, choices: &Choices) -> anyhow::Result<Vec<u8>> {
|
||||
let mut document = Document::load(pdf)?;
|
||||
let pages: Vec<ObjectId> = document.get_pages().into_values().collect();
|
||||
let picked = picked(choices, pages.len())?;
|
||||
let mut forms = BTreeMap::new();
|
||||
for &n in &picked {
|
||||
if let std::collections::btree_map::Entry::Vacant(slot) = forms.entry(n) {
|
||||
slot.insert(form(&mut document, pages[n])?);
|
||||
}
|
||||
}
|
||||
let shown = picked.iter().map(|&n| Shown::of(&document, pages[n])).collect::<anyhow::Result<Vec<_>>>()?;
|
||||
let laid = lay(choices, &picked, &shown)?;
|
||||
let tree = document.new_object_id();
|
||||
let (width, height) = choices.sheet;
|
||||
let mut sheets = Vec::with_capacity(laid.len());
|
||||
for placed in &laid {
|
||||
let mut drawn = String::new();
|
||||
let mut objects = Dictionary::new();
|
||||
for &(n, Matrix([a, b, c, d, e, f])) in placed {
|
||||
drawn.push_str(&format!("q {a:.4} {b:.4} {c:.4} {d:.4} {e:.4} {f:.4} cm /P{n} Do Q\n"));
|
||||
objects.set(format!("P{n}"), forms[&n]);
|
||||
}
|
||||
let mut stream = Stream::new(Dictionary::new(), drawn.into_bytes());
|
||||
stream.compress()?;
|
||||
let contents = document.add_object(stream);
|
||||
let media: Vec<Object> = vec![0.into(), 0.into(), (width as f32).into(), (height as f32).into()];
|
||||
let mut sheet = dictionary! {
|
||||
"Type" => "Page",
|
||||
"Parent" => tree,
|
||||
"MediaBox" => media,
|
||||
"Resources" => dictionary! { "XObject" => objects },
|
||||
"Contents" => contents,
|
||||
};
|
||||
if choices.upside_down {
|
||||
sheet.set("Rotate", 180);
|
||||
}
|
||||
sheets.push(sheet);
|
||||
}
|
||||
let kids: Vec<Object> = arrange(choices, sheets.len())?.into_iter().map(|n| document.add_object(sheets[n].clone()).into()).collect();
|
||||
let count = kids.len() as i64;
|
||||
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }.into());
|
||||
let root = document.trailer.get(b"Root")?.as_reference()?;
|
||||
let catalog = document.get_object_mut(root)?.as_dict_mut()?;
|
||||
catalog.set("Pages", tree);
|
||||
for key in STALE {
|
||||
catalog.remove(key.as_bytes());
|
||||
}
|
||||
document.prune_objects();
|
||||
let mut bytes = Vec::new();
|
||||
document.save_to(&mut bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The chosen pages, from zero, in the dialog's order.
|
||||
fn picked(choices: &Choices, count: usize) -> anyhow::Result<Vec<usize>> {
|
||||
let last = count.checked_sub(1).context("the document has no pages")? as u32;
|
||||
let picked: Vec<usize> = match &choices.ranges {
|
||||
None => (0..count).collect(),
|
||||
Some(ranges) => ranges.iter().filter(|(from, _)| *from <= last).flat_map(|&(from, to)| from as usize..=to.min(last) as usize).collect(),
|
||||
};
|
||||
if picked.is_empty() {
|
||||
bail!("none of the chosen pages are in the document");
|
||||
}
|
||||
Ok(picked)
|
||||
}
|
||||
|
||||
/// Sheets in print order: set, reverse, then copies.
|
||||
fn arrange(choices: &Choices, sheets: usize) -> anyhow::Result<Vec<usize>> {
|
||||
let mut order: Vec<usize> = (0..sheets)
|
||||
.filter(|n| match choices.set {
|
||||
Set::All => true,
|
||||
Set::Even => n % 2 == 1,
|
||||
Set::Odd => n % 2 == 0,
|
||||
})
|
||||
.collect();
|
||||
if order.is_empty() {
|
||||
bail!("the chosen page set leaves no sheet to print");
|
||||
}
|
||||
if choices.reverse {
|
||||
order.reverse();
|
||||
}
|
||||
let copies = choices.copies as usize;
|
||||
Ok(match choices.collate {
|
||||
true => order.iter().copied().cycle().take(order.len() * copies).collect(),
|
||||
false => order.into_iter().flat_map(|n| std::iter::repeat_n(n, copies)).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Each sheet's pages: which page, and where it goes.
|
||||
fn lay(choices: &Choices, picked: &[usize], shown: &[Shown]) -> anyhow::Result<Vec<Vec<(usize, Matrix)>>> {
|
||||
let (width, height) = choices.sheet;
|
||||
if choices.up == 1 {
|
||||
return picked
|
||||
.iter()
|
||||
.zip(shown)
|
||||
.map(|(&n, page)| {
|
||||
let (w, h) = page.size();
|
||||
let k = choices.scale;
|
||||
let fits = |across: f64, down: f64| k * across <= width + ROUNDING && k * down <= height + ROUNDING;
|
||||
// Placed from the sheet's top left; turned left if needed.
|
||||
let place = match (fits(w, h), fits(h, w)) {
|
||||
(true, _) => Matrix([k, 0.0, 0.0, k, 0.0, height - k * h]),
|
||||
(false, true) => Matrix([0.0, k, -k, 0.0, k * h, height - k * w]),
|
||||
(false, false) => bail!(
|
||||
"page {} at {:.0}% is larger than the {:.0} × {:.0} mm paper",
|
||||
n + 1,
|
||||
k * 100.0,
|
||||
width * 25.4 / 72.0,
|
||||
height * 25.4 / 72.0
|
||||
),
|
||||
};
|
||||
Ok(vec![(n, page.matrix().then(place))])
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let (cols, rows) = grid(choices.up, choices.sheet, shown);
|
||||
let (cell_w, cell_h) = (width / f64::from(cols), height / f64::from(rows));
|
||||
let mut sheets = Vec::new();
|
||||
for (pages, looks) in picked.chunks(choices.up as usize).zip(shown.chunks(choices.up as usize)) {
|
||||
let placed = pages.iter().zip(looks).enumerate().map(|(slot, (&n, page))| {
|
||||
let (col, row) = cell(slot as u32, (cols, rows), choices);
|
||||
let (w, h) = page.size();
|
||||
let k = (cell_w / w).min(cell_h / h) * choices.scale;
|
||||
// Centred in its cell.
|
||||
let left = f64::from(col) * cell_w + (cell_w - k * w) / 2.0;
|
||||
let bottom = height - f64::from(row + 1) * cell_h + (cell_h - k * h) / 2.0;
|
||||
(n, page.matrix().then(Matrix([k, 0.0, 0.0, k, left, bottom])))
|
||||
});
|
||||
sheets.push(placed.collect());
|
||||
}
|
||||
Ok(sheets)
|
||||
}
|
||||
|
||||
/// Columns and rows for `up` pages; the largest fit best.
|
||||
fn grid(up: u32, (width, height): (f64, f64), shown: &[Shown]) -> (u32, u32) {
|
||||
let (w, h) = shown.iter().map(Shown::size).fold((0.0, 0.0), |(a, b), (w, h)| (w.max(a), h.max(b)));
|
||||
let fit = |(cols, rows): (u32, u32)| (width / f64::from(cols) / w).min(height / f64::from(rows) / h);
|
||||
let grids = (1..=up).filter(|&cols| up.is_multiple_of(cols)).map(|cols| (cols, up / cols));
|
||||
grids.fold((up, 1), |best, grid| if fit(grid) > fit(best) { grid } else { best })
|
||||
}
|
||||
|
||||
/// Slot `n`'s column and row, by the dialog's n-up order.
|
||||
fn cell(n: u32, (cols, rows): (u32, u32), choices: &Choices) -> (u32, u32) {
|
||||
let order = choices.order;
|
||||
let (col, row) = if order.across_first { (n % cols, n / cols) } else { (n / rows, n % rows) };
|
||||
(if order.leftward { cols - 1 - col } else { col }, if order.upward { rows - 1 - row } else { row })
|
||||
}
|
||||
|
||||
/// The page as a form, printable annotations drawn on top.
|
||||
fn form(document: &mut Document, page: ObjectId) -> anyhow::Result<ObjectId> {
|
||||
let mut drawn = b"q\n".to_vec();
|
||||
for content in document.get_page_contents(page) {
|
||||
drawn.extend(document.get_object(content)?.as_stream()?.decompressed_content()?);
|
||||
drawn.push(b'\n');
|
||||
}
|
||||
drawn.extend(b"Q\n");
|
||||
let mut resources = match inherited(document, page, b"Resources")? {
|
||||
Some(resources) => resources.as_dict()?.clone(),
|
||||
None => Dictionary::new(),
|
||||
};
|
||||
let mut objects = match resources.get(b"XObject") {
|
||||
Ok(objects) => document.dereference(objects)?.1.as_dict()?.clone(),
|
||||
Err(_) => Dictionary::new(),
|
||||
};
|
||||
let mut n = 0;
|
||||
for (look, place) in appearances(document, page)? {
|
||||
// Names the page already uses stay its own.
|
||||
while objects.has(format!("ElyAnnot{n}").as_bytes()) {
|
||||
n += 1;
|
||||
}
|
||||
let [a, b, c, d, e, f] = place.0;
|
||||
drawn.extend(format!("q {a:.4} {b:.4} {c:.4} {d:.4} {e:.4} {f:.4} cm /ElyAnnot{n} Do Q\n").into_bytes());
|
||||
objects.set(format!("ElyAnnot{n}"), look);
|
||||
let look = document.get_object_mut(look)?.as_stream_mut()?;
|
||||
if look.dict.get(b"Subtype").is_err() {
|
||||
look.dict.set("Subtype", "Form");
|
||||
}
|
||||
}
|
||||
resources.set("XObject", objects);
|
||||
let [x0, y0, x1, y1] = Shown::of(document, page)?.corners;
|
||||
let bounds: Vec<Object> = [x0, y0, x1, y1].into_iter().map(|n| (n as f32).into()).collect();
|
||||
let mut dict = dictionary! { "Type" => "XObject", "Subtype" => "Form", "BBox" => bounds, "Resources" => resources };
|
||||
if let Some(group) = inherited(document, page, b"Group")? {
|
||||
dict.set("Group", group.clone());
|
||||
}
|
||||
let mut stream = Stream::new(dict, drawn);
|
||||
stream.compress()?;
|
||||
Ok(document.add_object(stream))
|
||||
}
|
||||
|
||||
/// Printable annotations' looks, and where each goes on the page.
|
||||
fn appearances(document: &Document, page: ObjectId) -> anyhow::Result<Vec<(ObjectId, Matrix)>> {
|
||||
let Ok(annots) = document.get_dictionary(page)?.get(b"Annots") else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let turn = Shown::of(document, page)?.turn;
|
||||
let mut looks = Vec::new();
|
||||
for annot in document.dereference(annots)?.1.as_array()? {
|
||||
let annot = document.dereference(annot)?.1.as_dict()?;
|
||||
let flags = annot.get(b"F").and_then(Object::as_i64).unwrap_or(0);
|
||||
// Hidden, or not marked for print: left out.
|
||||
if flags & 2 != 0 || flags & 4 == 0 {
|
||||
continue;
|
||||
}
|
||||
let Some(look) = appearance(document, annot)? else {
|
||||
continue;
|
||||
};
|
||||
let stream = document.get_object(look)?.as_stream()?;
|
||||
let numbers = |object: &Object| -> anyhow::Result<Vec<f64>> {
|
||||
document.dereference(object)?.1.as_array()?.iter().map(|n| Ok(f64::from(n.as_float()?))).collect()
|
||||
};
|
||||
let bounds = numbers(stream.dict.get(b"BBox")?)?;
|
||||
let rect = numbers(annot.get(b"Rect")?)?;
|
||||
let own = match stream.dict.get(b"Matrix") {
|
||||
Ok(matrix) => Matrix(numbers(matrix)?.try_into().map_err(|_| anyhow!("an appearance matrix is not six numbers"))?),
|
||||
Err(_) => Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),
|
||||
};
|
||||
let ([bx0, by0, bx1, by1], [rx0, ry0, rx1, ry1]) = (four(&bounds)?, four(&rect)?);
|
||||
// The look's box, through its matrix, fills the rectangle.
|
||||
let corners = [(bx0, by0), (bx1, by0), (bx0, by1), (bx1, by1)].map(|corner| own.apply(corner));
|
||||
let (lx0, ly0) = corners.iter().fold((f64::MAX, f64::MAX), |(x, y), &(a, b)| (x.min(a), y.min(b)));
|
||||
let (lx1, ly1) = corners.iter().fold((f64::MIN, f64::MIN), |(x, y), &(a, b)| (x.max(a), y.max(b)));
|
||||
if lx1 - lx0 <= 0.0 || ly1 - ly0 <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let (sx, sy) = ((rx1 - rx0).abs() / (lx1 - lx0), (ry1 - ry0).abs() / (ly1 - ly0));
|
||||
let mut place = Matrix([sx, 0.0, 0.0, sy, rx0.min(rx1) - sx * lx0, ry0.min(ry1) - sy * ly0]);
|
||||
// NoRotate: upright as shown, turned about its top left.
|
||||
if flags & 16 != 0 {
|
||||
place = place.then(unturned(turn, (rx0.min(rx1), ry0.max(ry1))));
|
||||
}
|
||||
looks.push((look, place));
|
||||
}
|
||||
Ok(looks)
|
||||
}
|
||||
|
||||
/// Turns back a page's `turn` about `(x, y)`.
|
||||
fn unturned(turn: i64, (x, y): (f64, f64)) -> Matrix {
|
||||
let (cos, sin) = match turn {
|
||||
90 => (0.0, 1.0),
|
||||
180 => (-1.0, 0.0),
|
||||
270 => (0.0, -1.0),
|
||||
_ => (1.0, 0.0),
|
||||
};
|
||||
Matrix([cos, sin, -sin, cos, x - cos * x + sin * y, y - sin * x - cos * y])
|
||||
}
|
||||
|
||||
fn four(numbers: &[f64]) -> anyhow::Result<[f64; 4]> {
|
||||
numbers.try_into().map_err(|_| anyhow!("an annotation's box is not four numbers"))
|
||||
}
|
||||
|
||||
/// An annotation's normal look in its state; None draws nothing.
|
||||
fn appearance(document: &Document, annot: &Dictionary) -> anyhow::Result<Option<ObjectId>> {
|
||||
let subtype = annot.get(b"Subtype")?.as_name()?;
|
||||
let normal = match annot.get(b"AP") {
|
||||
Ok(looks) => document.dereference(looks)?.1.as_dict()?.get(b"N").ok(),
|
||||
Err(_) => None,
|
||||
};
|
||||
let Some(normal) = normal else {
|
||||
// Links and popups have no look of their own.
|
||||
if matches!(subtype, b"Link" | b"Popup") {
|
||||
return Ok(None);
|
||||
}
|
||||
bail!("a printable {} annotation has no appearance", String::from_utf8_lossy(subtype));
|
||||
};
|
||||
if let Ok(id) = normal.as_reference()
|
||||
&& document.get_object(id)?.as_stream().is_ok()
|
||||
{
|
||||
return Ok(Some(id));
|
||||
}
|
||||
// A look per state: the one /AS names, if any.
|
||||
let states = document.dereference(normal)?.1.as_dict()?;
|
||||
let state = annot.get(b"AS").and_then(Object::as_name).context("an annotation with states names none")?;
|
||||
Ok(states.get(state).ok().map(Object::as_reference).transpose()?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,307 @@
|
||||
use lopdf::{Document, Object, Stream, content::Content, dictionary};
|
||||
|
||||
use super::{Choices, Set, Shown, compose};
|
||||
use crate::print::linux::choices::Order;
|
||||
|
||||
/// Pages with these boxes, each with these extra entries.
|
||||
fn pages(boxes: &[([f32; 4], lopdf::Dictionary)]) -> (tempfile::TempDir, std::path::PathBuf) {
|
||||
let mut document = Document::with_version("1.7");
|
||||
let tree = document.new_object_id();
|
||||
let kids: Vec<Object> = boxes
|
||||
.iter()
|
||||
.map(|(corners, extra)| {
|
||||
let content = document.add_object(Stream::new(dictionary! {}, b"0 g 0 0 10 10 re f".to_vec()));
|
||||
let media: Vec<Object> = corners.iter().map(|&n| n.into()).collect();
|
||||
let mut page = dictionary! { "Type" => "Page", "Parent" => tree, "MediaBox" => media, "Contents" => content };
|
||||
page.extend(extra);
|
||||
document.add_object(page).into()
|
||||
})
|
||||
.collect();
|
||||
let count = kids.len() as i64;
|
||||
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }.into());
|
||||
let catalog = document.add_object(dictionary! { "Type" => "Catalog", "Pages" => tree });
|
||||
document.trailer.set("Root", catalog);
|
||||
let folder = tempfile::tempdir().expect("a folder");
|
||||
let pdf = folder.path().join("pages.pdf");
|
||||
document.save(&pdf).expect("saves");
|
||||
(folder, pdf)
|
||||
}
|
||||
|
||||
fn plain(box_: [f32; 4]) -> ([f32; 4], lopdf::Dictionary) {
|
||||
(box_, dictionary! {})
|
||||
}
|
||||
|
||||
fn choices(sheet: (f64, f64)) -> Choices {
|
||||
Choices {
|
||||
ranges: None,
|
||||
set: Set::All,
|
||||
reverse: false,
|
||||
copies: 1,
|
||||
collate: true,
|
||||
scale: 1.0,
|
||||
up: 1,
|
||||
order: Order { across_first: true, leftward: false, upward: false },
|
||||
sheet,
|
||||
upside_down: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A sheet's size; each form's width and placed corners.
|
||||
type Sheet = ((i64, i64), Vec<(i64, [i64; 4])>);
|
||||
|
||||
fn sheets(bytes: &[u8]) -> Vec<Sheet> {
|
||||
let document = Document::load_mem(bytes).expect("a PDF");
|
||||
let round = |n: f64| n.round() as i64;
|
||||
document
|
||||
.get_pages()
|
||||
.into_values()
|
||||
.map(|page| {
|
||||
let dict = document.get_dictionary(page).expect("a page");
|
||||
let media: Vec<f64> = dict.get(b"MediaBox").and_then(Object::as_array).expect("a box").iter().map(|n| f64::from(n.as_float().expect("a number"))).collect();
|
||||
let content = Content::decode(&document.get_page_content(page)).expect("content");
|
||||
let objects = dict.get(b"Resources").and_then(Object::as_dict).and_then(|r| r.get(b"XObject")).and_then(Object::as_dict).expect("forms");
|
||||
let mut matrix = [1.0; 6];
|
||||
let mut placed = Vec::new();
|
||||
for op in content.operations {
|
||||
match op.operator.as_str() {
|
||||
"cm" => matrix = op.operands.iter().map(|n| f64::from(n.as_float().expect("a number"))).collect::<Vec<_>>().try_into().expect("six"),
|
||||
"Do" => {
|
||||
let form = objects.get(op.operands[0].as_name().expect("a name")).and_then(Object::as_reference).expect("a form");
|
||||
let bounds: Vec<f64> = document.get_object(form).and_then(Object::as_stream).expect("a stream").dict.get(b"BBox").and_then(Object::as_array).expect("a box").iter().map(|n| f64::from(n.as_float().expect("a number"))).collect();
|
||||
let m = super::Matrix(matrix);
|
||||
let corners = [(bounds[0], bounds[1]), (bounds[2], bounds[3])].map(|corner| m.apply(corner));
|
||||
let (x0, x1) = (corners[0].0.min(corners[1].0), corners[0].0.max(corners[1].0));
|
||||
let (y0, y1) = (corners[0].1.min(corners[1].1), corners[0].1.max(corners[1].1));
|
||||
placed.push((round(bounds[2] - bounds[0]), [x0, y0, x1, y1].map(round)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
((round(media[2]), round(media[3])), placed)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_unit_scales_the_page() {
|
||||
let (_folder, pdf) = pages(&[([0.0, 0.0, 421.0, 297.5], dictionary! { "UserUnit" => 2 })]);
|
||||
let document = Document::load(&pdf).expect("loads");
|
||||
let page = document.get_pages()[&1];
|
||||
assert_eq!(Shown::of(&document, page).expect("reads").size(), (842.0, 595.0));
|
||||
// On A4 landscape it fills the sheet, from its corner.
|
||||
let laid = sheets(&compose(&pdf, &choices((842.0, 595.0))).expect("composes"));
|
||||
assert_eq!(laid, [((842, 595), vec![(421, [0, 0, 842, 595])])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chosen_pages_print_scaled_from_the_top_left() {
|
||||
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 595.0, 842.0]), plain([0.0, 0.0, 420.0, 595.0]), plain([0.0, 0.0, 300.0, 300.0])]);
|
||||
let only_second = Choices { ranges: Some(vec![(1, 1)]), scale: 0.5, ..choices((595.0, 842.0)) };
|
||||
let laid = sheets(&compose(&pdf, &only_second).expect("composes"));
|
||||
assert_eq!(laid, [((595, 842), vec![(420, [0, 545, 210, 842])])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_that_fits_only_turned_turns_left() {
|
||||
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 842.0, 595.0])]);
|
||||
let bytes = compose(&pdf, &choices((595.0, 842.0))).expect("composes");
|
||||
assert_eq!(sheets(&bytes), [((595, 842), vec![(842, [0, 0, 595, 842])])]);
|
||||
// Its top left lands at the sheet's bottom left.
|
||||
let document = Document::load_mem(&bytes).expect("a PDF");
|
||||
let content = Content::decode(&document.get_page_content(document.get_pages()[&1])).expect("content");
|
||||
let cm = content.operations.iter().find(|op| op.operator == "cm").expect("a matrix");
|
||||
let m: Vec<f64> = cm.operands.iter().map(|n| f64::from(n.as_float().expect("a number"))).collect();
|
||||
let corner = super::Matrix(m.try_into().expect("six")).apply((0.0, 595.0));
|
||||
assert_eq!((corner.0.round(), corner.1.round()), (0.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crop_box_past_the_media_box_is_cut_to_it() {
|
||||
let crop = |corners: [i64; 4]| -> Object { corners.map(Object::from).to_vec().into() };
|
||||
let (_folder, pdf) = pages(&[([0.0, 0.0, 612.0, 792.0], dictionary! { "CropBox" => crop([0, 0, 700, 792]) })]);
|
||||
// The form's box clips at 612: x 650 stays hidden.
|
||||
let laid = sheets(&compose(&pdf, &choices((612.0, 792.0))).expect("composes"));
|
||||
assert_eq!(laid, [((612, 792), vec![(612, [0, 0, 612, 792])])]);
|
||||
let (_folder, pdf) = pages(&[([0.0, 0.0, 612.0, 792.0], dictionary! { "CropBox" => crop([700, 0, 800, 792]) })]);
|
||||
assert!(compose(&pdf, &choices((612.0, 792.0))).is_err(), "nothing left to show");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_page_shows_turned() {
|
||||
let (_folder, pdf) = pages(&[([0.0, 0.0, 595.0, 842.0], dictionary! { "Rotate" => 90 })]);
|
||||
let document = Document::load(&pdf).expect("loads");
|
||||
let shown = Shown::of(&document, document.get_pages()[&1]).expect("reads");
|
||||
assert_eq!(shown.size(), (842.0, 595.0));
|
||||
// Turned clockwise, the page's top left becomes its top right.
|
||||
assert_eq!(shown.matrix().apply((0.0, 842.0)), (842.0, 595.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_large_a_page_fails() {
|
||||
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 1000.0, 600.0])]);
|
||||
let error = compose(&pdf, &choices((595.0, 842.0))).expect_err("does not fit");
|
||||
assert!(error.to_string().contains("page 1 at 100% is larger than the 210 × 297 mm paper"), "{error}");
|
||||
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 595.0, 842.0])]);
|
||||
assert!(compose(&pdf, &Choices { scale: 2.0, ..choices((595.0, 842.0)) }).is_err(), "scaled past the paper");
|
||||
// A4 is 595.28 points wide: 600 would lose its edge.
|
||||
let a4 = (210.0 * 72.0 / 25.4, 297.0 * 72.0 / 25.4);
|
||||
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 600.0, 842.0])]);
|
||||
assert!(compose(&pdf, &choices(a4)).is_err(), "a page 1.6 mm wider than A4");
|
||||
// A4 in whole points still takes an A4 page.
|
||||
let (_folder, pdf) = pages(&[plain([0.0, 0.0, a4.0 as f32, a4.1 as f32])]);
|
||||
assert!(compose(&pdf, &choices((595.0, 842.0))).is_ok(), "rounding is no overflow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_gtk_range_runs_to_the_last_page() {
|
||||
use zbus::zvariant::{OwnedValue, Value};
|
||||
let widths = [100.0, 110.0, 120.0];
|
||||
let boxes: Vec<_> = widths.iter().map(|&w| plain([0.0, 0.0, w, 100.0])).collect();
|
||||
let (_folder, pdf) = pages(&boxes);
|
||||
let owned = |value: Value<'static>| OwnedValue::try_from(value).expect("owned");
|
||||
let settings = [("print-pages", "ranges"), ("page-ranges", "1--1")].map(|(key, value)| (key.to_string(), owned(Value::from(value))));
|
||||
let setup = [("Width", Value::from(210.0)), ("Height", Value::from(297.0)), ("Orientation", Value::from("portrait"))];
|
||||
let setup = setup.map(|(key, value)| (key.to_string(), owned(value)));
|
||||
let chosen = super::super::choices::chosen(&settings.into(), &setup.into()).expect("reads");
|
||||
let printed: Vec<i64> = sheets(&compose(&pdf, &chosen).expect("composes")).iter().map(|sheet| sheet.1[0].0).collect();
|
||||
assert_eq!(printed, [110, 120], "pages two and three");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_up_fills_cells_in_the_chosen_order() {
|
||||
let sizes = [100.0, 110.0, 120.0, 130.0, 140.0];
|
||||
let boxes: Vec<_> = sizes.iter().map(|&w| plain([0.0, 0.0, w, w * 1.5])).collect();
|
||||
let (_folder, pdf) = pages(&boxes);
|
||||
let up = Choices { up: 4, ..choices((400.0, 600.0)) };
|
||||
let laid = sheets(&compose(&pdf, &up).expect("composes"));
|
||||
assert_eq!(laid.len(), 2, "five pages, four a sheet");
|
||||
let corner = |(width, [x0, _, _, y1]): &(i64, [i64; 4])| (*width, x0 / 200, (600 - y1) / 300);
|
||||
let cells: Vec<_> = laid[0].1.iter().map(corner).collect();
|
||||
assert_eq!(cells, [(100, 0, 0), (110, 1, 0), (120, 0, 1), (130, 1, 1)]);
|
||||
// Every page fills its 200 × 300 cell, centred.
|
||||
assert_eq!(laid[1].1, [(140, [0, 300, 200, 600])]);
|
||||
let upward = Choices { order: Order { across_first: false, leftward: true, upward: true }, ..up };
|
||||
let laid = sheets(&compose(&pdf, &upward).expect("composes"));
|
||||
let cells: Vec<_> = laid[0].1.iter().map(corner).collect();
|
||||
assert_eq!(cells, [(100, 1, 1), (110, 1, 0), (120, 0, 1), (130, 0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_order_and_copies_choose_the_sheets() {
|
||||
let widths = [100.0, 110.0, 120.0];
|
||||
let boxes: Vec<_> = widths.iter().map(|&w| plain([0.0, 0.0, w, 100.0])).collect();
|
||||
let (_folder, pdf) = pages(&boxes);
|
||||
let order = |chosen: Choices| -> Vec<i64> { sheets(&compose(&pdf, &chosen).expect("composes")).iter().map(|sheet| sheet.1[0].0).collect() };
|
||||
let base = choices((595.0, 842.0));
|
||||
assert_eq!(order(Choices { set: Set::Odd, ..choices((595.0, 842.0)) }), [100, 120]);
|
||||
assert_eq!(order(Choices { set: Set::Even, ..choices((595.0, 842.0)) }), [110]);
|
||||
assert_eq!(order(Choices { reverse: true, ..choices((595.0, 842.0)) }), [120, 110, 100]);
|
||||
assert_eq!(order(Choices { copies: 2, ..choices((595.0, 842.0)) }), [100, 110, 120, 100, 110, 120]);
|
||||
assert_eq!(order(Choices { copies: 2, collate: false, ..base }), [100, 100, 110, 110, 120, 120]);
|
||||
let none = compose(&pdf, &Choices { ranges: Some(vec![(5, 9)]), ..choices((595.0, 842.0)) });
|
||||
assert!(none.is_err(), "no chosen page is in the document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printable_annotations_are_drawn_where_they_sit() {
|
||||
let mut document = Document::with_version("1.7");
|
||||
let look = document.add_object(Stream::new(
|
||||
dictionary! { "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 10.into(), 20.into()] },
|
||||
b"0 g 0 0 10 20 re f".to_vec(),
|
||||
));
|
||||
let rect = |x: i64| -> Object { vec![x.into(), 100.into(), (x + 30).into(), 160.into()].into() };
|
||||
let shown = dictionary! { "Subtype" => "Square", "F" => 4, "Rect" => rect(50), "AP" => dictionary! { "N" => look } };
|
||||
let unprinted = dictionary! { "Subtype" => "Square", "F" => 0, "Rect" => rect(200), "AP" => dictionary! { "N" => look } };
|
||||
let annots: Vec<Object> = vec![document.add_object(shown).into(), document.add_object(unprinted).into()];
|
||||
let tree = document.new_object_id();
|
||||
let content = document.add_object(Stream::new(dictionary! {}, Vec::new()));
|
||||
let media: Vec<Object> = vec![0.into(), 0.into(), 595.into(), 842.into()];
|
||||
let page = document.add_object(dictionary! { "Type" => "Page", "Parent" => tree, "MediaBox" => media, "Contents" => content, "Annots" => annots });
|
||||
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }.into());
|
||||
let looks = super::appearances(&document, page).expect("reads");
|
||||
assert_eq!(looks.len(), 1, "only the printable one");
|
||||
let (id, place) = looks[0];
|
||||
assert_eq!(id, look);
|
||||
assert_eq!((place.apply((0.0, 0.0)), place.apply((10.0, 20.0))), ((50.0, 100.0), (80.0, 160.0)));
|
||||
}
|
||||
|
||||
/// One A4 page, turned `rotate`: its annotations and own forms.
|
||||
fn annotated(rotate: i64, build: impl FnOnce(&mut Document) -> (Vec<lopdf::Dictionary>, lopdf::Dictionary)) -> (Document, lopdf::ObjectId) {
|
||||
let mut document = Document::with_version("1.7");
|
||||
let (annots, own) = build(&mut document);
|
||||
let annots: Vec<Object> = annots.into_iter().map(|annot| document.add_object(annot).into()).collect();
|
||||
let tree = document.new_object_id();
|
||||
let content = document.add_object(Stream::new(dictionary! {}, b"/ElyAnnot0 Do".to_vec()));
|
||||
let media: Vec<Object> = vec![0.into(), 0.into(), 595.into(), 842.into()];
|
||||
let resources = dictionary! { "XObject" => own };
|
||||
let page = dictionary! { "Type" => "Page", "Parent" => tree, "MediaBox" => media, "Contents" => content, "Annots" => annots, "Rotate" => rotate, "Resources" => resources };
|
||||
let page = document.add_object(page);
|
||||
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }.into());
|
||||
(document, page)
|
||||
}
|
||||
|
||||
fn square(document: &mut Document, flags: i64) -> lopdf::Dictionary {
|
||||
let look = document.add_object(Stream::new(
|
||||
dictionary! { "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 100.into(), 80.into()] },
|
||||
b"1 0 0 rg 0 0 100 80 re f".to_vec(),
|
||||
));
|
||||
let rect: Vec<Object> = vec![50.into(), 100.into(), 150.into(), 180.into()];
|
||||
dictionary! { "Subtype" => "Square", "F" => flags, "Rect" => rect, "AP" => dictionary! { "N" => look } }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_no_rotate_annotation_stays_upright_about_its_top_left() {
|
||||
let (document, page) = annotated(90, |document| (vec![square(document, 20)], dictionary! {}));
|
||||
let (_, place) = super::appearances(&document, page).expect("reads")[0];
|
||||
let shown = Shown::of(&document, page).expect("reads").matrix();
|
||||
let at = |corner| {
|
||||
let (x, y) = shown.apply(place.apply(corner));
|
||||
(x.round(), y.round())
|
||||
};
|
||||
// Shown: its top left stays put, its top runs right.
|
||||
assert_eq!(at((0.0, 80.0)), (180.0, 545.0));
|
||||
assert_eq!(at((100.0, 80.0)), (280.0, 545.0));
|
||||
assert_eq!(at((0.0, 0.0)), (180.0, 465.0));
|
||||
// Without the flag, it turns with the page.
|
||||
let (document, page) = annotated(90, |document| (vec![square(document, 4)], dictionary! {}));
|
||||
let (_, place) = super::appearances(&document, page).expect("reads")[0];
|
||||
let (x, y) = shown.apply(place.apply((0.0, 80.0)));
|
||||
assert_eq!((x.round(), y.round()), (180.0, 545.0));
|
||||
let (x, y) = shown.apply(place.apply((100.0, 80.0)));
|
||||
assert_eq!((x.round(), y.round()), (180.0, 445.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_annotation_name_leaves_the_page_its_own() {
|
||||
let mut blue = None;
|
||||
let (mut document, page) = annotated(0, |document| {
|
||||
let form = dictionary! { "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 1.into(), 1.into()] };
|
||||
let own = *blue.insert(document.add_object(Stream::new(form, b"0 0 1 rg".to_vec())));
|
||||
(vec![square(document, 4)], dictionary! { "ElyAnnot0" => own })
|
||||
});
|
||||
let blue = blue.expect("made");
|
||||
let form = super::form(&mut document, page).expect("a form");
|
||||
let form = document.get_object(form).and_then(Object::as_stream).expect("a stream");
|
||||
let objects = form.dict.get(b"Resources").and_then(Object::as_dict).and_then(|r| r.get(b"XObject")).and_then(Object::as_dict).expect("forms");
|
||||
assert_eq!(objects.get(b"ElyAnnot0").and_then(Object::as_reference).expect("kept"), blue);
|
||||
let drawn = String::from_utf8(form.decompressed_content().expect("content")).expect("text");
|
||||
assert!(drawn.contains("/ElyAnnot0 Do") && drawn.contains("/ElyAnnot1 Do"), "{drawn}");
|
||||
let added = objects.get(b"ElyAnnot1").and_then(Object::as_reference).expect("the annotation's");
|
||||
assert_ne!(added, blue);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printable_annotation_without_a_look_fails() {
|
||||
let rect: Vec<Object> = vec![50.into(), 100.into(), 150.into(), 180.into()];
|
||||
let bare = dictionary! { "Subtype" => "Square", "F" => 4, "Rect" => rect.clone() };
|
||||
let (document, page) = annotated(0, |_| (vec![bare], dictionary! {}));
|
||||
let error = super::appearances(&document, page).expect_err("cannot be drawn");
|
||||
assert!(error.to_string().contains("a printable Square annotation has no appearance"), "{error}");
|
||||
// A link draws nothing; an unset state draws nothing.
|
||||
let link = dictionary! { "Subtype" => "Link", "F" => 4, "Rect" => rect.clone() };
|
||||
let (mut document, page) = annotated(0, |_| (vec![link], dictionary! {}));
|
||||
assert!(super::appearances(&document, page).expect("reads").is_empty());
|
||||
let on = document.add_object(Stream::new(dictionary! { "BBox" => vec![0.into(), 0.into(), 1.into(), 1.into()] }, Vec::new()));
|
||||
let off = dictionary! { "Subtype" => "Widget", "F" => 4, "Rect" => rect, "AS" => "Off", "AP" => dictionary! { "N" => dictionary! { "Yes" => on } } };
|
||||
assert_eq!(super::appearance(&document, &off).expect("reads"), None);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! macOS: PDFKit's print operation and panel.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// Shows the print panel for `pdf`; false when cancelled.
|
||||
pub async fn print_pdf(pdf: &Path) -> anyhow::Result<bool> {
|
||||
use objc2::{AllocAnyThread, MainThreadMarker};
|
||||
use objc2_app_kit::{NSPaperOrientation, NSPrintInfo, NSPrintJobSavingURL, NSPrintSaveJob};
|
||||
use objc2_foundation::{NSCopying, NSSize, NSString, NSURL};
|
||||
use objc2_pdf_kit::{PDFDisplayBox, PDFDocument, PDFPrintScalingMode};
|
||||
|
||||
let mtm =
|
||||
MainThreadMarker::new().ok_or_else(|| anyhow::anyhow!("printing needs the main thread"))?;
|
||||
let url = NSURL::fileURLWithPath(&NSString::from_str(&pdf.to_string_lossy()));
|
||||
let document = unsafe { PDFDocument::initWithURL(PDFDocument::alloc(), &url) }
|
||||
.ok_or_else(|| anyhow::anyhow!("{} is no readable PDF", pdf.display()))?;
|
||||
let sizes: Vec<(f64, f64)> = (0..unsafe { document.pageCount() })
|
||||
.filter_map(|n| unsafe { document.pageAtIndex(n) })
|
||||
.map(|page| {
|
||||
let size = unsafe { page.boundsForBox(PDFDisplayBox::MediaBox) }.size;
|
||||
// A page turned a quarter shows its other side up.
|
||||
match unsafe { page.rotation() }.rem_euclid(180) == 90 {
|
||||
true => (size.height, size.width),
|
||||
false => (size.width, size.height),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let (width, height) = super::paper_for(&sizes).ok_or_else(|| anyhow::anyhow!("{} has no pages", pdf.display()))?;
|
||||
let paper = NSSize::new(width, height);
|
||||
if let Some(scale) = crate::env::value("ELY_PRINT_SHARED_SCALE") {
|
||||
// Tests start from a shared scale the copy must undo.
|
||||
NSPrintInfo::sharedPrintInfo().setScalingFactor(scale.parse()?);
|
||||
}
|
||||
// The PDF already holds the document's paper, margins and scale.
|
||||
let info = NSPrintInfo::sharedPrintInfo().copy();
|
||||
info.setScalingFactor(1.0);
|
||||
info.setOrientation(match paper.width > paper.height {
|
||||
true => NSPaperOrientation::Landscape,
|
||||
false => NSPaperOrientation::Portrait,
|
||||
});
|
||||
info.setPaperSize(paper);
|
||||
info.setTopMargin(0.0);
|
||||
info.setBottomMargin(0.0);
|
||||
info.setLeftMargin(0.0);
|
||||
info.setRightMargin(0.0);
|
||||
log::info!("print: paper {}x{} points", paper.width, paper.height);
|
||||
let operation = unsafe {
|
||||
document.printOperationForPrintInfo_scalingMode_autoRotate(
|
||||
Some(&info),
|
||||
PDFPrintScalingMode::PageScaleNone,
|
||||
true,
|
||||
mtm,
|
||||
)
|
||||
}
|
||||
.ok_or_else(|| anyhow::anyhow!("no print operation for {}", pdf.display()))?;
|
||||
// Tests read the real job: saved to a file.
|
||||
let saved = crate::env::value("ELY_PRINT_TO");
|
||||
if let Some(to) = &saved {
|
||||
let info = operation.printInfo();
|
||||
info.setJobDisposition(unsafe { NSPrintSaveJob });
|
||||
let to = NSURL::fileURLWithPath(&NSString::from_str(to));
|
||||
unsafe { info.dictionary().insert(NSPrintJobSavingURL, &to) };
|
||||
}
|
||||
operation.setShowsPrintPanel(saved.is_none());
|
||||
operation.setShowsProgressPanel(saved.is_none());
|
||||
let printed = operation.runOperation();
|
||||
log::info!("print: the panel closed, printed {printed}");
|
||||
Ok(printed)
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
//! Windows: the system print dialog; Windows' PDF renderer draws.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context as _, anyhow, bail};
|
||||
use windows::{
|
||||
Data::Pdf::{PdfDocument, PdfPage, PdfPageRenderOptions},
|
||||
Foundation::{Rect, Size},
|
||||
Graphics::Imaging::BitmapEncoder,
|
||||
Storage::{
|
||||
StorageFile,
|
||||
Streams::{DataReader, InMemoryRandomAccessStream},
|
||||
},
|
||||
Win32::{
|
||||
Foundation::ERROR_CANCELLED,
|
||||
Graphics::Gdi::{
|
||||
BITMAPINFO, CreateDCW, DIB_RGB_COLORS, DeleteDC, GM_ADVANCED, GetDeviceCaps, HDC, LOGPIXELSX, LOGPIXELSY,
|
||||
PHYSICALHEIGHT, PHYSICALOFFSETX, PHYSICALOFFSETY, PHYSICALWIDTH, SRCCOPY, SetGraphicsMode, SetWorldTransform,
|
||||
StretchDIBits, XFORM,
|
||||
},
|
||||
Storage::Xps::{AbortDoc, DOCINFOW, EndDoc, EndPage, StartDocW, StartPage},
|
||||
System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize},
|
||||
UI::{
|
||||
Controls::Dialogs::{
|
||||
PD_NOCURRENTPAGE, PD_NOSELECTION, PD_PAGENUMS, PD_PRINTTOFILE, PD_RESULT_PRINT, PD_USEDEVMODECOPIESANDCOLLATE,
|
||||
PRINTDLGEX_FLAGS, PRINTDLGEXW, PRINTPAGERANGE, PrintDlgExW, START_PAGE_GENERAL,
|
||||
},
|
||||
Input::KeyboardAndMouse::GetActiveWindow,
|
||||
},
|
||||
},
|
||||
core::{HSTRING, PCWSTR},
|
||||
};
|
||||
|
||||
mod printer;
|
||||
|
||||
use printer::{Devmode, default_printer, device, free, global, names, settings};
|
||||
|
||||
/// The printer tests write their job to a file with.
|
||||
const TO_FILE: &str = "Microsoft Print to PDF";
|
||||
/// Bytes one rendered band may take.
|
||||
const BAND: usize = 32 << 20;
|
||||
/// The probe's width, in pixels asked.
|
||||
const PROBE: u32 = 200;
|
||||
|
||||
/// Shows the print dialog, then prints; false when cancelled.
|
||||
pub async fn print_pdf(pdf: &Path) -> anyhow::Result<bool> {
|
||||
let pdf = std::path::absolute(pdf)?;
|
||||
let sizes = {
|
||||
let pdf = pdf.clone();
|
||||
super::off(move || winrt(|| sizes(&open(&pdf)?))).await?
|
||||
};
|
||||
let paper = super::paper_for(&sizes).ok_or_else(|| anyhow!("{} has no pages", pdf.display()))?;
|
||||
log::info!("print: paper {}x{} points", paper.0, paper.1);
|
||||
let every = (0..sizes.len() as u32).collect();
|
||||
// Tests read the real job: written by the file printer.
|
||||
let job = match crate::env::value("ELY_PRINT_TO") {
|
||||
Some(to) => {
|
||||
let printer = wide(TO_FILE);
|
||||
let settings = settings(&printer, paper)?;
|
||||
Job { printer, settings, pages: every, output: Some(wide(&to)) }
|
||||
}
|
||||
None => match ask(every, paper)? {
|
||||
Some(job) => job,
|
||||
None => {
|
||||
log::info!("print: the dialog was cancelled");
|
||||
return Ok(false);
|
||||
}
|
||||
},
|
||||
};
|
||||
let printed = super::off(move || winrt(|| job.print(&pdf))).await?;
|
||||
log::info!("print: the job ended, printed {printed}");
|
||||
Ok(printed)
|
||||
}
|
||||
|
||||
/// What the dialog chose.
|
||||
struct Job {
|
||||
printer: Vec<u16>,
|
||||
settings: Devmode,
|
||||
pages: Vec<u32>,
|
||||
output: Option<Vec<u16>>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// Draws the chosen pages; false when its save prompt cancels.
|
||||
fn print(self, pdf: &Path) -> anyhow::Result<bool> {
|
||||
let document = open(pdf)?;
|
||||
let dc = unsafe { CreateDCW(PCWSTR::null(), PCWSTR(self.printer.as_ptr()), PCWSTR::null(), Some(self.settings.as_ptr())) };
|
||||
if dc.is_invalid() {
|
||||
bail!("the printer cannot be opened: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
let printed = self.draw(&document, dc);
|
||||
if !unsafe { DeleteDC(dc) }.as_bool() {
|
||||
log::warn!("print: the printer's context stays open");
|
||||
}
|
||||
printed
|
||||
}
|
||||
|
||||
fn draw(&self, document: &PdfDocument, dc: HDC) -> anyhow::Result<bool> {
|
||||
// The driver may have swapped our paper; nothing is cut.
|
||||
let paper = Paper::of(dc);
|
||||
for &n in &self.pages {
|
||||
let size = document.GetPage(n)?.Size()?;
|
||||
if paper.fit(size).is_none() {
|
||||
let (width, height) = paper.millimetres();
|
||||
let mm = |dips: f32| f64::from(dips) * 25.4 / 96.0;
|
||||
bail!(
|
||||
"page {} is {:.0} × {:.0} mm; the printer's paper is {width:.0} × {height:.0} mm",
|
||||
n + 1,
|
||||
mm(size.Width),
|
||||
mm(size.Height)
|
||||
);
|
||||
}
|
||||
}
|
||||
let name = wide("Ely Office");
|
||||
let info = DOCINFOW {
|
||||
cbSize: size_of::<DOCINFOW>() as i32,
|
||||
lpszDocName: PCWSTR(name.as_ptr()),
|
||||
lpszOutput: self.output.as_ref().map_or(PCWSTR::null(), |output| PCWSTR(output.as_ptr())),
|
||||
..Default::default()
|
||||
};
|
||||
if unsafe { StartDocW(dc, &info) } <= 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(ERROR_CANCELLED.0 as i32) {
|
||||
return Ok(false);
|
||||
}
|
||||
bail!("the printer refused the job: {error}");
|
||||
}
|
||||
let drawn = scale(document).and_then(|scale| self.pages.iter().try_for_each(|&n| page(document, n, dc, &paper, scale)));
|
||||
if let Err(error) = drawn {
|
||||
unsafe { AbortDoc(dc) };
|
||||
return Err(error);
|
||||
}
|
||||
if unsafe { EndDoc(dc) } <= 0 {
|
||||
bail!("the printer did not finish the job: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the dialog over the active window; None when cancelled.
|
||||
fn ask(every: Vec<u32>, paper: (f64, f64)) -> anyhow::Result<Option<Job>> {
|
||||
let owner = unsafe { GetActiveWindow() };
|
||||
if owner.is_invalid() {
|
||||
bail!("no window is active to own the print dialog");
|
||||
}
|
||||
let printer = default_printer()?;
|
||||
let settings = settings(&printer, paper)?;
|
||||
let mut ranges = [PRINTPAGERANGE::default(); 32];
|
||||
let mut dialog = PRINTDLGEXW {
|
||||
lStructSize: size_of::<PRINTDLGEXW>() as u32,
|
||||
hwndOwner: owner,
|
||||
hDevMode: global(settings.bytes())?,
|
||||
hDevNames: global(&names(&printer))?,
|
||||
Flags: PD_NOSELECTION | PD_NOCURRENTPAGE | PD_USEDEVMODECOPIESANDCOLLATE,
|
||||
nMaxPageRanges: ranges.len() as u32,
|
||||
lpPageRanges: ranges.as_mut_ptr(),
|
||||
nMinPage: 1,
|
||||
nMaxPage: every.len() as u32,
|
||||
nCopies: 1,
|
||||
nStartPage: START_PAGE_GENERAL,
|
||||
..Default::default()
|
||||
};
|
||||
let shown = unsafe { PrintDlgExW(&mut dialog) };
|
||||
let chosen = shown.map_err(anyhow::Error::from).and_then(|()| {
|
||||
if dialog.dwResultAction != PD_RESULT_PRINT {
|
||||
return Ok(None);
|
||||
}
|
||||
let (pages, output) = chosen(dialog.Flags, &ranges[..dialog.nPageRanges as usize], every.len() as u32);
|
||||
Ok(Some(Job { printer: device(dialog.hDevNames)?, settings: Devmode::copied(dialog.hDevMode)?, pages, output }))
|
||||
});
|
||||
// The dialog may replace either block; we free both.
|
||||
free(dialog.hDevMode)?;
|
||||
free(dialog.hDevNames)?;
|
||||
chosen
|
||||
}
|
||||
|
||||
/// The pages and output the dialog's answer chose.
|
||||
fn chosen(flags: PRINTDLGEX_FLAGS, ranges: &[PRINTPAGERANGE], count: u32) -> (Vec<u32>, Option<Vec<u16>>) {
|
||||
let pages = match flags.contains(PD_PAGENUMS) {
|
||||
true => ranges.iter().flat_map(|range| range.nFromPage.max(1) - 1..range.nToPage.min(count)).collect(),
|
||||
false => (0..count).collect(),
|
||||
};
|
||||
// "FILE:" makes the spooler ask for the file's name.
|
||||
let output = flags.contains(PD_PRINTTOFILE).then(|| wide("FILE:"));
|
||||
(pages, output)
|
||||
}
|
||||
|
||||
/// The printer's paper, in its device pixels.
|
||||
struct Paper {
|
||||
dpi: (i32, i32),
|
||||
size: (i32, i32),
|
||||
offset: (i32, i32),
|
||||
}
|
||||
|
||||
impl Paper {
|
||||
fn of(dc: HDC) -> Self {
|
||||
let caps = |index| unsafe { GetDeviceCaps(Some(dc), index) };
|
||||
Self {
|
||||
dpi: (caps(LOGPIXELSX), caps(LOGPIXELSY)),
|
||||
size: (caps(PHYSICALWIDTH), caps(PHYSICALHEIGHT)),
|
||||
offset: (caps(PHYSICALOFFSETX), caps(PHYSICALOFFSETY)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixels, and whether it turns; None if too large.
|
||||
fn fit(&self, size: Size) -> Option<((i32, i32), bool)> {
|
||||
let ((dpi_x, dpi_y), (paper_x, paper_y)) = (self.dpi, self.size);
|
||||
let pixels = |dips: f32, dpi: i32| (f64::from(dips) * f64::from(dpi) / 96.0).round() as i32;
|
||||
// A page fits upright or turned, within rounding.
|
||||
let fits = |pixels: i32, paper: i32, dpi: i32| f64::from(pixels - paper) <= f64::from(dpi) * super::ROUNDING / 72.0;
|
||||
let (across, down) = (pixels(size.Width, dpi_x), pixels(size.Height, dpi_y));
|
||||
if fits(across, paper_x, dpi_x) && fits(down, paper_y, dpi_y) {
|
||||
return Some(((across, down), false));
|
||||
}
|
||||
let (across, down) = (pixels(size.Width, dpi_y), pixels(size.Height, dpi_x));
|
||||
(fits(across, paper_y, dpi_y) && fits(down, paper_x, dpi_x)).then_some(((across, down), true))
|
||||
}
|
||||
|
||||
fn millimetres(&self) -> (f64, f64) {
|
||||
let mm = |pixels: i32, dpi: i32| f64::from(pixels) * 25.4 / f64::from(dpi);
|
||||
(mm(self.size.0, self.dpi.0), mm(self.size.1, self.dpi.1))
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixels given per pixel asked: the renderer counts DIPs.
|
||||
fn scale(document: &PdfDocument) -> anyhow::Result<f64> {
|
||||
let options = PdfPageRenderOptions::new()?;
|
||||
options.SetDestinationWidth(PROBE)?;
|
||||
options.SetDestinationHeight(PROBE)?;
|
||||
let (across, _) = bitmap(&rendered(&document.GetPage(0)?, &options)?)?.size;
|
||||
log::info!("print: the renderer gives {across} pixels per {PROBE} asked");
|
||||
Ok(f64::from(across) / f64::from(PROBE))
|
||||
}
|
||||
|
||||
/// Draws page `n` at its size from the paper's corner.
|
||||
fn page(document: &PdfDocument, n: u32, dc: HDC, paper: &Paper, scale: f64) -> anyhow::Result<()> {
|
||||
let page = document.GetPage(n)?;
|
||||
let size = page.Size()?;
|
||||
let ((width, height), turned) = paper.fit(size).with_context(|| format!("page {} does not fit the paper", n + 1))?;
|
||||
let (offset_x, offset_y) = paper.offset;
|
||||
if unsafe { StartPage(dc) } <= 0 {
|
||||
bail!("the printer refused page {}: {}", n + 1, std::io::Error::last_os_error());
|
||||
}
|
||||
// Device pixels start at the printable area, not the paper.
|
||||
let place = match turned {
|
||||
// A turned page's top runs up its left edge.
|
||||
true => XFORM { eM11: 0.0, eM12: -1.0, eM21: 1.0, eM22: 0.0, eDx: -offset_x as f32, eDy: (width - offset_y) as f32 },
|
||||
false => XFORM { eM11: 1.0, eM12: 0.0, eM21: 0.0, eM22: 1.0, eDx: -offset_x as f32, eDy: -offset_y as f32 },
|
||||
};
|
||||
if unsafe { SetGraphicsMode(dc, GM_ADVANCED) } == 0 || !unsafe { SetWorldTransform(dc, &place) }.as_bool() {
|
||||
bail!("the printer cannot place page {}", n + 1);
|
||||
}
|
||||
let rows = (BAND / (width.max(1) as usize * 4)).max(1) as i32;
|
||||
let mut top = 0;
|
||||
while top < height {
|
||||
let band = rows.min(height - top);
|
||||
let bmp = render(&page, size, (width, height), (top, band), scale)?;
|
||||
draw(dc, &bmp, top, width, band)?;
|
||||
top += band;
|
||||
}
|
||||
if unsafe { EndPage(dc) } <= 0 {
|
||||
bail!("the printer did not take page {}: {}", n + 1, std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The page's band from row `top`, as a BMP file.
|
||||
fn render(page: &PdfPage, size: Size, (width, height): (i32, i32), (top, rows): (i32, i32), scale: f64) -> anyhow::Result<Vec<u8>> {
|
||||
let options = PdfPageRenderOptions::new()?;
|
||||
let row = f64::from(size.Height) / f64::from(height);
|
||||
options.SetSourceRect(Rect {
|
||||
X: 0.0,
|
||||
Y: (f64::from(top) * row) as f32,
|
||||
Width: size.Width,
|
||||
Height: (f64::from(rows) * row) as f32,
|
||||
})?;
|
||||
let asked = |pixels: i32| ((f64::from(pixels) / scale).round() as u32).max(1);
|
||||
options.SetDestinationWidth(asked(width))?;
|
||||
options.SetDestinationHeight(asked(rows))?;
|
||||
rendered(page, &options)
|
||||
}
|
||||
|
||||
/// The page as `options` asks, as a BMP file.
|
||||
fn rendered(page: &PdfPage, options: &PdfPageRenderOptions) -> anyhow::Result<Vec<u8>> {
|
||||
options.SetBitmapEncoderId(BitmapEncoder::BmpEncoderId()?)?;
|
||||
let stream = InMemoryRandomAccessStream::new()?;
|
||||
page.RenderWithOptionsToStreamAsync(&stream, options)?.join()?;
|
||||
let length = u32::try_from(stream.Size()?)?;
|
||||
let reader = DataReader::CreateDataReader(&stream.GetInputStreamAt(0)?)?;
|
||||
reader.LoadAsync(length)?.join()?;
|
||||
let mut bytes = vec![0; length as usize];
|
||||
reader.ReadBytes(&mut bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// A BMP file's pixel size and where its pixels start.
|
||||
struct Bitmap {
|
||||
size: (i32, i32),
|
||||
start: usize,
|
||||
}
|
||||
|
||||
fn bitmap(bmp: &[u8]) -> anyhow::Result<Bitmap> {
|
||||
let word = |at: usize| bmp.get(at..at + 4).map(|bytes| u32::from_le_bytes(bytes.try_into().expect("four bytes")));
|
||||
let (Some(start), Some(across), Some(down)) = (word(10), word(18), word(22)) else {
|
||||
bail!("the renderer gave no bitmap");
|
||||
};
|
||||
if !bmp.starts_with(b"BM") || start as usize >= bmp.len() {
|
||||
bail!("the renderer gave a broken bitmap");
|
||||
}
|
||||
// Rows run up the file when its height is positive.
|
||||
Ok(Bitmap { size: (across as i32, (down as i32).abs()), start: start as usize })
|
||||
}
|
||||
|
||||
/// Stretches one BMP band over `width` by `rows` at `top`.
|
||||
fn draw(dc: HDC, bmp: &[u8], top: i32, width: i32, rows: i32) -> anyhow::Result<()> {
|
||||
let Bitmap { size: (across, down), start } = bitmap(bmp)?;
|
||||
// Asking in DIPs rounds; a few pixels off is that.
|
||||
if (across - width).abs() > 4 || (down - rows).abs() > 4 {
|
||||
bail!("the renderer gave a {across}x{down} bitmap for {width}x{rows}");
|
||||
}
|
||||
let info = bmp[14..].as_ptr().cast::<BITMAPINFO>();
|
||||
let bits = bmp[start..].as_ptr().cast();
|
||||
let copied = unsafe { StretchDIBits(dc, 0, top, width, rows, 0, 0, across, down, Some(bits), info, DIB_RGB_COLORS, SRCCOPY) };
|
||||
if copied <= 0 {
|
||||
bail!("the printer took none of the page: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens `pdf` with Windows' PDF renderer.
|
||||
fn open(pdf: &Path) -> anyhow::Result<PdfDocument> {
|
||||
let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(pdf))?
|
||||
.join()
|
||||
.with_context(|| format!("{} cannot be opened", pdf.display()))?;
|
||||
PdfDocument::LoadFromFileAsync(&file)?.join().with_context(|| format!("{} is no readable PDF", pdf.display()))
|
||||
}
|
||||
|
||||
/// Each page's size in points, as it shows.
|
||||
fn sizes(document: &PdfDocument) -> anyhow::Result<Vec<(f64, f64)>> {
|
||||
let points = |dips: f32| f64::from(dips) * 72.0 / 96.0;
|
||||
(0..document.PageCount()?)
|
||||
.map(|n| {
|
||||
let size = document.GetPage(n)?.Size()?;
|
||||
Ok((points(size.Width), points(size.Height)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs `work` with the thread joined to the Windows Runtime.
|
||||
fn winrt<T>(work: impl FnOnce() -> anyhow::Result<T>) -> anyhow::Result<T> {
|
||||
unsafe { RoInitialize(RO_INIT_MULTITHREADED) }?;
|
||||
let result = work();
|
||||
unsafe { RoUninitialize() };
|
||||
result
|
||||
}
|
||||
|
||||
fn wide(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain([0]).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use windows::Win32::UI::Controls::Dialogs::{PD_PAGENUMS, PD_PRINTTOFILE, PRINTDLGEX_FLAGS, PRINTPAGERANGE};
|
||||
|
||||
use super::{chosen, wide};
|
||||
|
||||
#[test]
|
||||
fn the_dialog_answer_picks_pages_and_output() {
|
||||
let ranges = [PRINTPAGERANGE { nFromPage: 2, nToPage: 3 }, PRINTPAGERANGE { nFromPage: 5, nToPage: 9 }];
|
||||
assert_eq!(chosen(PRINTDLGEX_FLAGS(0), &ranges, 3), (vec![0, 1, 2], None));
|
||||
assert_eq!(chosen(PD_PAGENUMS, &ranges, 6), (vec![1, 2, 4, 5], None));
|
||||
// Print to file: the spooler asks where.
|
||||
assert_eq!(chosen(PD_PAGENUMS | PD_PRINTTOFILE, &ranges[..1], 6), (vec![1, 2], Some(wide("FILE:"))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! The printer's settings and the global blocks the dialog trades.
|
||||
|
||||
use anyhow::{Context as _, bail};
|
||||
use windows::{
|
||||
Win32::{
|
||||
Foundation::{GlobalFree, HGLOBAL, POINT},
|
||||
Graphics::{
|
||||
Gdi::{
|
||||
DEVMODEW, DM_IN_BUFFER, DM_ORIENTATION, DM_OUT_BUFFER, DM_PAPERLENGTH, DM_PAPERSIZE, DM_PAPERWIDTH,
|
||||
DMORIENT_LANDSCAPE, DMORIENT_PORTRAIT, DMPAPER_USER,
|
||||
},
|
||||
Printing::{ClosePrinter, DocumentPropertiesW, GetDefaultPrinterW, OpenPrinterW, PRINTER_HANDLE},
|
||||
},
|
||||
Storage::Xps::{DC_PAPERS, DC_PAPERSIZE, DeviceCapabilitiesW},
|
||||
System::Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock},
|
||||
UI::Controls::Dialogs::DEVNAMES,
|
||||
},
|
||||
core::{PCWSTR, PWSTR},
|
||||
};
|
||||
|
||||
use super::wide;
|
||||
|
||||
/// `printer`'s settings, set to the document's paper.
|
||||
pub(super) fn settings(printer: &[u16], (width, height): (f64, f64)) -> anyhow::Result<Devmode> {
|
||||
let name = PCWSTR(printer.as_ptr());
|
||||
let mut handle = PRINTER_HANDLE::default();
|
||||
unsafe { OpenPrinterW(name, &mut handle, None) }
|
||||
.with_context(|| format!("the printer {} cannot be opened", String::from_utf16_lossy(&printer[..printer.len() - 1])))?;
|
||||
let set = || -> anyhow::Result<Devmode> {
|
||||
let bytes = unsafe { DocumentPropertiesW(None, handle, name, None, None, 0) };
|
||||
let mut settings = Devmode::zeroed(usize::try_from(bytes).ok().filter(|&b| b >= size_of::<DEVMODEW>()).context("the printer gives no settings")?);
|
||||
answered(unsafe { DocumentPropertiesW(None, handle, name, Some(settings.as_mut_ptr()), None, DM_OUT_BUFFER.0) })?;
|
||||
// Forms stand upright, in tenths of a millimetre.
|
||||
let tenths = |points: f64| (points * 254.0 / 72.0).round();
|
||||
let (short, long) = (tenths(width.min(height)), tenths(width.max(height)));
|
||||
if long > f64::from(i16::MAX) {
|
||||
bail!("the page is larger than any paper");
|
||||
}
|
||||
let points = |tenths: i32| f64::from(tenths) * 72.0 / 254.0;
|
||||
let page = (width.min(height), width.max(height));
|
||||
let form = forms(name, &settings)?.into_iter().find(|&(_, across, down)| crate::print::holds((points(across), points(down)), page));
|
||||
let fields = settings.fields();
|
||||
unsafe {
|
||||
let paper = &mut fields.Anonymous1.Anonymous1;
|
||||
match form {
|
||||
Some((id, ..)) => {
|
||||
paper.dmPaperSize = id as i16;
|
||||
fields.dmFields = (fields.dmFields | DM_PAPERSIZE) & !(DM_PAPERWIDTH | DM_PAPERLENGTH);
|
||||
}
|
||||
None => {
|
||||
paper.dmPaperSize = DMPAPER_USER as i16;
|
||||
paper.dmPaperWidth = short as i16;
|
||||
paper.dmPaperLength = long as i16;
|
||||
fields.dmFields |= DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH;
|
||||
}
|
||||
}
|
||||
paper.dmOrientation = if width > height { DMORIENT_LANDSCAPE } else { DMORIENT_PORTRAIT } as i16;
|
||||
}
|
||||
fields.dmFields |= DM_ORIENTATION;
|
||||
// The driver settles what it cannot do.
|
||||
let asked = settings.clone();
|
||||
answered(unsafe {
|
||||
DocumentPropertiesW(None, handle, name, Some(settings.as_mut_ptr()), Some(asked.as_ptr()), DM_IN_BUFFER.0 | DM_OUT_BUFFER.0)
|
||||
})?;
|
||||
Ok(settings)
|
||||
};
|
||||
let settings = set();
|
||||
unsafe { ClosePrinter(handle) }?;
|
||||
settings
|
||||
}
|
||||
|
||||
/// The printer's forms: id, then size in tenth millimetres.
|
||||
fn forms(printer: PCWSTR, settings: &Devmode) -> anyhow::Result<Vec<(u16, i32, i32)>> {
|
||||
let count = unsafe { DeviceCapabilitiesW(printer, PCWSTR::null(), DC_PAPERS, None, Some(settings.as_ptr())) };
|
||||
let count = usize::try_from(count).context("the printer lists no forms")?;
|
||||
let mut ids = vec![0u16; count];
|
||||
let mut sizes = vec![POINT::default(); count];
|
||||
let listed = [
|
||||
unsafe { DeviceCapabilitiesW(printer, PCWSTR::null(), DC_PAPERS, Some(PWSTR(ids.as_mut_ptr())), Some(settings.as_ptr())) },
|
||||
unsafe { DeviceCapabilitiesW(printer, PCWSTR::null(), DC_PAPERSIZE, Some(PWSTR(sizes.as_mut_ptr().cast())), Some(settings.as_ptr())) },
|
||||
];
|
||||
if listed != [count as i32; 2] {
|
||||
bail!("the printer's forms changed while read");
|
||||
}
|
||||
Ok(ids.into_iter().zip(sizes).map(|(id, size)| (id, size.x, size.y)).collect())
|
||||
}
|
||||
|
||||
/// The default printer's name, ending in a nul.
|
||||
pub(super) fn default_printer() -> anyhow::Result<Vec<u16>> {
|
||||
let mut length = 0;
|
||||
// Asked with no buffer, it fails and gives the length.
|
||||
let _ = unsafe { GetDefaultPrinterW(None, &mut length) };
|
||||
if length == 0 {
|
||||
bail!("no default printer is set up");
|
||||
}
|
||||
let mut name = vec![0u16; length as usize];
|
||||
if !unsafe { GetDefaultPrinterW(Some(PWSTR(name.as_mut_ptr())), &mut length) }.as_bool() {
|
||||
bail!("the default printer cannot be read: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Names `printer`, so the dialog keeps our settings.
|
||||
pub(super) fn names(printer: &[u16]) -> Vec<u8> {
|
||||
let driver = wide("winspool");
|
||||
let header = (size_of::<DEVNAMES>() / 2) as u16;
|
||||
let offsets = [header, header + driver.len() as u16, header + (driver.len() + printer.len()) as u16, 0];
|
||||
let words = offsets.into_iter().chain(driver).chain(printer.iter().copied()).chain([0]);
|
||||
words.flat_map(u16::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
/// A DEVNAMES block's device name, ending in a nul.
|
||||
pub(super) fn device(names: HGLOBAL) -> anyhow::Result<Vec<u16>> {
|
||||
let base = lock(names)?.cast::<u16>();
|
||||
let offset = unsafe { (*base.cast::<DEVNAMES>()).wDeviceOffset } as usize;
|
||||
let start = unsafe { base.add(offset) };
|
||||
let length = (0..).take_while(|&n| unsafe { *start.add(n) } != 0).count();
|
||||
let name = unsafe { std::slice::from_raw_parts(start, length + 1) }.to_vec();
|
||||
unlock(names);
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// A DEVMODE with its driver's tail, kept aligned.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Devmode {
|
||||
words: Vec<u64>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Devmode {
|
||||
fn zeroed(bytes: usize) -> Self {
|
||||
Self { words: vec![0; bytes.div_ceil(8)], bytes }
|
||||
}
|
||||
|
||||
/// A copy of the DEVMODE in `block`.
|
||||
pub(super) fn copied(block: HGLOBAL) -> anyhow::Result<Self> {
|
||||
let bytes = unsafe { GlobalSize(block) };
|
||||
if bytes < size_of::<DEVMODEW>() {
|
||||
bail!("the dialog gave no printer settings");
|
||||
}
|
||||
let mut settings = Self::zeroed(bytes);
|
||||
let source = lock(block)?;
|
||||
unsafe { std::ptr::copy_nonoverlapping(source.cast::<u8>(), settings.words.as_mut_ptr().cast(), bytes) };
|
||||
unlock(block);
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
pub(super) fn as_ptr(&self) -> *const DEVMODEW {
|
||||
self.words.as_ptr().cast()
|
||||
}
|
||||
|
||||
fn as_mut_ptr(&mut self) -> *mut DEVMODEW {
|
||||
self.words.as_mut_ptr().cast()
|
||||
}
|
||||
|
||||
fn fields(&mut self) -> &mut DEVMODEW {
|
||||
unsafe { &mut *self.as_mut_ptr() }
|
||||
}
|
||||
|
||||
pub(super) fn bytes(&self) -> &[u8] {
|
||||
unsafe { std::slice::from_raw_parts(self.words.as_ptr().cast(), self.bytes) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A movable global block holding `bytes`.
|
||||
pub(super) fn global(bytes: &[u8]) -> anyhow::Result<HGLOBAL> {
|
||||
let block = unsafe { GlobalAlloc(GMEM_MOVEABLE, bytes.len()) }?;
|
||||
let target = lock(block)?;
|
||||
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), target.cast(), bytes.len()) };
|
||||
unlock(block);
|
||||
Ok(block)
|
||||
}
|
||||
|
||||
fn lock(block: HGLOBAL) -> anyhow::Result<*mut core::ffi::c_void> {
|
||||
let pointer = unsafe { GlobalLock(block) };
|
||||
if pointer.is_null() {
|
||||
bail!("a printer block cannot be read: {}", std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(pointer)
|
||||
}
|
||||
|
||||
fn unlock(block: HGLOBAL) {
|
||||
// An error here only says the block is now unlocked.
|
||||
if let Err(error) = unsafe { GlobalUnlock(block) }
|
||||
&& error.code().is_err()
|
||||
{
|
||||
log::warn!("print: a printer block stays locked: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn free(block: HGLOBAL) -> anyhow::Result<()> {
|
||||
if block.is_invalid() {
|
||||
return Ok(());
|
||||
}
|
||||
// Freed, it answers null; windows-rs calls that an error.
|
||||
match unsafe { GlobalFree(Some(block)) } {
|
||||
Err(error) if error.code().is_ok() => Ok(()),
|
||||
Err(error) => Err(error.into()),
|
||||
Ok(_) => bail!("a printer block cannot be freed: {}", std::io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
|
||||
/// DocumentProperties answers IDOK on success.
|
||||
fn answered(code: i32) -> anyhow::Result<()> {
|
||||
if code < 0 {
|
||||
bail!("the printer refused its settings");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Printing through a Windows file printer and fake Linux portal.
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use std::path::Path;
|
||||
|
||||
/// Pages of `sizes` points, each with an inch square.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fixture(path: &Path, sizes: &[(f32, f32)]) {
|
||||
use lopdf::{Document, Object, Stream, dictionary};
|
||||
|
||||
let mut document = Document::with_version("1.7");
|
||||
let tree = document.new_object_id();
|
||||
let kids: Vec<Object> = sizes
|
||||
.iter()
|
||||
.map(|&(width, height)| {
|
||||
let square = format!("0 g 72 {} 72 72 re f", height - 144.0);
|
||||
let content = document.add_object(Stream::new(dictionary! {}, square.into_bytes()));
|
||||
let media: Vec<Object> = vec![0.into(), 0.into(), width.into(), height.into()];
|
||||
document
|
||||
.add_object(dictionary! { "Type" => "Page", "Parent" => tree, "MediaBox" => media, "Contents" => content })
|
||||
.into()
|
||||
})
|
||||
.collect();
|
||||
let count = kids.len() as i64;
|
||||
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }.into());
|
||||
let catalog = document.add_object(dictionary! { "Type" => "Catalog", "Pages" => tree });
|
||||
document.trailer.set("Root", catalog);
|
||||
document.save(path).expect("the fixture saves");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn main() {
|
||||
let folder = tempfile::tempdir().expect("a folder");
|
||||
unsafe { windows::Win32::System::WinRT::RoInitialize(windows::Win32::System::WinRT::RO_INIT_MULTITHREADED) }.expect("the runtime");
|
||||
// A5, then wide A5: the paper stays upright.
|
||||
let mixed = printed(folder.path(), "mixed", &[(420.0, 595.0), (595.0, 420.0)]);
|
||||
assert_eq!(papers(&mixed), [(420, 595), (420, 595)]);
|
||||
let square = |page| windows_page::dark(&mixed, page, (108, 108));
|
||||
assert_eq!((square(0), square(1)), (true, false), "the upright page keeps its corner");
|
||||
// Turned left, its top left lands bottom left.
|
||||
assert!(windows_page::dark(&mixed, 1, (108, 487)), "the turned page's square");
|
||||
assert!(!windows_page::dark(&mixed, 0, (312, 108)), "nothing at the upright page's other corner");
|
||||
// A4 landscape alone turns the paper.
|
||||
let wide = printed(folder.path(), "wide", &[(842.0, 595.0)]);
|
||||
assert_eq!(papers(&wide), [(842, 595)]);
|
||||
assert!(windows_page::dark(&wide, 0, (108, 108)), "the wide page keeps its corner");
|
||||
// A paper the printer lacks: refused, nothing cut or written.
|
||||
let source = folder.path().join("custom.pdf");
|
||||
fixture(&source, &[(1000.0, 600.0)]);
|
||||
let job = folder.path().join("custom-job.pdf");
|
||||
unsafe { std::env::set_var("ELY_PRINT_TO", &job) };
|
||||
let error = futures::executor::block_on(ely_platform::print::print_pdf(&source)).expect_err("no such paper");
|
||||
assert!(error.to_string().contains("page 1 is 353 × 212 mm; the printer's paper is"), "{error}");
|
||||
assert!(!job.exists(), "nothing printed");
|
||||
// 1.6 mm past A4: refused, not cut.
|
||||
fixture(&source, &[(600.0, 842.0)]);
|
||||
let error = futures::executor::block_on(ely_platform::print::print_pdf(&source)).expect_err("past A4");
|
||||
assert!(error.to_string().contains("page 1 is 212 × 297 mm; the printer's paper is"), "{error}");
|
||||
assert!(!job.exists(), "nothing printed");
|
||||
println!("print: windows ok");
|
||||
}
|
||||
|
||||
/// Prints `sizes` through the file printer; the job's PDF.
|
||||
#[cfg(windows)]
|
||||
fn printed(folder: &Path, name: &str, sizes: &[(f32, f32)]) -> std::path::PathBuf {
|
||||
let source = folder.join(format!("{name}.pdf"));
|
||||
fixture(&source, sizes);
|
||||
let job = folder.join(format!("{name}-job.pdf"));
|
||||
// Before any thread starts: the job goes to a file.
|
||||
unsafe { std::env::set_var("ELY_PRINT_TO", &job) };
|
||||
assert!(futures::executor::block_on(ely_platform::print::print_pdf(&source)).expect("prints"), "printed");
|
||||
job
|
||||
}
|
||||
|
||||
/// Each printed page's paper in whole points.
|
||||
#[cfg(windows)]
|
||||
fn papers(job: &Path) -> Vec<(i64, i64)> {
|
||||
let document = lopdf::Document::load(job).expect("the job is a PDF");
|
||||
document
|
||||
.get_pages()
|
||||
.into_values()
|
||||
.map(|page| {
|
||||
let media = document.get_dictionary(page).and_then(|page| page.get(b"MediaBox")).expect("a media box");
|
||||
let corners: Vec<f32> = media.as_array().expect("an array").iter().map(|n| n.as_float().expect("a number")).collect();
|
||||
((corners[2] - corners[0]).round() as i64, (corners[3] - corners[1]).round() as i64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reads printed pages back through Windows' own renderer.
|
||||
#[cfg(windows)]
|
||||
mod windows_page {
|
||||
use std::path::Path;
|
||||
|
||||
use windows::{
|
||||
Data::Pdf::{PdfDocument, PdfPageRenderOptions},
|
||||
Storage::{
|
||||
StorageFile,
|
||||
Streams::{DataReader, InMemoryRandomAccessStream},
|
||||
},
|
||||
core::HSTRING,
|
||||
};
|
||||
|
||||
/// Whether `(x, y)` points from the top left is dark.
|
||||
pub fn dark(job: &Path, page: u32, (x, y): (u32, u32)) -> bool {
|
||||
let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(job)).and_then(|file| file.join()).expect("the job opens");
|
||||
let document = PdfDocument::LoadFromFileAsync(&file).and_then(|document| document.join()).expect("the job reads");
|
||||
let page = document.GetPage(page).expect("the page");
|
||||
let size = page.Size().expect("its size");
|
||||
let options = PdfPageRenderOptions::new().expect("options");
|
||||
// Asked in DIPs; scaled back to one pixel per point.
|
||||
options.SetDestinationWidth((size.Width * 0.75).round() as u32).expect("a width");
|
||||
let stream = InMemoryRandomAccessStream::new().expect("a stream");
|
||||
page.RenderWithOptionsToStreamAsync(&stream, &options).and_then(|render| render.join()).expect("renders");
|
||||
let length = stream.Size().expect("a size") as u32;
|
||||
let reader = DataReader::CreateDataReader(&stream.GetInputStreamAt(0).expect("a start")).expect("a reader");
|
||||
reader.LoadAsync(length).and_then(|load| load.join()).expect("loads");
|
||||
let mut png = vec![0; length as usize];
|
||||
reader.ReadBytes(&mut png).expect("reads");
|
||||
let image = image::load_from_memory(&png).expect("a PNG").to_luma8();
|
||||
let scale = f64::from(image.width()) / f64::from(size.Width * 0.75);
|
||||
let at = |point: u32| (f64::from(point) * scale) as u32;
|
||||
image.get_pixel(at(x), at(y)).0[0] < 64
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn main() {
|
||||
use std::io::BufRead as _;
|
||||
|
||||
// A private session bus: the stand-in portal and nothing else.
|
||||
let bus = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--nopidfile", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
let Ok(mut bus) = bus else {
|
||||
println!("SKIP: no dbus-daemon");
|
||||
return;
|
||||
};
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(bus.stdout.take().expect("its address")).read_line(&mut address).expect("reads the address");
|
||||
// Before any thread starts: the portal client finds this bus.
|
||||
unsafe { std::env::set_var("DBUS_SESSION_BUS_ADDRESS", address.trim()) };
|
||||
let folder = tempfile::tempdir().expect("a folder");
|
||||
let wide = folder.path().join("wide.pdf");
|
||||
fixture(&wide, &[(842.0, 595.0)]);
|
||||
let three = folder.path().join("three.pdf");
|
||||
fixture(&three, &[(595.0, 842.0), (420.0, 595.0), (300.0, 300.0)]);
|
||||
futures::executor::block_on(portal::check(&wide, &three));
|
||||
bus.kill().expect("the bus stops");
|
||||
println!("print: linux ok");
|
||||
}
|
||||
|
||||
/// A stand-in for org.freedesktop.portal.Print.
|
||||
#[cfg(target_os = "linux")]
|
||||
mod portal {
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io::Read as _,
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use zbus::{
|
||||
Connection,
|
||||
message::Header,
|
||||
zvariant::{OwnedFd, OwnedObjectPath, OwnedValue, Value},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Seen {
|
||||
cancel: bool,
|
||||
/// What the dialog answers the user chose.
|
||||
choices: Vec<(&'static str, &'static str)>,
|
||||
setup: HashMap<String, OwnedValue>,
|
||||
formats: Option<Vec<String>>,
|
||||
token: Option<u32>,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
struct Portal(Arc<Mutex<Seen>>);
|
||||
|
||||
/// The request object the caller listens on.
|
||||
fn handle(header: &Header<'_>, options: &HashMap<String, OwnedValue>) -> OwnedObjectPath {
|
||||
let sender = header.sender().expect("a sender").trim_start_matches(':').replace('.', "_");
|
||||
let token: &str = options.get("handle_token").expect("a handle token").downcast_ref().expect("a string");
|
||||
OwnedObjectPath::try_from(format!("/org/freedesktop/portal/desktop/request/{sender}/{token}")).expect("a path")
|
||||
}
|
||||
|
||||
async fn answer(connection: &Connection, handle: &OwnedObjectPath, code: u32, results: HashMap<&str, Value<'_>>) {
|
||||
connection
|
||||
.emit_signal(None::<()>, handle, "org.freedesktop.portal.Request", "Response", &(code, results))
|
||||
.await
|
||||
.expect("the response goes out");
|
||||
}
|
||||
|
||||
#[zbus::interface(name = "org.freedesktop.portal.Print")]
|
||||
impl Portal {
|
||||
// The portal's own signature.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn prepare_print(
|
||||
&self,
|
||||
#[zbus(header)] header: Header<'_>,
|
||||
#[zbus(connection)] connection: &Connection,
|
||||
_parent: &str,
|
||||
_title: &str,
|
||||
_settings: HashMap<String, OwnedValue>,
|
||||
page_setup: HashMap<String, OwnedValue>,
|
||||
options: HashMap<String, OwnedValue>,
|
||||
) -> OwnedObjectPath {
|
||||
let handle = handle(&header, &options);
|
||||
let formats = options.get("supported_output_file_formats").map(|formats| formats.try_clone().expect("a copy").try_into().expect("strings"));
|
||||
let (cancel, choices) = {
|
||||
let mut seen = self.0.lock().expect("the record");
|
||||
(seen.setup, seen.formats) = (page_setup.clone(), formats);
|
||||
(seen.cancel, seen.choices.clone())
|
||||
};
|
||||
// GTK hands every setting back as text.
|
||||
let settings: HashMap<String, Value> = choices.into_iter().map(|(key, value)| (key.to_string(), Value::from(value))).collect();
|
||||
let results = match cancel {
|
||||
true => HashMap::new(),
|
||||
false => HashMap::from([
|
||||
("settings", Value::from(settings)),
|
||||
("page-setup", Value::from(page_setup)),
|
||||
("token", Value::from(7u32)),
|
||||
]),
|
||||
};
|
||||
answer(connection, &handle, u32::from(cancel), results).await;
|
||||
handle
|
||||
}
|
||||
|
||||
async fn print(
|
||||
&self,
|
||||
#[zbus(header)] header: Header<'_>,
|
||||
#[zbus(connection)] connection: &Connection,
|
||||
_parent: &str,
|
||||
_title: &str,
|
||||
fd: OwnedFd,
|
||||
options: HashMap<String, OwnedValue>,
|
||||
) -> OwnedObjectPath {
|
||||
let handle = handle(&header, &options);
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::from(std::os::fd::OwnedFd::from(fd)).read_to_end(&mut bytes).expect("the job reads");
|
||||
let token = options.get("token").map(|token| token.downcast_ref::<u32>().expect("a number"));
|
||||
{
|
||||
let mut seen = self.0.lock().expect("the record");
|
||||
(seen.token, seen.bytes) = (token, Some(bytes));
|
||||
}
|
||||
answer(connection, &handle, 0, HashMap::new()).await;
|
||||
handle
|
||||
}
|
||||
|
||||
#[zbus(property, name = "version")]
|
||||
fn version(&self) -> u32 {
|
||||
3
|
||||
}
|
||||
}
|
||||
|
||||
/// A sheet's size, then each form's width and placed corners.
|
||||
type Sheet = ((i64, i64), Vec<(i64, [i64; 4])>);
|
||||
|
||||
fn sheets(bytes: &[u8]) -> Vec<Sheet> {
|
||||
use lopdf::{Document, Object, content::Content};
|
||||
|
||||
let document = Document::load_mem(bytes).expect("a PDF");
|
||||
let numbers = |object: &Object| -> Vec<f64> { object.as_array().expect("numbers").iter().map(|n| f64::from(n.as_float().expect("a number"))).collect() };
|
||||
let round = |n: f64| n.round() as i64;
|
||||
let pages = document.get_pages().into_values().map(|page| {
|
||||
let dict = document.get_dictionary(page).expect("a page");
|
||||
let media = numbers(dict.get(b"MediaBox").expect("a box"));
|
||||
let resources = dict.get(b"Resources").and_then(Object::as_dict).expect("resources");
|
||||
let forms = resources.get(b"XObject").and_then(Object::as_dict).expect("forms");
|
||||
let content = Content::decode(&document.get_page_content(page)).expect("content");
|
||||
let mut m = vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
let mut placed = Vec::new();
|
||||
for op in content.operations {
|
||||
match op.operator.as_str() {
|
||||
"cm" => m = op.operands.iter().map(|n| f64::from(n.as_float().expect("a number"))).collect(),
|
||||
"Do" => {
|
||||
let form = forms.get(op.operands[0].as_name().expect("a name")).and_then(Object::as_reference).expect("a form");
|
||||
let stream = document.get_object(form).and_then(Object::as_stream).expect("a stream");
|
||||
let b = numbers(stream.dict.get(b"BBox").expect("a box"));
|
||||
let at = |x: f64, y: f64| (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]);
|
||||
let ((x0, y0), (x1, y1)) = (at(b[0], b[1]), at(b[2], b[3]));
|
||||
placed.push((round(b[2] - b[0]), [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)].map(round)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
((round(media[2]), round(media[3])), placed)
|
||||
});
|
||||
pages.collect()
|
||||
}
|
||||
|
||||
pub async fn check(source: &Path, three: &Path) {
|
||||
let seen = Arc::new(Mutex::new(Seen::default()));
|
||||
let _portal = zbus::connection::Builder::session()
|
||||
.and_then(|builder| builder.name("org.freedesktop.portal.Desktop"))
|
||||
.and_then(|builder| builder.serve_at("/org/freedesktop/portal/desktop", Portal(seen.clone())))
|
||||
.expect("a portal")
|
||||
.build()
|
||||
.await
|
||||
.expect("the portal serves");
|
||||
assert!(ely_platform::print::print_pdf(source).await.expect("prints"), "printed");
|
||||
{
|
||||
let seen = seen.lock().expect("the record");
|
||||
let text = |key: &str| seen.setup.get(key).map(|value| value.downcast_ref::<String>().expect("text"));
|
||||
let number = |key: &str| seen.setup.get(key).map(|value| value.downcast_ref::<f64>().expect("a number").round());
|
||||
assert_eq!(text("Name").as_deref(), Some("iso_a4"));
|
||||
assert_eq!(text("Orientation").as_deref(), Some("landscape"));
|
||||
assert_eq!((number("Width"), number("Height"), number("MarginTop")), (Some(210.0), Some(297.0), Some(0.0)));
|
||||
assert_eq!(seen.token, Some(7), "the print carries the dialog's token");
|
||||
assert_eq!(seen.formats.as_deref(), Some(["pdf".to_string()].as_slice()), "PDF is all we hand over");
|
||||
let printed = sheets(seen.bytes.as_deref().expect("a job"));
|
||||
assert_eq!(printed, [((842, 595), vec![(842, [0, 0, 842, 595])])], "the page fills its sheet");
|
||||
}
|
||||
// Page two at half size, from the sheet's top left.
|
||||
let choices = vec![("print-pages", "ranges"), ("page-ranges", "1"), ("scale", "50")];
|
||||
*seen.lock().expect("the record") = Seen { choices, ..Seen::default() };
|
||||
assert!(ely_platform::print::print_pdf(three).await.expect("prints"), "printed");
|
||||
let printed = sheets(seen.lock().expect("the record").bytes.as_deref().expect("a job"));
|
||||
assert_eq!(printed, [((595, 842), vec![(420, [0, 545, 210, 842])])]);
|
||||
// Two copies, uncollated, of the last two pages, in reverse.
|
||||
let choices = vec![("print-pages", "ranges"), ("page-ranges", "1--1"), ("reverse", "true"), ("n-copies", "2"), ("collate", "false")];
|
||||
*seen.lock().expect("the record") = Seen { choices, ..Seen::default() };
|
||||
assert!(ely_platform::print::print_pdf(three).await.expect("prints"), "printed");
|
||||
let printed = sheets(seen.lock().expect("the record").bytes.as_deref().expect("a job"));
|
||||
let widths: Vec<i64> = printed.iter().map(|(_, placed)| placed[0].0).collect();
|
||||
assert_eq!(widths, [300, 300, 420, 420]);
|
||||
// Cancelled, nothing prints.
|
||||
*seen.lock().expect("the record") = Seen { cancel: true, ..Seen::default() };
|
||||
assert!(!ely_platform::print::print_pdf(source).await.expect("cancels"), "not printed");
|
||||
assert_eq!(seen.lock().expect("the record").bytes, None, "no job went out");
|
||||
}
|
||||
}
|
||||
|
||||
/// macOS prints through tests/scripts/print.sh, in a real window.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn main() {}
|
||||
@@ -19,6 +19,9 @@ log.workspace = true
|
||||
notify.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
gpui_windows = { package = "gpui-pre-windows", version = "=0.3.8" }
|
||||
|
||||
[features]
|
||||
test-support = []
|
||||
|
||||
|
||||
@@ -131,9 +131,6 @@ fn label(command: &Command, cx: &App) -> SharedString {
|
||||
|
||||
/// Why `id` cannot run; a document lifts the no-document block.
|
||||
pub fn blocked(id: &str, document: bool, cx: &App) -> Option<SharedString> {
|
||||
if id == PRINT.id && !ely_platform::print::BUILT {
|
||||
return Some(i18n::text(cx, "command.blocked.unbuilt", &[]));
|
||||
}
|
||||
let command = RENAMING.iter().find(|command| command.id == id)?;
|
||||
let key = command.blocked.filter(|_| !document)?;
|
||||
Some(i18n::text(cx, key, &[]))
|
||||
@@ -190,11 +187,8 @@ pub fn menus(
|
||||
}
|
||||
|
||||
pub fn bind_keys(cx: &mut App) {
|
||||
// Without a print panel, Print stays off the keyboard.
|
||||
if ely_platform::print::BUILT {
|
||||
cx.bind_keys([KeyBinding::new(PRINT.keys, Print, Some(CONTEXT))]);
|
||||
}
|
||||
cx.bind_keys([
|
||||
KeyBinding::new(PRINT.keys, Print, Some(CONTEXT)),
|
||||
KeyBinding::new(NEW.keys, New, Some(CONTEXT)),
|
||||
KeyBinding::new(OPEN.keys, Open, Some(CONTEXT)),
|
||||
KeyBinding::new(SAVE.keys, Save, Some(CONTEXT)),
|
||||
|
||||
@@ -41,7 +41,6 @@ const EN: &[(&str, &str)] = &[
|
||||
("command.file.export", "Export…"),
|
||||
("command.file.print", "Print…"),
|
||||
("command.blocked.no_document", "No open document"),
|
||||
("command.blocked.unbuilt", "Not built for this platform yet"),
|
||||
("palette.group.file", "File"),
|
||||
("gallery.ready", "Ready"),
|
||||
("gallery.nav", "Navigation"),
|
||||
@@ -97,7 +96,6 @@ const ZH_CN: &[(&str, &str)] = &[
|
||||
("command.file.export", "导出…"),
|
||||
("command.file.print", "打印…"),
|
||||
("command.blocked.no_document", "没有打开的文档"),
|
||||
("command.blocked.unbuilt", "此平台尚未构建"),
|
||||
("palette.group.file", "文件"),
|
||||
("gallery.ready", "就绪"),
|
||||
("gallery.nav", "导航"),
|
||||
@@ -147,6 +145,8 @@ pub fn install(cx: &mut App) {
|
||||
|
||||
/// Installs the catalogs speaking `locale` (en-US or zh-CN).
|
||||
pub fn install_as(locale: &'static str, cx: &mut App) {
|
||||
#[cfg(target_os = "windows")]
|
||||
gpui_windows::set_text_language(locale);
|
||||
let (en, zh) = catalogs();
|
||||
cx.set_global(
|
||||
I18n::new(locale)
|
||||
|
||||
@@ -6,6 +6,7 @@ pub(super) const EN: &[(&str, &str)] = &[
|
||||
("mark.pane.search", "Search"),
|
||||
("mark.recent", "Recent"),
|
||||
("mark.recent.none", "Nothing opened yet"),
|
||||
("mark.recent.clear", "Clear Recent Files"),
|
||||
("mark.outline.none", "No headings"),
|
||||
("mark.search", "Results"),
|
||||
("mark.search.file", "This file"),
|
||||
@@ -82,6 +83,8 @@ pub(super) const EN: &[(&str, &str)] = &[
|
||||
("mark.git.ignored", "Git: ignored"),
|
||||
("mark.git.conflicted", "Git: conflicted"),
|
||||
("mark.git.unknown", "Git: unknown"),
|
||||
("mark.git.none", "Git: needs ElyTree"),
|
||||
("mark.git.needs", "Ely's Git comes with ElyTree. Install ElyTree from the Ely Office release to see this file's Git status."),
|
||||
("mark.git.open", "Show this file's history in ElyTree"),
|
||||
("mark.git.missing", "ElyTree is not installed. Install ElyTree from the Ely Office release to see this file's history."),
|
||||
("mark.git.failed", "ElyTree did not open: {error}"),
|
||||
@@ -106,6 +109,7 @@ pub(super) const ZH_CN: &[(&str, &str)] = &[
|
||||
("mark.pane.search", "搜索"),
|
||||
("mark.recent", "最近"),
|
||||
("mark.recent.none", "还没有打开过文件"),
|
||||
("mark.recent.clear", "清除最近文件"),
|
||||
("mark.outline.none", "没有标题"),
|
||||
("mark.search", "结果"),
|
||||
("mark.search.file", "本文件"),
|
||||
@@ -182,6 +186,8 @@ pub(super) const ZH_CN: &[(&str, &str)] = &[
|
||||
("mark.git.ignored", "Git:已忽略"),
|
||||
("mark.git.conflicted", "Git:有冲突"),
|
||||
("mark.git.unknown", "Git:未知"),
|
||||
("mark.git.none", "Git:需要 ElyTree"),
|
||||
("mark.git.needs", "Ely 的 Git 随 ElyTree 安装。请从 Ely Office 发行包安装 ElyTree 后查看此文件的 Git 状态。"),
|
||||
("mark.git.open", "在 ElyTree 中查看此文件的历史"),
|
||||
("mark.git.missing", "未安装 ElyTree。请从 Ely Office 发行包安装 ElyTree 后查看此文件的历史。"),
|
||||
("mark.git.failed", "ElyTree 没能打开:{error}"),
|
||||
|
||||
@@ -53,3 +53,44 @@ fn each_app_shows_its_own_sections(cx: &mut TestAppContext) {
|
||||
assert_eq!(shown, keys, "{app:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A main window's frame.
|
||||
struct Main(gpui::FocusHandle);
|
||||
|
||||
impl gpui::Render for Main {
|
||||
fn render(&mut self, _: &mut gpui::Window, _: &mut gpui::Context<Self>) -> impl gpui::IntoElement {
|
||||
crate::shell::Shell::new("main", &self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far below the title bar the content starts.
|
||||
fn below_title(cx: &mut TestAppContext, window: gpui::AnyWindowHandle) -> gpui::Pixels {
|
||||
let mut shown = gpui::VisualTestContext::from_window(window, cx);
|
||||
for _ in 0..3 {
|
||||
shown.update(|window, _| window.refresh());
|
||||
shown.run_until_parked();
|
||||
}
|
||||
let title = shown.debug_bounds("shell-title").expect("a title bar");
|
||||
shown.debug_bounds("shell-body").expect("a body").origin.y - title.bottom()
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn only_the_main_window_carries_menus_and_updates(cx: &mut TestAppContext) {
|
||||
installed(cx);
|
||||
cx.update(|cx| {
|
||||
let menus = crate::commands::menus(AppId::Mark, &crate::commands::OPENING, false, Vec::new(), cx);
|
||||
cx.set_menus(menus);
|
||||
});
|
||||
let main = cx.add_window(|_, cx| Main(cx.focus_handle()));
|
||||
let menus = below_title(cx, main.into());
|
||||
// macOS keeps menus in the system bar.
|
||||
match cfg!(target_os = "macos") {
|
||||
true => assert_eq!(menus, gpui::px(0.0), "no menu row on macOS"),
|
||||
false => assert!(menus > gpui::px(0.0), "the main window shows the menus"),
|
||||
}
|
||||
cx.update(crate::updates::offer_for_tests);
|
||||
let main = cx.add_window(|_, cx| Main(cx.focus_handle()));
|
||||
assert!(below_title(cx, main.into()) > menus, "the main window shows the update");
|
||||
let settings = cx.add_window(|window, cx| SettingsView::new(AppId::Mark, window, cx));
|
||||
assert_eq!(below_title(cx, settings.into()), gpui::px(0.0), "settings repeats neither");
|
||||
}
|
||||
@@ -353,6 +353,7 @@ impl Render for SettingsView {
|
||||
})
|
||||
.collect();
|
||||
Shell::new(text(cx, "settings.title", &[]), &self.focus)
|
||||
.secondary()
|
||||
.child(div().size_full().p_6().flex().flex_col().gap_4().children(unreadable).children(app_error).children(unsaved).child(layout))
|
||||
.children(dialog)
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ use ely_gpui_component::{
|
||||
theme::{ActiveTheme, TextSize},
|
||||
};
|
||||
use gpui::{
|
||||
AnyElement, AnyView, App, ElementId, FocusHandle, IntoElement, ParentElement, RenderOnce,
|
||||
SharedString, Styled, Window, div,
|
||||
AnyElement, AnyView, App, ElementId, FocusHandle, InteractiveElement, IntoElement,
|
||||
ParentElement, RenderOnce, SharedString, Styled, Window, div,
|
||||
};
|
||||
|
||||
mod page;
|
||||
@@ -32,6 +32,7 @@ pub struct Shell {
|
||||
right: Option<AnyView>,
|
||||
status: Option<StatusBar>,
|
||||
page: Option<ElementId>,
|
||||
main: bool,
|
||||
body: Vec<AnyElement>,
|
||||
}
|
||||
|
||||
@@ -45,10 +46,17 @@ impl Shell {
|
||||
right: None,
|
||||
status: None,
|
||||
page: None,
|
||||
main: true,
|
||||
body: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Beside the main window: no menus, no update banner.
|
||||
pub fn secondary(mut self) -> Self {
|
||||
self.main = false;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn tabs(mut self, tabs: EditorTabs) -> Self {
|
||||
self.tabs = Some(tabs);
|
||||
self
|
||||
@@ -98,6 +106,7 @@ impl RenderOnce for Shell {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let length = motion::duration(motion::BASE, cx);
|
||||
let content = div()
|
||||
.debug_selector(|| "shell-body".into())
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.h_full()
|
||||
@@ -123,9 +132,13 @@ impl RenderOnce for Shell {
|
||||
let header = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.child(TitleBar::new("titlebar").title(self.title))
|
||||
.children(crate::updates::updater(cx))
|
||||
.children(menu_bar(cx))
|
||||
.child(
|
||||
div()
|
||||
.debug_selector(|| "shell-title".into())
|
||||
.child(TitleBar::new("titlebar").title(self.title)),
|
||||
)
|
||||
.children(self.main.then(|| crate::updates::updater(cx)).flatten())
|
||||
.children(self.main.then(|| menu_bar(cx)).flatten())
|
||||
.children(self.tabs);
|
||||
// Panels give way so the content keeps its room.
|
||||
let (left, right) = (panel::fitted(Side::Left, window, cx), panel::fitted(Side::Right, window, cx));
|
||||
|
||||
@@ -379,7 +379,7 @@ mod tests {
|
||||
})
|
||||
.expect("the window lives");
|
||||
cx.run_until_parked();
|
||||
// Save without a document is blocked; so is Print unbuilt.
|
||||
// Save without a document is blocked.
|
||||
window
|
||||
.update(cx, |_, window, cx| root.update(cx, |root, cx| root.run_from_palette("file.save", window, cx)))
|
||||
.expect("the window lives");
|
||||
|
||||
@@ -359,6 +359,25 @@ impl Render for Updates {
|
||||
}
|
||||
}
|
||||
|
||||
/// An offered release, for window tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn offer_for_tests(cx: &mut App) {
|
||||
let release = Release {
|
||||
version: semver::Version::new(9, 0, 0),
|
||||
url: "https://example.test/9.dmg".into(),
|
||||
sha256: String::new(),
|
||||
};
|
||||
let updates = cx.new(|_| Updates {
|
||||
app: AppId::Mark,
|
||||
bundle: PathBuf::new(),
|
||||
offer: Some((release, Phase::Offered)),
|
||||
dismissed: false,
|
||||
pending: None,
|
||||
note: None,
|
||||
});
|
||||
cx.set_global(Updater(updates));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
随发行说明发布,每个版本一份。支持某格式不等于支持它的全部功能;下表只写已验证的内容、已知限制与保存行为。
|
||||
|
||||
版本:Ely Office 0.1.3(首版六个应用:ElyDoc、ElyTable、ElyShow、ElyPDF、ElyTree、ElyMark)。日期 2026-10-11。
|
||||
内核:LibreOffice 26.2.6.3(8221e31,加 `patches/libreoffice` 0001–0047);MuPDF 1.28.5(8ad45e9,加 `patches/mupdf` 0001–0005);Git 2.56.0(a018953)与 git-lfs 3.8.0。
|
||||
版本:Ely Office 0.1.7(首版六个应用:ElyDoc、ElyTable、ElyShow、ElyPDF、ElyTree、ElyMark)。日期 2026-10-17。
|
||||
内核:LibreOffice 26.2.6.3(8221e31,加 `patches/libreoffice` 0001–0048);MuPDF 1.28.5(8ad45e9,加 `patches/mupdf` 0001–0005);Git 2.56.0(a018953)与 git-lfs 3.8.0。
|
||||
验证机:macOS 27.0 arm64。Windows 与 Linux 未验证。本机没有 Microsoft Office:与 Office 的交叉检查未做(待做)。
|
||||
|
||||
## 往返验证
|
||||
@@ -16,6 +16,8 @@
|
||||
| XLSX 公式 | 公式文本与缓存结果:整数、日期序号、`#DIV/0!` 错误值、文本严格相等,浮点按用例声明的 1e-12 容差;第二次会话的公式 | 通过 |
|
||||
| PPTX 演示 | 三张幻灯片、隐藏的那张仍隐藏、备注文字(含中文) | 通过 |
|
||||
|
||||
打印:macOS 经 PDFKit 的打印面板,Windows 经系统打印对话框(真窗口核对到 Microsoft Print to PDF),Linux 经桌面门户(只对替身门户核对,真桌面未核对);纸张取文档的,按原大印。打印机没有该纸张、或页面放不下所选纸张时报错,不裁切。Linux 由 Ely 照对话框的选择排页(页码范围、奇偶页、倒序、份数与逐份、缩放、每张页数),只交出 PDF。
|
||||
|
||||
字体:缺失字体由内核报出,ElyDoc 页面上方列出缺失的字体(`doc.fonts.missing`),分页可能与有字体时不同;字体一致与缺失两种环境的对照未做。产品不带微软字体。
|
||||
|
||||
## ElyDoc
|
||||
@@ -24,7 +26,7 @@
|
||||
| --- | --- |
|
||||
| 编辑与保存 | DOCX、ODT(保存保留原格式;另存为默认 DOCX) |
|
||||
| 导入或受限 | DOC、RTF 按原格式保存;含宏的文件(docm、dotm、带 Basic 的 ODF/OLE)进风险模式,只能另存副本,宏不运行 |
|
||||
| 输出 | PDF(页码范围、批注、修订标记)、打印(macOS) |
|
||||
| 输出 | PDF(页码范围、批注、修订标记)、打印 |
|
||||
|
||||
已验证:文字与段落格式、样式、页面与分节、页眉页脚、表格、图片锚点与环绕、目录、脚注尾注、书签、交叉引用、题注、公式、批注与回复、修订、查找替换、拼写(英文)、比较、邮件合并。限制:交叉引用只指向书签;公式导出 DOCX 后在 Word 中是否可编辑未验证。
|
||||
|
||||
@@ -34,7 +36,7 @@
|
||||
| --- | --- |
|
||||
| 编辑与保存 | XLSX、ODS(保存保留 xlsx、ods、xls、fods;另存为默认 XLSX) |
|
||||
| 导入或受限 | XLS;CSV、TSV、TXT 经导入对话框(编码、分隔符、引号、逐列类型)成为新工作簿,原文件不动;xlsm、xltm 进风险模式 |
|
||||
| 输出 | PDF(全部工作表,按页面设置)、CSV 与 TSV(当前工作表的显示值,UTF-8)、打印(macOS) |
|
||||
| 输出 | PDF(全部工作表,按页面设置)、CSV 与 TSV(当前工作表的显示值,UTF-8)、打印 |
|
||||
|
||||
公式语法为 Excel A1。XLSX 与非 LibreOffice 生成的 ODF 载入时总是重算。限制:不支持的函数显示 `#NAME?`,原公式保留,缓存值不保留;外部链接不刷新,显示保存时的值;1904 日期系统未专门验证。
|
||||
|
||||
@@ -44,7 +46,7 @@
|
||||
| --- | --- |
|
||||
| 编辑与保存 | PPTX、ODP(另存为默认 PPTX) |
|
||||
| 导入或受限 | PPT;章节(`p14:sectionLst`)内核不保留;媒体默认嵌入 |
|
||||
| 输出 | PDF(幻灯片或讲义 1、2、3、4、6、9 张一页)、PNG(每张 1920 宽)、打印(macOS) |
|
||||
| 输出 | PDF(幻灯片或讲义 1、2、3、4、6、9 张一页)、PNG(每张 1920 宽)、打印 |
|
||||
|
||||
限制:Ely 提供一组基础切换与动画,文件自带的其他效果照原样保留并显示内核名称;批注不做回复(Impress 无回复结构);Windows 与 Linux 的媒体播放未构建。
|
||||
|
||||
@@ -54,7 +56,7 @@
|
||||
| --- | --- |
|
||||
| 编辑与保存 | 页面增删移转裁剪、文字与图片改动、批注、表单字段(文本、复选、单选、选择框)、书签、链接、属性、附件、OCR 文字层、内容删除与清理、密码与权限、数字签名 |
|
||||
| 导入或受限 | XFA 表单不支持;已签名文件另存为未签名副本;修复过的文件只能另存;多选列表框按单选填写 |
|
||||
| 输出 | PDF、页面图片(PNG 72/150/300 dpi)、文本、优化的 PDF、打印(macOS) |
|
||||
| 输出 | PDF、页面图片(PNG 72/150/300 dpi)、文本、优化的 PDF、打印 |
|
||||
|
||||
保存经 MuPDF 写快照后紧缩写出;签名经增量更新写出并重开核对摘要。独立阅读器 PDFKit 读回页序、改动的文字与字段值(`crates/ely-pdf-engine/tests/independent.rs`)。限制:证书吊销状态不核验;Windows 与 Linux 的证书信任未构建。
|
||||
|
||||
|
||||
+2
-2
@@ -16,10 +16,10 @@
|
||||
|
||||
## ElyMark 的菜单与快捷键
|
||||
|
||||
- 段落与格式菜单照 Typora。标题:Ctrl+1 至 Ctrl+6,Ctrl+0 段落,Ctrl+= 与 Ctrl+- 升降一级。块:Ctrl+Shift+K 代码块,Ctrl+Shift+M 公式块,Ctrl+Shift+Q 引用,Ctrl+Shift+[ 有序列表,Ctrl+Shift+] 无序列表,Ctrl+Shift+X 任务列表。
|
||||
- 段落与格式菜单照 Typora。菜单里带 Shift 的标点键写成所出的字符,如 Ctrl+{ 即 Ctrl+Shift+[。标题:Ctrl+1 至 Ctrl+6,Ctrl+0 段落,Ctrl+= 与 Ctrl+- 升降一级。块:Ctrl+Shift+K 代码块,Ctrl+Shift+M 公式块,Ctrl+Shift+Q 引用,Ctrl+Shift+[ 有序列表,Ctrl+Shift+] 无序列表,Ctrl+Shift+X 任务列表。
|
||||
- 格式:Ctrl+B 加粗,Ctrl+I 斜体,Ctrl+U 下划线,Ctrl+Shift+` 代码,Alt+Shift+5 删除线,Ctrl+K 超链接,Ctrl+Shift+I 插入图片,Ctrl+\ 清除样式。
|
||||
- 表格在“段落 ▸ 表格”:Ctrl+T 插入,Ctrl+Enter 下方插入行,Ctrl+Shift+Backspace 删除行,Alt+方向键移动行列,“格式化表格源码”对齐各列。
|
||||
- 视图:Ctrl+/ 在源代码与可视之间切换,F8 专注,F9 打字机,Ctrl+Shift+= 放大,Ctrl+Shift+- 缩小,Ctrl+Shift+0 实际大小;可视、源码、预览在“视图”菜单里选。
|
||||
- 视图:Ctrl+/ 在源代码与可视之间切换,F8 专注,F9 打字机,Ctrl+Shift+= 放大,Ctrl+Shift+- 缩小,Ctrl+Shift+0 实际大小(Windows 的中文输入法占着这个键,在 Windows 上用 Ctrl+Shift+9);可视、源码、预览在“视图”菜单里选。
|
||||
- 编辑:Ctrl+Shift+C 复制为 Markdown(无选区时复制全文),Ctrl+Shift+V 粘贴为纯文本;另有复制为纯文本、复制为 HTML 代码(图片保留原地址)、复制为富文本。
|
||||
- 右键菜单照 Typora,随所点之处变化:剪切、复制、粘贴、删除为一行图标;链接可打开、复制地址;图片可打开所在位置(网络图片在浏览器打开)、删除;代码块可复制其内容;公式与 HTML 块可编辑;加粗、斜体、代码、超链接与引用、列表各为一行图标;表格里为“表格 ▸”,别处为“段落 ▸”;“插入 ▸”;引用、列表、代码块等可整块删除。右键落在选区里时选区保留;正在编辑的块右键后仍开着。源码模式只有剪贴板与“复制/粘贴为”,预览只有复制。
|
||||
- 命令用不了时(如在代码里设标题、插入点不在表格里),提示写明原因,文字不动。macOS 上 Ctrl 为 Cmd。
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@
|
||||
|
||||
## 自有代码
|
||||
|
||||
Ely Office 的自有代码以 AGPL-3.0-or-later 发布,全文在仓库根的 `LICENSE`,并随每个应用包放在 `Resources/Licenses/LICENSE`。组件库 Ely-GPUI-Components 保留其 MIT/Apache-2.0。
|
||||
Ely Office 的自有代码以 MIT 发布,全文在仓库根的 `LICENSE`,并随每个应用包放在 `Resources/Licenses/LICENSE`。随包的引擎不随之改许可:ElyPDF 链接的 MuPDF 是 AGPL-3.0,ElyPDF 的发行包整体须按 AGPL 履行(对应源码见上游源码包);ElyDoc、ElyTable、ElyShow 的 LibreOffice 仍为 MPL-2.0 等;ElyTree 带的 Git 仍为 GPL-2.0。组件库 Ely-GPUI-Components 保留其 MIT/Apache-2.0。
|
||||
|
||||
## 每个发行版附带
|
||||
|
||||
@@ -12,7 +12,7 @@ Ely Office 的自有代码以 AGPL-3.0-or-later 发布,全文在仓库根的 `
|
||||
| --- | --- | --- |
|
||||
| `ElyOffice-<版本>-source.tar.gz` | 自有源码、`Cargo.lock`、`rust-toolchain.toml`、上游补丁(`patches/libreoffice`、`patches/mupdf`)、构建与取上游的脚本(各上游钉在提交,脚本里写明地址与散列)、测试、文档 | `packaging/macos/release.sh` |
|
||||
| `ElyOffice-<版本>-upstream-source.tar.gz` | 实际编译的 MuPDF 源码(钉住的提交加我们的补丁,AGPL)与随包 Git 的源码(v2.56.0,GPLv2) | 同上;`tests/scripts/release-macos.sh` 核对其中是打过补丁的 MuPDF |
|
||||
| 各应用包 `Resources/Licenses/` | Ely 的 AGPL 全文;`rust-crates.txt`(链进该应用各二进制的全部 crate 与其许可文件,无许可文件的取标准文本并写明作者);所带引擎的许可与通知(见下) | `packaging/licenses.sh`,缺任何一份即打包失败 |
|
||||
| 各应用包 `Resources/Licenses/` | Ely 的 MIT 全文;`rust-crates.txt`(链进该应用各二进制的全部 crate 与其许可文件,无许可文件的取标准文本并写明作者);所带引擎的许可与通知(见下) | `packaging/licenses.sh`,缺任何一份即打包失败 |
|
||||
|
||||
## 第三方,按应用
|
||||
|
||||
|
||||
+9
-14
@@ -10,26 +10,21 @@ root = pathlib.Path(__file__).resolve().parent.parent
|
||||
standard = root / "packaging" / "licenses"
|
||||
host = next(line.split()[1] for line in subprocess.run(
|
||||
["rustc", "-vV"], check=True, capture_output=True, text=True).stdout.splitlines() if line.startswith("host:"))
|
||||
# Only what this machine's build links.
|
||||
meta = json.loads(subprocess.run(
|
||||
["cargo", "metadata", "--format-version", "1", "--locked", "--filter-platform", host,
|
||||
["cargo", "metadata", "--format-version", "1", "--locked",
|
||||
"--manifest-path", str(root / "Cargo.toml")],
|
||||
check=True, capture_output=True, text=True).stdout)
|
||||
by_id = {package["id"]: package for package in meta["packages"]}
|
||||
own = set(meta["workspace_members"])
|
||||
nodes = {node["id"]: node for node in meta["resolve"]["nodes"]}
|
||||
# What links in: normal edges, for this machine's target.
|
||||
wanted, stack = set(), [pid for pid in own if by_id[pid]["name"] in sys.argv[1:]]
|
||||
if len(stack) != len(sys.argv) - 1:
|
||||
if len([pid for pid in own if by_id[pid]["name"] in sys.argv[1:]]) != len(sys.argv) - 1:
|
||||
sys.exit(f"crates.py: unknown package among {sys.argv[1:]}")
|
||||
while stack:
|
||||
pid = stack.pop()
|
||||
if pid in wanted:
|
||||
continue
|
||||
wanted.add(pid)
|
||||
for dep in nodes[pid]["deps"]:
|
||||
if any(kind["kind"] is None for kind in dep["dep_kinds"]):
|
||||
stack.append(dep["pkg"])
|
||||
# Cargo decides which normal edges link on this target.
|
||||
tree = subprocess.run(
|
||||
["cargo", "tree", "--locked", "-e", "normal", "--target", host, "--prefix", "none", "-f", "{p}",
|
||||
"--manifest-path", str(root / "Cargo.toml"), *[arg for name in sys.argv[1:] for arg in ("-p", name)]],
|
||||
check=True, capture_output=True, text=True).stdout
|
||||
linked = {tuple(line.split()[:2]) for line in tree.splitlines() if line.strip()}
|
||||
wanted = {pid for pid, package in by_id.items() if (package["name"], "v" + package["version"]) in linked}
|
||||
|
||||
out, missing = [], []
|
||||
for pid in sorted(wanted - own, key=lambda pid: (by_id[pid]["name"], by_id[pid]["version"])):
|
||||
|
||||
@@ -88,8 +88,8 @@ case $slug in
|
||||
put KaTeX "$katex/fonts/OFL.txt" "$katex/fonts/FONT_NOTICE.txt"
|
||||
;;
|
||||
esac
|
||||
# ElyTree carries Git; on Windows and Linux ElyMark does too.
|
||||
if [ "$slug" = ely-tree ] || { [ "$slug" = ely-mark ] && [ "$(uname)" != Darwin ]; }; then
|
||||
# ElyTree carries Git; on Linux ElyMark does too.
|
||||
if [ "$slug" = ely-tree ] || { [ "$slug" = ely-mark ] && [ "$(uname)" = Linux ]; }; then
|
||||
case $(uname) in
|
||||
MINGW* | MSYS*) put Git "$root/engines/git/LICENSE.txt" ;;
|
||||
*) put Git "$root/engines/git-src/COPYING" "$root/engines/git-src/LGPL-2.1" ;;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -18,6 +18,13 @@ row=$(awk -F'\t' -v slug="$slug" '$1 == slug { print $2 "\t" $3 }' "$root/packag
|
||||
}
|
||||
name=${row%%$'\t'*}
|
||||
categories=${row##*$'\t'}
|
||||
# Ely is MIT; bundled engines keep their licences.
|
||||
case $slug in
|
||||
ely-doc | ely-table | ely-show) license="MIT AND MPL-2.0" ;;
|
||||
ely-pdf) license="MIT AND AGPL-3.0-or-later" ;;
|
||||
ely-tree) license="MIT AND GPL-2.0-only" ;;
|
||||
*) license=MIT ;;
|
||||
esac
|
||||
# The types it opens, from packaging/types.tsv; none drops the line.
|
||||
mimes=$(awk -F'\t' -v slug="$slug" '$1 == slug && !seen[$3]++ { printf "%s;", $3 }' "$root/packaging/types.tsv")
|
||||
desktop_entry() {
|
||||
@@ -193,7 +200,7 @@ maintainer: ZacharyZhang
|
||||
vendor: ZacharyZhang
|
||||
description: $name, part of Ely Office
|
||||
homepage: https://git.zacharyzhang.com/ZacharyZhang-NY/ElyOffice
|
||||
license: AGPL-3.0-or-later
|
||||
license: $license
|
||||
contents:
|
||||
- src: $appdir/usr
|
||||
dst: /opt/ely-office/$slug
|
||||
|
||||
@@ -112,6 +112,9 @@ PLIST
|
||||
for target in ${inner[@]+"${inner[@]}"} "$app"; do
|
||||
if [ "$identity" = - ]; then
|
||||
codesign --force --sign - "$target"
|
||||
elif [ "$(basename "$target")" = ely-lok-worker ]; then
|
||||
# UNO's bridge maps its vtables with MAP_JIT.
|
||||
codesign --force --options runtime --timestamp --entitlements "$root/packaging/macos/lok-worker.entitlements" --sign "$identity" "$target"
|
||||
else
|
||||
codesign --force --options runtime --timestamp --sign "$identity" "$target"
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key><true/>
|
||||
</dict>
|
||||
</plist>
|
||||
+31
-19
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Usage: release.sh [batch]; a dmg per app of the batch.
|
||||
# Usage: release.sh [batch]; a dmg per app, one of all.
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
@@ -12,32 +12,44 @@ releases=https://git.zacharyzhang.com/ZacharyZhang-NY/ElyOffice/releases
|
||||
echo "release.sh: notarizing needs ELY_SIGN_IDENTITY, a Developer ID" >&2
|
||||
exit 1
|
||||
}
|
||||
# Usage: dmg <out> <volume> <app>...; apps beside Applications.
|
||||
dmg() {
|
||||
local out=$1 volume=$2 stage
|
||||
shift 2
|
||||
rm -f "$out"
|
||||
# Drag an app onto Applications.
|
||||
stage=$(mktemp -d)
|
||||
for app in "$@"; do ditto "$app" "$stage/$(basename "$app")"; done
|
||||
ln -s /Applications "$stage/Applications"
|
||||
hdiutil create -quiet -volname "$volume" -srcfolder "$stage" -format UDZO "$out"
|
||||
rm -rf "$stage"
|
||||
if [ -n "${ELY_NOTARY_PROFILE:-}" ]; then
|
||||
codesign --force --timestamp --sign "$ELY_SIGN_IDENTITY" "$out"
|
||||
xcrun notarytool submit "$out" --keychain-profile "$ELY_NOTARY_PROFILE" --wait
|
||||
xcrun stapler staple "$out"
|
||||
else
|
||||
echo "release.sh: $out is not notarized (no ELY_NOTARY_PROFILE)" >&2
|
||||
fi
|
||||
echo "$out"
|
||||
}
|
||||
"$root/packaging/source.sh" "$dist"
|
||||
awk -F'\t' -v batch="$batch" '$4 == batch { print $1 "\t" $2 }' "$root/packaging/apps.tsv" |
|
||||
while IFS=$'\t' read -r slug name; do
|
||||
"$root/packaging/macos/bundle.sh" "$slug" release
|
||||
codesign --verify --deep --strict "$dist/$name.app"
|
||||
dmg=$dist/$name-$version-$arch.dmg
|
||||
rm -f "$dmg"
|
||||
# The app beside Applications: drag one onto the other.
|
||||
stage=$(mktemp -d)
|
||||
ditto "$dist/$name.app" "$stage/$name.app"
|
||||
ln -s /Applications "$stage/Applications"
|
||||
hdiutil create -quiet -volname "$name" -srcfolder "$stage" -format UDZO "$dmg"
|
||||
rm -rf "$stage"
|
||||
if [ -n "${ELY_NOTARY_PROFILE:-}" ]; then
|
||||
codesign --force --timestamp --sign "$ELY_SIGN_IDENTITY" "$dmg"
|
||||
xcrun notarytool submit "$dmg" --keychain-profile "$ELY_NOTARY_PROFILE" --wait
|
||||
xcrun stapler staple "$dmg"
|
||||
else
|
||||
echo "release.sh: $dmg is not notarized (no ELY_NOTARY_PROFILE)" >&2
|
||||
fi
|
||||
echo "$dmg"
|
||||
out=$dist/$name-$version-$arch.dmg
|
||||
dmg "$out" "$name" "$dist/$name.app"
|
||||
# What the app's update check reads from the latest release.
|
||||
sha=$(shasum -a 256 "$dmg" | cut -d' ' -f1)
|
||||
url="$releases/download/v$version/$(basename "$dmg")"
|
||||
sha=$(shasum -a 256 "$out" | cut -d' ' -f1)
|
||||
url="$releases/download/v$version/$(basename "$out")"
|
||||
printf '{"version": "%s", "assets": {"macos-%s": {"url": "%s", "sha256": "%s"}}}\n' \
|
||||
"$version" "${arch/arm64/aarch64}" "$url" "$sha" >"$dist/$slug.json"
|
||||
echo "$dist/$slug.json"
|
||||
done
|
||||
# Every app of the batch in one dmg.
|
||||
apps=()
|
||||
for name in $(awk -F'\t' -v batch="$batch" '$4 == batch { print $2 }' "$root/packaging/apps.tsv"); do
|
||||
apps+=("$dist/$name.app")
|
||||
done
|
||||
dmg "$dist/ElyOffice-$version-$arch.dmg" "Ely Office" "${apps[@]}"
|
||||
rm -rf "$root/target/release/incremental"
|
||||
+2
-1
@@ -64,7 +64,8 @@ if [ "$slug" = ely-pdf ]; then
|
||||
mkdir "$out/tessdata"
|
||||
cp "$tessdata"/{eng,chi_sim,chi_tra}.traineddata "$out/tessdata/"
|
||||
fi
|
||||
if [ "$slug" = ely-tree ] || [ "$slug" = ely-mark ]; then
|
||||
# ElyTree carries Git; so does Linux ElyMark's standalone AppImage.
|
||||
if [ "$slug" = ely-tree ] || { [ "$slug" = ely-mark ] && [ "$(uname)" = Linux ]; }; then
|
||||
need "$root/engines/git" "scripts/build-git.sh and scripts/fetch-git-lfs.sh"
|
||||
cp -R "$root/engines/git" "$out/git"
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
; Installs the ticked apps, each by its own setup.
|
||||
Unicode true
|
||||
!include "MUI2.nsh"
|
||||
|
||||
!ifndef VERSION
|
||||
!error "pass -DVERSION"
|
||||
!endif
|
||||
!ifndef APPS
|
||||
!error "pass -DAPPS, from packaging/windows/bundle.sh"
|
||||
!endif
|
||||
!ifndef OUTFILE
|
||||
!error "pass -DOUTFILE"
|
||||
!endif
|
||||
|
||||
Name "Ely Office ${VERSION}"
|
||||
OutFile "${OUTFILE}"
|
||||
RequestExecutionLevel user
|
||||
; The setups inside are compressed already.
|
||||
SetCompress off
|
||||
|
||||
!insertmacro MUI_PAGE_COMPONENTS
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
!insertmacro MUI_LANGUAGE "SimpChinese"
|
||||
!insertmacro MUI_LANGUAGE "English"
|
||||
|
||||
LangString Failed ${LANG_SIMPCHINESE} "$R0 未装上,其安装程序退出码为 $R1(2 表示文件被占用或安装位置被占)。之前装上的应用照旧可用。"
|
||||
LangString Failed ${LANG_ENGLISH} "$R0 was not installed; its setup exited with $R1 (2: a file is in use or in the way). Apps installed before it work."
|
||||
|
||||
Function .onInit
|
||||
InitPluginsDir
|
||||
FunctionEnd
|
||||
|
||||
; One section per app; its setup runs silent.
|
||||
!macro ElyApp NAME SETUP
|
||||
Section "${NAME}"
|
||||
SetOutPath "$PLUGINSDIR"
|
||||
File "/oname=${NAME}-setup.exe" "${SETUP}"
|
||||
DetailPrint "${NAME}"
|
||||
StrCpy $R0 "${NAME}"
|
||||
ClearErrors
|
||||
ExecWait '"$PLUGINSDIR\${NAME}-setup.exe" /S' $R1
|
||||
IfErrors 0 +2
|
||||
StrCpy $R1 "-"
|
||||
Delete "$PLUGINSDIR\${NAME}-setup.exe"
|
||||
StrCmp $R1 0 ely_done_${NAME}
|
||||
MessageBox MB_ICONSTOP "$(Failed)" /SD IDOK
|
||||
SetErrorLevel 2
|
||||
Abort
|
||||
ely_done_${NAME}:
|
||||
SectionEnd
|
||||
!macroend
|
||||
|
||||
!include "${APPS}"
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds dist/ElyOffice-<version>-windows-x86_64-setup.exe from the apps' setups.
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
dist=${ELY_DIST:-$root/dist}
|
||||
version=$(awk -F'"' '/^version = / { print $2; exit }' "$root/Cargo.toml")
|
||||
makensis=${MAKENSIS:-"/c/Program Files (x86)/NSIS/makensis.exe"}
|
||||
[ -x "$makensis" ] || {
|
||||
echo "bundle.sh: no makensis at $makensis; install NSIS" >&2
|
||||
exit 1
|
||||
}
|
||||
apps=$root/target/stage/bundle-apps.nsh
|
||||
mkdir -p "$(dirname "$apps")"
|
||||
: >"$apps"
|
||||
for name in $(awk -F'\t' '$4 == 1 { print $2 }' "$root/packaging/apps.tsv"); do
|
||||
setup=$dist/$name-$version-windows-x86_64-setup.exe
|
||||
[ -f "$setup" ] || {
|
||||
echo "bundle.sh: no $setup; run installer.sh first" >&2
|
||||
exit 1
|
||||
}
|
||||
printf '!insertmacro ElyApp "%s" "%s"\n' "$name" "$(cygpath -w "$setup")" >>"$apps"
|
||||
done
|
||||
out=$dist/ElyOffice-$version-windows-x86_64-setup.exe
|
||||
"$makensis" -V2 -INPUTCHARSET UTF8 -DVERSION="$version" -DAPPS="$(cygpath -w "$apps")" \
|
||||
-DOUTFILE="$(cygpath -w "$out")" "$(cygpath -w "$root/packaging/windows/bundle.nsi")"
|
||||
echo "$out"
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prints what an install owns: files.sh <stage> <slug>
|
||||
set -euo pipefail
|
||||
|
||||
stage=${1:?staged folder from packaging/stage.sh}
|
||||
slug=${2:?app slug, such as ely-doc}
|
||||
cd "$stage"
|
||||
[ -z "$(find . -type l)" ] || {
|
||||
echo "files.sh: links in $stage" >&2
|
||||
exit 1
|
||||
}
|
||||
# Folders first, parents before children; then files.
|
||||
{
|
||||
find . -mindepth 1 -type d | sort | sed 's|$|/|'
|
||||
{ find . -type f; echo "./$slug.ico"; echo ./uninstall.exe; } | sort -u
|
||||
} | sed 's|^\./||' | while IFS= read -r path; do
|
||||
case $path in *\\* | *[[:cntrl:]]*)
|
||||
echo "files.sh: unsafe name $path" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
printf '%s\r\n' "${path//\//\\}"
|
||||
done
|
||||
+328
-16
@@ -1,6 +1,7 @@
|
||||
; Per-user installer; pass APP_NAME, APP_SLUG, VERSION, STAGE, ICON, TYPES.
|
||||
; Per-user installer; pass each define the checks below name.
|
||||
Unicode true
|
||||
!include "MUI2.nsh"
|
||||
!include "LogicLib.nsh"
|
||||
|
||||
!ifndef APP_NAME
|
||||
!error "pass -DAPP_NAME"
|
||||
@@ -21,6 +22,9 @@ Unicode true
|
||||
!error "pass -DTYPES, from packaging/windows/types.sh"
|
||||
!endif
|
||||
!include "${TYPES}"
|
||||
!ifndef LIST
|
||||
!error "pass -DLIST, from packaging/windows/files.sh"
|
||||
!endif
|
||||
!ifndef OUTFILE
|
||||
!define OUTFILE "${APP_SLUG}-${VERSION}-setup.exe"
|
||||
!endif
|
||||
@@ -34,6 +38,7 @@ RequestExecutionLevel user
|
||||
InstallDir "$LOCALAPPDATA\Programs\Ely Office\${APP_NAME}"
|
||||
InstallDirRegKey HKCU "Software\Ely Office\${APP_NAME}" "InstallDir"
|
||||
SetCompressor /SOLID lzma
|
||||
AllowSkipFiles off
|
||||
|
||||
!insertmacro MUI_PAGE_DIRECTORY
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
@@ -45,11 +50,302 @@ SetCompressor /SOLID lzma
|
||||
LangString DeleteData ${LANG_SIMPCHINESE} "同时删除 ${APP_NAME} 的缓存、账号与本地历史吗?你的文档不受影响。"
|
||||
LangString DeleteData ${LANG_ENGLISH} "Also delete the cache, accounts and local history of ${APP_NAME}? Your documents stay."
|
||||
|
||||
LangString Busy ${LANG_SIMPCHINESE} "${APP_NAME} 的文件正被占用,未作任何改动。请关闭 ${APP_NAME} 后重试:"
|
||||
LangString Busy ${LANG_ENGLISH} "A file of ${APP_NAME} is in use; nothing was changed. Close ${APP_NAME} and try again:"
|
||||
LangString Stuck ${LANG_SIMPCHINESE} "旧版的文件放回原处失败,留在:"
|
||||
LangString Stuck ${LANG_ENGLISH} "Could not put the old files back; they are in:"
|
||||
LangString Left ${LANG_SIMPCHINESE} "新版已装好,旧版的文件删不掉,留在:"
|
||||
LangString Left ${LANG_ENGLISH} "The new version is installed; the old files could not be deleted from:"
|
||||
LangString NoList ${LANG_SIMPCHINESE} "找不到安装清单,未删除任何文件:"
|
||||
LangString NoList ${LANG_ENGLISH} "No install list found; nothing was deleted:"
|
||||
|
||||
LangString Taken ${LANG_SIMPCHINESE} "安装位置已有不属于 ${APP_NAME} 的文件,未作任何改动:"
|
||||
LangString Taken ${LANG_ENGLISH} "A file ${APP_NAME} did not install is in the way; nothing was changed:"
|
||||
|
||||
; Lists a legacy folder's files and folders to $R2.
|
||||
Function ElyWalk
|
||||
Push "|"
|
||||
Push $R1
|
||||
walk:
|
||||
Pop $R1
|
||||
StrCmp $R1 "|" done
|
||||
FileWrite $R2 "$R1\$\r$\n"
|
||||
FindFirst $R3 $R4 "$INSTDIR\$R1\*"
|
||||
entry:
|
||||
StrCmp $R4 "" closed
|
||||
StrCmp $R4 "." skip
|
||||
StrCmp $R4 ".." skip
|
||||
IfFileExists "$INSTDIR\$R1\$R4\*.*" 0 file
|
||||
Push "$R1\$R4"
|
||||
Goto skip
|
||||
file:
|
||||
FileWrite $R2 "$R1\$R4$\r$\n"
|
||||
skip:
|
||||
FindNext $R3 $R4
|
||||
Goto entry
|
||||
closed:
|
||||
FindClose $R3
|
||||
Goto walk
|
||||
done:
|
||||
FunctionEnd
|
||||
|
||||
!macro ElyLegacyDir NAME
|
||||
IfFileExists "$INSTDIR\${NAME}\*.*" 0 +3
|
||||
StrCpy $R1 "${NAME}"
|
||||
Call ElyWalk
|
||||
!macroend
|
||||
|
||||
!macro ElyLegacy ID PATTERN
|
||||
FindFirst $R3 $R4 "$INSTDIR\${PATTERN}"
|
||||
ely_legacy_${ID}:
|
||||
StrCmp $R4 "" ely_legacy_end_${ID}
|
||||
FileWrite $R2 "$R4$\r$\n"
|
||||
FindNext $R3 $R4
|
||||
Goto ely_legacy_${ID}
|
||||
ely_legacy_end_${ID}:
|
||||
FindClose $R3
|
||||
!macroend
|
||||
|
||||
; Sets $R0 to the list an earlier install owns.
|
||||
Function ElyOwned
|
||||
StrCpy $R0 ""
|
||||
StrCpy $R7 ""
|
||||
; A copy, as this install rewrites the list.
|
||||
IfFileExists "$INSTDIR\.ely-installed" 0 unlisted
|
||||
StrCpy $R0 "$PLUGINSDIR\owned.txt"
|
||||
StrCpy $R7 "listed"
|
||||
CopyFiles /SILENT "$INSTDIR\.ely-installed" "$R0"
|
||||
Goto done
|
||||
unlisted:
|
||||
; Older releases: only the folder our key names.
|
||||
ReadRegStr $R1 HKCU "Software\Ely Office\${APP_NAME}" "InstallDir"
|
||||
StrCmp $R1 "$INSTDIR" 0 done
|
||||
IfFileExists "$INSTDIR\${APP_SLUG}.exe" 0 done
|
||||
StrCpy $R0 "$PLUGINSDIR\legacy.txt"
|
||||
FileOpen $R2 "$R0" w
|
||||
!insertmacro ElyLegacyDir libreoffice
|
||||
!insertmacro ElyLegacyDir tessdata
|
||||
!insertmacro ElyLegacyDir git
|
||||
!insertmacro ElyLegacyDir content
|
||||
!insertmacro ElyLegacyDir locales
|
||||
!insertmacro ElyLegacyDir licenses
|
||||
FileWrite $R2 "${APP_SLUG}.ico$\r$\n"
|
||||
!insertmacro ElyLegacy exe "*.exe"
|
||||
!insertmacro ElyLegacy dll "*.dll"
|
||||
!insertmacro ElyLegacy pak "*.pak"
|
||||
!insertmacro ElyLegacy bin "*.bin"
|
||||
!insertmacro ElyLegacy dat "*.dat"
|
||||
!insertmacro ElyLegacy json "*.json"
|
||||
FileClose $R2
|
||||
done:
|
||||
FunctionEnd
|
||||
|
||||
!macro ElyAside UN
|
||||
; Next line of $R2: path $R3, kind $R6.
|
||||
Function ${UN}ElyNext
|
||||
next:
|
||||
ClearErrors
|
||||
FileRead $R2 $R3
|
||||
IfErrors 0 trim
|
||||
StrCpy $R6 ""
|
||||
Return
|
||||
trim:
|
||||
StrCpy $R6 "$R3" 1 -1
|
||||
StrCmp $R6 "$\r" cut
|
||||
StrCmp $R6 "$\n" cut
|
||||
StrCmp $R3 "" next
|
||||
StrCmp $R6 "\" 0 +4
|
||||
StrCpy $R3 "$R3" -1
|
||||
StrCpy $R6 "d"
|
||||
Return
|
||||
StrCpy $R6 "f"
|
||||
Return
|
||||
cut:
|
||||
StrCpy $R3 "$R3" -1
|
||||
Goto trim
|
||||
FunctionEnd
|
||||
|
||||
; Removes the empty folders $R0 lists under $R1.
|
||||
Function ${UN}ElyPrune
|
||||
pass:
|
||||
StrCpy $8 ""
|
||||
FileOpen $R2 "$R0" r
|
||||
next:
|
||||
Call ${UN}ElyNext
|
||||
StrCmp $R6 "" passed
|
||||
StrCmp $R6 "f" next
|
||||
IfFileExists "$R1\$R3\*.*" 0 next
|
||||
ClearErrors
|
||||
RMDir "$R1\$R3"
|
||||
IfErrors next
|
||||
StrCpy $8 "again"
|
||||
Goto next
|
||||
passed:
|
||||
FileClose $R2
|
||||
StrCmp $8 "again" pass
|
||||
FunctionEnd
|
||||
|
||||
; Moves $R0's files to numbered .ely-old entries; $R5: blocker.
|
||||
Function ${UN}ElyAside
|
||||
StrCpy $R5 ""
|
||||
StrCpy $R9 "$INSTDIR\.ely-old"
|
||||
RMDir /r "$R9"
|
||||
IfFileExists "$R9" 0 +3
|
||||
StrCpy $R5 "$R9"
|
||||
Return
|
||||
ClearErrors
|
||||
FileOpen $R2 "$R0" r
|
||||
IfErrors 0 check
|
||||
StrCpy $R5 "$R0"
|
||||
Return
|
||||
check:
|
||||
; Every file first: running or locked ones refuse writing.
|
||||
Call ${UN}ElyNext
|
||||
StrCmp $R6 "" checked
|
||||
StrCmp $R6 "d" check
|
||||
IfFileExists "$INSTDIR\$R3\*.*" check
|
||||
IfFileExists "$INSTDIR\$R3" 0 check
|
||||
ClearErrors
|
||||
FileOpen $R4 "$INSTDIR\$R3" a
|
||||
IfErrors refused
|
||||
FileClose $R4
|
||||
Goto check
|
||||
checked:
|
||||
CreateDirectory "$R9"
|
||||
FileSeek $R2 0 SET
|
||||
; Numbered names keep backup paths short.
|
||||
StrCpy $9 0
|
||||
move:
|
||||
Call ${UN}ElyNext
|
||||
StrCmp $R6 "" moved
|
||||
StrCmp $R6 "d" move
|
||||
IntOp $9 $9 + 1
|
||||
IfFileExists "$INSTDIR\$R3\*.*" move
|
||||
IfFileExists "$INSTDIR\$R3" 0 move
|
||||
ClearErrors
|
||||
Rename "$INSTDIR\$R3" "$R9\$9"
|
||||
IfErrors 0 move
|
||||
StrCpy $R5 "$INSTDIR\$R3"
|
||||
FileClose $R2
|
||||
Call ${UN}ElyBack
|
||||
Return
|
||||
moved:
|
||||
FileClose $R2
|
||||
Return
|
||||
refused:
|
||||
StrCpy $R5 "$INSTDIR\$R3"
|
||||
FileClose $R2
|
||||
FunctionEnd
|
||||
|
||||
; Puts $R0's files back from .ely-old.
|
||||
Function ${UN}ElyBack
|
||||
FileOpen $R2 "$R0" r
|
||||
StrCpy $9 0
|
||||
back:
|
||||
Call ${UN}ElyNext
|
||||
StrCmp $R6 "" done
|
||||
StrCmp $R6 "d" back
|
||||
IntOp $9 $9 + 1
|
||||
IfFileExists "$R9\$9" 0 back
|
||||
Rename "$R9\$9" "$INSTDIR\$R3"
|
||||
Goto back
|
||||
done:
|
||||
FileClose $R2
|
||||
RMDir "$R9"
|
||||
IfFileExists "$R9" 0 +2
|
||||
MessageBox MB_ICONSTOP "$(Stuck)$\r$\n$R9" /SD IDOK
|
||||
FunctionEnd
|
||||
!macroend
|
||||
!insertmacro ElyAside ""
|
||||
!insertmacro ElyAside "un."
|
||||
|
||||
; Sets $R5 to a path in the way.
|
||||
Function ElyClear
|
||||
StrCpy $R5 ""
|
||||
FileOpen $R2 "$PLUGINSDIR\new.txt" r
|
||||
FileOpen $7 "$PLUGINSDIR\made.txt" w
|
||||
next:
|
||||
Call ElyNext
|
||||
StrCmp $R6 "" done
|
||||
StrCmp $R6 "d" folder
|
||||
IfFileExists "$INSTDIR\$R3" taken next
|
||||
folder:
|
||||
IfFileExists "$INSTDIR\$R3\*.*" next
|
||||
IfFileExists "$INSTDIR\$R3" taken
|
||||
FileWrite $7 "$R3\$\r$\n"
|
||||
Goto next
|
||||
taken:
|
||||
StrCpy $R5 "$INSTDIR\$R3"
|
||||
done:
|
||||
FileClose $7
|
||||
FileClose $R2
|
||||
FunctionEnd
|
||||
|
||||
; Removes what this install wrote, then restores the old.
|
||||
Function .onInstFailed
|
||||
StrCmp $R8 "copying" 0 done
|
||||
FileOpen $R2 "$PLUGINSDIR\new.txt" r
|
||||
drop:
|
||||
Call ElyNext
|
||||
StrCmp $R6 "" dropped
|
||||
StrCmp $R6 "d" drop
|
||||
Delete "$INSTDIR\$R3"
|
||||
Goto drop
|
||||
dropped:
|
||||
FileClose $R2
|
||||
Delete "$INSTDIR\.ely-installed"
|
||||
Push $R0
|
||||
StrCpy $R0 "$PLUGINSDIR\made.txt"
|
||||
StrCpy $R1 "$INSTDIR"
|
||||
Call ElyPrune
|
||||
Pop $R0
|
||||
StrCmp $R0 "" done
|
||||
Call ElyBack
|
||||
StrCmp $R7 "listed" 0 done
|
||||
CopyFiles /SILENT "$R0" "$INSTDIR\.ely-installed"
|
||||
done:
|
||||
FunctionEnd
|
||||
|
||||
Section "Install"
|
||||
InitPluginsDir
|
||||
SetOutPath "$PLUGINSDIR"
|
||||
File "/oname=new.txt" "${LIST}"
|
||||
; An earlier install moves aside whole, or nothing changes.
|
||||
Call ElyOwned
|
||||
StrCmp $R0 "" clear
|
||||
Call ElyAside
|
||||
StrCmp $R5 "" clear
|
||||
MessageBox MB_ICONSTOP "$(Busy)$\r$\n$R5" /SD IDOK
|
||||
SetErrorLevel 2
|
||||
Quit
|
||||
clear:
|
||||
; Never write over a file this app did not install.
|
||||
Call ElyClear
|
||||
StrCmp $R5 "" copy
|
||||
StrCmp $R0 "" +2
|
||||
Call ElyBack
|
||||
MessageBox MB_ICONSTOP "$(Taken)$\r$\n$R5" /SD IDOK
|
||||
SetErrorLevel 2
|
||||
Quit
|
||||
copy:
|
||||
StrCpy $R8 "copying"
|
||||
; A file that cannot be written fails the install.
|
||||
ClearErrors
|
||||
SetOutPath "$INSTDIR"
|
||||
File /r "${STAGE}\*.*"
|
||||
File "/oname=${APP_SLUG}.ico" "${ICON}"
|
||||
WriteUninstaller "$INSTDIR\uninstall.exe"
|
||||
CopyFiles /SILENT "$PLUGINSDIR\new.txt" "$INSTDIR\.ely-installed"
|
||||
IfErrors 0 +2
|
||||
Abort
|
||||
StrCpy $R8 ""
|
||||
; Old folders the new release leaves empty.
|
||||
StrCmp $R0 "" +3
|
||||
StrCpy $R1 "$INSTDIR"
|
||||
Call ElyPrune
|
||||
RMDir /r "$INSTDIR\.ely-old"
|
||||
IfFileExists "$INSTDIR\.ely-old" 0 +2
|
||||
MessageBox MB_ICONEXCLAMATION "$(Left)$\r$\n$INSTDIR\.ely-old" /SD IDOK
|
||||
CreateShortcut "$SMPROGRAMS\${APP_NAME}.lnk" "$INSTDIR\${APP_SLUG}.exe" "" "$INSTDIR\${APP_SLUG}.ico"
|
||||
WriteRegStr HKCU "Software\Ely Office\${APP_NAME}" "InstallDir" "$INSTDIR"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "${APP_NAME}"
|
||||
@@ -63,26 +359,42 @@ Section "Install"
|
||||
SectionEnd
|
||||
|
||||
Section "Uninstall"
|
||||
; What stage.sh lays out, and nothing else.
|
||||
RMDir /r "$INSTDIR\libreoffice"
|
||||
RMDir /r "$INSTDIR\tessdata"
|
||||
RMDir /r "$INSTDIR\git"
|
||||
RMDir /r "$INSTDIR\content"
|
||||
RMDir /r "$INSTDIR\locales"
|
||||
RMDir /r "$INSTDIR\licenses"
|
||||
Delete "$INSTDIR\*.exe"
|
||||
Delete "$INSTDIR\*.dll"
|
||||
Delete "$INSTDIR\*.pak"
|
||||
Delete "$INSTDIR\*.bin"
|
||||
Delete "$INSTDIR\*.dat"
|
||||
Delete "$INSTDIR\*.json"
|
||||
Delete "$INSTDIR\${APP_SLUG}.ico"
|
||||
StrCpy $R5 "$INSTDIR\.ely-installed"
|
||||
IfFileExists "$R5" listed
|
||||
MessageBox MB_ICONSTOP "$(NoList)$\r$\n$INSTDIR" /SD IDOK
|
||||
SetErrorLevel 2
|
||||
Quit
|
||||
listed:
|
||||
; The list is checked too, before anything moves.
|
||||
ClearErrors
|
||||
FileOpen $R4 "$R5" a
|
||||
IfErrors busy
|
||||
FileClose $R4
|
||||
InitPluginsDir
|
||||
StrCpy $R0 "$PLUGINSDIR\owned.txt"
|
||||
CopyFiles /SILENT "$R5" "$R0"
|
||||
Call un.ElyAside
|
||||
StrCmp $R5 "" gone busy
|
||||
gone:
|
||||
ClearErrors
|
||||
Delete "$INSTDIR\.ely-installed"
|
||||
IfErrors 0 deleted
|
||||
Call un.ElyBack
|
||||
StrCpy $R5 "$INSTDIR\.ely-installed"
|
||||
busy:
|
||||
MessageBox MB_ICONSTOP "$(Busy)$\r$\n$R5" /SD IDOK
|
||||
SetErrorLevel 2
|
||||
Quit
|
||||
deleted:
|
||||
RMDir /r "$INSTDIR\.ely-old"
|
||||
StrCpy $R1 "$INSTDIR"
|
||||
Call un.ElyPrune
|
||||
RMDir "$INSTDIR"
|
||||
Delete "$SMPROGRAMS\${APP_NAME}.lnk"
|
||||
DeleteRegKey HKCU "Software\Ely Office\${APP_NAME}"
|
||||
DeleteRegKey HKCU "${UNINSTALL_KEY}"
|
||||
!insertmacro ElyTypesUninstall
|
||||
MessageBox MB_YESNO|MB_DEFBUTTON2 "$(DeleteData)" IDNO done
|
||||
MessageBox MB_YESNO|MB_DEFBUTTON2 "$(DeleteData)" /SD IDNO IDNO done
|
||||
RMDir /r "$LOCALAPPDATA\ElyOffice\${APP_SLUG}"
|
||||
done:
|
||||
SectionEnd
|
||||
@@ -18,12 +18,18 @@ makensis=${MAKENSIS:-"/c/Program Files (x86)/NSIS/makensis.exe"}
|
||||
}
|
||||
stage=$root/target/stage/$slug
|
||||
"$root/packaging/stage.sh" "$slug" "$stage"
|
||||
# Explorer's New copies these; the install list owns them.
|
||||
for ext in $(awk -F'\t' -v slug="$slug" '$1 == slug { print $2 }' "$root/packaging/types.tsv"); do
|
||||
[ ! -e "$root/packaging/windows/new/new.$ext" ] || cp "$root/packaging/windows/new/new.$ext" "$stage/"
|
||||
done
|
||||
types=$root/target/stage/$slug-types.nsh
|
||||
"$root/packaging/windows/types.sh" "$slug" >"$types"
|
||||
list=$root/target/stage/$slug-files.txt
|
||||
"$root/packaging/windows/files.sh" "$stage" "$slug" >"$list"
|
||||
mkdir -p "$dist"
|
||||
out=$dist/$name-$version-windows-x86_64-setup.exe
|
||||
"$makensis" -V2 -INPUTCHARSET UTF8 -DAPP_NAME="$name" -DAPP_SLUG="$slug" -DVERSION="$version" \
|
||||
-DSTAGE="$(cygpath -w "$stage")" -DICON="$(cygpath -w "$root/assets/icons/$slug.ico")" \
|
||||
-DTYPES="$(cygpath -w "$types")" -DOUTFILE="$(cygpath -w "$out")" \
|
||||
-DTYPES="$(cygpath -w "$types")" -DLIST="$(cygpath -w "$list")" -DOUTFILE="$(cygpath -w "$out")" \
|
||||
"$(cygpath -w "$root/packaging/windows/installer.nsi")"
|
||||
echo "$out"
|
||||
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Writes packaging/windows/new: the blank files Explorer's New makes.
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
soffice=$root/engines/lo-src/instdir/program/soffice.com
|
||||
[ -x "$soffice" ] || {
|
||||
echo "templates.sh: no kernel at $soffice; run scripts/build-libreoffice.sh" >&2
|
||||
exit 1
|
||||
}
|
||||
out=$root/packaging/windows/new
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mkdir "$work/in"
|
||||
# The kernel reads an empty file as a new document.
|
||||
for ext in docx xlsx pptx; do
|
||||
: >"$work/in/new.$ext"
|
||||
"$soffice" --headless --norestore "-env:UserInstallation=file:///$(cygpath -m "$work/profile")" \
|
||||
--convert-to "$ext" --outdir "$(cygpath -w "$out")" "$(cygpath -w "$work/in/new.$ext")"
|
||||
[ -s "$out/new.$ext" ] || {
|
||||
echo "templates.sh: the kernel wrote no new.$ext" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
: >"$out/new.md"
|
||||
@@ -10,11 +10,16 @@ progid="ElyOffice.$name"
|
||||
classes='Software\Classes'
|
||||
exts=$(awk -F'\t' -v slug="$slug" '$1 == slug && $2 != "/" { print $2 }' "$root/packaging/types.tsv")
|
||||
folder=$(awk -F'\t' -v slug="$slug" '$1 == slug && $2 == "/" { print "yes" }' "$root/packaging/types.tsv")
|
||||
# Types Explorer's New menu makes, from packaging/windows/new.
|
||||
fresh=""
|
||||
for ext in $exts; do
|
||||
[ ! -e "$root/packaging/windows/new/new.$ext" ] || fresh="$fresh $ext"
|
||||
done
|
||||
|
||||
# Open With lists the app; the user's default stays theirs.
|
||||
echo '!macro ElyTypesInstall'
|
||||
if [ -n "$exts" ]; then
|
||||
echo " WriteRegStr HKCU \"$classes\\$progid\" \"\" \"$name\""
|
||||
echo " WriteRegStr HKCU \"$classes\\$progid\" \"\" \"$name Document\""
|
||||
echo " WriteRegStr HKCU \"$classes\\$progid\\DefaultIcon\" \"\" \"\$INSTDIR\\$slug.ico\""
|
||||
echo " WriteRegStr HKCU \"$classes\\$progid\\shell\\open\\command\" \"\" '\"\$INSTDIR\\$slug.exe\" \"%1\"'"
|
||||
echo " WriteRegStr HKCU \"$classes\\Applications\\$slug.exe\" \"FriendlyAppName\" \"$name\""
|
||||
@@ -23,6 +28,20 @@ if [ -n "$exts" ]; then
|
||||
echo " WriteRegStr HKCU \"$classes\\Applications\\$slug.exe\\SupportedTypes\" \".$ext\" \"\""
|
||||
done
|
||||
fi
|
||||
for ext in $fresh; do
|
||||
echo " WriteRegStr HKCU \"$classes\\.$ext\\ShellNew\" \"FileName\" \"\$INSTDIR\\new.$ext\""
|
||||
# New needs a class; take only a handlerless type.
|
||||
echo " ReadRegStr \$0 HKCR \".$ext\" \"\""
|
||||
echo " ClearErrors"
|
||||
# A default naming no class handles nothing either.
|
||||
echo " \${If} \$0 != \"\""
|
||||
echo " EnumRegKey \$1 HKCR \"\$0\" 0"
|
||||
echo " \${EndIf}"
|
||||
echo " \${If} \$0 == \"\""
|
||||
echo " \${OrIf} \${Errors}"
|
||||
echo " WriteRegStr HKCU \"$classes\\.$ext\" \"\" \"$progid\""
|
||||
echo " \${EndIf}"
|
||||
done
|
||||
if [ -n "$folder" ]; then
|
||||
echo " WriteRegStr HKCU \"$classes\\Directory\\shell\\$progid\" \"\" \"Open in $name\""
|
||||
echo " WriteRegStr HKCU \"$classes\\Directory\\shell\\$progid\" \"Icon\" \"\$INSTDIR\\$slug.ico\""
|
||||
@@ -39,6 +58,17 @@ if [ -n "$exts" ]; then
|
||||
echo " DeleteRegValue HKCU \"$classes\\.$ext\\OpenWithProgids\" \"$progid\""
|
||||
done
|
||||
fi
|
||||
# Only what this install wrote.
|
||||
for ext in $fresh; do
|
||||
echo " ReadRegStr \$0 HKCU \"$classes\\.$ext\\ShellNew\" \"FileName\""
|
||||
echo " \${If} \$0 == \"\$INSTDIR\\new.$ext\""
|
||||
echo " DeleteRegKey HKCU \"$classes\\.$ext\\ShellNew\""
|
||||
echo " \${EndIf}"
|
||||
echo " ReadRegStr \$0 HKCU \"$classes\\.$ext\" \"\""
|
||||
echo " \${If} \$0 == \"$progid\""
|
||||
echo " DeleteRegValue HKCU \"$classes\\.$ext\" \"\""
|
||||
echo " \${EndIf}"
|
||||
done
|
||||
if [ -n "$folder" ]; then
|
||||
echo " DeleteRegKey HKCU \"$classes\\Directory\\shell\\$progid\""
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
LOK: a font the lookup finds is not missing
|
||||
|
||||
The fonts-missing filter compared names as written: a document's
|
||||
"宋体" against the used face "SimSun", or "DEJAVU SANS" against
|
||||
"DejaVu Sans". The font lookup finds families by their English
|
||||
search name (GetEnglishSearchFontName: lower ASCII, no spaces,
|
||||
localized CJK names translated), so these fonts were found and
|
||||
used, yet reported missing. On Linux the kernel names fontconfig
|
||||
families in its UI language, English, so every localized name in
|
||||
a document failed the check. Compare search names instead.
|
||||
|
||||
--- a/desktop/source/lib/init.cxx
|
||||
+++ b/desktop/source/lib/init.cxx
|
||||
@@ -168,6 +168,7 @@
|
||||
#include <vcl/vclevent.hxx>
|
||||
#include <vcl/GestureEventPan.hxx>
|
||||
#include <vcl/svapp.hxx>
|
||||
+#include <unotools/fontdefs.hxx>
|
||||
#include <unotools/resmgr.hxx>
|
||||
#include <tools/debug.hxx>
|
||||
#include <tools/fract.hxx>
|
||||
@@ -3047,11 +3048,12 @@
|
||||
sal_Int32 nIndex = 0;
|
||||
do
|
||||
{
|
||||
- const OUString aFamily
|
||||
- = x.mOriginalFont.getToken(0, ';', nIndex);
|
||||
+ // Names compare as the font lookup matches them.
|
||||
+ const OUString aFamily = GetEnglishSearchFontName(
|
||||
+ x.mOriginalFont.getToken(0, ';', nIndex));
|
||||
for (const auto &j : x.mUsedFonts)
|
||||
- if (j == aFamily
|
||||
- || j.startsWith(Concat2View(aFamily + "/")))
|
||||
+ if (GetEnglishSearchFontName(j.getToken(0, '/'))
|
||||
+ == aFamily)
|
||||
return true;
|
||||
} while (nIndex >= 0);
|
||||
}
|
||||
+28
-3
@@ -55,7 +55,10 @@ rm -rf "$dist"
|
||||
batch=$(awk -F'\t' '$4 == 1 { print $1 }' packaging/apps.tsv)
|
||||
case $os in
|
||||
macos) packaging/macos/release.sh 1 ;;
|
||||
windows) for slug in $batch; do packaging/windows/installer.sh "$slug"; done ;;
|
||||
windows)
|
||||
for slug in $batch; do packaging/windows/installer.sh "$slug"; done
|
||||
packaging/windows/bundle.sh
|
||||
;;
|
||||
linux) for slug in $batch; do ${inside[@]+"${inside[@]}"} packaging/linux/package.sh "$slug"; done ;;
|
||||
*)
|
||||
echo "ci.sh: no release for $os" >&2
|
||||
@@ -63,8 +66,10 @@ case $os in
|
||||
;;
|
||||
esac
|
||||
|
||||
# macOS's release.sh writes its own source archives.
|
||||
[ "$os" = macos ] || packaging/source.sh "$dist"
|
||||
# Windows checkouts flatten symlinks; Linux and macOS write source.
|
||||
if [ "$os" = linux ]; then
|
||||
packaging/source.sh "$dist"
|
||||
fi
|
||||
|
||||
# The tag's release, made by whichever platform comes first.
|
||||
api=https://git.zacharyzhang.com/api/v1/repos/ZacharyZhang-NY/ElyOffice
|
||||
@@ -76,9 +81,29 @@ if ! id=$(release_id 2>/dev/null); then
|
||||
curl -fsS -H "$auth" -H "Content-Type: application/json" -d "$body" "$api/releases" >/dev/null || true
|
||||
id=$(release_id)
|
||||
fi
|
||||
names=()
|
||||
for file in "$dist"/*; do
|
||||
[ -f "$file" ] || continue
|
||||
name=$(basename "$file")
|
||||
# Linux alone publishes the source pair.
|
||||
if [ "$os" != linux ] && [[ $name == *-source.tar.gz ]]; then
|
||||
echo "ci.sh: $name is Linux's to upload"
|
||||
continue
|
||||
fi
|
||||
names+=("$name")
|
||||
done
|
||||
# Rebuilt bytes differ; never mix them with earlier uploads.
|
||||
have=$(curl -fsS -H "$auth" "$api/releases/$id/assets" | python3 -c 'import json, sys; print("\n".join(a["name"] for a in json.load(sys.stdin)))')
|
||||
taken=()
|
||||
for name in "${names[@]}"; do
|
||||
if grep -qxF "$name" <<<"$have"; then taken+=("$name"); fi
|
||||
done
|
||||
if [ ${#taken[@]} -gt 0 ]; then
|
||||
echo "ci.sh: already on $tag; delete them, then rerun: ${taken[*]}" >&2
|
||||
exit 1
|
||||
fi
|
||||
for name in "${names[@]}"; do
|
||||
file=$dist/$name
|
||||
echo "ci.sh: uploading $name"
|
||||
curl -fsS -H "$auth" -F "attachment=@$file" "$api/releases/$id/assets?name=$name" >/dev/null
|
||||
done
|
||||
|
||||
@@ -36,7 +36,7 @@ fetch() { # name url rev [sparse paths...]
|
||||
echo "fetch $name $rev"
|
||||
}
|
||||
|
||||
fetch Ely-GPUI-Components https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components.git 6df9ab0aa6cba99e6a79da80f79fc166f09890a8
|
||||
fetch Ely-GPUI-Components https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components.git 5a53c08c844210ea80c6a92aec708e2de8ffa721
|
||||
fetch zed https://github.com/zed-industries/zed.git 1a28cff4b409169bac058bca40dfbfeb7621d19b
|
||||
fetch libreoffice-core https://github.com/LibreOffice/core.git 8221e31b3ac356a1623c672912a3d2b492f7e3d1 \
|
||||
include/LibreOfficeKit libreofficekit desktop/source/lib desktop/inc \
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ const en = {
|
||||
ElyTree: "Stage lines, commit, read the graph. Git without a terminal.",
|
||||
ElyMark: "Markdown as you read it. Math and diagrams in place.",
|
||||
offline: "Works with the network off.",
|
||||
open: "Open source, under the AGPL.",
|
||||
open: "Open source, under the MIT licence.",
|
||||
local: "Your files stay in your folders.",
|
||||
download: "Download",
|
||||
platforms: "Out now for macOS, Windows and Linux.",
|
||||
@@ -48,7 +48,7 @@ const zh: typeof en = {
|
||||
ElyTree: "按行暂存、提交、看提交图。不用终端的 Git。",
|
||||
ElyMark: "写的就是看到的 Markdown。公式与图表就地显示。",
|
||||
offline: "断网照常工作。",
|
||||
open: "开源,AGPL 许可。",
|
||||
open: "开源,MIT 许可。",
|
||||
local: "文件留在你自己的文件夹里。",
|
||||
download: "下载",
|
||||
platforms: "macOS、Windows 与 Linux 版已发布。",
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
node_modules
|
||||
out
|
||||
public/footage
|
||||
public/fonts/*.ttf
|
||||
public/fonts/*.otf
|
||||
node_modules
|
||||
public/audio
|
||||
__pycache__
|
||||
Loaded 100 of 222 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user