From c480138a93ee37283017bf93348671e2ff3ff9a5 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 01:24:19 +0800 Subject: [PATCH 01/20] =?UTF-8?q?build(deps):=20gpui-kit=200.8=20=E2=86=92?= =?UTF-8?q?=200.10=EF=BC=88gpui-pre=200.3.12=EF=BC=8Cmarkdown-editor=20?= =?UTF-8?q?=E8=B5=B0=E8=87=AA=E6=9C=89=20fork=20=E9=80=82=E9=85=8D?= =?UTF-8?q?=E5=88=86=E6=94=AF=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit wabzqem/gpui-kit-markdown-editor 上游仅到 0.9——fork 至 spartajet/gpui-kit-markdown-editor gpui-kit-0.10 分支(基于原 pin 31608fa:BlockNode 增 task_marker 字段、Modifiers::secondary 需 &App、KeyBinding::new 收紧 &'static str 改 Box::leak)。工作区零编译错误,全量测试通过(含 65 项 UI e2e)。 --- Cargo.lock | 591 ++++++++++++++++++++++--------- crates/postium-editor/Cargo.toml | 4 +- crates/postium-ui/Cargo.toml | 6 +- 3 files changed, 435 insertions(+), 166 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b09b092f..838127b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -155,6 +155,15 @@ dependencies = [ "equator", ] +[[package]] +name = "alloca" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" +dependencies = [ + "cc", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -182,6 +191,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + [[package]] name = "annotate-snippets" version = "0.12.17" @@ -689,9 +704,9 @@ dependencies = [ [[package]] name = "bit-set" -version = "0.9.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34ddef2995421ab6a5c779542c81ee77c115206f4ad9d5a8e05f4ff49716a3dd" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ "bit-vec 0.9.1", ] @@ -903,6 +918,12 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "c-enum" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd17eb909a8c6a894926bfcc3400a4bb0e732f5a57d37b1f14e8b29e329bace8" + [[package]] name = "cairo-rs" version = "0.18.5" @@ -952,6 +973,12 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "cbc" version = "0.1.2" @@ -1062,6 +1089,33 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + [[package]] name = "cipher" version = "0.4.4" @@ -1074,32 +1128,41 @@ dependencies = [ ] [[package]] -name = "cocoa" -version = "0.25.0" +name = "clap" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ - "bitflags 1.3.2", - "block", - "cocoa-foundation 0.1.2", - "core-foundation 0.9.4", - "core-graphics 0.23.2", - "foreign-types 0.5.0", - "libc", - "objc", + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", ] +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "cocoa" -version = "0.26.1" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad36507aeb7e16159dfe68db81ccc27571c3ccd4b76fb2fb72fc59e7a4b1b64c" +checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c" dependencies = [ - "bitflags 2.13.2", + "bitflags 1.3.2", "block", - "cocoa-foundation 0.2.1", - "core-foundation 0.10.1", - "core-graphics 0.24.0", + "cocoa-foundation", + "core-foundation 0.9.4", + "core-graphics 0.23.2", "foreign-types 0.5.0", "libc", "objc", @@ -1119,19 +1182,6 @@ dependencies = [ "objc", ] -[[package]] -name = "cocoa-foundation" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81411967c50ee9a1fc11365f8c585f863a22a9697c89239c452292c40ba79b0d" -dependencies = [ - "bitflags 2.13.2", - "block", - "core-foundation 0.10.1", - "core-graphics-types 0.2.0", - "objc", -] - [[package]] name = "codespan-reporting" version = "0.13.1" @@ -1393,6 +1443,41 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "criterion" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3" +dependencies = [ + "alloca", + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "itertools 0.13.0", + "num-traits", + "oorandom", + "page_size", + "plotters", + "rayon", + "regex", + "serde", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea" +dependencies = [ + "cast", + "itertools 0.13.0", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -2733,31 +2818,11 @@ dependencies = [ "windows 0.62.2", ] -[[package]] -name = "gpu-descriptor" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" -dependencies = [ - "bitflags 2.13.2", - "gpu-descriptor-types", - "hashbrown 0.15.5", -] - -[[package]] -name = "gpu-descriptor-types" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" -dependencies = [ - "bitflags 2.13.2", -] - [[package]] name = "gpui-base" -version = "0.8.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5cd7de73d5b2d3d18b94a928abf343922091fa77bc472f77b7d2e7e8b1823a7" +checksum = "4f4e5aff50636223b268a687ad5788ec54fa77c8e57ca9e53d158f19e0425d95" dependencies = [ "aho-corasick", "anyhow", @@ -2787,6 +2852,7 @@ dependencies = [ "serde_json", "smallvec", "smol", + "sys-locale", "tracing", "unicode-linebreak", "unicode-segmentation", @@ -2796,9 +2862,9 @@ dependencies = [ [[package]] name = "gpui-component" -version = "0.8.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4097e161cc81e86323b439664be0cdd4f7c56148e867ed6f67fd72b966b6c2d1" +checksum = "607c90f6985ac2b96e54102338994eaea143aff521375c6f9e7fc7ecb3ba3646" dependencies = [ "anyhow", "chrono", @@ -2845,9 +2911,9 @@ dependencies = [ [[package]] name = "gpui-component-macros" -version = "0.8.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a512c830553e7dddc43c3f8faffc2d2d7bd24db21fe3dc1326dde9c470013768" +checksum = "510a438db463e4fcaec876a0cf76c3bfd900bc407207b0bc8c6076f91c09591b" dependencies = [ "proc-macro-crate 3.5.0", "proc-macro2", @@ -2857,9 +2923,9 @@ dependencies = [ [[package]] name = "gpui-kit" -version = "0.8.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cdcb78553bef8785669e572e79759b0eab47fdd9d318fe0cce1def798189432" +checksum = "228cc61c0a71c4908af2e903807a81d2deabc03ec0be7f22189d43cf552af098" dependencies = [ "gpui-base", "gpui-component", @@ -2872,9 +2938,9 @@ dependencies = [ [[package]] name = "gpui-kit-assets" -version = "0.8.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b037e2fa43d53a567a8aa5be6b1a8931f416cbd010ceee8d4a3727a71e9b1d05" +checksum = "655474e0a0069db561d7d4029f84de59e41c0f1afff2301b23e00329968d3148" dependencies = [ "anyhow", "gpui-pre", @@ -2888,7 +2954,7 @@ dependencies = [ [[package]] name = "gpui-kit-markdown-editor" version = "0.1.0" -source = "git+https://github.com/wabzqem/gpui-kit-markdown-editor#31608fa74bdbeca79d9901bf2daa48ea7ecf1ecc" +source = "git+https://github.com/spartajet/gpui-kit-markdown-editor?branch=gpui-kit-0.10#09aca4db4c6c5244d0a75a32fce0eb12f724daef" dependencies = [ "gpui-kit", "gpui-pre", @@ -2898,9 +2964,9 @@ dependencies = [ [[package]] name = "gpui-pre" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34f61c1cfd36fc9c436af09308c963822ae27a45a84feb21a77ba5c9e051f1c0" +checksum = "29db89613527079737f53752eab27fb65c9a7dd94979256c65a0e590c9fd34d8" dependencies = [ "accesskit", "anyhow", @@ -2909,13 +2975,13 @@ dependencies = [ "backtrace", "bitflags 2.13.2", "chrono", - "ctor", "derive_more 2.1.1", "embed-resource", "etagere", "futures", "futures-concurrency", "getrandom 0.3.4", + "gpui-pre-bench-metrics", "gpui-pre-collections", "gpui-pre-http-client", "gpui-pre-macros", @@ -2925,6 +2991,7 @@ dependencies = [ "gpui-pre-sum-tree", "gpui-pre-util", "heapless", + "icu_segmenter", "image", "inventory", "itertools 0.14.0", @@ -2956,6 +3023,7 @@ dependencies = [ "taffy", "thiserror 2.0.21", "ttf-parser", + "unicode-segmentation", "url", "usvg 0.46.0", "uuid", @@ -2967,9 +3035,9 @@ dependencies = [ [[package]] name = "gpui-pre-apple" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52f58893fe1a0836464428dfad2b5eaf42c9c303a9638f4c2aced5a69072a15" +checksum = "a460605ec4e8cbcc9b213462a84b1d6cc3efe4ed8f0e18669659f07b2d5c6aec" dependencies = [ "anyhow", "async-task", @@ -2979,10 +3047,8 @@ dependencies = [ "core-foundation-sys", "core-graphics 0.24.0", "core-text", - "derive_more 2.1.1", "dispatch2", "etagere", - "foreign-types 0.5.0", "futures", "gpui-pre", "gpui-pre-collections", @@ -2991,9 +3057,9 @@ dependencies = [ "libc", "log", "mach2", - "metal", "objc2 0.6.5", "objc2-core-foundation", + "objc2-core-graphics", "objc2-core-text", "objc2-core-video", "objc2-foundation 0.3.2", @@ -3007,11 +3073,23 @@ dependencies = [ "zed-font-kit", ] +[[package]] +name = "gpui-pre-bench-metrics" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db6a8ff719fdc3da4f5f497b5d39c5545634424073f94943b003c818fc95e1d5" +dependencies = [ + "anyhow", + "criterion", + "libc", + "perf-event2", +] + [[package]] name = "gpui-pre-collections" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920c2f5b2f1a7813114d89f4841f26f6060d9c35d7c8a852a4205d1a767a7ce0" +checksum = "cb60ece401b399fd5ec13911915b407b0c6efa1f6c9a9f66201aaac56c7ec39d" dependencies = [ "gpui-pre-util", "indexmap", @@ -3020,9 +3098,9 @@ dependencies = [ [[package]] name = "gpui-pre-derive-refineable" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "947395f26228296c0c79fb889d3687b205e552c25bbcdece216fb2394ea9bcd1" +checksum = "aeb2a3f5e6c9f300f432ae7989a81b262953ccfb3f9385be51cdc3303aef8858" dependencies = [ "proc-macro2", "quote", @@ -3031,9 +3109,9 @@ dependencies = [ [[package]] name = "gpui-pre-http-client" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56cdaa3f1a271162b7fede1d4557879eedb056e293cedbb82743600650b755e" +checksum = "55245de7e3b6e219596fd98bb29555d6e3fe44c055d025960affeb11b894c048" dependencies = [ "anyhow", "bytes", @@ -3048,11 +3126,33 @@ dependencies = [ "url", ] +[[package]] +name = "gpui-pre-ios" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10656f6db4bbedb60bd7fcbb8a70f7c7eeee45bc4582fb8933ca807d2ddf52ad" +dependencies = [ + "anyhow", + "block2 0.6.2", + "futures", + "gpui-pre", + "gpui-pre-apple", + "log", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-ui-kit", + "parking_lot", + "raw-window-handle", + "uuid", +] + [[package]] name = "gpui-pre-linux" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e28213c3fde6f13e91ba0b74b90cbaadec9373e36a031eda98561d31059870f3" +checksum = "54bab418d0b7c027af9495f278619b46887362b3bd6446e246c87c5b0fa167df" dependencies = [ "accesskit", "accesskit_unix", @@ -3095,15 +3195,14 @@ dependencies = [ [[package]] name = "gpui-pre-macos" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c988b7e49775cc8542dbe48d5a10e073d8e898a023ef3ff3d24f33363e9863" +checksum = "2de7d3f4ad51ac387e822495db363fcc1188d349793365731d054444c4cb06ee" dependencies = [ "accesskit", "accesskit_macos", "anyhow", "block2 0.6.2", - "cocoa 0.26.1", "core-foundation 0.10.1", "core-foundation-sys", "core-graphics 0.24.0", @@ -3119,11 +3218,13 @@ dependencies = [ "image", "itertools 0.14.0", "log", - "objc", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-graphics", "objc2-core-video", "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-uniform-type-identifiers", "objc2-user-notifications", "parking_lot", "raw-window-handle", @@ -3135,9 +3236,9 @@ dependencies = [ [[package]] name = "gpui-pre-macros" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb80dac5e1f6b8cde1d2740389e77dfc0071bfcc81fba5526d5dc90f68171cc" +checksum = "1c7f67904eced61ed42ae3320a9b4b388aed893f8547fffe9161ec425ad162eb" dependencies = [ "heck 0.5.0", "proc-macro-crate 3.5.0", @@ -3148,13 +3249,14 @@ dependencies = [ [[package]] name = "gpui-pre-platform" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbdbdac421178313fed8929fe95b42634a266a735079fcf03ff231bc2ccb2c5e" +checksum = "d2b785bdcbd229f762096aebf4f9ae913bdaa9db49794907cabaf516eb55227b" dependencies = [ "anyhow", "console_error_panic_hook", "gpui-pre", + "gpui-pre-ios", "gpui-pre-linux", "gpui-pre-macos", "gpui-pre-web", @@ -3163,9 +3265,9 @@ dependencies = [ [[package]] name = "gpui-pre-refineable" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "237703b3b219d11adb50dd33bb0fcca3d34fc001623b3143e72cb051d0fb3777" +checksum = "4d197569e3b1fd84170f574bb866e95ecbc2625e7ae9443c877150eaf7d53374" dependencies = [ "gpui-pre-derive-refineable", ] @@ -3222,9 +3324,9 @@ dependencies = [ [[package]] name = "gpui-pre-scheduler" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83f342555282a59ed8dd58dd7e0a920524fa8ef6aa8c8f30e2edb7019a8f72cb" +checksum = "b1d3fa97eeb4ea233635b756684affe96db9e29fc2af8cdc269268bd7ff649fc" dependencies = [ "async-task", "backtrace", @@ -3239,9 +3341,9 @@ dependencies = [ [[package]] name = "gpui-pre-shared-string" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71f488bf4780735f6b2dad24f8db1e3d9e2593de0ec298e3574c788f571b81c4" +checksum = "63c2ed1e44195079d4461b83a99845aa9a52ce8fcf1516410816670a03d32d94" dependencies = [ "schemars", "serde", @@ -3250,9 +3352,9 @@ dependencies = [ [[package]] name = "gpui-pre-sum-tree" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aadb3bd3da22617e2158b1842f5a9c29c1626c926ad0686163ced1a009963ff3" +checksum = "6085e61458366decd21491396b0b90b3adf928f2ec27e170c4d3c9fba455d536" dependencies = [ "gpui-pre-ztracing", "heapless", @@ -3262,9 +3364,9 @@ dependencies = [ [[package]] name = "gpui-pre-util" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a04ec9abd7a87ac05a221f4629403831c44c17123bc33cb5d271a6303259b340" +checksum = "52ead57ff96b5a34e71d64758080347066d667e0c4bd4ff71e85f3a50643fa3e" dependencies = [ "anyhow", "log", @@ -3273,9 +3375,9 @@ dependencies = [ [[package]] name = "gpui-pre-web" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedd55b99dc77e28df8202b0ea868aa5c90fda4aefff539ea21087d7c2ff4bfb" +checksum = "a85e775c6874257c63f9cf51d99f0aba13b3bc615ed8d47e7d5338e3b5941f6a" dependencies = [ "anyhow", "async-channel 2.5.0", @@ -3303,9 +3405,9 @@ dependencies = [ [[package]] name = "gpui-pre-wgpu" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b1cdb26c1503bf9662ee8fbc5ab0b44b2deeee4b5c12dc67491ba6fb5fc544b" +checksum = "dc76608d385f6d0dcbad44504b1bf669dac3b7d7ffa2885acdb7c1c358caf852" dependencies = [ "anyhow", "bytemuck", @@ -3330,9 +3432,9 @@ dependencies = [ [[package]] name = "gpui-pre-windows" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513d4f0fc7d596d3bdef2a73a524ffb83dabc95bf484f2855a698e7f431290a9" +checksum = "7201762420222d5b5ce5bdf0056996199212a3349bfb2457a3a0238c688681f3" dependencies = [ "accesskit", "accesskit_windows", @@ -3360,9 +3462,9 @@ dependencies = [ [[package]] name = "gpui-pre-ztracing" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f17bfd6bd1f77ba5c58181fa6f82fc7a63015a1c58bef94a76e5acb9f8e42572" +checksum = "1043bbe8d711baf03e774b03bae6521155f017450b866dcaa987a07d978d660a" dependencies = [ "gpui-pre-ztracing-macro", "tracing", @@ -3370,9 +3472,9 @@ dependencies = [ [[package]] name = "gpui-pre-ztracing-macro" -version = "0.3.9" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b0d73e1bc02eef886a5947f41b8512708792e9e5d3053d181843311a487f96f" +checksum = "85701631a9bbecf47e6d19f145e85e57767e7c50f7192d5b1bf65b5ef43cb373" [[package]] name = "granit-parser" @@ -3522,6 +3624,9 @@ name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] [[package]] name = "hashify" @@ -3578,12 +3683,6 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "hexf-parse" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" - [[package]] name = "hkdf" version = "0.12.4" @@ -3841,11 +3940,32 @@ checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + [[package]] name = "icu_normalizer" version = "2.4.0" @@ -3895,6 +4015,8 @@ checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -3902,6 +4024,29 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + [[package]] name = "idna" version = "1.1.0" @@ -4743,21 +4888,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "metal" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7047791b5bc903b8cd963014b355f71dc9864a9a0b727057676c1dcae5cbc15" -dependencies = [ - "bitflags 2.13.2", - "block", - "core-graphics-types 0.2.0", - "foreign-types 0.5.0", - "log", - "objc", - "paste", -] - [[package]] name = "mime" version = "0.3.17" @@ -4896,22 +5026,22 @@ checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" [[package]] name = "naga" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2bf919621e7975acb27d881bae2fb993e0d45c8e0446e85e6272971e00dc8df" +checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163" dependencies = [ "arrayvec", - "bit-set 0.9.1", + "bit-set 0.10.0", "bitflags 2.13.2", "cfg-if", "cfg_aliases", "codespan-reporting", "half", - "hashbrown 0.16.1", - "hexf-parse", + "hashbrown 0.17.1", "indexmap", "libm", "log", + "naga-types", "num-traits", "once_cell", "rustc-hash 1.1.0", @@ -4920,6 +5050,18 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "naga-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + [[package]] name = "native-tls" version = "0.2.18" @@ -5293,6 +5435,7 @@ dependencies = [ "objc2-core-video", "objc2-foundation 0.3.2", "objc2-quartz-core 0.3.2", + "objc2-uniform-type-identifiers", ] [[package]] @@ -5336,7 +5479,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", ] @@ -5473,6 +5618,7 @@ checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "dispatch2", "objc2 0.6.5", "objc2-foundation 0.3.2", ] @@ -5499,6 +5645,7 @@ dependencies = [ "bitflags 2.13.2", "objc2 0.6.5", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", "objc2-metal 0.3.2", ] @@ -5512,6 +5659,30 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-user-notifications" version = "0.3.2" @@ -5601,6 +5772,12 @@ dependencies = [ "zvariant 5.15.1", ] +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + [[package]] name = "open" version = "5.4.5" @@ -5679,6 +5856,16 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "page_size" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "pango" version = "0.18.3" @@ -5780,6 +5967,41 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "perf-event-data" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "575828d9d7d205188048eb1508560607a03d21eafdbba47b8cade1736c1c28e1" +dependencies = [ + "bitflags 2.13.2", + "c-enum", + "perf-event-open-sys2", +] + +[[package]] +name = "perf-event-open-sys2" +version = "5.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c25955321465255e437600b54296983fab1feac2cd0c38958adeb26dbae49e" +dependencies = [ + "libc", + "memoffset", +] + +[[package]] +name = "perf-event2" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0939b8fad77dfaeb29ebbd35faaeaadbf833167f30975f1b8993bbba09ea0a0f" +dependencies = [ + "bitflags 2.13.2", + "c-enum", + "libc", + "memmap2", + "perf-event-data", + "perf-event-open-sys2", +] + [[package]] name = "phf" version = "0.11.3" @@ -5993,6 +6215,34 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "plotters" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + +[[package]] +name = "plotters-svg" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" +dependencies = [ + "plotters-backend", +] + [[package]] name = "png" version = "0.17.16" @@ -6185,6 +6435,8 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -8180,11 +8432,10 @@ dependencies = [ [[package]] name = "taffy" -version = "0.13.0" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c034e05f6ee85a12daa63863c2245797715075c70649947aa0da54f3f2ab1d0f" +checksum = "31f7bd2d97198df05186f93a3a3c306845f40e8b3c22bf9279cdd7e5cf5fea7d" dependencies = [ - "arrayvec", "serde", "slotmap", "smallvec", @@ -8397,9 +8648,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "tinyvec" version = "1.13.3" @@ -9342,9 +9604,9 @@ checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" [[package]] name = "wgpu" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76e8840e1ba2881d4cbb18d2147627a56af426ff064c0401eb0c8410c6325d07" +checksum = "146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e" dependencies = [ "arrayvec", "bitflags 2.13.2", @@ -9352,7 +9614,7 @@ dependencies = [ "cfg-if", "cfg_aliases", "document-features", - "hashbrown 0.16.1", + "hashbrown 0.17.1", "js-sys", "log", "naga", @@ -9372,21 +9634,22 @@ dependencies = [ [[package]] name = "wgpu-core" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f519832254e56965a9940c4af57dcb75f702b6f6fa4a0b172f685395843a4d7" +checksum = "ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a" dependencies = [ "arrayvec", - "bit-set 0.9.1", + "bit-set 0.10.0", "bit-vec 0.9.1", "bitflags 2.13.2", "bytemuck", "cfg_aliases", "document-features", - "hashbrown 0.16.1", + "hashbrown 0.17.1", "indexmap", "log", "naga", + "naga-types", "once_cell", "parking_lot", "portable-atomic", @@ -9406,50 +9669,50 @@ dependencies = [ [[package]] name = "wgpu-core-deps-apple" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e39e26c4c0e07589e67d18546cf79ff45383659fc72fca4dd293358a0347f3" +checksum = "7d3f2f24aee039ffe9ef527300daf6b7428c58edeefdaa1700f4fa0fd754df16" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-emscripten" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01e09be551dc939498bdd5f6b2c66e55ab275dad25825267a08605a80fc9f0af" +checksum = "55ccf093bd215ae9dc4f96df293e675513ac1f2569f8293a2911cc34ca3505d1" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-wasm" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1fb1798be2a912497d4c224f72d39bb0cb34af50e8bcc29865bc339c943059" +checksum = "b20f43aeb9962d05e61e3ccb717e2e27ba1b04e979d4ca7e361384f8ee03db56" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-windows-linux-android" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e592c1bbef6ad047647ae6e666ebd8cee7a32bb4544d9700ec96cbf73230257" +checksum = "1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-hal" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97ace1c17727311c22a46e4e3faf56ea6de81af99dcc839bdfb54857b94d448d" +checksum = "a57452fe453658e141aafdb09de1028afa498805fab518238ddf372a518813ff" dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set 0.9.1", + "bit-set 0.10.0", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", @@ -9458,17 +9721,18 @@ dependencies = [ "glow", "glutin_wgl_sys", "gpu-allocator", - "gpu-descriptor", - "hashbrown 0.16.1", + "hashbrown 0.17.1", "js-sys", "khronos-egl", "libc", "libloading 0.8.9", "log", "naga", + "naga-types", "ndk-sys", "objc2 0.6.5", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", "objc2-metal 0.3.2", "objc2-quartz-core 0.3.2", @@ -9483,6 +9747,7 @@ dependencies = [ "raw-window-metal", "renderdoc-sys", "smallvec", + "static_assertions", "thiserror 2.0.21", "wasm-bindgen", "wayland-sys", @@ -9496,9 +9761,9 @@ dependencies = [ [[package]] name = "wgpu-naga-bridge" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95226013f547544b223281cd16a4fb549aa9dcb562adbda0faae4c73ffbbc161" +checksum = "44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f" dependencies = [ "naga", "wgpu-types", @@ -9506,15 +9771,17 @@ dependencies = [ [[package]] name = "wgpu-types" -version = "29.0.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84bf84cd9ca8ca45e2b223a3868f1adf9bfc0c66aeac212e76ee7e40fdadf8f5" +checksum = "a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6" dependencies = [ "bitflags 2.13.2", "bytemuck", "js-sys", "log", + "naga-types", "raw-window-handle", + "static_assertions", "web-sys", ] @@ -10616,7 +10883,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6b338d705ae33a43ca00287c11129303a7a0aa57b101b72a1c08c863f698ac8" dependencies = [ "anyhow", - "cocoa 0.25.0", + "cocoa", "core-graphics-helmer-fork", "log", "objc", @@ -10721,6 +10988,7 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", + "zerovec", ] [[package]] @@ -10729,6 +10997,7 @@ version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", diff --git a/crates/postium-editor/Cargo.toml b/crates/postium-editor/Cargo.toml index 04ce9ab6..f653eff7 100644 --- a/crates/postium-editor/Cargo.toml +++ b/crates/postium-editor/Cargo.toml @@ -6,8 +6,8 @@ license.workspace = true description = "Postium Mail 原生邮件编辑器组件(GPUI/WYSIWYG,md⇄HTML)" [dependencies] -gpui-kit = "0.8" -gpui-kit-markdown-editor = { git = "https://github.com/wabzqem/gpui-kit-markdown-editor" } +gpui-kit = "0.10" +gpui-kit-markdown-editor = { git = "https://github.com/spartajet/gpui-kit-markdown-editor", branch = "gpui-kit-0.10" } pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } scraper = "0.23" ego-tree = "0.10" diff --git a/crates/postium-ui/Cargo.toml b/crates/postium-ui/Cargo.toml index 127a4f45..a47e8178 100644 --- a/crates/postium-ui/Cargo.toml +++ b/crates/postium-ui/Cargo.toml @@ -13,8 +13,8 @@ path = "src/main.rs" postium-core = { path = "../postium-core" } postium-editor = { path = "../postium-editor" } postium-html = { path = "../postium-html" } -gpui-kit = "0.8" -gpui-kit-assets = "0.8" +gpui-kit = "0.10" +gpui-kit-assets = "0.10" tokio.workspace = true smol.workspace = true serde.workspace = true @@ -35,7 +35,7 @@ regex = "1" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp"] } [dev-dependencies] -gpui-pre = { version = "0.3.9", package = "gpui-pre", features = ["test-support"] } +gpui-pre = { version = "0.3.12", package = "gpui-pre", features = ["test-support"] } tempfile = "3" [build-dependencies] From cee1025ab448d0b7ec0e2c93215d10015bce3f08 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 01:53:31 +0800 Subject: [PATCH 02/20] =?UTF-8?q?build(deps):=20=E6=8E=A5=E5=85=A5=20gpui-?= =?UTF-8?q?base=20mailview-ext=20=E8=A1=A5=E4=B8=81=E5=88=86=E6=94=AF?= =?UTF-8?q?=EF=BC=88html=5Fblock=5Fparser/renderer=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [patch.crates-io] 指向 spartajet/gpui-kit mailview-ext(基于 v0.10.0 单 commit:HTML 格式自定义块扩展点,对称复制 markdown 模式;上游 1735 测试零扰动 + 端到端认领测试)。工作区全量测试通过。上游 PR 合入后删此段回归官方版。 --- Cargo.lock | 3 +-- Cargo.toml | 7 +++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 838127b5..b934a6a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2821,8 +2821,7 @@ dependencies = [ [[package]] name = "gpui-base" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f4e5aff50636223b268a687ad5788ec54fa77c8e57ca9e53d158f19e0425d95" +source = "git+https://github.com/spartajet/gpui-kit?branch=mailview-ext#c29c7fb2b6ee34568fbdc09feaf462957e1b2768" dependencies = [ "aho-corasick", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 293741ba..e53330d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,13 @@ resolver = "2" members = ["crates/postium-core", "crates/postium-editor", "crates/postium-ui", "crates/postium-html"] exclude = ["src-tauri", "e2e"] +# MailView 扩展补丁:gpui-base 0.10 增加 html_block_parser/html_block_renderer +# (HTML 格式的自定义块扩展点,对称复制其 markdown 已有模式)。 +# 上游 PR 合入后删除本段即可回归官方版本。 +# fork 维护纪律:单 commit 补丁,基于 v0.10.0 tag 的 mailview-ext 分支。 +[patch.crates-io] +gpui-base = { git = "https://github.com/spartajet/gpui-kit", branch = "mailview-ext" } + [workspace.package] version = "0.3.0" edition = "2024" From 667d1299e19f5623eb69865a9de22aef515d92b1 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 02:16:54 +0800 Subject: [PATCH 03/20] =?UTF-8?q?feat(mailview):=20S1=E2=80=94=E2=80=94Tex?= =?UTF-8?q?tView=20=E5=AE=BF=E4=B8=BB=E6=8E=A5=E7=AE=A1=E6=AD=A3=E6=96=87?= =?UTF-8?q?=E6=B8=B2=E6=9F=93=EF=BC=88=E6=A0=87=E8=AE=B0=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E5=8C=96=20+=20=E5=9D=97=E8=AE=A4=E9=A2=86=20+=20=E6=B8=90?= =?UTF-8?q?=E8=BF=9B=E5=9B=9E=E8=90=BD=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit postium-html:serialize_marker_html 索引占位序列化 + 10 fixture 快照锁定(内容零泄漏不变式)。 postium-ui:mail_view.rs 编排层——TextViewState 经补丁 html_with_extensions 构造(认领解析器参与首次解析,无二次重解析/首帧闪),DetailStore 内容键缓存(容量 8,深浅通道共用);每帧重注册同形闭包零重解析(长度比较)。 email_detail html_body 路由:全部块类型已迁移(段落/标题/列表/容器/图片/HR)→ MailView;含 Table/Quote(S2/S3 迁入)→ 旧路径整篇,行为零变。 渲染内核开放:RenderCtx/on_link 收紧 Send+Sync(跨线程渲染闭包口径),mail_frame_ctx/mail_render_block 供宿主路径复用;探针体系两路径共用。 e2e:mail_view_renders_blocks_inside_text_view_host 验证标记→认领→渲染→探针全链路;66 测试全绿。 --- ...ss_9c64d9b8-6f37-4f93-a431-49fa2190b517.md | 85 ++++++++++ Cargo.lock | 31 ++-- crates/postium-html/src/lib.rs | 2 + crates/postium-html/src/serialize.rs | 88 ++++++++++ .../fixtures/markers/attack-non-whitelist.txt | 1 + .../tests/fixtures/markers/business-zh.txt | 6 + .../tests/fixtures/markers/cid-inline.txt | 1 + .../tests/fixtures/markers/dark-native.txt | 1 + .../markers/image-only-newsletter.txt | 1 + .../tests/fixtures/markers/long-zh-plain.txt | 1 + .../markers/marketing-nested-table.txt | 1 + .../fixtures/markers/newsletter-table.txt | 1 + .../tests/fixtures/markers/outlook-export.txt | 1 + .../tests/fixtures/markers/structure-rich.txt | 1 + crates/postium-html/tests/markers.rs | 70 ++++++++ crates/postium-ui/Cargo.toml | 3 + crates/postium-ui/src/e2e_mail_view_tests.rs | 153 ++++++++++++++++++ crates/postium-ui/src/e2e_tests.rs | 5 +- crates/postium-ui/src/main.rs | 2 + crates/postium-ui/src/stores/detail.rs | 34 ++++ crates/postium-ui/src/views/email_detail.rs | 22 ++- crates/postium-ui/src/views/email_html.rs | 43 ++++- crates/postium-ui/src/views/mail_view.rs | 113 +++++++++++++ crates/postium-ui/src/views/mod.rs | 1 + 24 files changed, 643 insertions(+), 24 deletions(-) create mode 100644 .zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md create mode 100644 crates/postium-html/src/serialize.rs create mode 100644 crates/postium-html/tests/fixtures/markers/attack-non-whitelist.txt create mode 100644 crates/postium-html/tests/fixtures/markers/business-zh.txt create mode 100644 crates/postium-html/tests/fixtures/markers/cid-inline.txt create mode 100644 crates/postium-html/tests/fixtures/markers/dark-native.txt create mode 100644 crates/postium-html/tests/fixtures/markers/image-only-newsletter.txt create mode 100644 crates/postium-html/tests/fixtures/markers/long-zh-plain.txt create mode 100644 crates/postium-html/tests/fixtures/markers/marketing-nested-table.txt create mode 100644 crates/postium-html/tests/fixtures/markers/newsletter-table.txt create mode 100644 crates/postium-html/tests/fixtures/markers/outlook-export.txt create mode 100644 crates/postium-html/tests/fixtures/markers/structure-rich.txt create mode 100644 crates/postium-html/tests/markers.rs create mode 100644 crates/postium-ui/src/e2e_mail_view_tests.rs create mode 100644 crates/postium-ui/src/views/mail_view.rs diff --git a/.zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md b/.zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md new file mode 100644 index 00000000..f0939c94 --- /dev/null +++ b/.zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md @@ -0,0 +1,85 @@ +# MailView 实施计划:邮件正文渲染全面迁入 gpui-kit TextView(fork 补丁路线) + +## Context + +当前邮件正文 = `postium-html`(sanitize→IR)→ `email_html.rs` 递归构建 GPUI div 树(1638 行)。痛点:每帧整树重建、无虚拟滚动、文本组间无真行内混排。gpui-kit 0.10(2026-11-16 发布)的 TextView 提供块流编排、ListState 虚拟滚动、保留态 TextViewState,但其原生 html 管线无富样式 run 注入(文字色/字号丢失)、TableCell 无 colspan。 + +**用户决策**:① 全量 S0–S3;② 文本渲染与表格同采用自定义接管——不牺牲颜色/字号保真;③ fork 建公开仓库 spartajet/gpui-kit。 + +**架构定案(自定义块接管)**:MailView = Entity 包装 TextViewState;IR 序列化为**标记 HTML**(每块一个索引占位元素);经 fork 补丁的 `html_block_parser` 把每个块认领为 `MarkdownNode{name:"mail-block", data:块索引}`;`html_block_renderer("mail-block")` 分派到我们自己的渲染器(从 email_html.rs 平移)。TextView 只当**块流宿主**(编排/虚拟滚动/保留态/无障碍文本管线),全部视觉与交互由我们现有代码渲染——**保真度零损失,探针体系原样存活**。未迁移块类型的文档自动回落旧渲染器(渐进切换)。 + +**前置条件**:PR #12(enhanced-textview→main)合并后,从 main 拉 `feat/mailview-renderer` 分支。 + +--- + +## 阶段计划 + +### S0 升级 gpui-kit 0.8 → 0.10(~0.5 天) +- `crates/postium-ui/Cargo.toml`:`gpui-kit`/`gpui-kit-assets` 0.8→0.10,dev-dep `gpui-pre` 0.3.9→0.3.12;postium-editor 同步。 +- **先验证风险点**:`gpui-kit-markdown-editor`(git wabzqem,rev 31608fa,postium-editor 依赖)是否兼容 0.10——查其仓库有无 0.10 分支;不兼容则给该依赖也走 [patch] 或临时固定。 +- 全量 `cargo build --workspace && cargo test --workspace`(CI 门禁=windows+ubuntu 双平台同款命令)。已知升级面:26 处 `use gpui_kit::*` glob、e2e_tests.rs 33 个 `#[gpui_pre::test]`。关键 API(shape_text/paint_image/text_system)已验证 0.3.9→0.3.12 签名稳定。 +- 产出:0.10 vanilla 全绿提交。 + +### S0.5 fork + 补丁(~1 天) +- `gh repo fork longbridge/gpui-kit --clone`(spartajet);从 `v0.10.0` tag 拉 `mailview-ext` 分支,**单 commit** 补丁: + - `text_view.rs`:`pub fn html_block_parser(F: Fn(&RcDom Node, attrs) -> Option)` + `pub fn html_block_renderer(name, F: Fn(&MarkdownNode, &mut Window, &mut App) -> E)`——逐行对称复制 markdown 已有模式(markdown_ext.rs 的 MarkdownExtensions 容器复用/平行)。 + - `format/html.rs`:块级 parse 循环(`local_name!("table")` 分支附近)前插扩展询问点,经 NodeContext 线程穿透(仿 image_source 的传递方式)。 + - 补丁**零业务代码**;`MarkdownNode::new(name, text, data)` 已是 pub(markdown_ext.rs:121)。 +- 推送 fork;根 `Cargo.toml` 加 `[patch.crates-io] gpui-base = { git = "https://github.com/spartajet/gpui-kit", branch = "mailview-ext" }`;全量测试。 +- 同步向上游开 **draft PR**(有 markdown 对称先例,接收概率中高;合入即删 patch 两行)。 + +### S1 序列化器 + MailView 骨架 + 简单块接管(~2-3 天) +- **postium-html 新增 `src/serialize.rs`**:`serialize_marker_html(blocks: &[Block]) -> String`——每块产 `
`(表格/引用等一律占位,内容不进 HTML);纯函数,复用现有 10 组 fixture 做序列化快照测试(沿 `UPDATE_SNAPSHOTS` 模式)。S1 内先用单测验证 html5ever RcDom 保真回读 `data-mb` 属性(若属性被吞,退路:`` 编码)。 +- **postium-ui 新增 `views/mail_view.rs`**: + - `MailView` Entity:持 `Entity`(`TextView::html(id, marker_html)` + `html_block_parser/html_block_renderer` 挂接);parser 闭包捕获 `Arc>`(BlockSpec = IR Block 克隆),渲染器经 `WeakEntity` 每帧读取 ImageCtx/QuoteFold/HtmlSelection/theme 快照。 + - `stores/detail.rs` `CachedDoc` 扩展:序列化串 + `BlockSpec` 表 + `Entity` 惰性缓存(浅/深双通道沿 dark_doc OnceLock 模式)。 + - 首批块渲染器(从 email_html.rs 平移):Hr(389)、Heading、块级 Image(1027-1120 的三源分发+占位)、纯文本 Paragraph(725-804 文本组 + 807-980 SelectableText 原样复用)。 + - **渐进回落规则**:文档含未迁移块类型 → 整篇走旧 `render_html_document`(S1 末即在 email_detail.rs:502 切换主入口,fixture 覆盖的简单文档即刻走新路径)。 + - 探针:块渲染器内继续调 `when_probe`(html-root/html-hr/html-img/html-txt-*)——e2e 断言大面积存活。 + +### S2 富文本 runs + 链接 + 划选 + 引用折叠(~3-4 天) +- 富样式 runs(颜色/字号/粗斜删除线)进文本块渲染器:现有 InlineStyle→TextRun 映射代码平移,**保真不降级**(用户决策②)。 +- 链接:SelectableText 命中→`on_link`→`open_safe_url` 语义不变;`link_tooltip`(0.10 新 API)加悬停真实 URL 预览(反钓鱼,增量功能)。 +- 划选:HtmlSelection 保留,但**组注册表改为文档级预计算**(MailView 构建时由 IR 一次性算出 groups Vec,渲染期只报索引)——同时修掉现每帧注册的脆弱性,并为虚拟化下跨块选择铺路;Ctrl+C/Esc 沿 `EmailHtmlBody` key_context 动作不变。TextView 自身 `selectable(false)`(避免双选中系统)。 +- 引用折叠:QuoteFold/`DetailStore.quote_expanded`/`toggle_quote` 状态机不动(detail.rs:86-94),引用块渲染器平移 email_html.rs:310-370 的折叠 UI。 +- 图片门控:ImageCtx 三源缓存、`allow_remote_images` 流程、load-images 条(email_detail.rs:901-931)、`collect_remote_image_urls` 全部不动——我们自己的 img() 元素渲染,**不需要 image_source resolver**(无默认拉取隐私风险,因为图片不出现在序列化 HTML 里)。 + +### S3 MailTableCell 表格接管(~2-3 天) +- 新增 `views/mail_table.rs`:flex 表格渲染平移(email_html.rs:440-474 的 colspan→grow/width→basis 映射 + 已归一化网格的边框/列宽消费);嵌套表格/单元格内任意块递归复用其他块渲染器。 +- 表格操作:单元格右键/悬停菜单(复制单元格文本、整表转制表符文本进剪贴板);`MarkdownNode.text` 填表格纯文本表示 → TextView 全选/复制管线自动含表格。 +- e2e 的 colspan 宽度比例断言(e2e_tests.rs:2261-2279)作为迁移验收。 + +### S4 收尾切换与退役(~1-2 天) +- 回落规则删除(全类型已迁移);滚动决策:v1 `scrollable(false)`(外层 overflow_y_scroll 不动、行为零变),v2 项:单 TextView `scrollable(true)` 启用 ListState 虚拟滚动(长邮件每帧收益),需配合预计算组表的跨块选择验证。 +- e2e 全量过一遍并修余量(滚动容器语义、status bar 测试 2637);删除 email_html.rs 中已无调用方的死代码(预计 SelectableText 保留、整树递归入口退役);文档更新:MECHANICS.md、README、`docs/plans/2026-11-16-mailtextview-feasibility.md` 追加实施结论章。 +- 提交拆分:每阶段独立 commit,S0/S0.5 各自成 PR-able。 + +--- + +## 关键文件清单 + +| 动作 | 文件 | +|---|---| +| 新增 | `crates/postium-html/src/serialize.rs`(+快照测试)、`crates/postium-ui/src/views/mail_view.rs`、`crates/postium-ui/src/views/mail_table.rs` | +| 修改 | `crates/postium-ui/src/views/email_detail.rs`(html_body 切换 MailView)、`crates/postium-ui/src/stores/detail.rs`(CachedDoc 扩展)、`crates/postium-ui/src/views/email_html.rs`(改造为块渲染器库,渐进退役)、`crates/postium-ui/src/e2e_tests.rs`(HtmlRenderProbe 驱动 MailView + 余量断言修正)、根 `Cargo.toml`([patch.crates-io])、`crates/postium-ui/Cargo.toml` + `crates/postium-editor/Cargo.toml`(0.10 版本) | +| 复用不动 | `ImageCtx`/`decode_render_image_cached`、`HtmlSelection`+`SelectableText`、`QuoteFold`/`quote_expanded`、`allow_remote_images` 状态机、`collect_remote_image_urls`、`adapt_document` 深色管线、10 组 fixture 快照、CI 门禁 | + +## 验证方案 + +1. **每阶段**:`cargo build --workspace && cargo test --workspace`(= CI test.yml 门禁,双平台)。 +2. **postium-html**:序列化快照测试(marker HTML 字节级对比,10 fixture 全覆盖)。 +3. **e2e**(cargo test 内含,33 个 GPUI 测试):重点集——`html_render_smoke`(1962)、`html_render_table_and_link`(2112, colspan 比例=表格迁移验收)、`html_images_blocked_until_allowed`(2828, 门控回归)、`html_email_display_keeps_status_bar`(2637, 布局回归)、`html_cache_same_id_new_content_renders`(2542, 缓存键回归)。 +4. **手工冒烟**:真实账户打开典型邮件 ×10 fixture + aliyun 模板——深/浅色切换、引用折叠、图片拦截→放行→加载条消失、链接点击/悬停预览、Ctrl+C 划选复制、长邮件(long-zh-plain)滚动流畅度。 +5. **补丁回归**:S0.5 后对比 vanilla 0.10 与 patch 版跑同一测试集,确认补丁零行为扰动。 + +## 风险与对策 + +- **markdown-editor git 依赖不兼容 0.10**(S0 卡点):查 wabzqem 仓库 0.10 支持;否则同法 [patch] 或临时降级该组件功能。 +- **补丁 rebase**:上游约每周发版;单 commit 纪律 + 插入点固定在 html.rs 块级 match,冲突面最小化;上游 PR 合入后移除 patch。 +- **data-mb 属性被 html5ever 规范化**:S1 第一件事写回读单测验证;退路 `` 编码。 +- **虚拟化×跨块选择**:v1 不开 scrollable 规避;预计算组表已为 v2 铺路。 +- **上游拒收 PR**:长期养单 commit 小 fork(已接受)。 + +## 工作量 + +S0 0.5d + S0.5 1d + S1 2-3d + S2 3-4d + S3 2-3d + S4 1-2d ≈ **10-13 个工作日**。 \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index b934a6a5..b8a6a5eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1781,7 +1781,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.3", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1819,7 +1819,7 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" dependencies = [ - "libloading 0.8.9", + "libloading 0.7.4", ] [[package]] @@ -2044,7 +2044,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2821,7 +2821,7 @@ dependencies = [ [[package]] name = "gpui-base" version = "0.10.0" -source = "git+https://github.com/spartajet/gpui-kit?branch=mailview-ext#c29c7fb2b6ee34568fbdc09feaf462957e1b2768" +source = "git+https://github.com/spartajet/gpui-kit?branch=mailview-ext#fa3ef2eca10acd79b49a1ac2c88bc8431cf3469b" dependencies = [ "aho-corasick", "anyhow", @@ -5014,7 +5014,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png 0.18.1", "thiserror 2.0.21", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5212,7 +5212,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6411,6 +6411,7 @@ dependencies = [ "gpui-kit-assets", "gpui-pre", "image", + "markup5ever_rcdom 0.3.0", "open", "png 0.17.16", "postium-core", @@ -6745,7 +6746,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -7394,7 +7395,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -8048,7 +8049,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8117,7 +8118,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8485,7 +8486,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -9014,7 +9015,7 @@ dependencies = [ "once_cell", "png 0.18.1", "thiserror 2.0.21", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -9068,7 +9069,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -9815,7 +9816,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -10458,7 +10459,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" dependencies = [ "cfg-if", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] diff --git a/crates/postium-html/src/lib.rs b/crates/postium-html/src/lib.rs index 80d51c0d..813aaf04 100644 --- a/crates/postium-html/src/lib.rs +++ b/crates/postium-html/src/lib.rs @@ -28,6 +28,7 @@ pub mod builder; pub mod error; pub mod pipeline; pub mod sanitize; +pub mod serialize; pub mod style; pub mod types; @@ -36,6 +37,7 @@ pub use builder::build_document; pub use error::HtmlError; pub use pipeline::{inline_css, render_pipeline}; pub use sanitize::{sanitize_lenient, strip_mso_comments}; +pub use serialize::serialize_marker_html; pub use style::{merge_inline, parse_block_style, parse_color, parse_inline_style}; pub use types::{ Align, Block, BlockStyle, Border, HtmlDocument, ImageRef, ImageStyle, InlineRun, InlineStyle, diff --git a/crates/postium-html/src/serialize.rs b/crates/postium-html/src/serialize.rs new file mode 100644 index 00000000..d6780800 --- /dev/null +++ b/crates/postium-html/src/serialize.rs @@ -0,0 +1,88 @@ +//! 标记序列化:净化后 IR → TextView html 管线可解析的标记 HTML。 +//! +//! MailView 渲染路线(docs/plans/2026-11-16-mailtextview-feasibility.md 实施版): +//! 每个顶层块序列化为一个**索引占位元素** `
`——内容不进 +//! HTML(图片 URL、富样式、表格网格都不暴露给 TextView 的内建解析),由 gpui-base +//! mailview-ext 补丁的 `html_block_parser` 在解析期认领为自定义块,渲染期经 +//! `html_block_renderer` 回到 postium-ui 的块渲染器(复用 email_html 的全部保真 +//! 代码:富样式 runs / 图片三源门控 / 探针)。 +//! +//! 由此本模块的契约极简: +//! - 输出只含有序占位元素,顺序 = `blocks` 顺序(渲染层按索引回查 IR); +//! - 空块列表输出空串(调用方走纯文本兜底,不构造 TextView); +//! - 字节级确定性(快照测试锁定)。 +//! +//! 占位元素选 `
`:div 在 TextView html 解析器的块级标签表内(会 +//! 进入 parse_node 的元素分派),`data-mb` 是自定义属性不与任何内建语义冲突; +//! 上游认领测试(gpui-kit mailview-ext)已验证该形态可被 html_block_parser 拦截。 + +use crate::types::Block; + +/// 每块的标记模板:`
`(无内容、无闭合简写歧义)。 +fn marker(i: usize) -> String { + format!("
") +} + +/// 把顶层块序列化为标记 HTML。块与块之间以换行分隔(html5ever 解析不依赖 +/// 换行,分隔只为可读性与快照 diff 友好)。 +pub fn serialize_marker_html(blocks: &[Block]) -> String { + blocks + .iter() + .enumerate() + .map(|(i, _)| marker(i)) + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_blocks_serialize_to_empty_string() { + assert_eq!(serialize_marker_html(&[]), ""); + } + + #[test] + fn markers_are_sequential_and_ordered() { + let blocks = vec![ + Block::Hr, + Block::Paragraph { + style: Default::default(), + runs: vec![], + align: crate::types::Align::Left, + }, + Block::Hr, + ]; + assert_eq!( + serialize_marker_html(&blocks), + "
\n
\n
" + ); + } + + #[test] + fn block_content_never_leaks_into_markers() { + // 富样式/图片/链接内容都不得进入序列化输出——内容只经 IR 通道回渲染层。 + let blocks = vec![Block::Paragraph { + style: Default::default(), + runs: vec![ + crate::types::InlineRun::Text { + text: "机密正文 ".into(), + style: Default::default(), + }, + crate::types::InlineRun::Image { + src: crate::types::ImageRef::Remote { + url: "https://track.example.test/pixel.png".into(), + }, + alt: "追踪像素".into(), + style: Default::default(), + }, + ], + align: crate::types::Align::Left, + }]; + let out = serialize_marker_html(&blocks); + assert_eq!(out, "
"); + assert!(!out.contains("script")); + assert!(!out.contains("track.example")); + } +} diff --git a/crates/postium-html/tests/fixtures/markers/attack-non-whitelist.txt b/crates/postium-html/tests/fixtures/markers/attack-non-whitelist.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/attack-non-whitelist.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/business-zh.txt b/crates/postium-html/tests/fixtures/markers/business-zh.txt new file mode 100644 index 00000000..a29f2290 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/business-zh.txt @@ -0,0 +1,6 @@ +
+
+
+
+
+
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/cid-inline.txt b/crates/postium-html/tests/fixtures/markers/cid-inline.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/cid-inline.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/dark-native.txt b/crates/postium-html/tests/fixtures/markers/dark-native.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/dark-native.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/image-only-newsletter.txt b/crates/postium-html/tests/fixtures/markers/image-only-newsletter.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/image-only-newsletter.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/long-zh-plain.txt b/crates/postium-html/tests/fixtures/markers/long-zh-plain.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/long-zh-plain.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/marketing-nested-table.txt b/crates/postium-html/tests/fixtures/markers/marketing-nested-table.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/marketing-nested-table.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/newsletter-table.txt b/crates/postium-html/tests/fixtures/markers/newsletter-table.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/newsletter-table.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/outlook-export.txt b/crates/postium-html/tests/fixtures/markers/outlook-export.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/outlook-export.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/fixtures/markers/structure-rich.txt b/crates/postium-html/tests/fixtures/markers/structure-rich.txt new file mode 100644 index 00000000..502bc394 --- /dev/null +++ b/crates/postium-html/tests/fixtures/markers/structure-rich.txt @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/crates/postium-html/tests/markers.rs b/crates/postium-html/tests/markers.rs new file mode 100644 index 00000000..b6dda368 --- /dev/null +++ b/crates/postium-html/tests/markers.rs @@ -0,0 +1,70 @@ +//! 标记序列化快照:全部 fixture 经完整管线 → IR → serialize_marker_html, +//! 输出字节级锁定(MailView 路线的回归护栏——顺序、数量、无内容泄漏)。 + +use std::fs; +use std::path::{Path, PathBuf}; + +use postium_html::{render_pipeline, serialize_marker_html}; + +const FIXTURES_DIR: &str = "tests/fixtures"; +const SNAPSHOTS_DIR: &str = "tests/fixtures/markers"; + +fn fixture_paths() -> Vec { + let mut paths: Vec<_> = fs::read_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join(FIXTURES_DIR)) + .expect("tests/fixtures 目录应存在") + .map(|entry| entry.expect("目录项应可读").path()) + .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "html")) + .collect(); + paths.sort(); + paths +} + +#[test] +fn fixtures_match_marker_snapshots() { + let update = std::env::var("UPDATE_SNAPSHOTS").as_deref() == Ok("1"); + let snapshots_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join(SNAPSHOTS_DIR); + let paths = fixture_paths(); + assert!(paths.len() >= 10, "fixture 语料应至少 10 封"); + + for path in &paths { + let name = path + .file_stem() + .expect("fixture 应有文件名") + .to_string_lossy() + .into_owned(); + let html = + fs::read_to_string(path).unwrap_or_else(|err| panic!("{name}: fixture 应可读:{err}")); + let doc = render_pipeline(&html) + .unwrap_or_else(|err| panic!("{name}: 完整管线应成功,实际 {err:?}")); + let actual = serialize_marker_html(&doc.blocks); + + let snapshot = snapshots_dir.join(format!("{name}.txt")); + if update { + fs::create_dir_all(&snapshots_dir).expect("快照目录应可创建"); + fs::write(&snapshot, &actual).unwrap_or_else(|err| panic!("{name}: 快照应可写:{err}")); + println!("{name}: 标记快照已更新({} 字节)", actual.len()); + continue; + } + + let expected = fs::read_to_string(&snapshot).unwrap_or_else(|err| { + panic!( + "{name}: 标记快照缺失({err})——先运行 \ + `UPDATE_SNAPSHOTS=1 cargo test -p postium-html --test markers` 生成并人工审阅" + ) + }); + assert_eq!( + actual, expected, + "{name}: 标记快照不一致——序列化顺序/形态变更需人工审阅" + ); + + // 不变式:每个 fixture 至少一个标记;输出不含任何正文内容(内容只走 IR 通道)。 + let marker_count = actual.lines().count(); + assert!(marker_count >= 1, "{name}: 标记数应 ≥1"); + for line in actual.lines() { + assert!( + line.starts_with("
"), + "{name}: 标记形态异常:{line}" + ); + } + } +} diff --git a/crates/postium-ui/Cargo.toml b/crates/postium-ui/Cargo.toml index a47e8178..ae799204 100644 --- a/crates/postium-ui/Cargo.toml +++ b/crates/postium-ui/Cargo.toml @@ -33,6 +33,9 @@ regex = "1" # 默认全家桶,feature 统一后实际编译集为并集——此处声明的是本 crate 自身 # 的最小契约,gpui-pre 若将来裁剪不至连带放大。 image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp"] } +# MailView 标记认领解析器(S1):闭包签名引用 gpui-base html 管线的 RcDom +# Node 类型——与 base 同版本(Cargo.lock 统一实例),仅类型对齐无额外逻辑。 +markup5ever_rcdom = "0.3" [dev-dependencies] gpui-pre = { version = "0.3.12", package = "gpui-pre", features = ["test-support"] } diff --git a/crates/postium-ui/src/e2e_mail_view_tests.rs b/crates/postium-ui/src/e2e_mail_view_tests.rs new file mode 100644 index 00000000..268dee80 --- /dev/null +++ b/crates/postium-ui/src/e2e_mail_view_tests.rs @@ -0,0 +1,153 @@ +//! MailView(TextView 宿主 + 自定义块接管)e2e(S1)。 +//! +//! 与 HtmlRenderProbe(旧路径直驱)相对:本组直接驱动 mail_view 的 +//! 构造/渲染入口,断言「标记序列化 → html_block_parser 认领 → 块渲染器 +//! → 探针」全链路在 TextView 宿主内走通;app 级路由(EmailDetailView +//! html_body 分流)由 html_email_renders_via_new_renderer 覆盖(纯段落 +//! 文档 → MailView 路径)。 + +use std::sync::Arc; + +use gpui_kit::base::TextViewState; +use gpui_kit::{div, App, AppContext as _, Context, Entity, IntoElement, ParentElement, Render, Styled, px}; +use postium_html::{ + Align, Block, BlockStyle, HtmlDocument, ImageRef, ImageStyle, InlineRun, InlineStyle, SafeUrl, +}; + +use crate::views::email_html::ImageCtx; +use crate::views::html_selection::HtmlSelection; +use crate::views::mail_view; + +/// 宿主探针视图:真实 TextViewState(html_with_extensions 构造,与生产同径)。 +struct MailViewProbe { + state: Entity, + doc: HtmlDocument, +} + +impl Render for MailViewProbe { + fn render(&mut self, _: &mut gpui_kit::Window, cx: &mut Context) -> impl IntoElement { + div() + .w(px(400.)) + .h(px(600.)) + .overflow_hidden() + .child(mail_view::render( + &self.state, + &self.doc, + false, + ImageCtx::default(), + HtmlSelection::default(), + None, + Arc::new(|_: &SafeUrl| {}), + // Context 解引用到 &mut App(gpui 标准解引用链) + cx, + )) + } +} + +#[gpui_pre::test] +fn mail_view_renders_blocks_inside_text_view_host(cx: &mut gpui_pre::TestAppContext) { + fn text(t: &str) -> InlineRun { + InlineRun::Text { + text: t.into(), + style: InlineStyle::default(), + } + } + + let doc = HtmlDocument { + blocks: vec![ + Block::Heading { + level: 1, + align: Align::Left, + runs: vec![text("TitleProbeText")], + }, + // 容器 + 内嵌段落(递归支持集判定) + Block::Container { + style: BlockStyle::default(), + children: vec![Block::Paragraph { + style: BlockStyle::default(), + runs: vec![text("ContainerProbe")], + align: Align::Left, + }], + }, + // 列表(items: Vec>) + Block::List { + ordered: false, + items: vec![vec![Block::Paragraph { + style: BlockStyle::default(), + runs: vec![text("ListItemProbe")], + align: Align::Left, + }]], + }, + // 链接段落(SelectableText 命中链路在旧路径 e2e 覆盖,此处验证渲染存在) + Block::Paragraph { + style: BlockStyle::default(), + runs: vec![ + text("正文前缀"), + InlineRun::Link { + href: SafeUrl::Http("https://example.com/mailview".into()), + runs: vec![text("LinkProbeText")], + }, + ], + align: Align::Left, + }, + Block::Hr, + ], + }; + + // 支持集判定:无 Table/Quote → MailView 路径 + assert!(mail_view::supported(&doc), "无表格/引用的文档应走 MailView"); + + let state = cx.update(|app: &mut App| mail_view::build_text_view_state(&doc, app)); + let (root, cx) = cx.add_window_view(|_, cx| { + crate::e2e_tests::setup(cx); + MailViewProbe { + state: state.clone(), + doc, + } + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + let _ = root; // 探针视图仅承载渲染 + + // 根锚点 + 各块探针:证明块渲染器在 TextView 宿主内产出内容 + for key in [ + "html-root", + "html-hr", + "html-txt-TitleProbeText", + "html-txt-ContainerProbe", + "html-txt-ListItemProbe", + "html-txt-正文前缀LinkProbeTex", + ] { + let bounds = cx.debug_bounds(key).unwrap_or_else(|| panic!("{key} 应存在")); + assert!( + bounds.size.width > px(0.) || bounds.size.height > px(0.), + "{key} 应有非零尺寸(实际 {bounds:?})" + ); + } + + // 图片块支持集(无 src 的 Invalid 占位形态)——仅判定,不渲染断言(占位框 + // 探针 html-img 由旧路径 e2e 覆盖渲染细节) + let img_doc = HtmlDocument { + blocks: vec![Block::Image { + src: ImageRef::Invalid, + alt: "占位".into(), + style: ImageStyle::default(), + }], + }; + assert!(mail_view::supported(&img_doc), "块级图片应在支持集内"); + + // 回落判定:Table/Quote → 旧路径 + let quote_doc = HtmlDocument { + blocks: vec![Block::Quote { + children: vec![Block::Paragraph { + style: BlockStyle::default(), + runs: vec![text("引用")], + align: Align::Left, + }], + }], + }; + assert!(!mail_view::supported("e_doc), "引用块应回落旧路径(S2 迁入)"); +} diff --git a/crates/postium-ui/src/e2e_tests.rs b/crates/postium-ui/src/e2e_tests.rs index 8caa78b1..52d7c2ee 100644 --- a/crates/postium-ui/src/e2e_tests.rs +++ b/crates/postium-ui/src/e2e_tests.rs @@ -81,7 +81,7 @@ fn wait_for( panic!("等待条件超时"); } -fn setup(cx: &mut gpui_pre::App) { +pub(crate) fn setup(cx: &mut gpui_pre::App) { gpui_kit::init(cx); postium_editor::init(cx); cx.set_global(crate::i18n::I18nGlobal { @@ -1931,7 +1931,8 @@ fn dav_config_modal_opens_and_closes_on_escape(cx: &mut TestAppContext) { struct HtmlRenderProbe { doc: postium_html::HtmlDocument, /// 链接点击回调(Task 10:e2e 注入捕获闭包断言 SafeUrl 通路)。 - on_link: Arc, + /// `Send + Sync`:渲染管线回调口径(MailView 渲染闭包跨线程句柄,S1)。 + on_link: Arc, } impl gpui_kit::Render for HtmlRenderProbe { diff --git a/crates/postium-ui/src/main.rs b/crates/postium-ui/src/main.rs index ee366252..b7521a9b 100644 --- a/crates/postium-ui/src/main.rs +++ b/crates/postium-ui/src/main.rs @@ -14,6 +14,8 @@ mod tray; mod views; mod window_state; +#[cfg(test)] +mod e2e_mail_view_tests; #[cfg(test)] mod e2e_tests; diff --git a/crates/postium-ui/src/stores/detail.rs b/crates/postium-ui/src/stores/detail.rs index 0bf3daa8..05dd129e 100644 --- a/crates/postium-ui/src/stores/detail.rs +++ b/crates/postium-ui/src/stores/detail.rs @@ -41,6 +41,10 @@ pub struct DetailStore { /// 确定稳定),值 = 展开。默认不在集合 = 折叠。换邮件/重解析后 id 语义 /// 不变(Quote 块遍历顺序由文档结构决定)。 pub quote_expanded: std::collections::HashSet, + /// MailView TextViewState 缓存(S1):键与 html_cache 同源(内容感知二元 + /// 组),容量 8 FIFO 逐出。标记 HTML 只含块索引占位——深浅通道共用同一 + /// 宿主态(块内容渲染期经闭包回读当前通道文档),主题切换零重建。 + mail_view_states: std::collections::VecDeque<(i32, u64, gpui_kit::Entity)>, } #[derive(Clone, Copy)] @@ -60,6 +64,7 @@ impl DetailStore { images: HtmlRenderState::default(), html_cache: EmailHtmlCache::default(), quote_expanded: std::collections::HashSet::new(), + mail_view_states: std::collections::VecDeque::new(), } } @@ -267,6 +272,35 @@ impl DetailStore { pub fn cached_doc(&mut self, email_id: i32, html: &str, dark: bool) -> Option { self.html_cache.doc_for(content_key(email_id, html), html, dark) } + + /// MailView 宿主态取用(S1):内容感知键命中直接返回;未命中经 + /// [`crate::views::mail_view::build_text_view_state`] 构造(认领解析器参与 + /// 首次解析),入缓存并 FIFO 逐出(容量 8,与 html_cache 口径一致)。 + pub fn mail_text_view_state( + &mut self, + email_id: i32, + html: &str, + doc: &HtmlDocument, + cx: &mut gpui_kit::App, + ) -> gpui_kit::Entity { + let key = content_key(email_id, html); + if let Some(pos) = self + .mail_view_states + .iter() + .position(|(id, hash, _)| *id == key.0 && *hash == key.1) + { + // 命中提升为最近使用(队尾) + let entry = self.mail_view_states.remove(pos).expect("pos 来自 iter().position()"); + self.mail_view_states.push_back(entry.clone()); + return entry.2.clone(); + } + let state = crate::views::mail_view::build_text_view_state(doc, cx); + self.mail_view_states.push_back((key.0, key.1, state.clone())); + while self.mail_view_states.len() > 8 { + self.mail_view_states.pop_front(); + } + state + } } // --------------------------------------------------------------------------- diff --git a/crates/postium-ui/src/views/email_detail.rs b/crates/postium-ui/src/views/email_detail.rs index 31ef1131..62316432 100644 --- a/crates/postium-ui/src/views/email_detail.rs +++ b/crates/postium-ui/src/views/email_detail.rs @@ -499,7 +499,27 @@ fn html_body( ) as std::sync::Arc; let quotes = crate::views::email_html::QuoteFold { expanded, on_toggle }; - let el = render_html_document(&doc, dark, images, selection, Some(quotes), open_safe_url, cx); + // 路由(S1 渐进切换):全部块类型已迁移 → MailView(TextView 宿主 + 自有 + // 块渲染器,mail_view.rs);含 Table/Quote(S2/S3 迁入)→ 旧路径整篇渲染, + // 行为零变。两路径共用同一渲染内核与探针键。 + let el = if crate::views::mail_view::supported(&doc) { + let state = store.update(cx, |store, cx| { + store.mail_text_view_state(email_id, html, &doc, cx) + }); + crate::views::mail_view::render( + &state, + &doc, + dark, + images, + selection, + Some(quotes), + // Send+Sync 口径(mail_view 渲染闭包跨线程句柄):fn 指针天然满足。 + std::sync::Arc::new(open_safe_url), + cx, + ) + } else { + render_html_document(&doc, dark, images, selection, Some(quotes), open_safe_url, cx) + }; Some((el, remote_urls)) } diff --git a/crates/postium-ui/src/views/email_html.rs b/crates/postium-ui/src/views/email_html.rs index 4a505ebe..4a160dd8 100644 --- a/crates/postium-ui/src/views/email_html.rs +++ b/crates/postium-ui/src/views/email_html.rs @@ -113,7 +113,10 @@ impl HtmlRenderState { } /// 渲染期常量:主题衍生默认色板 + 主题字体 + 链接回调,一次取齐(帧内不可变)。 -struct RenderCtx { +/// +/// `pub(crate)`:MailView 编排层(mail_view.rs)复用同一渲染内核——TextView +/// 宿主路径的块渲染器直接消费本 ctx(S1 起)。 +pub(crate) struct RenderCtx { dark: bool, font_family: SharedString, foreground: Hsla, @@ -126,7 +129,9 @@ struct RenderCtx { selection_bg: Hsla, /// 链接点击回调(SelectableText hitbox → 调用方打开动作;email_detail /// 侧为 open::that_detached 系统处理,见其 open_safe_url)。 - on_link: Arc, + /// `Send + Sync`:MailView 的块渲染闭包经 TextView 注册为跨线程句柄, + /// 回调须随 RenderCtx 整体满足(与 QuoteFold.on_toggle 同口径)。 + pub(crate) on_link: Arc, /// 图片三源上下文(Remote 查 resolved / Cid 扫 attachments / DataUri 解码)。 images: ImageCtx, /// 文本划选状态(组注册表 + 锚点/游标,线上反馈①)。 @@ -144,7 +149,7 @@ impl RenderCtx { } fn new( dark: bool, - on_link: Arc, + on_link: Arc, images: ImageCtx, selection: HtmlSelection, quotes: Option, @@ -223,7 +228,7 @@ pub fn render_html_document( images: ImageCtx, selection: HtmlSelection, quotes: Option, - on_link: impl Fn(&SafeUrl) + 'static, + on_link: impl Fn(&SafeUrl) + Send + Sync + 'static, cx: &mut App, ) -> AnyElement { selection.begin_frame(); @@ -235,6 +240,31 @@ pub fn render_html_document( .into_any_element() } +/// MailView 编排层帧入口(S1):帧初始化(划选组注册表清零 + 引用 id 计数 +/// 重置,与 [`render_html_document`] 同语义)+ 渲染内核 ctx 构造。 +/// +/// MailView 路径下块的渲染顺序由 TextView 决定(标记序 = 文档序),帧首 +/// 初始化语义不变。 +pub(crate) fn mail_frame_ctx( + dark: bool, + on_link: Arc, + images: ImageCtx, + selection: HtmlSelection, + quotes: Option, + cx: &App, +) -> RenderCtx { + selection.begin_frame(); + QUOTE_ID.store(0, std::sync::atomic::Ordering::Relaxed); + RenderCtx::new(dark, on_link, images, selection, quotes, cx) +} + +/// MailView 块渲染器入口(S1):单块 → GPUI 元素(复用渲染内核全部保真 +/// 逻辑:富样式 runs / 图片三源 / 探针)。容器内继承链从文档根默认值起 +/// (宿主路径块均为顶层块,语义等价 [`render_html_document`] 的根遍历)。 +pub(crate) fn mail_render_block(block: &Block, rcx: &RenderCtx) -> AnyElement { + render_block(block, Inherited::default(), rcx) +} + /// 引用块 id 计数器(每帧从 QUOTE_FRAME_BASE 起点递增;render_html_document /// 每帧开头重置,同一文档内顺序稳定 → id 稳定)。 static QUOTE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -822,7 +852,7 @@ struct SelectableText { selection: HtmlSelection, ranges: Vec>, urls: Vec, - on_link: Arc, + on_link: Arc, } #[derive(Default)] @@ -1367,8 +1397,9 @@ fn heading_size(level: u8) -> f32 { // --------------------------------------------------------------------------- // 测试探针(仅测试构建生效):块级锚点与行内文本段以选择器写入渲染树, // e2e 经 `VisualTestContext::debug_bounds` 查询;正常构建直通零开销。 +// `pub(crate)`:mail_view 宿主路径同用(html-root 根锚点等,S1)。 // --------------------------------------------------------------------------- -trait ProbeExt: Sized { +pub(crate) trait ProbeExt: Sized { fn when_probe(self, selector: &str) -> Self; } diff --git a/crates/postium-ui/src/views/mail_view.rs b/crates/postium-ui/src/views/mail_view.rs new file mode 100644 index 00000000..249b9a8a --- /dev/null +++ b/crates/postium-ui/src/views/mail_view.rs @@ -0,0 +1,113 @@ +//! MailView:邮件正文渲染编排层(S1)。 +//! +//! 架构(docs/plans/2026-11-16-mailtextview-feasibility.md 实施版): +//! TextView 作**块流宿主**(保留态 + 块编排 + 无障碍文本管线),全部视觉 +//! 与交互由自有块渲染器接管(复用 email_html 渲染内核的富样式/图片门控/ +//! 探针——保真度零损失)。数据通道:IR 顶层块 → [`serialize_marker_html`] +//! 索引占位元素 → gpui-base mailview-ext 补丁的 `html_block_parser` 认领为 +//! 自定义块(`data: usize` = 块索引)→ `html_block_renderer("mail-block")` +//! 按索引回读 IR 渲染。正文内容不进入标记 HTML(URL/富样式/表格网格均不 +//! 暴露给 TextView 内建解析)。 +//! +//! 渐进回落:文档含未迁移块类型(S1 为 Table/Quote,S2/S3 迁移)→ 整篇走 +//! 旧 [`email_html::render_html_document`] 路径,行为零变。 +//! +//! 状态缓存:`TextViewState` 按内容感知键缓存在 DetailStore(标记 HTML 与 +//! 深浅通道无关——块内容渲染期经闭包回读当前通道文档),经补丁的 +//! `html_with_extensions` 构造,解析器参与首次解析(无二次重解析、无首帧 +//! 空白闪)。 + +use std::sync::Arc; + +use gpui_kit::base::{MarkdownNode, TextView, TextViewState}; +use gpui_kit::{AnyElement, App, AppContext as _, Entity, IntoElement as _, ParentElement as _, Styled as _}; +use markup5ever_rcdom::NodeData; +use postium_html::{serialize_marker_html, Block, HtmlDocument, SafeUrl}; + +use super::email_html::{self, ImageCtx, ProbeExt as _, QuoteFold}; +use super::html_selection::HtmlSelection; + +/// S1 支持集递归判定:Table/Quote 暂留旧路径(S2/S3 迁入)。 +fn block_supported(block: &Block) -> bool { + match block { + Block::Table { .. } | Block::Quote { .. } => false, + Block::Container { children, .. } => children.iter().all(block_supported), + Block::List { items, .. } => items.iter().all(|group| group.iter().all(block_supported)), + _ => true, + } +} + +/// 文档是否可走 MailView 路径(全部块类型已迁移;空文档不值得建宿主)。 +pub fn supported(doc: &HtmlDocument) -> bool { + !doc.blocks.is_empty() && doc.blocks.iter().all(block_supported) +} + +/// 标记认领解析器:`
` → `MarkdownNode { name: "mail-block", +/// data: i }`。纯索引提取(无捕获、无副作用),供 +/// `TextViewState::html_with_extensions` 首次解析与元素每帧重注册共用—— +/// 两侧必须同形(形状一致才不触发重解析,见补丁 has_same_html_block_parsers)。 +pub(crate) fn extract_mail_block(node: &markup5ever_rcdom::Node) -> Option { + let NodeData::Element { ref name, ref attrs, .. } = node.data else { + return None; + }; + let index = attrs + .borrow() + .iter() + .find(|attr| &*attr.name.local == "data-mb") + .and_then(|attr| attr.value.parse::().ok())?; + // name 一致性约束:认领即自定义块,渲染分派按 name 查注册表。 + (name.local.trim() == "div").then(|| MarkdownNode::new("mail-block", index)) +} + +/// MailView 帧渲染:宿主 TextView + 认领解析器 + 块渲染器接线。 +/// +/// `state`:DetailStore 缓存的 TextViewState(`html_with_extensions` 构造)。 +/// `doc`:当前深/浅通道文档(块渲染闭包按索引回读,通道切换零重建)。 +/// +/// 每帧重注册的解析器/渲染器闭包与状态内注册形状一致(长度比较不触发重 +/// 解析);渲染闭包捕获本帧 RenderCtx(主题快照 + 三源图片 + 划选 + 折叠 +/// 上下文),块渲染语义与旧路径逐块等价。 +#[allow(clippy::too_many_arguments)] +pub fn render( + state: &Entity, + doc: &HtmlDocument, + dark: bool, + images: ImageCtx, + selection: HtmlSelection, + quotes: Option, + on_link: Arc, + cx: &mut App, +) -> AnyElement { + let rcx = email_html::mail_frame_ctx(dark, on_link, images, selection, quotes, cx); + let blocks = Arc::new(doc.blocks.clone()); + let tv = TextView::new(state) + .selectable(false) + .html_block_parser(extract_mail_block) + .html_block_renderer("mail-block", move |node: &MarkdownNode, _window, _cx| { + let index = node + .data::() + .copied() + .unwrap_or(usize::MAX); + blocks + .get(index) + .map(|block| email_html::mail_render_block(block, &rcx)) + .unwrap_or_else(|| gpui_kit::div().into_any_element()) + }); + gpui_kit::div() + .w_full() + .when_probe("html-root") + .child(tv) + .into_any_element() +} + +/// 供 DetailStore 构造缓存态的便捷入口:标记 HTML + 扩展(认领解析器)→ +/// TextViewState(补丁 `html_with_extensions`:解析器参与首次解析)。 +pub(crate) fn build_text_view_state( + doc: &HtmlDocument, + cx: &mut App, +) -> Entity { + let marker_html = serialize_marker_html(&doc.blocks); + let mut extensions = gpui_kit::base::MarkdownExtensions::default(); + extensions.push_html_block_parser(extract_mail_block); + cx.new(|cx| TextViewState::html_with_extensions(&marker_html, Arc::new(extensions), cx)) +} diff --git a/crates/postium-ui/src/views/mod.rs b/crates/postium-ui/src/views/mod.rs index 44fdc9a3..9de69934 100644 --- a/crates/postium-ui/src/views/mod.rs +++ b/crates/postium-ui/src/views/mod.rs @@ -5,6 +5,7 @@ pub mod contacts; pub mod email_detail; pub mod email_html; pub mod html_selection; +pub mod mail_view; pub mod email_list; pub mod recipient_field; pub mod settings; From ce2500d65fa56238006227e2c06b8d2e1845bb2d Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 02:18:51 +0800 Subject: [PATCH 04/20] =?UTF-8?q?feat(mailview):=20S2/S3=E2=80=94=E2=80=94?= =?UTF-8?q?=E5=BC=95=E7=94=A8=E6=8A=98=E5=8F=A0=E4=B8=8E=E8=A1=A8=E6=A0=BC?= =?UTF-8?q?=E5=85=A8=E9=87=8F=E8=BF=81=E5=85=A5=E5=AE=BF=E4=B8=BB=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=EF=BC=88=E8=B7=AF=E7=94=B1=E6=94=BE=E5=BC=80=EF=BC=8C?= =?UTF-8?q?e2e=20=E8=A3=81=E5=86=B3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 渲染内核(render_block 递归全类型)本就与旧路径共用——S1 的 Table/Quote 排除只是保守路由。本轮放开后 e2e 全绿裁决:smoke(引用折叠)、table_and_link(colspan 宽度比例断言)、html_email_display_keeps_status_bar(aliyun 真实模板:嵌套表格+图片门控+导航布局)均经 TextView 宿主路径通过。66 测试 × 3 并发模式全绿。 预计算组表(虚拟化下跨块选择)与 link_tooltip(悬停反钓鱼)为 v2 增量项,随虚拟滚动启用一并实施。 --- crates/postium-ui/src/e2e_mail_view_tests.rs | 9 +++++++-- crates/postium-ui/src/views/mail_view.rs | 14 ++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/crates/postium-ui/src/e2e_mail_view_tests.rs b/crates/postium-ui/src/e2e_mail_view_tests.rs index 268dee80..4e3a0409 100644 --- a/crates/postium-ui/src/e2e_mail_view_tests.rs +++ b/crates/postium-ui/src/e2e_mail_view_tests.rs @@ -139,7 +139,8 @@ fn mail_view_renders_blocks_inside_text_view_host(cx: &mut gpui_pre::TestAppCont }; assert!(mail_view::supported(&img_doc), "块级图片应在支持集内"); - // 回落判定:Table/Quote → 旧路径 + // 全量路由(S2/S3):引用与表格块同走宿主路径(渲染内核共用,e2e + // smoke/table_and_link 裁决);空文档仍不值得建宿主。 let quote_doc = HtmlDocument { blocks: vec![Block::Quote { children: vec![Block::Paragraph { @@ -149,5 +150,9 @@ fn mail_view_renders_blocks_inside_text_view_host(cx: &mut gpui_pre::TestAppCont }], }], }; - assert!(!mail_view::supported("e_doc), "引用块应回落旧路径(S2 迁入)"); + assert!(mail_view::supported("e_doc), "引用块应走宿主路径(S2 已迁入)"); + assert!( + !mail_view::supported(&HtmlDocument { blocks: vec![] }), + "空文档不应建宿主(纯文本兜底)" + ); } diff --git a/crates/postium-ui/src/views/mail_view.rs b/crates/postium-ui/src/views/mail_view.rs index 249b9a8a..27eaf5d8 100644 --- a/crates/postium-ui/src/views/mail_view.rs +++ b/crates/postium-ui/src/views/mail_view.rs @@ -27,14 +27,12 @@ use postium_html::{serialize_marker_html, Block, HtmlDocument, SafeUrl}; use super::email_html::{self, ImageCtx, ProbeExt as _, QuoteFold}; use super::html_selection::HtmlSelection; -/// S1 支持集递归判定:Table/Quote 暂留旧路径(S2/S3 迁入)。 -fn block_supported(block: &Block) -> bool { - match block { - Block::Table { .. } | Block::Quote { .. } => false, - Block::Container { children, .. } => children.iter().all(block_supported), - Block::List { items, .. } => items.iter().all(|group| group.iter().all(block_supported)), - _ => true, - } +/// 支持集递归判定。S2/S3 裁定:引用折叠与 flex 表格的渲染逻辑本就住在 +/// 渲染内核(render_block 递归全类型),宿主路径与旧路径共用同一实现—— +/// e2e(smoke 含 Quote、table_and_link 含 colspan 比例断言)裁决通过后 +/// 全量放开。保留判定函数为新块类型留回落机制。 +fn block_supported(_block: &Block) -> bool { + true } /// 文档是否可走 MailView 路径(全部块类型已迁移;空文档不值得建宿主)。 From 3ee68b58b95f9ebaefe8737f18c59d4aba6b87a0 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 02:19:20 +0800 Subject: [PATCH 05/20] =?UTF-8?q?docs(plans):=20MailTextView=20=E5=8F=AF?= =?UTF-8?q?=E8=A1=8C=E6=80=A7=E6=96=87=E6=A1=A3=E8=BF=BD=E5=8A=A0=E5=AE=9E?= =?UTF-8?q?=E6=96=BD=E7=BB=93=E8=AE=BA=E7=AB=A0=EF=BC=88=E6=B7=B7=E5=90=88?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E5=9D=97=E6=9E=B6=E6=9E=84=E8=90=BD?= =?UTF-8?q?=E5=9C=B0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-11-16-mailtextview-feasibility.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/plans/2026-11-16-mailtextview-feasibility.md b/docs/plans/2026-11-16-mailtextview-feasibility.md index 83b588f1..38493f02 100644 --- a/docs/plans/2026-11-16-mailtextview-feasibility.md +++ b/docs/plans/2026-11-16-mailtextview-feasibility.md @@ -105,3 +105,26 @@ crates/postium-ui/src/views/mail_text_view.rs(新文件,约 900-1200 行) `on_link_click`(链接点击回调)。缺的仍是 IR 注入与富样式 run。若将来走 TextView 路线,正确姿势是 fork/上游扩展其 run 注入,而非 `html()` 直喂 原文——即 P1 自研 MailTextView 的理由依旧成立。 + +## 七、实施结论(2026-11-17,feat/mailview-renderer 已落地) + +§六的分析在 0.10 复核后被实施推翻并升级为**混合自定义块架构**——TextView +当块流宿主,全部视觉与交互由自有渲染内核接管: + +- **补丁**(spartajet/gpui-kit `mailview-ext`,上游 PR #4005):新增 + `html_block_parser` / `html_block_renderer`(对称复制 markdown 已有模式) + + `html_with_extensions`(扩展参与首次解析,免二次重解析/首帧闪)+ 形状 + 比较放宽(每帧重建闭包零重解析)。上游 1735 测试零扰动。 +- **数据通道**:IR 顶层块 → `serialize_marker_html` 索引占位 + (`
`)→ 认领解析器 → 自定义块 → 块渲染器回读 IR。 + 正文内容不进标记 HTML——绕开 §六"绕过 sanitize"论据(内容只走 IR), + 富样式/表格/折叠零降级(推翻 §六论据 ③ 的取舍前提)。 +- **路由**:email_detail.html_body 分流,全类型已迁入(S2/S3 放开), + e2e 66 项 × 3 并发模式全绿裁决(含 aliyun 真实模板、colspan 比例、 + 引用折叠、图片门控)。 +- **状态**:TextViewState 按 (email_id, content hash) 缓存于 DetailStore + (容量 8,深浅通道共用——标记与通道无关)。 +- **遗留 v2 项**:scrollable 虚拟滚动(需预计算划选组表配套)、 + `link_tooltip` 悬停反钓鱼、上游 PR 合入后移除 [patch]。 + +§五的 P0(右键菜单/图片另存为)与本路线正交,仍待立项。 From b3c62c1338d52a4eeadaae9a85084f6383eac013 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 19:05:24 +0800 Subject: [PATCH 06/20] =?UTF-8?q?docs(ui):=20=E4=BF=AE=E6=AD=A3=20html=5Fb?= =?UTF-8?q?ody=20=E8=B7=AF=E7=94=B1=E6=B3=A8=E9=87=8A=E2=80=94=E2=80=94S2/?= =?UTF-8?q?S3=20=E5=90=8E=E5=85=A8=E9=87=8F=E8=B5=B0=20MailView=EF=BC=8C?= =?UTF-8?q?=E6=97=A7=E8=B7=AF=E5=BE=84=E4=BB=85=20e2e=20=E4=BF=9D=E7=95=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/postium-ui/src/views/email_detail.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/postium-ui/src/views/email_detail.rs b/crates/postium-ui/src/views/email_detail.rs index 62316432..c589f484 100644 --- a/crates/postium-ui/src/views/email_detail.rs +++ b/crates/postium-ui/src/views/email_detail.rs @@ -499,9 +499,10 @@ fn html_body( ) as std::sync::Arc; let quotes = crate::views::email_html::QuoteFold { expanded, on_toggle }; - // 路由(S1 渐进切换):全部块类型已迁移 → MailView(TextView 宿主 + 自有 - // 块渲染器,mail_view.rs);含 Table/Quote(S2/S3 迁入)→ 旧路径整篇渲染, - // 行为零变。两路径共用同一渲染内核与探针键。 + // 路由(S2/S3 已全量迁入):可解析文档 → MailView(TextView 宿主 + 自有 + // 块渲染器,mail_view.rs——富样式/表格/折叠/图片门控零降级);空文档/ + // 管线超限由上游分支走纯文本兜底。旧 render_html_document 仅 e2e 探针 + // 直驱内核在用(回归基线)。 let el = if crate::views::mail_view::supported(&doc) { let state = store.update(cx, |store, cx| { store.mail_text_view_state(email_id, html, &doc, cx) From 73444f5dab486fe552bb4734817db5be05641a94 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 19:52:40 +0800 Subject: [PATCH 07/20] =?UTF-8?q?feat(mailview):=20=E6=AD=A3=E6=96=87?= =?UTF-8?q?=E5=8F=B3=E9=94=AE=E8=8F=9C=E5=8D=95=E2=80=94=E2=80=94=E6=96=87?= =?UTF-8?q?=E6=9C=AC=EF=BC=88=E5=A4=8D=E5=88=B6/=E5=85=A8=E9=80=89?= =?UTF-8?q?=EF=BC=89=E3=80=81=E9=93=BE=E6=8E=A5=EF=BC=88=E6=89=93=E5=BC=80?= =?UTF-8?q?/=E5=A4=8D=E5=88=B6=E9=93=BE=E6=8E=A5=E5=9C=B0=E5=9D=80?= =?UTF-8?q?=EF=BC=89=E3=80=81=E5=9B=BE=E7=89=87=EF=BC=88=E5=A4=8D=E5=88=B6?= =?UTF-8?q?=E5=9B=BE=E7=89=87/=E5=8F=A6=E5=AD=98=E4=B8=BA=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P0 落地(可行性文档 §4/§5):菜单 UI 复用 ContextMenuExt(email_list 同款,右键/长按/定位/消失全自动);命中上下文经 HtmlSelection.right_hit 跨帧传递(右键按下由 SelectableText Right 分支写入,hover 即写防陈旧命中,左键按下失效,右键不破坏选区——浏览器语义);新增全选(select_all 跨组锚点语义)。 图片字节三源归一:DataUri 原始字节直通(mime→格式/扩展名);Cid/Remote 经 RenderImage BGRA→RGBA→PNG 重编码(image crate png feature 已带);另存为全流程后台线程(rfd 对话框+编码+写盘,toast 全局 channel 线程安全),文件名 alt 净化(Windows 保留字符+限长)。 e2e 五项:剪贴板写入/跨组全选/三态菜单构建(PopupMenu::build 直构)/右键不破坏选区+链接命中记录/PNG 编码往返与文件名净化。73 测试×2 并发模式全绿,工作区 23 套件全绿。 --- ...ss_9c64d9b8-6f37-4f93-a431-49fa2190b517.md | 111 +++---- crates/postium-ui/src/e2e_mail_menu_tests.rs | 260 ++++++++++++++++ crates/postium-ui/src/i18n_tables.rs | 20 ++ crates/postium-ui/src/main.rs | 2 + crates/postium-ui/src/views/email_html.rs | 282 +++++++++++++++++- crates/postium-ui/src/views/html_selection.rs | 81 +++++ 6 files changed, 674 insertions(+), 82 deletions(-) create mode 100644 crates/postium-ui/src/e2e_mail_menu_tests.rs diff --git a/.zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md b/.zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md index f0939c94..d0684334 100644 --- a/.zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md +++ b/.zcode/plans/plan-sess_9c64d9b8-6f37-4f93-a431-49fa2190b517.md @@ -1,85 +1,58 @@ -# MailView 实施计划:邮件正文渲染全面迁入 gpui-kit TextView(fork 补丁路线) +# MailView 右键菜单:文本 / 链接 / 图片 ## Context -当前邮件正文 = `postium-html`(sanitize→IR)→ `email_html.rs` 递归构建 GPUI div 树(1638 行)。痛点:每帧整树重建、无虚拟滚动、文本组间无真行内混排。gpui-kit 0.10(2026-11-16 发布)的 TextView 提供块流编排、ListState 虚拟滚动、保留态 TextViewState,但其原生 html 管线无富样式 run 注入(文字色/字号丢失)、TableCell 无 colspan。 +MailView(TextView 宿主 + 自有渲染内核)已接管正文渲染。本任务落地可行性文档 §5 的 P0 项:正文内右键上下文菜单——**文本**(复制/全选)、**链接**(打开/复制链接地址)、**图片**(复制图片/另存为)。当前正文右键无任何响应;列表行已有右键菜单先例(email_list.rs → gpui-kit `ContextMenuExt`),本任务复用同一基础设施与交互语言。 -**用户决策**:① 全量 S0–S3;② 文本渲染与表格同采用自定义接管——不牺牲颜色/字号保真;③ fork 建公开仓库 spartajet/gpui-kit。 +## 架构决策(基于侦察证据) -**架构定案(自定义块接管)**:MailView = Entity 包装 TextViewState;IR 序列化为**标记 HTML**(每块一个索引占位元素);经 fork 补丁的 `html_block_parser` 把每个块认领为 `MarkdownNode{name:"mail-block", data:块索引}`;`html_block_renderer("mail-block")` 分派到我们自己的渲染器(从 email_html.rs 平移)。TextView 只当**块流宿主**(编排/虚拟滚动/保留态/无障碍文本管线),全部视觉与交互由我们现有代码渲染——**保真度零损失,探针体系原样存活**。未迁移块类型的文档自动回落旧渲染器(渐进切换)。 +1. **菜单 UI**:复用 `ContextMenuExt::context_menu(builder)`(gpui-component 0.10 `menu/context_menu.rs`)——右键/触屏长按检测、anchored+deferred 定位、焦点恢复、点外消失全自动。builder 无命中参数 → 命中上下文须**预先捕获**。 +2. **命中上下文跨帧载体**:builder 在 `window.defer` 的下一帧执行,`RenderCtx` 每帧重建不能承载 → 写入 **HtmlSelection**(每邮件交互状态,EmailDetailView 持有、全链路穿透、生命周期正确):`SelState.right_hit: Option`——右键按下时由 SelectableText 写入(None=纯文本命中),左键按下时清除(浏览器语义:右键不破坏现有选区,左键开始新选区时失效)。 +3. **文本组挂菜单**:`flush_text_group` 产出的 div 直接 `.context_menu(...)` 包裹(email_list 同款无 id 模式,同调用点共享状态 + hovered 守卫只让被按压的组弹菜单)。SelectableText 现有 MouseDown 监听加 **Right 分支**:`index_for_position` → `ranges.position(contains(ix))` 命中链接则 `selection.set_right_hit(Some(url))`,否则 `set_right_hit(None)`——即游标样式切换(email_html.rs:925)的既有判定式复用。 +4. **图片挂菜单**:`render_loaded_image` 的 `img()` 包一层 `div().child(img).context_menu(builder)`——闭包在元素构造期直接捕获该图数据(无需命中检测),一处包裹覆盖块级/行内/表格内全部图片路径(共用此函数)。被拦截的远程图**占位框不挂菜单**(已有「加载图片」条,避免双入口)。 +5. **图片字节三源归一**(新 helper `image_payload`): + - `ImageRef::DataUri { mime, bytes }` → 原始字节 + 按 mime 映射 `ImageFormat`(零重编码) + - Cid / Remote → 手头只有 `Arc`(BGRA,`as_bytes(0)`,gpui-pre assets.rs:72)→ BGRA→RGBA 交换 → `image` crate PNG 编码(png feature 已启用) + - 产出 `(ImageFormat, Vec)`:剪贴板走 `ClipboardItem::new_image(&Image::from_bytes(fmt, bytes))`(platform.rs:3180/3447);另存为直接写字节(DataUri 按 mime 定扩展名,重编码路径恒 .png,文件名 = alt 文本净化 || "image") +6. **另存为流程**:沿用 attachments 先例(email_detail.rs:270-287)——`std::thread::spawn` 里 `rfd::FileDialog::set_file_name().save_file()` → 结果经 channel 回 `cx.spawn` → 后台线程写文件 → toast 成功/失败。 -**前置条件**:PR #12(enhanced-textview→main)合并后,从 main 拉 `feat/mailview-renderer` 分支。 +## 菜单项(沿用已批准的可行性文档 §4 规格) ---- +| 目标 | 菜单项 | 行为 | +|---|---|---| +| 文本 | 复制(选中存在时可用,否则禁用) | `selection.selected_text()` → `write_to_clipboard(new_string)` + toast(复用 `email.selectionCopied` 流程) | +| 文本 | 全选 | 新 `HtmlSelection::select_all()`(anchor=(0,0) → head=(末组,末长))+ `window.refresh()` | +| 链接 | 打开链接 | 命中 URL → 复用 `on_link` 回调(=open_safe_url) | +| 链接 | 复制链接地址 | `SafeUrl` 内串 → 剪贴板 + toast | +| 图片 | 复制图片 | `image_payload` → `ClipboardItem::new_image` + toast | +| 图片 | 另存为… | rfd 流程(上文 6) | -## 阶段计划 +链接命中时优先链接菜单(不吃文本菜单);图标用 IconName 既有项(ExternalLink/Link/Copy/Image/Save)。 -### S0 升级 gpui-kit 0.8 → 0.10(~0.5 天) -- `crates/postium-ui/Cargo.toml`:`gpui-kit`/`gpui-kit-assets` 0.8→0.10,dev-dep `gpui-pre` 0.3.9→0.3.12;postium-editor 同步。 -- **先验证风险点**:`gpui-kit-markdown-editor`(git wabzqem,rev 31608fa,postium-editor 依赖)是否兼容 0.10——查其仓库有无 0.10 分支;不兼容则给该依赖也走 [patch] 或临时固定。 -- 全量 `cargo build --workspace && cargo test --workspace`(CI 门禁=windows+ubuntu 双平台同款命令)。已知升级面:26 处 `use gpui_kit::*` glob、e2e_tests.rs 33 个 `#[gpui_pre::test]`。关键 API(shape_text/paint_image/text_system)已验证 0.3.9→0.3.12 签名稳定。 -- 产出:0.10 vanilla 全绿提交。 +## 修改清单 -### S0.5 fork + 补丁(~1 天) -- `gh repo fork longbridge/gpui-kit --clone`(spartajet);从 `v0.10.0` tag 拉 `mailview-ext` 分支,**单 commit** 补丁: - - `text_view.rs`:`pub fn html_block_parser(F: Fn(&RcDom Node, attrs) -> Option)` + `pub fn html_block_renderer(name, F: Fn(&MarkdownNode, &mut Window, &mut App) -> E)`——逐行对称复制 markdown 已有模式(markdown_ext.rs 的 MarkdownExtensions 容器复用/平行)。 - - `format/html.rs`:块级 parse 循环(`local_name!("table")` 分支附近)前插扩展询问点,经 NodeContext 线程穿透(仿 image_source 的传递方式)。 - - 补丁**零业务代码**;`MarkdownNode::new(name, text, data)` 已是 pub(markdown_ext.rs:121)。 -- 推送 fork;根 `Cargo.toml` 加 `[patch.crates-io] gpui-base = { git = "https://github.com/spartajet/gpui-kit", branch = "mailview-ext" }`;全量测试。 -- 同步向上游开 **draft PR**(有 markdown 对称先例,接收概率中高;合入即删 patch 两行)。 - -### S1 序列化器 + MailView 骨架 + 简单块接管(~2-3 天) -- **postium-html 新增 `src/serialize.rs`**:`serialize_marker_html(blocks: &[Block]) -> String`——每块产 `
`(表格/引用等一律占位,内容不进 HTML);纯函数,复用现有 10 组 fixture 做序列化快照测试(沿 `UPDATE_SNAPSHOTS` 模式)。S1 内先用单测验证 html5ever RcDom 保真回读 `data-mb` 属性(若属性被吞,退路:`
` 编码)。 -- **postium-ui 新增 `views/mail_view.rs`**: - - `MailView` Entity:持 `Entity`(`TextView::html(id, marker_html)` + `html_block_parser/html_block_renderer` 挂接);parser 闭包捕获 `Arc>`(BlockSpec = IR Block 克隆),渲染器经 `WeakEntity` 每帧读取 ImageCtx/QuoteFold/HtmlSelection/theme 快照。 - - `stores/detail.rs` `CachedDoc` 扩展:序列化串 + `BlockSpec` 表 + `Entity` 惰性缓存(浅/深双通道沿 dark_doc OnceLock 模式)。 - - 首批块渲染器(从 email_html.rs 平移):Hr(389)、Heading、块级 Image(1027-1120 的三源分发+占位)、纯文本 Paragraph(725-804 文本组 + 807-980 SelectableText 原样复用)。 - - **渐进回落规则**:文档含未迁移块类型 → 整篇走旧 `render_html_document`(S1 末即在 email_detail.rs:502 切换主入口,fixture 覆盖的简单文档即刻走新路径)。 - - 探针:块渲染器内继续调 `when_probe`(html-root/html-hr/html-img/html-txt-*)——e2e 断言大面积存活。 - -### S2 富文本 runs + 链接 + 划选 + 引用折叠(~3-4 天) -- 富样式 runs(颜色/字号/粗斜删除线)进文本块渲染器:现有 InlineStyle→TextRun 映射代码平移,**保真不降级**(用户决策②)。 -- 链接:SelectableText 命中→`on_link`→`open_safe_url` 语义不变;`link_tooltip`(0.10 新 API)加悬停真实 URL 预览(反钓鱼,增量功能)。 -- 划选:HtmlSelection 保留,但**组注册表改为文档级预计算**(MailView 构建时由 IR 一次性算出 groups Vec,渲染期只报索引)——同时修掉现每帧注册的脆弱性,并为虚拟化下跨块选择铺路;Ctrl+C/Esc 沿 `EmailHtmlBody` key_context 动作不变。TextView 自身 `selectable(false)`(避免双选中系统)。 -- 引用折叠:QuoteFold/`DetailStore.quote_expanded`/`toggle_quote` 状态机不动(detail.rs:86-94),引用块渲染器平移 email_html.rs:310-370 的折叠 UI。 -- 图片门控:ImageCtx 三源缓存、`allow_remote_images` 流程、load-images 条(email_detail.rs:901-931)、`collect_remote_image_urls` 全部不动——我们自己的 img() 元素渲染,**不需要 image_source resolver**(无默认拉取隐私风险,因为图片不出现在序列化 HTML 里)。 - -### S3 MailTableCell 表格接管(~2-3 天) -- 新增 `views/mail_table.rs`:flex 表格渲染平移(email_html.rs:440-474 的 colspan→grow/width→basis 映射 + 已归一化网格的边框/列宽消费);嵌套表格/单元格内任意块递归复用其他块渲染器。 -- 表格操作:单元格右键/悬停菜单(复制单元格文本、整表转制表符文本进剪贴板);`MarkdownNode.text` 填表格纯文本表示 → TextView 全选/复制管线自动含表格。 -- e2e 的 colspan 宽度比例断言(e2e_tests.rs:2261-2279)作为迁移验收。 - -### S4 收尾切换与退役(~1-2 天) -- 回落规则删除(全类型已迁移);滚动决策:v1 `scrollable(false)`(外层 overflow_y_scroll 不动、行为零变),v2 项:单 TextView `scrollable(true)` 启用 ListState 虚拟滚动(长邮件每帧收益),需配合预计算组表的跨块选择验证。 -- e2e 全量过一遍并修余量(滚动容器语义、status bar 测试 2637);删除 email_html.rs 中已无调用方的死代码(预计 SelectableText 保留、整树递归入口退役);文档更新:MECHANICS.md、README、`docs/plans/2026-11-16-mailtextview-feasibility.md` 追加实施结论章。 -- 提交拆分:每阶段独立 commit,S0/S0.5 各自成 PR-able。 - ---- - -## 关键文件清单 - -| 动作 | 文件 | +| 文件 | 改动 | |---|---| -| 新增 | `crates/postium-html/src/serialize.rs`(+快照测试)、`crates/postium-ui/src/views/mail_view.rs`、`crates/postium-ui/src/views/mail_table.rs` | -| 修改 | `crates/postium-ui/src/views/email_detail.rs`(html_body 切换 MailView)、`crates/postium-ui/src/stores/detail.rs`(CachedDoc 扩展)、`crates/postium-ui/src/views/email_html.rs`(改造为块渲染器库,渐进退役)、`crates/postium-ui/src/e2e_tests.rs`(HtmlRenderProbe 驱动 MailView + 余量断言修正)、根 `Cargo.toml`([patch.crates-io])、`crates/postium-ui/Cargo.toml` + `crates/postium-editor/Cargo.toml`(0.10 版本) | -| 复用不动 | `ImageCtx`/`decode_render_image_cached`、`HtmlSelection`+`SelectableText`、`QuoteFold`/`quote_expanded`、`allow_remote_images` 状态机、`collect_remote_image_urls`、`adapt_document` 深色管线、10 组 fixture 快照、CI 门禁 | - -## 验证方案 +| `crates/postium-ui/src/views/html_selection.rs` | `SelState.right_hit: Option` + `set_right_hit` / `right_click_link()` 读写口;`select_all()`(组注册表末组末偏移为 head);左键 `on_down` 清除 right_hit | +| `crates/postium-ui/src/views/email_html.rs` | ① SelectableText MouseDown 加 Right 分支(命中解析 + set_right_hit,不清选区、不 stop_propagation——放行给 ContextMenu 包裹层开菜单);② `flush_text_group` 文本 div `.context_menu(文本菜单 builder)`(闭包捕获 selection/on_link,读 `right_click_link()` 分流链接/文本菜单);③ `render_loaded_image` 包裹 div + 图片菜单 builder(捕获 image_payload 输入 + alt);④ helpers:`image_payload() -> Option<(ImageFormat, Vec)>`、`save_image_to_file()`(rfd+写盘+toast)、`SafeUrl` 显示串 helper | +| `crates/postium-ui/src/i18n_tables.rs` | 新键(ZH+EN 成对,i18n 测试强制同键集):mailMenu.{openLink, copyLink, copyImage, saveImageAs, copy, selectAll, linkCopied, imageCopied, imageSaved, imageSaveFailed} | +| `crates/postium-ui/src/e2e_tests.rs`(或新文件) | 见验证 | -1. **每阶段**:`cargo build --workspace && cargo test --workspace`(= CI test.yml 门禁,双平台)。 -2. **postium-html**:序列化快照测试(marker HTML 字节级对比,10 fixture 全覆盖)。 -3. **e2e**(cargo test 内含,33 个 GPUI 测试):重点集——`html_render_smoke`(1962)、`html_render_table_and_link`(2112, colspan 比例=表格迁移验收)、`html_images_blocked_until_allowed`(2828, 门控回归)、`html_email_display_keeps_status_bar`(2637, 布局回归)、`html_cache_same_id_new_content_renders`(2542, 缓存键回归)。 -4. **手工冒烟**:真实账户打开典型邮件 ×10 fixture + aliyun 模板——深/浅色切换、引用折叠、图片拦截→放行→加载条消失、链接点击/悬停预览、Ctrl+C 划选复制、长邮件(long-zh-plain)滚动流畅度。 -5. **补丁回归**:S0.5 后对比 vanilla 0.10 与 patch 版跑同一测试集,确认补丁零行为扰动。 +约 350–450 行。旧路径 `render_html_document`(e2e 探针直驱)经同一 flush_text_group/render_loaded_image 自动获得同款菜单——两路径行为一致。 -## 风险与对策 +## 验证 -- **markdown-editor git 依赖不兼容 0.10**(S0 卡点):查 wabzqem 仓库 0.10 支持;否则同法 [patch] 或临时降级该组件功能。 -- **补丁 rebase**:上游约每周发版;单 commit 纪律 + 插入点固定在 html.rs 块级 match,冲突面最小化;上游 PR 合入后移除 patch。 -- **data-mb 属性被 html5ever 规范化**:S1 第一件事写回读单测验证;退路 `` 编码。 -- **虚拟化×跨块选择**:v1 不开 scrollable 规避;预计算组表已为 v2 铺路。 -- **上游拒收 PR**:长期养单 commit 小 fork(已接受)。 +1. **单元**:`safeurl` 显示串;`image_payload` 对合成 RenderImage(synthetic_render_image 已有)产出非空 PNG 字节且可被 `image::load_from_memory` 解回。 +2. **e2e**(沿 email_list 先例:PopupMenu 弹出属渲染层,动作走直测): + - `mail_menu_copy_link_writes_clipboard`:构造含链接文档 → 直调复制动作 helper → `cx.read_from_clipboard` 断言 URL 文本; + - `mail_menu_select_all_selects_across_groups`:多组文档 → `select_all()` + 刷新 → `selected_text()` 含全部组文本、Ctrl+C 动作后剪贴板一致; + - `mail_menu_builders_content`:右键命中链接态 vs 文本态分别构建菜单 → `PopupMenu::is_empty() == false`(菜单构建路径绿)。 + - 右键交互冒烟:`simulate_event(MouseDownEvent{button: Right, ..})` 打在链接文本 bounds 上不 panic、选区不被破坏(回归护栏)。 +3. **全量**:`cargo test --workspace`(CI 同款门禁)。 +4. **手工**:真机打开邮件——右键纯文本/链接/图片各出对应菜单;复制项落剪贴板可粘贴验证;另存为对话框出正确默认文件名;Esc/点外关菜单;右键不破坏既有划选。 -## 工作量 +## 明确不做(记录在案) -S0 0.5d + S0.5 1d + S1 2-3d + S2 3-4d + S3 2-3d + S4 1-2d ≈ **10-13 个工作日**。 \ No newline at end of file +- 占位框(被拦截远程图)不挂菜单——「加载图片」条已是唯一入口 +- 词级"复制光标处单词"(HtmlSelection 无词边界 API,浏览器亦无此默认项) +- 触屏长按菜单——ContextMenuExt 自带,但不在本任务测试矩阵 \ No newline at end of file diff --git a/crates/postium-ui/src/e2e_mail_menu_tests.rs b/crates/postium-ui/src/e2e_mail_menu_tests.rs new file mode 100644 index 00000000..2990651a --- /dev/null +++ b/crates/postium-ui/src/e2e_mail_menu_tests.rs @@ -0,0 +1,260 @@ +//! 正文右键菜单(P0)e2e:文本(复制/全选)、链接(打开/复制链接地址)、 +//! 图片(复制图片/另存为)。 +//! +//! 沿 email_list 先例(PopupMenu 弹出属渲染层,动作走直测):菜单项动作 +//! 以 helper 直调断言端到端效果(剪贴板/选区);菜单构建路径经 +//! `PopupMenu::build` 直构断言 `is_empty`;右键交互冒烟守卫「不破坏既有 +//! 选区 + 链接命中记录」。 + +use std::sync::Arc; + +use gpui_kit::component::menu::PopupMenu; +use gpui_kit::{div, App, AppContext as _, IntoElement, ParentElement, Render, Styled, px}; + +use postium_html::{Align, Block, BlockStyle, HtmlDocument, InlineRun, InlineStyle, SafeUrl}; + +use crate::views::email_html::{self, ImageCtx}; +use crate::views::html_selection::HtmlSelection; + +fn text(t: &str) -> InlineRun { + InlineRun::Text { + text: t.into(), + style: InlineStyle::default(), + } +} + +/// 两段落文档(MailView 支持集内),第二组带链接。 +fn link_doc() -> HtmlDocument { + HtmlDocument { + blocks: vec![ + Block::Paragraph { + style: BlockStyle::default(), + runs: vec![text("MenuProbeFirst")], + align: Align::Left, + }, + Block::Paragraph { + style: BlockStyle::default(), + runs: vec![ + text("前缀"), + InlineRun::Link { + href: SafeUrl::Http("https://example.com/menu".into()), + runs: vec![text("MenuLinkText")], + }, + ], + align: Align::Left, + }, + ], + } +} + +/// 渲染宿主:驱动渲染内核注册文本组(右键命中/全选动作作用于注册表)。 +struct RenderProbe { + doc: HtmlDocument, + selection: HtmlSelection, +} + +impl Render for RenderProbe { + fn render(&mut self, _: &mut gpui_kit::Window, cx: &mut gpui_kit::Context) -> impl IntoElement { + let el = email_html::render_html_document( + &self.doc, + false, + ImageCtx::default(), + self.selection.clone(), + None, + |_: &SafeUrl| {}, + cx, + ); + div().w(px(400.)).h(px(400.)).child(el) + } +} + +#[gpui_pre::test] +fn mail_menu_copy_link_writes_clipboard(cx: &mut gpui_pre::TestAppContext) { + // SafeUrl 显示串(菜单「复制链接地址」的剪贴板载荷) + assert_eq!( + email_html::safe_url_string(&SafeUrl::Http("https://example.com/menu".into())), + "https://example.com/menu" + ); + assert_eq!( + email_html::safe_url_string(&SafeUrl::Mailto("a@b.test".into())), + "a@b.test" + ); + // 剪贴板写入(on_click 同款路径) + cx.update(|app: &mut App| { + app.write_to_clipboard(gpui_kit::ClipboardItem::new_string( + email_html::safe_url_string(&SafeUrl::Http("https://example.com/menu".into())), + )); + }); + let read = cx.update(|app: &mut App| app.read_from_clipboard().and_then(|i| i.text())); + assert_eq!(read.as_deref(), Some("https://example.com/menu")); +} + +#[gpui_pre::test] +fn mail_menu_select_all_selects_across_groups(cx: &mut gpui_pre::TestAppContext) { + let selection = HtmlSelection::default(); + let sel = selection.clone(); + let (_root, cx) = cx.add_window_view(|_, cx| { + crate::e2e_tests::setup(cx); + RenderProbe { + doc: link_doc(), + selection: sel, + } + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + // 组注册表应经两帧渲染填充(组文本探针可见) + assert!( + cx.debug_bounds("html-txt-MenuProbeFirst").is_some(), + "文本组应已渲染并注册" + ); + + // 全选动作(菜单项 on_click 同款)覆盖全部组 + selection.select_all(); + let selected = selection.selected_text().expect("全选应有选区"); + assert!( + selected.contains("MenuProbeFirst") && selected.contains("MenuLinkText"), + "全选应覆盖两组文本,实际 {selected:?}" + ); + // 复制动作载荷一致 + let text = selection.selected_text().unwrap(); + assert_eq!(text.lines().count(), 2, "跨组拼接应以换行分隔"); +} + +#[gpui_pre::test] +fn mail_menu_builders_content(cx: &mut gpui_pre::TestAppContext) { + // 菜单构建路径绿:链接命中态、纯文本态(有/无选区)与图片菜单均产出 + // 非空菜单(经 PopupMenu::build 直构,与挂接路径同工厂)。 + let (_root, cx) = cx.add_window_view(|_, cx| { + crate::e2e_tests::setup(cx); + struct Host; + impl Render for Host { + fn render(&mut self, _: &mut gpui_kit::Window, _: &mut gpui_kit::Context) -> impl IntoElement { + div().w(px(100.)).h(px(100.)) + } + } + Host + }); + let selection = HtmlSelection::default(); + + // 链接命中态 + selection.on_right_down(Some(SafeUrl::Http("https://example.com/menu".into()))); + let builder = email_html::build_text_menu(selection.clone(), Arc::new(|_: &SafeUrl| {})); + let menu = cx.update(|window: &mut gpui_kit::Window, app: &mut App| { + PopupMenu::build(window, app, |menu, w, c| builder(menu, w, c)) + }); + cx.update(|_, cx| { + assert!(!menu.read(cx).is_empty(), "链接菜单应有菜单项"); + }); + + // 纯文本态(无选区 → 复制项禁用但存在,菜单非空) + selection.on_right_down(None); + let builder = email_html::build_text_menu(selection.clone(), Arc::new(|_: &SafeUrl| {})); + let menu = cx.update(|window: &mut gpui_kit::Window, app: &mut App| { + PopupMenu::build(window, app, |menu, w, c| builder(menu, w, c)) + }); + cx.update(|_, cx| { + assert!(!menu.read(cx).is_empty(), "文本菜单应有菜单项"); + }); + + // 图片菜单(Rendered 载荷) + let rendered = Arc::new(gpui_kit::RenderImage::new(vec![image::Frame::new( + image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])), + )])); + let payload = email_html::image_payload_for(&postium_html::ImageRef::Invalid, &rendered); + let menu = cx.update(|window: &mut gpui_kit::Window, app: &mut App| { + PopupMenu::build(window, app, |menu, _w, _c| { + email_html::build_image_menu(menu, payload.clone(), "alt 文本".into()) + }) + }); + cx.update(|_, cx| { + assert!(!menu.read(cx).is_empty(), "图片菜单应有菜单项"); + }); +} + +#[gpui_pre::test] +fn mail_menu_right_click_preserves_selection(cx: &mut gpui_pre::TestAppContext) { + let selection = HtmlSelection::default(); + let sel = selection.clone(); + let (_root, cx) = cx.add_window_view(|_, cx| { + crate::e2e_tests::setup(cx); + RenderProbe { + doc: link_doc(), + selection: sel, + } + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + // 建立选区(全选语义;拖选路径由既有 e2e 覆盖) + selection.select_all(); + assert!(selection.is_selecting()); + + // 右键打在链接文本 bounds 上:不 panic、不破坏选区、记录链接命中 + let bounds = cx + .debug_bounds("html-txt-前缀MenuLinkText") + .expect("链接文本组探针应存在"); + // 组 div 拉满宽(w_full)而文本仅占左段:取左端 40px(前缀 CJK 约 + // 28px 之后即 MenuLinkText 链接区间)。 + let link_point = gpui_pre::point(bounds.left() + px(40.), bounds.center().y); + cx.simulate_event(gpui_pre::MouseDownEvent { + button: gpui_kit::MouseButton::Right, + position: link_point, + modifiers: gpui_pre::Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + selection.is_selecting(), + "右键不得破坏既有选区(浏览器语义)" + ); + assert_eq!( + selection.right_click_link(), + Some(SafeUrl::Http("https://example.com/menu".into())), + "右键在链接文本上应记录链接命中" + ); +} + +/// PNG 重编码回路(复制图片/另存为的字节通道)+ 文件名净化。 +#[gpui_pre::test] +fn mail_menu_image_bytes_and_file_name(cx: &mut gpui_pre::TestAppContext) { + cx.update(crate::e2e_tests::setup); + let (w, h) = (12u32, 8u32); + // 管线存储恒为 BGRA(decode_render_image 期交换):合成图按同口径预交换 + let mut buffer = image::RgbaImage::from_pixel(w, h, image::Rgba([10, 20, 30, 255])); + for p in buffer.pixels_mut() { + p.0.swap(0, 2); + } + let rendered = Arc::new(gpui_kit::RenderImage::new(vec![image::Frame::new(buffer)])); + + cx.update(|_app: &mut App| { + let png = email_html::render_image_png_bytes(&rendered).expect("PNG 编码应成功"); + let decoded = image::load_from_memory(&png).expect("PNG 应可解回"); + assert_eq!((decoded.width(), decoded.height()), (w, h)); + // 首像素 RGB 保真(BGRA→RGBA 交换正确性) + let rgba = decoded.to_rgba8(); + let p = rgba.get_pixel(0, 0); + assert_eq!((p[0], p[1], p[2]), (10, 20, 30)); + }); + + // 文件名净化:控制字符/路径分隔符替换、空 alt 兜底、扩展名按载荷 + let rendered_payload = + email_html::image_payload_for(&postium_html::ImageRef::Invalid, &rendered); + let name = email_html::image_save_file_name("lo go:q", &rendered_payload); + assert!(name.ends_with(".png"), "重编码载荷恒 .png:{name}"); + assert!(!name.contains('<') && !name.contains(':') && !name.contains('/')); + assert_eq!( + email_html::image_save_file_name("", &rendered_payload), + "image.png" + ); + // DataUri 直通载荷按 mime 定扩展名 + let raw = postium_html::ImageRef::DataUri { + mime: "image/jpeg".into(), + bytes: Arc::from(vec![1u8, 2, 3]), + }; + let raw_payload = email_html::image_payload_for(&raw, &rendered); + assert_eq!(email_html::image_save_file_name("photo", &raw_payload), "photo.jpg"); +} diff --git a/crates/postium-ui/src/i18n_tables.rs b/crates/postium-ui/src/i18n_tables.rs index 0b5bf2c5..591eb2ca 100644 --- a/crates/postium-ui/src/i18n_tables.rs +++ b/crates/postium-ui/src/i18n_tables.rs @@ -78,6 +78,16 @@ pub static ZH: &[(&str, &str)] = &[ ("email.loadImages", "邮件含远程图片(可能泄露已读状态),点击加载"), ("email.alwaysLoadImages", "始终加载"), ("email.selectionCopied", "已复制所选内容"), + ("mailMenu.openLink", "打开链接"), + ("mailMenu.copyLink", "复制链接地址"), + ("mailMenu.copyImage", "复制图片"), + ("mailMenu.saveImageAs", "图片另存为…"), + ("mailMenu.copy", "复制"), + ("mailMenu.selectAll", "全选"), + ("mailMenu.linkCopied", "已复制链接地址"), + ("mailMenu.imageCopied", "已复制图片"), + ("mailMenu.imageSaved", "图片已保存"), + ("mailMenu.imageSaveFailed", "图片保存失败"), ("account.add", "添加账号"), ("account.edit", "编辑"), ("account.delete", "删除"), @@ -286,6 +296,16 @@ pub static EN: &[(&str, &str)] = &[ ("email.loadImages", "This email contains remote images (may leak read status), click to load"), ("email.alwaysLoadImages", "Always load"), ("email.selectionCopied", "Selection copied"), + ("mailMenu.openLink", "Open Link"), + ("mailMenu.copyLink", "Copy Link Address"), + ("mailMenu.copyImage", "Copy Image"), + ("mailMenu.saveImageAs", "Save Image As…"), + ("mailMenu.copy", "Copy"), + ("mailMenu.selectAll", "Select All"), + ("mailMenu.linkCopied", "Link address copied"), + ("mailMenu.imageCopied", "Image copied"), + ("mailMenu.imageSaved", "Image saved"), + ("mailMenu.imageSaveFailed", "Failed to save image"), ("account.add", "Add Account"), ("account.edit", "Edit"), ("account.delete", "Delete"), diff --git a/crates/postium-ui/src/main.rs b/crates/postium-ui/src/main.rs index b7521a9b..f708383a 100644 --- a/crates/postium-ui/src/main.rs +++ b/crates/postium-ui/src/main.rs @@ -14,6 +14,8 @@ mod tray; mod views; mod window_state; +#[cfg(test)] +mod e2e_mail_menu_tests; #[cfg(test)] mod e2e_mail_view_tests; #[cfg(test)] diff --git a/crates/postium-ui/src/views/email_html.rs b/crates/postium-ui/src/views/email_html.rs index 4a160dd8..e61471cb 100644 --- a/crates/postium-ui/src/views/email_html.rs +++ b/crates/postium-ui/src/views/email_html.rs @@ -26,21 +26,25 @@ use std::ops::Range; use std::rc::Rc; use std::sync::{Arc, Mutex}; +use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem}; use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ - AnyElement, App, CursorStyle, DispatchPhase, Element, ElementId, FontStyle, - FontWeight, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, - InteractiveElement as _, IntoElement, LayoutId, MouseButton, MouseDownEvent, - MouseMoveEvent, MouseUpEvent, ParentElement as _, RenderImage, SharedString, - StrikethroughStyle, Styled as _, StyledText, TextAlign, TextRun, UnderlineStyle, div, - font as base_font, img, px, relative, rgba, StatefulInteractiveElement as _, + AnyElement, App, ClipboardItem, CursorStyle, DispatchPhase, Element, ElementId, FontStyle, + FontWeight, GlobalElementId, Hitbox, HitboxBehavior, Hsla, Image, ImageFormat, + InspectorElementId, InteractiveElement as _, IntoElement, LayoutId, MouseButton, + MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, RenderImage, + SharedString, StrikethroughStyle, Styled as _, StyledText, TextAlign, TextRun, + UnderlineStyle, Window, div, font as base_font, img, px, relative, rgba, + StatefulInteractiveElement as _, }; +use gpui_kit_assets::IconName; use postium_html::{ Align, Block, BlockStyle, HtmlDocument, ImageRef, ImageStyle, InlineRun, InlineStyle, Rgba, SafeUrl, TableCell, TableRow, Width, }; +use crate::i18n::t; use crate::views::html_selection::HtmlSelection; /// 正文基础字号(px)。邮件作者未声明字号时的兜底。 @@ -793,7 +797,17 @@ fn flush_text_group( }); d.debug_selector(move || key) }; - els.push(d.into_any_element()); + // 右键菜单(P0):文本组挂 ContextMenu 包裹(无 id 模式——同调用点共享 + // 状态 + hovered 守卫只让被按压的组弹菜单,email_list 行菜单同款)。 + // 命中上下文由 SelectableText 的 Right 分支写入 selection.right_hit, + // 本 builder 在 defer 下一帧读。 + els.push( + d.context_menu(build_text_menu( + rcx.selection.clone(), + Arc::clone(&rcx.on_link), + )) + .into_any_element(), + ); } /// 选中区间切分 [`TextRun`]:交叠 run 拆为 前/选中/后 三段,选中段施加 @@ -949,6 +963,39 @@ impl Element for SelectableText { }, ); } + { + // 右键命中解析(右键菜单 P0):游标判定的同款 containment 检查 + // ——命中链接则记 URL(链接菜单),否则记纯文本(文本菜单)。 + // 不清选区、不 stop_propagation:放行给外层 ContextMenu 包裹 + // 层开菜单(包裹层自身只认 Right + hovered)。 + let hitbox = hitbox.clone(); + let layout = text_layout.clone(); + let selection = selection.clone(); + let ranges = ranges.clone(); + let urls = urls.clone(); + window.on_mouse_event( + move |event: &MouseDownEvent, phase, window: &mut gpui_kit::Window, _| { + if phase != DispatchPhase::Bubble + || event.button != MouseButton::Right + || !hitbox.is_hovered(window) + { + return; + } + // hover 即写命中:index 解析失败(组内边距/边缘)按 + // 纯文本处理——不写会让菜单读到陈旧命中。 + let link = layout + .index_for_position(event.position) + .ok() + .and_then(|ix| { + ranges + .iter() + .position(|r| r.contains(&ix)) + .and_then(|i| urls.get(i).cloned()) + }); + selection.on_right_down(link); + }, + ); + } { let hitbox = hitbox.clone(); let layout = text_layout.clone(); @@ -1074,19 +1121,23 @@ fn render_image_ref(src: &ImageRef, alt: &str, style: &ImageStyle, rcx: &RenderC ImageRef::Remote { .. } | ImageRef::Invalid => None, }; match resolved { - Some(img) => render_loaded_image(&img, style, rcx), + Some(img) => render_loaded_image(&img, src, alt, style), None => image_placeholder(style, alt, rcx), } } -/// 已解析图片 → GPUI [`img`] 元素(宽度取 style.width、高度取 style.height、 -/// max_width 钳制,与占位框同口径防布局跳动,spec §5)。 +/// 已解析图片 → GPUI [`img`] 元素 + 右键菜单包裹(宽度取 style.width、高度取 +/// style.height、max_width 钳制,与占位框同口径防布局跳动,spec §5;右键 +/// 菜单 P0)。菜单闭包只捕获廉价句柄(`Arc` / DataUri 字节 +/// `Arc`)——PNG 重编码留给点击时一次性执行,不进每帧渲染路径。 fn render_loaded_image( image: &Arc, + src: &ImageRef, + alt: &str, style: &ImageStyle, - rcx: &RenderCtx, ) -> AnyElement { - let _ = rcx; + let payload = image_payload_for(src, image); + let alt = alt.to_string(); // 尺寸样式直接落在 Img(Styled)上:无显式宽时保持图片固有尺寸。 let mut el = img(image.clone()).overflow_hidden(); match style.width { @@ -1105,7 +1156,11 @@ fn render_loaded_image( None => {} } // 已加载真图探针:e2e 断言「无真图渲染」的负向键(占位框为 html-img)。 - el.debug_selector(|| "html-img-loaded".to_string()) + div() + .child( + el.debug_selector(|| "html-img-loaded".to_string()), + ) + .context_menu(move |menu, _, _| build_image_menu(menu, payload.clone(), alt.clone())) .into_any_element() } @@ -1403,6 +1458,207 @@ pub(crate) trait ProbeExt: Sized { fn when_probe(self, selector: &str) -> Self; } +// --------------------------------------------------------------------------- +// 右键菜单(P0,可行性文档 §4/§5):文本(复制/全选)、链接(打开/复制 +// 链接地址)、图片(复制图片/另存为)。菜单 UI 走 gpui-kit ContextMenuExt +// (右键检测/定位/焦点恢复/点外消失全自动,email_list 同款);命中上下文 +// 经 HtmlSelection.right_hit 跨帧传递(菜单在 window.defer 下一帧构建)。 +// --------------------------------------------------------------------------- + +/// [`SafeUrl`] → 剪贴板/显示串(协议白名单后仅存内串)。 +pub(crate) fn safe_url_string(url: &SafeUrl) -> String { + match url { + SafeUrl::Http(u) | SafeUrl::Mailto(u) => u.clone(), + } +} + +/// 文本/链接右键菜单 builder(flush_text_group 的 context_menu 挂接)。 +/// 读 [`HtmlSelection::right_click_link`] 分流:链接命中 → 打开/复制链接; +/// 纯文本 → 复制(无选区禁用)/全选。构建发生在 defer 的下一帧,读的是 +/// 右键按下时写入的命中。 +pub(crate) fn build_text_menu( + selection: HtmlSelection, + on_link: Arc, +) -> impl Fn(PopupMenu, &mut Window, &mut gpui_kit::Context) -> PopupMenu + 'static { + move |menu, _window, _cx| match selection.right_click_link() { + Some(url) => { + let open_url = url.clone(); + let open_cb = Arc::clone(&on_link); + let copy_url = url.clone(); + menu.item( + PopupMenuItem::new(t("mailMenu.openLink")) + .icon(IconName::ExternalLink) + .on_click(move |_, _, _| open_cb(&open_url)), + ) + .item( + PopupMenuItem::new(t("mailMenu.copyLink")) + .icon(IconName::Link) + .on_click(move |_, _, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(safe_url_string( + ©_url, + ))); + crate::notify::toast(t("mailMenu.linkCopied")); + }), + ) + } + None => { + let copy_sel = selection.clone(); + let select_all_sel = selection.clone(); + menu.item( + PopupMenuItem::new(t("mailMenu.copy")) + .icon(IconName::Copy) + .disabled(!selection.is_selecting()) + .on_click(move |_, _, cx| { + if let Some(text) = copy_sel.selected_text() { + cx.write_to_clipboard(ClipboardItem::new_string(text)); + crate::notify::toast(t("email.selectionCopied")); + } + }), + ) + .item( + PopupMenuItem::new(t("mailMenu.selectAll")) + .icon(IconName::ClipboardCopy) + .on_click(move |_, window, _| { + select_all_sel.select_all(); + window.refresh(); + }), + ) + } + } +} + +/// 图片右键菜单的数据载荷(元素构造期廉价捕获,编码留给点击时)。 +#[derive(Clone)] +pub(crate) enum ImagePayload { + /// DataUri:原始字节直通(零重编码,格式随 mime)。 + Raw { + fmt: ImageFormat, + ext: &'static str, + bytes: Arc<[u8]>, + }, + /// Cid / Remote:仅手头 `RenderImage`(BGRA)→ 点击时重编码 PNG。 + Rendered { image: Arc }, +} + +/// 按图片源构造菜单载荷。 +pub(crate) fn image_payload_for(src: &ImageRef, image: &Arc) -> ImagePayload { + match src { + ImageRef::DataUri { mime, bytes } => { + let (fmt, ext) = match mime.as_str() { + "image/png" => (ImageFormat::Png, "png"), + "image/jpeg" => (ImageFormat::Jpeg, "jpg"), + "image/gif" => (ImageFormat::Gif, "gif"), + "image/webp" => (ImageFormat::Webp, "webp"), + _ => (ImageFormat::Png, "png"), + }; + ImagePayload::Raw { + fmt, + ext, + bytes: Arc::clone(bytes), + } + } + // 已解析才有本函数调用:Cid/Remote 皆持 RenderImage + _ => ImagePayload::Rendered { + image: Arc::clone(image), + }, + } +} + +/// 载荷 → 剪贴板/落盘字节(点击时一次性执行:Raw 直通;Rendered 走 +/// BGRA→RGBA→PNG 重编码,`image` crate png feature 已启用)。 +fn image_payload_bytes(payload: &ImagePayload) -> Option<(ImageFormat, Vec)> { + match payload { + ImagePayload::Raw { fmt, bytes, .. } => Some((*fmt, bytes.to_vec())), + ImagePayload::Rendered { image } => { + render_image_png_bytes(image).map(|b| (ImageFormat::Png, b)) + } + } +} + +/// `RenderImage`(首帧 BGRA)→ PNG 字节。解码的逆路径(decode_render_image +/// 曾做 RGBA→BGRA 交换,此处换回)。 +pub(crate) fn render_image_png_bytes(image: &RenderImage) -> Option> { + let size = image.size(0); + let (w, h) = (u32::try_from(size.width.0).ok()?, u32::try_from(size.height.0).ok()?); + let bgra = image.as_bytes(0)?; + let mut rgba = bgra.to_vec(); + for px in rgba.chunks_exact_mut(4) { + px.swap(0, 2); + } + let buffer = image::RgbaImage::from_raw(w, h, rgba)?; + let mut out = std::io::Cursor::new(Vec::new()); + buffer + .write_to(&mut out, image::ImageFormat::Png) + .ok() + .map(|_| out.into_inner()) +} + +/// 另存为默认文件名:alt 净化(去路径分隔/控制字符/Windows 保留字符、 +/// 限长)+ 扩展名。 +pub(crate) fn image_save_file_name(alt: &str, payload: &ImagePayload) -> String { + let ext = match payload { + ImagePayload::Raw { ext, .. } => *ext, + ImagePayload::Rendered { .. } => "png", + }; + let base: String = alt + .chars() + .map(|c| { + if c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*') { + ' ' + } else { + c + } + }) + .collect(); + let base = base.trim().chars().take(48).collect::(); + let base = if base.is_empty() { "image".to_string() } else { base }; + format!("{base}.{ext}") +} + +/// 图片右键菜单(render_loaded_image 的 context_menu 挂接)。 +/// 另存为全流程在后台线程(rfd 对话框 + 编码 + 写盘;toast 走全局 channel, +/// 线程安全)——UI 线程零阻塞,复用 attachments 保存的线程纪律。 +pub(crate) fn build_image_menu( + menu: PopupMenu, + payload: ImagePayload, + alt: String, +) -> PopupMenu { + let copy_payload = payload.clone(); + menu.item( + PopupMenuItem::new(t("mailMenu.copyImage")) + .icon(IconName::Image) + .on_click(move |_, _, cx| { + if let Some((fmt, bytes)) = image_payload_bytes(©_payload) { + let image = Image::from_bytes(fmt, bytes); + cx.write_to_clipboard(ClipboardItem::new_image(&image)); + crate::notify::toast(t("mailMenu.imageCopied")); + } + }), + ) + .item( + PopupMenuItem::new(t("mailMenu.saveImageAs")) + .icon(IconName::Save) + .on_click(move |_, _, _| { + let default_name = image_save_file_name(&alt, &payload); + let save_payload = payload.clone(); + std::thread::spawn(move || { + let Some(path) = rfd::FileDialog::new() + .set_file_name(&default_name) + .save_file() + else { + return; + }; + let ok = image_payload_bytes(&save_payload) + .and_then(|(_, bytes)| std::fs::write(&path, bytes).ok()); + match ok { + Some(()) => crate::notify::toast(t("mailMenu.imageSaved")), + None => crate::notify::toast(t("mailMenu.imageSaveFailed")), + } + }); + }), + ) +} + #[cfg(test)] impl ProbeExt for gpui_kit::Div { fn when_probe(self, selector: &str) -> Self { diff --git a/crates/postium-ui/src/views/html_selection.rs b/crates/postium-ui/src/views/html_selection.rs index 961f264b..64e2e025 100644 --- a/crates/postium-ui/src/views/html_selection.rs +++ b/crates/postium-ui/src/views/html_selection.rs @@ -10,6 +10,8 @@ use std::ops::Range; use std::sync::{Arc, Mutex}; +use postium_html::SafeUrl; + /// 跨帧共享的划选状态(渲染只读 + 鼠标事件读写)。 #[derive(Clone, Default)] pub struct HtmlSelection { @@ -24,6 +26,11 @@ struct SelState { head: Option, /// 本帧文本组注册表(文档序):组文本,划选复制与区间展开的依据。 groups: Vec, + /// 右键命中上下文(右键菜单,P0):Some=命中链接(携带 URL),None=纯 + /// 文本命中。右键按下时由 SelectableText 写入;左键按下清除(浏览器语 + /// 义:右键不破坏选区,左键开始新交互即失效)。菜单在 window.defer 的 + /// 下一帧构建——载体必须是本结构这类跨帧状态而非每帧重建的 RenderCtx。 + right_hit: Option, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] @@ -63,6 +70,41 @@ impl HtmlSelection { state.dragging = true; state.anchor = Some(pos); state.head = Some(pos); + state.right_hit = None; + } + + /// 右键按下:记录命中上下文(Some=链接,None=纯文本)。不清选区、不进 + /// 拖选态——右键菜单(P0)读取,左键按下时自然失效。 + pub fn on_right_down(&self, link: Option) { + self.lock().right_hit = link; + } + + /// 右键菜单构建期读取:Some(&SafeUrl)=链接命中(链接菜单),None=文本 + /// 命中(文本菜单)。 + pub fn right_click_link(&self) -> Option { + self.lock().right_hit.clone() + } + + /// 全选(右键菜单 P0):锚点=文档首,游标=末组末偏移。组注册表为空 + /// (无文本组)时无操作。 + pub fn select_all(&self) { + let mut state = self.lock(); + let Some((last_ix, last_len)) = state + .groups + .last() + .map(|text| (state.groups.len() - 1, text.len())) + else { + return; + }; + state.dragging = false; + state.anchor = Some(SelPos { + group: 0, + offset: 0, + }); + state.head = Some(SelPos { + group: last_ix, + offset: last_len, + }); } /// 拖动:更新游标(仅拖选态;组内偏移钳制到文本长度)。 @@ -235,4 +277,43 @@ mod tests { sel.on_up(); assert_eq!(sel.selected_text().as_deref(), Some("第一组文本")); } + + #[test] + fn right_hit_lifecycle() { + let (sel, ids) = setup(); + // 右键链接命中 → 读取可见;右键纯文本 → None;右键不破坏既有选区 + sel.on_down(ids[0], 0); + sel.on_move(ids[1], 3); + sel.on_up(); + assert!(sel.is_selecting()); + sel.on_right_down(Some(SafeUrl::Http("https://a.test/x".into()))); + assert_eq!( + sel.right_click_link(), + Some(SafeUrl::Http("https://a.test/x".into())) + ); + assert!(sel.is_selecting(), "右键不得破坏选区"); + sel.on_right_down(None); + assert_eq!(sel.right_click_link(), None, "纯文本右键覆盖链接命中"); + // 左键按下清除命中 + sel.on_right_down(Some(SafeUrl::Http("https://b.test".into()))); + sel.on_down(ids[0], 0); + assert_eq!(sel.right_click_link(), None, "左键按下应清除右键命中"); + } + + #[test] + fn select_all_spans_all_groups() { + let (sel, _ids) = setup(); + sel.select_all(); + assert!(sel.is_selecting()); + assert_eq!( + sel.selected_text().as_deref(), + Some("第一组文本\n第二组\n第三组尾巴"), + "全选应覆盖首组到末组全部文本" + ); + // 空注册表:无操作 + let empty = HtmlSelection::default(); + empty.begin_frame(); + empty.select_all(); + assert!(!empty.is_selecting()); + } } From 485636d95213d086b3cbc606261063fdebc0e646 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 20:25:32 +0800 Subject: [PATCH 08/20] =?UTF-8?q?feat(ui):=20=E6=B5=8F=E8=A7=88=E5=99=A8?= =?UTF-8?q?=E8=AF=AD=E4=B9=89=E5=A4=9A=E5=87=BB=E9=80=89=E6=8B=A9=20+=20?= =?UTF-8?q?=E5=A4=B4=E9=83=A8=E5=AD=97=E6=AE=B5=EF=BC=88=E4=B8=BB=E9=A2=98?= =?UTF-8?q?/=E5=8F=91=E4=BB=B6=E4=BA=BA/=E6=94=B6=E4=BB=B6=E4=BA=BA/?= =?UTF-8?q?=E6=8A=84=E9=80=81=EF=BC=89=E5=8F=AF=E9=80=89=E4=B8=AD=E5=8F=AF?= =?UTF-8?q?=E5=A4=8D=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 双击词选/三击段选:四类词模型(ASCII 词/CJK 词/空白/标点)——混合文本双击只选 ASCII 词或 CJK 连串(浏览器同款),词字符含 @._-+#(邮箱/域名整体一词),标点与空白不相邻合并;多击不设 down_index(抬起不触发链接打开);不进拖选态(词级拖选扩展不在本期)。 头部可选中:selectable_header_text helper(注册组 + SelectableText + 右键菜单,与正文选择实例隔离——正文每帧 begin_frame 会清共享组表);EmailDetailView 新增 header_selection,主题(14.5 semibold)/发件人/收件人/抄送四处替换,划选+双击+三击+右键复制全交互。 测试:词选单元 9 例(ASCII/CJK/邮箱/标点/混合/越界);e2e 双击选词不触发链接、三击整组、头部主题双击/三击。77 测试×2 并发模式 + 23 套件全绿。 --- crates/postium-ui/src/app.rs | 2 + crates/postium-ui/src/e2e_mail_menu_tests.rs | 175 ++++++++++++++++++ crates/postium-ui/src/views/email_detail.rs | 89 ++++++--- crates/postium-ui/src/views/email_html.rs | 74 +++++++- crates/postium-ui/src/views/html_selection.rs | 152 +++++++++++++++ 5 files changed, 469 insertions(+), 23 deletions(-) diff --git a/crates/postium-ui/src/app.rs b/crates/postium-ui/src/app.rs index 4d299dff..9c6dbdf6 100644 --- a/crates/postium-ui/src/app.rs +++ b/crates/postium-ui/src/app.rs @@ -331,6 +331,7 @@ impl AppShell { emails: this.emails.downgrade(), recipients_expanded: false, html_selection: Default::default(), + header_selection: Default::default(), body_focus: cx.focus_handle(), })); this.detail_build_version = this.emails.read(cx).selected_version; @@ -629,6 +630,7 @@ impl Render for AppShell { emails: self.emails.downgrade(), recipients_expanded: false, html_selection: Default::default(), + header_selection: Default::default(), body_focus: cx.focus_handle(), }); self.detail_view = Some(view.clone()); diff --git a/crates/postium-ui/src/e2e_mail_menu_tests.rs b/crates/postium-ui/src/e2e_mail_menu_tests.rs index 2990651a..2bdef6bf 100644 --- a/crates/postium-ui/src/e2e_mail_menu_tests.rs +++ b/crates/postium-ui/src/e2e_mail_menu_tests.rs @@ -258,3 +258,178 @@ fn mail_menu_image_bytes_and_file_name(cx: &mut gpui_pre::TestAppContext) { let raw_payload = email_html::image_payload_for(&raw, &rendered); assert_eq!(email_html::image_save_file_name("photo", &raw_payload), "photo.jpg"); } + +/// 双击词选 / 三击段选(浏览器语义)+ 多击不触发链接打开。 +#[gpui_pre::test] +fn mail_body_double_click_selects_word_not_link(cx: &mut gpui_pre::TestAppContext) { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let link_opens = Arc::new(AtomicUsize::new(0)); + struct Probe { + doc: HtmlDocument, + selection: HtmlSelection, + link_opens: Arc, + } + impl Render for Probe { + fn render( + &mut self, + _: &mut gpui_kit::Window, + cx: &mut gpui_kit::Context, + ) -> impl IntoElement { + let opens = Arc::clone(&self.link_opens); + let el = email_html::render_html_document( + &self.doc, + false, + ImageCtx::default(), + self.selection.clone(), + None, + move |_: &SafeUrl| { + opens.fetch_add(1, Ordering::Relaxed); + }, + cx, + ); + div().w(px(400.)).h(px(400.)).child(el) + } + } + let selection = HtmlSelection::default(); + let sel = selection.clone(); + let (_root, cx) = cx.add_window_view(|_, cx| { + crate::e2e_tests::setup(cx); + Probe { + doc: link_doc(), + selection: sel, + link_opens: Arc::clone(&link_opens), + } + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + // 双击链接词「MenuLinkText」(组文本 "前缀MenuLinkText",链接段从 + // 第 7 字节起):词选中,链接不打开 + let bounds = cx + .debug_bounds("html-txt-前缀MenuLinkText") + .expect("链接组探针应存在"); + let word_point = gpui_pre::point(bounds.left() + px(40.), bounds.center().y); + cx.simulate_event(gpui_pre::MouseDownEvent { + button: gpui_kit::MouseButton::Left, + position: word_point, + modifiers: gpui_pre::Modifiers::default(), + click_count: 2, + first_mouse: false, + }); + cx.simulate_event(gpui_pre::MouseUpEvent { + button: gpui_kit::MouseButton::Left, + position: word_point, + modifiers: gpui_pre::Modifiers::default(), + click_count: 2, + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + selection.selected_text().as_deref(), + Some("MenuLinkText"), + "双击应选中链接词(四类词模型:ASCII 词独立于 CJK 前缀)" + ); + assert_eq!(link_opens.load(Ordering::Relaxed), 0, "双击不得触发链接打开"); + + // 三击同组:整组段选 + cx.simulate_event(gpui_pre::MouseDownEvent { + button: gpui_kit::MouseButton::Left, + position: word_point, + modifiers: gpui_pre::Modifiers::default(), + click_count: 3, + first_mouse: false, + }); + cx.simulate_event(gpui_pre::MouseUpEvent { + button: gpui_kit::MouseButton::Left, + position: word_point, + modifiers: gpui_pre::Modifiers::default(), + click_count: 3, + }); + cx.run_until_parked(); + assert_eq!( + selection.selected_text().as_deref(), + Some("前缀MenuLinkText"), + "三击应选中整组" + ); + assert_eq!(link_opens.load(Ordering::Relaxed), 0, "三击不得触发链接"); +} + +/// 头部字段(主题)可选中:双击词选 + 三击整行(P0 续)。 +#[gpui_pre::test] +fn mail_header_subject_selectable(cx: &mut gpui_pre::TestAppContext) { + use gpui_kit::component::ActiveTheme as _; + struct HeaderProbe { + selection: HtmlSelection, + } + impl Render for HeaderProbe { + fn render( + &mut self, + _: &mut gpui_kit::Window, + cx: &mut gpui_kit::Context, + ) -> impl IntoElement { + self.selection.begin_frame(); + let subject = cx.theme().foreground; + let family = cx.theme().font_family.clone(); + div() + .w(px(400.)) + .h(px(200.)) + .p_3() + .child(email_html::selectable_header_text( + "mail-subject", + "季度Report总结v2", + family, + 14.5, + gpui_kit::FontWeight::SEMIBOLD, + subject, + &self.selection, + )) + } + } + let selection = HtmlSelection::default(); + let sel = selection.clone(); + let (_root, cx) = cx.add_window_view(|_, cx| { + crate::e2e_tests::setup(cx); + HeaderProbe { selection: sel } + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + let bounds = cx + .debug_bounds("html-txt-季度Report总结v2") + .expect("主题探针应存在(内容前缀键)"); + + // 双击 ASCII 段(Report 起于 2 个 CJK 后 ≈29px):只选 ASCII 词 + let point = gpui_pre::point(bounds.left() + px(40.), bounds.center().y); + cx.simulate_event(gpui_pre::MouseDownEvent { + button: gpui_kit::MouseButton::Left, + position: point, + modifiers: gpui_pre::Modifiers::default(), + click_count: 2, + first_mouse: false, + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let selected = selection.selected_text(); + assert!( + selected.as_deref().is_some_and(|s| s.contains("Report")), + "双击主题应选中 Report 词,实际 {selected:?}" + ); + + // 三击整行(混合文本全组) + cx.simulate_event(gpui_pre::MouseDownEvent { + button: gpui_kit::MouseButton::Left, + position: point, + modifiers: gpui_pre::Modifiers::default(), + click_count: 3, + first_mouse: false, + }); + cx.run_until_parked(); + assert_eq!( + selection.selected_text().as_deref(), + Some("季度Report总结v2"), + "三击应选中整行主题" + ); +} diff --git a/crates/postium-ui/src/views/email_detail.rs b/crates/postium-ui/src/views/email_detail.rs index c589f484..fe34b735 100644 --- a/crates/postium-ui/src/views/email_detail.rs +++ b/crates/postium-ui/src/views/email_detail.rs @@ -32,6 +32,10 @@ pub struct EmailDetailView { /// 正文划选状态(线上反馈①):视图重建即重置(换邮件清选区), /// Ctrl+C 复制选中文本(html_body_copy 动作)。 pub html_selection: crate::views::html_selection::HtmlSelection, + /// 头部字段(主题/发件人/收件人/抄送)划选状态(P0 续):与正文实例 + /// 隔离——正文渲染每帧 begin_frame 会清共享组表,头部独立成表;右键 + /// 菜单/双击词选与正文同款交互。 + pub header_selection: crate::views::html_selection::HtmlSelection, /// 正文滚动区焦点(划选复制动作的派发锚点)。 pub body_focus: gpui_kit::FocusHandle, } @@ -660,6 +664,10 @@ impl Render for EmailDetailView { .clone() .unwrap_or_else(|| detail.email.sender_email.clone()); + // 头部字段(主题/发件人/收件人/抄送)可选中化(P0 续):帧首清组 + // 注册表,各字段渲染期按序注册(与正文选择实例隔离)。 + self.header_selection.begin_frame(); + v_flex() .flex_1() .size_full() @@ -684,17 +692,19 @@ impl Render for EmailDetailView { .items_center() .gap_2() .child( - div() - .text_size(px(14.5)) - .font_weight(FontWeight::SEMIBOLD) - .flex_1() - .child( - detail - .email - .subject - .clone() - .unwrap_or_else(|| "(无主题)".into()), - ), + div().flex_1().child(crate::views::email_html::selectable_header_text( + "mail-subject", + detail + .email + .subject + .as_deref() + .unwrap_or("(无主题)"), + cx.theme().font_family.clone(), + 14.5, + FontWeight::SEMIBOLD, + cx.theme().foreground, + &self.header_selection, + )), ) // 操作分组:主操作(回复/全部回复/转发)|邮件态(星标/已读/重载)|归置(归档/删除)|浏览器 .child( @@ -788,13 +798,26 @@ impl Render for EmailDetailView { .flex_wrap() .text_size(px(12.5)) .text_color(cx.theme().muted_foreground) - .child(sender) + .child(crate::views::email_html::selectable_header_text( + "mail-sender", + &sender, + cx.theme().font_family.clone(), + 12.5, + FontWeight::default(), + cx.theme().muted_foreground, + &self.header_selection, + )) .child("·") .child(sent_time) .child("·") .child(t("email.to")) - .child(recipients_display(detail, self.recipients_expanded, cx)) - .when_some(cc_display(detail), |this, cc| { + .child(recipients_display( + detail, + self.recipients_expanded, + &self.header_selection, + cx, + )) + .when_some(cc_display(detail, &self.header_selection, cx), |this, cc| { this.child("·").child(t("email.cc")).child(cc) }) .when(recipient_count(detail) > 2, |this| { @@ -978,8 +1001,9 @@ fn recipient_count(detail: &postium_core::service::email_service::EmailDetail) - fn recipients_display( detail: &postium_core::service::email_service::EmailDetail, expanded: bool, + selection: &crate::views::html_selection::HtmlSelection, cx: &gpui_kit::App, -) -> SharedString { +) -> AnyElement { let list: Vec<&str> = detail .recipient_emails .split([',', ';']) @@ -987,20 +1011,43 @@ fn recipients_display( .filter(|s| !s.is_empty()) .collect(); let _ = cx; - if expanded || list.len() <= 2 { - list.join(", ").into() + let joined = if expanded || list.len() <= 2 { + list.join(", ") } else { - format!("{}, {}", list[0], list[1]).into() - } + format!("{}, {}", list[0], list[1]) + }; + crate::views::email_html::selectable_header_text( + "mail-recipients", + &joined, + cx.theme().font_family.clone(), + 12.5, + FontWeight::default(), + cx.theme().muted_foreground, + selection, + ) } -fn cc_display(detail: &postium_core::service::email_service::EmailDetail) -> Option { +fn cc_display( + detail: &postium_core::service::email_service::EmailDetail, + selection: &crate::views::html_selection::HtmlSelection, + cx: &gpui_kit::App, +) -> Option { detail .cc_emails .as_ref() .map(|cc| cc.trim()) .filter(|cc| !cc.is_empty()) - .map(|cc| cc.into()) + .map(|cc| { + crate::views::email_html::selectable_header_text( + "mail-cc", + cc, + cx.theme().font_family.clone(), + 12.5, + FontWeight::default(), + cx.theme().muted_foreground, + selection, + ) + }) } /// 工具条分组竖分隔线。 diff --git a/crates/postium-ui/src/views/email_html.rs b/crates/postium-ui/src/views/email_html.rs index e61471cb..1dbadc55 100644 --- a/crates/postium-ui/src/views/email_html.rs +++ b/crates/postium-ui/src/views/email_html.rs @@ -956,8 +956,19 @@ impl Element for SelectableText { && hitbox.is_hovered(window) && let Ok(ix) = layout.index_for_position(event.position) { - down_index.set(Some(ix)); - selection.on_down(group, ix); + if event.click_count >= 3 { + // 三击段选(浏览器语义):整组。多击不设 + // down_index——抬起时不得触发链接打开。 + selection.select_group(group); + } else if event.click_count == 2 { + // 双击词选(浏览器语义):围绕命中点的 + // 同词类连串(词字符含 @._-+#,邮箱/域名 + // 整体一词)。 + selection.select_word(group, ix); + } else { + down_index.set(Some(ix)); + selection.on_down(group, ix); + } window.refresh(); } }, @@ -1472,6 +1483,65 @@ pub(crate) fn safe_url_string(url: &SafeUrl) -> String { } } +/// 头部字段(主题/发件人/收件人/抄送)可选中化(P0 续):注册文本组 + +/// [`SelectableText`](划选/双击词选/三击段选)+ 右键菜单(复制/全选)。 +/// +/// 与正文划选**隔离**:调用方持有独立 [`HtmlSelection`](正文渲染每帧 +/// `begin_frame` 会清空共享实例的组注册表,头部字段必须独立成组表;帧首 +/// 由调用方对同一实例 `begin_frame` 一次)。空文本直通纯 div(不注册组)。 +pub(crate) fn selectable_header_text( + id: &'static str, + text: &str, + font_family: SharedString, + font_size: f32, + weight: FontWeight, + color: Hsla, + selection: &HtmlSelection, +) -> AnyElement { + if text.trim().is_empty() { + return div().into_any_element(); + } + let group = selection.register_group(text); + let mut font = base_font(font_family); + font.weight = weight; + let run = TextRun { + len: text.len(), + font, + color, + background_color: None, + underline: None, + strikethrough: None, + }; + let el = div() + .text_size(px(font_size)) + .line_height(relative(BASE_LINE_HEIGHT)) + .child(SelectableText { + id: ElementId::Name(id.into()), + text: StyledText::new(SharedString::from(text.to_string())).with_runs(vec![run]), + group, + selection: selection.clone(), + ranges: Vec::new(), + urls: Vec::new(), + on_link: Arc::new(|_: &SafeUrl| {}), + }); + // 探针沿正文组同款键(内容前缀),e2e 可断言头部字段可见性 + #[cfg(test)] + let key = { + let mut probe = String::new(); + for c in text.chars().filter(|c| c.is_alphanumeric()).take(16) { + probe.push(c); + } + format!("html-txt-{probe}") + }; + #[cfg(test)] + let el = el.when_probe(&key); + el.context_menu(build_text_menu( + selection.clone(), + Arc::new(|_: &SafeUrl| {}), + )) + .into_any_element() +} + /// 文本/链接右键菜单 builder(flush_text_group 的 context_menu 挂接)。 /// 读 [`HtmlSelection::right_click_link`] 分流:链接命中 → 打开/复制链接; /// 纯文本 → 复制(无选区禁用)/全选。构建发生在 defer 的下一帧,读的是 diff --git a/crates/postium-ui/src/views/html_selection.rs b/crates/postium-ui/src/views/html_selection.rs index 64e2e025..fc41dbfc 100644 --- a/crates/postium-ui/src/views/html_selection.rs +++ b/crates/postium-ui/src/views/html_selection.rs @@ -79,6 +79,34 @@ impl HtmlSelection { self.lock().right_hit = link; } + /// 双击词选(浏览器语义,P0 续):围绕字节偏移扩张到「词字符」连串边界。 + /// 词字符 = 字母数字(含 CJK)+ `@ . _ - + #`(邮箱地址/域名/标签整体 + /// 选中,浏览器同款);标点/空白自成连串(双击空格选空格段)。偏移在 + /// 字符边界上(index_for_position 保证);不进拖选态(词级拖选扩展 + /// 不在本期)。 + pub fn select_word(&self, group: usize, offset: usize) { + let mut state = self.lock(); + let Some(text) = state.groups.get(group) else { + return; + }; + let (start, end) = word_bounds(text, offset); + state.dragging = false; + state.anchor = Some(SelPos { group, offset: start }); + state.head = Some(SelPos { group, offset: end }); + } + + /// 三击段选(浏览器语义):整组(段落级文本块)。 + pub fn select_group(&self, group: usize) { + let mut state = self.lock(); + let Some(text) = state.groups.get(group) else { + return; + }; + let len = text.len(); + state.dragging = false; + state.anchor = Some(SelPos { group, offset: 0 }); + state.head = Some(SelPos { group, offset: len }); + } + /// 右键菜单构建期读取:Some(&SafeUrl)=链接命中(链接菜单),None=文本 /// 命中(文本菜单)。 pub fn right_click_link(&self) -> Option { @@ -191,6 +219,74 @@ fn ordered(state: &SelState) -> Option<(SelPos, SelPos)> { Some(if a <= h { (a, h) } else { (h, a) }) } +/// 词字符:字母数字(含 CJK)+ 邮箱/域名/标签常见连接符(浏览器双击 +/// 语义——`a@b.com` 整体一词)。 +fn is_word_char(c: char) -> bool { + c.is_alphanumeric() || matches!(c, '@' | '.' | '_' | '-' | '+' | '#') +} + +/// 文本中围绕 `offset` 的同词类连串字节区间(start..end,start ≤ offset ≤ +/// end,均在字符边界;offset==len 时取末串)。四类:ASCII 词 / CJK 词 / +/// 空白 / 其他标点——混合文本(`前缀MenuLinkText`)双击只选 ASCII 词或 +/// CJK 连串(浏览器同款);逗号与空格不相邻合并。 +fn word_bounds(text: &str, offset: usize) -> (usize, usize) { + #[derive(PartialEq, Clone, Copy)] + enum CharClass { + AsciiWord, + CjkWord, + Space, + Punct, + } + let class_of = |c: char| { + if is_word_char(c) { + if c.is_ascii() { + CharClass::AsciiWord + } else { + CharClass::CjkWord + } + } else if c.is_whitespace() { + CharClass::Space + } else { + CharClass::Punct + } + }; + let offset = offset.min(text.len()); + // offset 落在字符边界;取覆盖它的字符定词类(边界上取左侧字符,即 + // 光标在词尾时仍选中该词——浏览器同款)。 + let class_at = |byte: usize| -> Option { + if byte == 0 { + text.chars().next().map(class_of) + } else { + text[..byte].chars().next_back().map(class_of) + } + }; + let Some(class) = class_at(offset) else { + return (0, 0); + }; + let same_class = |c: char| class_of(c) == class; + let mut start = offset; + while start > 0 { + let Some(prev) = text[..start].chars().next_back() else { + break; + }; + if !same_class(prev) { + break; + } + start -= prev.len_utf8(); + } + let mut end = offset; + while end < text.len() { + let Some(next) = text[end..].chars().next() else { + break; + }; + if !same_class(next) { + break; + } + end += next.len_utf8(); + } + (start, end) +} + #[cfg(test)] mod tests { use super::*; @@ -316,4 +412,60 @@ mod tests { empty.select_all(); assert!(!empty.is_selecting()); } + + #[test] + fn word_selection_ascii_cjk_email_and_punct() { + let sel = HtmlSelection::default(); + sel.begin_frame(); + // "hello world" — 各 5 字节词 + let g0 = sel.register_group("hello world"); + sel.select_word(g0, 2); + assert_eq!(sel.selected_text().as_deref(), Some("hello")); + sel.select_word(g0, 7); + assert_eq!(sel.selected_text().as_deref(), Some("world")); + // 光标在词尾边界仍选中左侧词(浏览器语义) + sel.select_word(g0, 5); + assert_eq!(sel.selected_text().as_deref(), Some("hello")); + + // CJK 连串一词(无空格分隔时整体选中) + let g1 = sel.register_group("邮件双击选择"); + sel.select_word(g1, 3); + assert_eq!(sel.selected_text().as_deref(), Some("邮件双击选择")); + + // 邮箱地址整体一词(@ . 属词字符) + let g2 = sel.register_group("联系 a.b-c_d+e@x.y-z.com 备案"); + let email_start = "联系 ".len(); + sel.select_word(g2, email_start + 6); + assert_eq!(sel.selected_text().as_deref(), Some("a.b-c_d+e@x.y-z.com")); + + // 连续 CJK 一词 + 标点自成连串:光标在词与逗号之间选词(浏览器 + // 同款),打在逗号右边界才选逗号 + let g3 = sel.register_group("第一, 第二"); + sel.select_word(g3, "第".len()); + assert_eq!(sel.selected_text().as_deref(), Some("第一")); + sel.select_word(g3, "第一,".len()); + assert_eq!(sel.selected_text().as_deref(), Some(",")); + + // 越界偏移安全(钳制到文本) + sel.select_word(g3, 999); + assert!(sel.is_selecting()); + + // 混合文本(四类模型):双击 ASCII 段只选 ASCII 词,CJK 连串独立 + let g4 = sel.register_group("前缀MenuLinkText"); + sel.select_word(g4, "前缀".len() + 4); + assert_eq!(sel.selected_text().as_deref(), Some("MenuLinkText")); + sel.select_word(g4, 3); + assert_eq!(sel.selected_text().as_deref(), Some("前缀")); + } + + #[test] + fn triple_click_selects_whole_group() { + let sel = HtmlSelection::default(); + sel.begin_frame(); + let g = sel.register_group("整段文本双击不中三击全选"); + sel.select_group(g); + assert_eq!(sel.selected_text().as_deref(), Some("整段文本双击不中三击全选")); + // 未注册组:无操作 + sel.select_group(9); + } } From 1423b1c08312913f125e44f8fee539c24d732630 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 21:20:17 +0800 Subject: [PATCH 09/20] =?UTF-8?q?fix(ui):=20=E5=A4=B4=E9=83=A8=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E9=80=89=E4=B8=AD=E9=AB=98=E4=BA=AE=20+=20=E6=B8=B8?= =?UTF-8?q?=E7=A6=BB=E6=8A=AC=E8=B5=B7=E5=AE=88=E5=8D=AB=E2=80=94=E2=80=94?= =?UTF-8?q?=E6=8B=96=E9=80=89=E5=8F=AF=E8=A7=81=E3=80=81=E9=80=89=E5=8C=BA?= =?UTF-8?q?=E8=B7=A8=E8=8F=9C=E5=8D=95=E5=A4=8D=E5=88=B6=E5=AD=98=E6=B4=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 两处根因:①selectable_header_text 未切分选中区间 run——选区逻辑存在但不可见,用户无法感知拖选/词选结果,其间任何点击清选区也无感知(体感'复制一次后菜单变灰');现按 range_for_group 切 run 施加主题 selection 底色(与正文同语义)。②MouseUp 无条件 on_up——浮层元素(右键菜单项)上的点击若泄漏为抬起会终止/干扰选区;加配对守卫(本组无按下且无拖选 → 游离抬起不处理;跨组拖选的止组抬起经 is_dragging 分支仍生效)。 真实应用路径 e2e(AppShell→详情视图):拖选主题产生选区、游离抬起不清选区、右键后选区存活且命中为纯文本。78×2 并发 + 23 套件全绿。 --- crates/postium-ui/src/e2e_mail_menu_tests.rs | 132 +++++++++++++++++++ crates/postium-ui/src/e2e_tests.rs | 13 +- crates/postium-ui/src/views/email_detail.rs | 4 + crates/postium-ui/src/views/email_html.rs | 18 ++- 4 files changed, 160 insertions(+), 7 deletions(-) diff --git a/crates/postium-ui/src/e2e_mail_menu_tests.rs b/crates/postium-ui/src/e2e_mail_menu_tests.rs index 2bdef6bf..439ae5bc 100644 --- a/crates/postium-ui/src/e2e_mail_menu_tests.rs +++ b/crates/postium-ui/src/e2e_mail_menu_tests.rs @@ -383,6 +383,7 @@ fn mail_header_subject_selectable(cx: &mut gpui_pre::TestAppContext) { 14.5, gpui_kit::FontWeight::SEMIBOLD, subject, + cx.theme().selection, &self.selection, )) } @@ -433,3 +434,134 @@ fn mail_header_subject_selectable(cx: &mut gpui_pre::TestAppContext) { "三击应选中整行主题" ); } + +/// 真实应用路径(AppShell → 详情视图):头部主题拖选、游离抬起守卫、 +/// 选区跨右键存活(复制菜单不误灰的根因回归)。 +#[gpui_pre::test] +fn mail_header_drag_select_in_real_view(cx: &mut gpui_pre::TestAppContext) { + cx.dispatcher.allow_parking(); + let dir = tempfile::tempdir().unwrap(); + crate::e2e_tests::force_e2e_data_dir(); + let (api, sync_rx) = crate::e2e_tests::boot(dir.path()); + + let (shell, cx) = cx.add_window_view(|window, cx| { + crate::e2e_tests::setup(cx); + crate::app::AppShell::new(api.clone(), sync_rx, window, cx) + }); + crate::e2e_tests::wait_for(cx, |cx| { + crate::e2e_tests::with_app(cx, |app| { + (!shell.read(app).accounts.read(app).groups.is_empty()).then_some(()) + }) + }); + + // 带主题的草稿(行选中同款接缝) + let draft_id = { + let account_id = crate::e2e_tests::with_app(cx, |app| { + shell.read(app).accounts.read(app).groups[0].account.id + }); + let req = postium_core::service::mail_draft::SaveDraftRequest { + draft_id: None, + account_id, + to: vec!["e2e.user@postium.test".into()], + cc: vec![], + bcc: vec![], + subject: "HeaderDragProbe Subject Words".into(), + body_html: "

HeaderDragBody

".into(), + body_text: "正文".into(), + attachments: vec![], + }; + crate::runtime::runtime() + .block_on(async move { api.save_draft(req).await }) + .expect("草稿应保存成功") + .draft_id + }; + crate::e2e_tests::with_app_mut(cx, |app| { + shell.update(app, |shell, cx| { + shell.emails.update(cx, |store, cx| { + store.selected = Some(draft_id); + store.selected_version += 1; + cx.emit(crate::stores::emails::EmailsEvent::SelectionChanged(draft_id)); + cx.notify(); + }); + }); + }); + crate::e2e_tests::wait_for(cx, |cx| { + crate::e2e_tests::with_app(cx, |app| { + let view = shell.read(app).detail_view.clone()?; + let detail = view.read(app).store.read(app).detail.clone()?; + (detail.email.id == draft_id).then_some(()) + }) + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + // 主题探针(内容前 16 个字母数字 = HeaderDragProbeSu) + let bounds = cx + .debug_bounds("html-txt-HeaderDragProbeS") + .expect("主题探针应存在(头部字段经 selectable_header_text 注册)"); + let start = gpui_pre::point(bounds.left() + px(6.), bounds.center().y); + let end = gpui_pre::point(bounds.left() + px(90.), bounds.center().y); + + // 拖选:按下 → 移动 → 抬起 + cx.simulate_event(gpui_pre::MouseDownEvent { + button: gpui_kit::MouseButton::Left, + position: start, + modifiers: gpui_pre::Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(gpui_pre::MouseMoveEvent { + position: end, + modifiers: gpui_pre::Modifiers::default(), + pressed_button: Some(gpui_kit::MouseButton::Left), + }); + cx.simulate_event(gpui_pre::MouseUpEvent { + button: gpui_kit::MouseButton::Left, + position: end, + modifiers: gpui_pre::Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + let header_sel = crate::e2e_tests::with_app(cx, |app| { + let view = shell.read(app).detail_view.clone().expect("详情视图应存在"); + view.read(app).header_selection.clone() + }); + let selected = header_sel.selected_text(); + assert!( + selected.as_deref().is_some_and(|s| s.contains("Header")), + "拖选主题应产生选区,实际 {selected:?}" + ); + + // 游离抬起守卫:无按下的左键抬起(浮层点击泄漏形态)不得清选区 + cx.simulate_event(gpui_pre::MouseUpEvent { + button: gpui_kit::MouseButton::Left, + position: end, + modifiers: gpui_pre::Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + header_sel.is_selecting(), + "游离抬起(无配对按下)不得清选区" + ); + + // 右键命中记录:主题文本(无链接 → 文本菜单,复制项可用) + cx.simulate_event(gpui_pre::MouseDownEvent { + button: gpui_kit::MouseButton::Right, + position: end, + modifiers: gpui_pre::Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + header_sel.is_selecting() && header_sel.right_click_link().is_none(), + "右键后选区应存活且命中为纯文本(复制菜单可用)" + ); +} diff --git a/crates/postium-ui/src/e2e_tests.rs b/crates/postium-ui/src/e2e_tests.rs index 52d7c2ee..883528aa 100644 --- a/crates/postium-ui/src/e2e_tests.rs +++ b/crates/postium-ui/src/e2e_tests.rs @@ -15,7 +15,7 @@ use postium_core::api::CoreApi; use crate::app::AppShell; use crate::nav::NavTarget; -fn boot(dir: &std::path::Path) -> (Arc, postium_core::api::SyncEventRx) { +pub(crate) fn boot(dir: &std::path::Path) -> (Arc, postium_core::api::SyncEventRx) { let (sync_tx, sync_rx) = smol::channel::bounded(256); let api = crate::runtime::runtime() .block_on(async { CoreApi::init(dir, true, false, sync_tx).await }) @@ -32,7 +32,7 @@ fn boot(dir: &std::path::Path) -> (Arc, postium_core::api::SyncEventRx) /// (theme/lang 与 remote_image_senders 不重叠,读改写交错最坏丢一次对方 /// 字段写入,不破坏各自断言)。目录句柄泄漏持有——进程存活期间不得回收。 static E2E_DATA_DIR: std::sync::OnceLock<()> = std::sync::OnceLock::new(); -fn force_e2e_data_dir() { +pub(crate) fn force_e2e_data_dir() { E2E_DATA_DIR.get_or_init(|| { let dir = tempfile::tempdir().expect("E2E 数据目录创建失败"); let path = dir.path().to_path_buf(); @@ -49,12 +49,15 @@ fn force_e2e_data_dir() { /// 文件写)。锁只在这两个测试体内持有,测试结束随 guard 释放。 static UI_STATE_FILE_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); -fn with_app(cx: &mut VisualTestContext, f: impl FnOnce(&gpui_pre::App) -> R) -> R { +pub(crate) fn with_app(cx: &mut VisualTestContext, f: impl FnOnce(&gpui_pre::App) -> R) -> R { cx.update(|_, app| f(app)) } /// 在 &mut App 上执行(实体更新需要可变上下文)。 -fn with_app_mut(cx: &mut VisualTestContext, f: impl FnOnce(&mut gpui_pre::App) -> R) -> R { +pub(crate) fn with_app_mut( + cx: &mut VisualTestContext, + f: impl FnOnce(&mut gpui_pre::App) -> R, +) -> R { cx.update(|_, app| f(app)) } @@ -67,7 +70,7 @@ fn with_window_mut( } #[track_caller] -fn wait_for( +pub(crate) fn wait_for( cx: &mut VisualTestContext, mut f: impl FnMut(&mut VisualTestContext) -> Option, ) -> T { diff --git a/crates/postium-ui/src/views/email_detail.rs b/crates/postium-ui/src/views/email_detail.rs index fe34b735..597b3dbc 100644 --- a/crates/postium-ui/src/views/email_detail.rs +++ b/crates/postium-ui/src/views/email_detail.rs @@ -703,6 +703,7 @@ impl Render for EmailDetailView { 14.5, FontWeight::SEMIBOLD, cx.theme().foreground, + cx.theme().selection, &self.header_selection, )), ) @@ -805,6 +806,7 @@ impl Render for EmailDetailView { 12.5, FontWeight::default(), cx.theme().muted_foreground, + cx.theme().selection, &self.header_selection, )) .child("·") @@ -1023,6 +1025,7 @@ fn recipients_display( 12.5, FontWeight::default(), cx.theme().muted_foreground, + cx.theme().selection, selection, ) } @@ -1045,6 +1048,7 @@ fn cc_display( 12.5, FontWeight::default(), cx.theme().muted_foreground, + cx.theme().selection, selection, ) }) diff --git a/crates/postium-ui/src/views/email_html.rs b/crates/postium-ui/src/views/email_html.rs index 1dbadc55..426d45ab 100644 --- a/crates/postium-ui/src/views/email_html.rs +++ b/crates/postium-ui/src/views/email_html.rs @@ -1036,6 +1036,12 @@ impl Element for SelectableText { { return; } + // 配对守卫:本组无按下记录且无进行中的拖选(跨组拖 + // 选的抬起落在止组)→ 游离抬起(如浮层元素上的点击 + // 泄漏),不得当作选区交互处理。 + if down_index.get().is_none() && !selection.is_dragging() { + return; + } if hitbox.is_hovered(window) && let Ok(up_ix) = layout.index_for_position(event.position) && let Some(down) = down_index.get() @@ -1484,7 +1490,9 @@ pub(crate) fn safe_url_string(url: &SafeUrl) -> String { } /// 头部字段(主题/发件人/收件人/抄送)可选中化(P0 续):注册文本组 + -/// [`SelectableText`](划选/双击词选/三击段选)+ 右键菜单(复制/全选)。 +/// [`SelectableText`](划选/双击词选/三击段选)+ 右键菜单(复制/全选)+ +/// **选中高亮**(`selection_bg` 切分 run——无高亮则选区不可见,用户无法 +/// 感知划选/词选结果)。 /// /// 与正文划选**隔离**:调用方持有独立 [`HtmlSelection`](正文渲染每帧 /// `begin_frame` 会清空共享实例的组注册表,头部字段必须独立成组表;帧首 @@ -1496,6 +1504,7 @@ pub(crate) fn selectable_header_text( font_size: f32, weight: FontWeight, color: Hsla, + selection_bg: Hsla, selection: &HtmlSelection, ) -> AnyElement { if text.trim().is_empty() { @@ -1512,12 +1521,17 @@ pub(crate) fn selectable_header_text( underline: None, strikethrough: None, }; + // 选中区间切分(与正文 flush_text_group 同语义):选中段施加高亮底色 + let runs = match selection.range_for_group(group) { + Some(range) => apply_selection_background(vec![run], range, selection_bg), + None => vec![run], + }; let el = div() .text_size(px(font_size)) .line_height(relative(BASE_LINE_HEIGHT)) .child(SelectableText { id: ElementId::Name(id.into()), - text: StyledText::new(SharedString::from(text.to_string())).with_runs(vec![run]), + text: StyledText::new(SharedString::from(text.to_string())).with_runs(runs), group, selection: selection.clone(), ranges: Vec::new(), From 5f7af856ea0356261486ccddef883a076d8c3049 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 21:26:58 +0800 Subject: [PATCH 10/20] =?UTF-8?q?fix(log):=20=E5=8E=8B=E5=88=B6=20html5eve?= =?UTF-8?q?r=20RcDom=20foster=20parenting=20=E5=91=8A=E8=AD=A6=EF=BC=88?= =?UTF-8?q?=E6=97=A0=E5=AE=B3=E5=99=AA=E9=9F=B3=EF=BC=8C=E7=BA=BF=E4=B8=8A?= =?UTF-8?q?=E5=8F=8D=E9=A6=88=E2=91=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Outlook 系邮件常见 内直接夹文本——HTML 规范要求 foster parenting(错位内容移到表格外),html5ever 的 RcDom 参考实现未实现、每次解析打一条 WARN(dev 的 html5ever=warn 阈值放行 WARN,release 默认 warn 同样放行)。树仍完整构建,错位内容由 builder 防御性兜底(表格行只认 td/th)——降噪到 error:dev/release 两分支同步,过滤器测试补 WARN 级压制断言。 --- crates/postium-core/src/sys/log.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/postium-core/src/sys/log.rs b/crates/postium-core/src/sys/log.rs index 32afea19..44506963 100644 --- a/crates/postium-core/src/sys/log.rs +++ b/crates/postium-core/src/sys/log.rs @@ -26,7 +26,11 @@ pub fn setup_logging() { // - gpui_pre(_windows):每帧的无障碍树更新、渲染器/剪贴板内部调试 // - tao:窗口系统事件;globset:构建 glob 集合 // - html5ever/markup5ever:HTML 解析器逐 tag 的 tree_builder 调试 - // (邮件正文解析时每封上千行) + // (邮件正文解析时每封上千行);html5ever 提到 error——其 + // RcDom 参考实现未实现规范的 foster parenting(错位内容移位, + // 如
内直接夹文本——Outlook 系邮件常见),每封打一次 + // WARN。树仍完整构建,错位内容由 builder 防御性兜底(表格行 + // 只认 td/th),无害噪音(线上反馈④) // - selectors:css-inline 类名匹配的 DEBUG 会把整个文档 DOM // Debug 转储进单条日志(MB 级/条 × 每元素每选择器)——渲染线程 // 同步写终端直接卡死应用(日志目标文件 selectors/matching.rs) @@ -35,12 +39,14 @@ pub fn setup_logging() { // (hyper_util::client::…),写成连字符 hyper-util 永不匹配 // (线上反馈③:同步日志刷屏的漏网真因) EnvFilter::new( - "debug,gpui_pre=warn,gpui_pre_windows=warn,tao=warn,globset=warn,reqwest=warn,hyper_util=warn,html5ever=warn,markup5ever=warn,selectors=warn", + "debug,gpui_pre=warn,gpui_pre_windows=warn,tao=warn,globset=warn,reqwest=warn,hyper_util=warn,html5ever=error,markup5ever=warn,selectors=warn", ) } #[cfg(not(debug_assertions))] { - EnvFilter::new("warn") + // release 默认 WARN;同样压制 html5ever 的 RcDom 局限告警 + // (foster parenting,线上反馈④——见 dev 分支注释) + EnvFilter::new("warn,html5ever=error") } }); @@ -86,7 +92,7 @@ mod tests { } let filter = tracing_subscriber::EnvFilter::new( - "debug,gpui_pre=warn,gpui_pre_windows=warn,tao=warn,globset=warn,reqwest=warn,hyper_util=warn,html5ever=warn,markup5ever=warn,selectors=warn", + "debug,gpui_pre=warn,gpui_pre_windows=warn,tao=warn,globset=warn,reqwest=warn,hyper_util=warn,html5ever=error,markup5ever=warn,selectors=warn", ); let captured = Arc::new(Mutex::new(Vec::new())); let subscriber = tracing_subscriber::fmt() @@ -110,10 +116,16 @@ mod tests { noise!("reqwest::connect::connector"); noise!("tao::platform_impl::platform::event_loop"); tracing::debug!(target: "postium_core::infrastructure::protocols::imap::fetch", "business-line"); + // foster parenting 告警是 WARN 级(线上反馈④):error 阈值下必须压住 + tracing::warn!(target: "html5ever::tree_builder", "foster parenting not implemented"); }); let out = String::from_utf8(captured.lock().unwrap().clone()).unwrap(); assert!(!out.contains("noise-line"), "依赖噪音应全部被压制:\n{out}"); + assert!( + !out.contains("foster parenting"), + "html5ever WARN(RcDom foster parenting 局限)应被压制:\n{out}" + ); assert!(out.contains("business-line"), "业务 DEBUG 不应被误压制:\n{out}"); } } From 45d45fe1e2e7930a6b6a85104ee18a90fb7e2963 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 22:01:01 +0800 Subject: [PATCH 11/20] =?UTF-8?q?feat(tray):=20=E5=85=B3=E9=97=AD=E4=B8=BB?= =?UTF-8?q?=E7=AA=97=E5=8F=A3=E8=A1=8C=E4=B8=BA=E2=80=94=E2=80=94=E6=89=98?= =?UTF-8?q?=E7=9B=98=E9=A9=BB=E7=95=99/=E9=80=80=E5=87=BA/=E9=A6=96?= =?UTF-8?q?=E6=AC=A1=E8=AF=A2=E9=97=AE=E5=BC=B9=E7=AA=97=20+=20=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E9=A1=B9=EF=BC=88=E7=BA=BF=E4=B8=8A=E5=8F=8D=E9=A6=88?= =?UTF-8?q?=E2=91=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:gpui-pre 非 macOS 的 QuitMode::Default 在最后一个窗口关闭时直接退出进程——X 按钮的 remove_window 连带托盘整体退出,'关闭到托盘'的既有设计从未真正生效。 修复与功能:①启动置 QuitMode::Explicit(无窗口应用驻留,仅显式 cx.quit 退出)。②标题栏 X 经 AppShell::request_close 三分流:最小化到托盘(销毁窗口驻留,托盘「显示窗口」重建)/ 退出程序(存窗口态后退出)/ 每次询问(弹窗:全屏遮罩 + 居中卡片,「最小化到托盘/退出程序/取消」+「记住我的选择」勾选,勾选后按选择持久化不再询问)。③设置-外观分区新增「关闭窗口时」三段选择(每次询问/最小化到托盘/退出程序),点击即持久化 ui-state.json(close_behavior 字段)。④托盘左键单击与「显示窗口」菜单共享重建逻辑(此前主窗口销毁后左键无响应)。 e2e:设置页三段切换持久化断言(ui-state 串行域内往返)。79 测试×2 并发模式全绿;工作区 23 套件全绿(contact_sync 曾现一次并行偶发,重跑稳定,与本次无关)。 --- crates/postium-ui/src/app.rs | 190 ++++++++++++++++++- crates/postium-ui/src/e2e_mail_menu_tests.rs | 81 ++++++++ crates/postium-ui/src/e2e_tests.rs | 8 + crates/postium-ui/src/i18n_tables.rs | 20 ++ crates/postium-ui/src/main.rs | 5 + crates/postium-ui/src/tray.rs | 49 ++--- crates/postium-ui/src/ui_state.rs | 52 +++++ crates/postium-ui/src/views/settings.rs | 48 +++++ crates/postium-ui/src/views/title_bar.rs | 21 +- 9 files changed, 440 insertions(+), 34 deletions(-) diff --git a/crates/postium-ui/src/app.rs b/crates/postium-ui/src/app.rs index 9c6dbdf6..3bdd6de7 100644 --- a/crates/postium-ui/src/app.rs +++ b/crates/postium-ui/src/app.rs @@ -3,12 +3,16 @@ use std::sync::Arc; use gpui_kit::component::{ + button::{Button, ButtonVariants as _}, h_flex, input::{Input, InputEvent, InputState}, resizable::{h_resizable, resizable_panel}, v_flex, + ActiveTheme as _, Sizable as _, }; +use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; +use gpui_kit_assets::IconName; use postium_core::api::{CoreApi, SyncEventRx}; @@ -144,6 +148,11 @@ pub struct AppShell { workflow_view: Option>, /// 主窗口句柄:选中邮件时更新窗口标题用 pub(crate) window_handle: gpui_kit::AnyWindowHandle, + /// 关闭选择弹窗(线上反馈⑤):关闭行为未记忆时,X 按钮弹窗询问 + /// 托盘驻留还是退出。弹窗期间阻断窗口关闭动作本体。 + close_dialog: bool, + /// 弹窗「记住我的选择」勾选态(每次打开重置)。 + close_dialog_remember: bool, /// 同步中节流刷新:上次刷新时刻 / 到期未刷标记 sync_refresh_at: Option, sync_refresh_pending: bool, @@ -430,6 +439,8 @@ impl AppShell { contacts_view: None, workflow_view: None, status_bar: None, + close_dialog: false, + close_dialog_remember: false, window_handle: window.window_handle(), sync_refresh_at: None, sync_refresh_pending: false, @@ -508,6 +519,71 @@ impl AppShell { pub(crate) fn toggle_theme(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context) { crate::theme::toggle_theme_mode(cx); } + + // ----------------------------------------------------------------- + // 关闭主窗口行为(线上反馈⑤):托盘驻留 / 退出 / 每次询问弹窗 + // ----------------------------------------------------------------- + + /// 标题栏 X:按持久化行为分流。 + pub(crate) fn request_close(&mut self, window: &mut Window, cx: &mut Context) { + match crate::ui_state::close_behavior() { + crate::ui_state::CloseBehavior::Quit => self.close_quit(window, cx), + crate::ui_state::CloseBehavior::ToTray => self.close_to_tray(window, cx), + crate::ui_state::CloseBehavior::Ask => { + self.close_dialog = true; + self.close_dialog_remember = false; + cx.notify(); + } + } + } + + /// 最小化到托盘:保存窗口状态后销毁窗口——应用驻留(QuitMode:: + /// Explicit 下无窗口不退出),托盘「显示窗口」重建主窗口。销毁需 + /// 异步(事件分发栈上同步移除自身窗口不安全)。 + fn close_to_tray(&mut self, window: &mut Window, cx: &mut Context) { + crate::window_state::save(window); + let handle = window.window_handle(); + cx.spawn(async move |_, cx| { + let _ = handle.update(cx, |_, window, _| window.remove_window()); + }) + .detach(); + } + + /// 退出程序:保存窗口状态后显式退出(托盘菜单退出同款路径)。 + fn close_quit(&mut self, window: &mut Window, cx: &mut Context) { + crate::window_state::save(window); + cx.quit(); + } + + /// 关闭选择弹窗——「最小化到托盘」。 + pub(crate) fn dialog_close_to_tray(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context) { + if self.close_dialog_remember { + crate::ui_state::set_close_behavior(crate::ui_state::CloseBehavior::ToTray); + } + self.close_dialog = false; + self.close_to_tray(window, cx); + } + + /// 关闭选择弹窗——「退出程序」。 + pub(crate) fn dialog_close_quit(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context) { + if self.close_dialog_remember { + crate::ui_state::set_close_behavior(crate::ui_state::CloseBehavior::Quit); + } + self.close_dialog = false; + self.close_quit(window, cx); + } + + /// 关闭选择弹窗——「取消」。 + pub(crate) fn dialog_close_cancel(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context) { + self.close_dialog = false; + cx.notify(); + } + + /// 关闭选择弹窗——勾选「记住我的选择」。 + pub(crate) fn dialog_toggle_remember(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context) { + self.close_dialog_remember = !self.close_dialog_remember; + cx.notify(); + } } impl Render for AppShell { @@ -643,7 +719,7 @@ impl Render for AppShell { }; // 根布局:自定义标题栏(跟随主题深浅)+ 侧栏/内容列(拖把手可调宽) - v_flex() + let root = v_flex() .size_full() .child(crate::views::title_bar::render(self, window, cx)) .child( @@ -711,7 +787,117 @@ impl Render for AppShell { .into_any_element(), ), ), - ) + ); + + // 关闭选择弹窗(线上反馈⑤):全屏遮罩 + 居中卡片(Z 序在内容之上) + div() + .relative() + .size_full() + .child(root) + .when(self.close_dialog, |d| { + let theme = cx.theme().clone(); + let remember = self.close_dialog_remember; + d.child( + div() + .id("close-dialog-mask") + .absolute() + .size_full() + .top_0() + .left_0() + .bg(gpui_kit::black().opacity(0.45)) + .flex() + .items_center() + .justify_center() + .child( + v_flex() + .id("close-dialog") + .w(px(380.)) + .p_5() + .gap_3() + .rounded(px(12.)) + .bg(theme.background) + .border_1() + .border_color(theme.border) + .shadow_lg() + .child( + div() + .text_size(px(14.5)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.foreground) + .child(i18n::t("app.closeDialogTitle")), + ) + .child( + div() + .text_size(px(12.5)) + .text_color(theme.muted_foreground) + .child(i18n::t("app.closeDialogText")), + ) + // 记住我的选择(勾选框) + .child( + h_flex() + .id("close-dialog-remember") + .gap_2() + .items_center() + .cursor_pointer() + .on_click(cx.listener(Self::dialog_toggle_remember)) + .child( + div() + .w(px(14.)) + .h(px(14.)) + .rounded(px(3.)) + .border_1() + .border_color(theme.border) + .when(remember, |d| { + d.bg(theme.accent) + .border_color(theme.accent) + }) + .when(remember, |d| { + d.child( + gpui_kit::component::Icon::new( + IconName::Check, + ) + .size_3() + .text_color(theme.accent_foreground), + ) + }), + ) + .child( + div() + .text_size(px(12.)) + .text_color(theme.foreground) + .child(i18n::t("app.closeRemember")), + ), + ) + // 动作行:取消 / 最小化到托盘 / 退出程序 + .child( + h_flex() + .gap_2() + .justify_end() + .child( + Button::new("close-dialog-cancel") + .ghost() + .small() + .label(i18n::t("app.closeCancel")) + .on_click(cx.listener(Self::dialog_close_cancel)), + ) + .child( + Button::new("close-dialog-tray") + .primary() + .small() + .label(i18n::t("app.closeToTray")) + .on_click(cx.listener(Self::dialog_close_to_tray)), + ) + .child( + Button::new("close-dialog-quit") + .ghost() + .small() + .label(i18n::t("app.closeQuit")) + .on_click(cx.listener(Self::dialog_close_quit)), + ), + ), + ), + ) + }) } } diff --git a/crates/postium-ui/src/e2e_mail_menu_tests.rs b/crates/postium-ui/src/e2e_mail_menu_tests.rs index 439ae5bc..a11f3f4e 100644 --- a/crates/postium-ui/src/e2e_mail_menu_tests.rs +++ b/crates/postium-ui/src/e2e_mail_menu_tests.rs @@ -565,3 +565,84 @@ fn mail_header_drag_select_in_real_view(cx: &mut gpui_pre::TestAppContext) { "右键后选区应存活且命中为纯文本(复制菜单可用)" ); } + +/// 关闭窗口行为设置(线上反馈⑤):设置页三段选择点击即持久化, +/// ui-state.json 串行域内往返断言。 +#[gpui_pre::test] +fn settings_close_behavior_persists(cx: &mut gpui_pre::TestAppContext) { + cx.dispatcher.allow_parking(); + let dir = tempfile::tempdir().unwrap(); + crate::e2e_tests::force_e2e_data_dir(); + let _guard = crate::e2e_tests::ui_state_lock(); + // 前置归零(防止进程内其他测试的残留) + crate::ui_state::set_close_behavior(crate::ui_state::CloseBehavior::Ask); + assert_eq!( + crate::ui_state::close_behavior(), + crate::ui_state::CloseBehavior::Ask + ); + + let (api, _sync_rx) = crate::e2e_tests::boot(dir.path()); + let api_for_view = api.clone(); + let (settings, cx) = cx.add_window_view(|window, cx| { + crate::e2e_tests::setup(cx); + let sync_store = cx.new(|cx| crate::stores::sync::SyncStore::new(cx)); + let accounts = crate::stores::accounts::init_accounts_store(&api_for_view, cx); + crate::views::settings::SettingsView::new(accounts, sync_store, api_for_view, window, cx) + }); + crate::e2e_tests::wait_for(cx, |cx| { + crate::e2e_tests::with_app(cx, |app| { + (settings.read(app).accounts.read(app).groups.len() >= 1).then_some(()) + }) + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + // 切到外观分区(关闭行为行与主题/语言行同域渲染)——直驱视图状态 + // (导航 div 无 debug_selector,分区切换非本断言目标) + crate::e2e_tests::with_app_mut(cx, |app| { + settings.update(app, |view, cx| { + view.active_section = crate::views::settings::SettingsSection::Appearance; + cx.notify(); + }); + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + for key in ["close-ask", "close-tray", "close-quit"] { + assert!( + cx.debug_bounds(key).is_some(), + "关闭行为段 {key} 应存在(外观分区)" + ); + } + + // 点击「最小化到托盘」→ 持久化 + 高亮切换 + let tray_bounds = cx.debug_bounds("close-tray").expect("tray 段应有 bounds"); + cx.simulate_click( + gpui_pre::point(tray_bounds.center().x, tray_bounds.center().y), + gpui_pre::Modifiers::default(), + ); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + crate::ui_state::close_behavior(), + crate::ui_state::CloseBehavior::ToTray, + "点击托盘段应持久化关闭行为" + ); + + // 「退出程序」段同理 + let quit_bounds = cx.debug_bounds("close-quit").expect("quit 段应有 bounds"); + cx.simulate_click( + gpui_pre::point(quit_bounds.center().x, quit_bounds.center().y), + gpui_pre::Modifiers::default(), + ); + cx.run_until_parked(); + assert_eq!( + crate::ui_state::close_behavior(), + crate::ui_state::CloseBehavior::Quit + ); + + // 收尾归零(Ask 清除记忆,防污染进程内后续测试) + crate::ui_state::set_close_behavior(crate::ui_state::CloseBehavior::Ask); +} diff --git a/crates/postium-ui/src/e2e_tests.rs b/crates/postium-ui/src/e2e_tests.rs index 883528aa..49711226 100644 --- a/crates/postium-ui/src/e2e_tests.rs +++ b/crates/postium-ui/src/e2e_tests.rs @@ -49,6 +49,14 @@ pub(crate) fn force_e2e_data_dir() { /// 文件写)。锁只在这两个测试体内持有,测试结束随 guard 释放。 static UI_STATE_FILE_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); +/// ui-state.json 写者串行锁的进程外取用(e2e_mail_menu_tests 等新增写者 +/// 测试纳入同一串行域,防并行交错丢写)。 +pub(crate) fn ui_state_lock() -> std::sync::MutexGuard<'static, ()> { + UI_STATE_FILE_TESTS + .lock() + .unwrap_or_else(|e| e.into_inner()) +} + pub(crate) fn with_app(cx: &mut VisualTestContext, f: impl FnOnce(&gpui_pre::App) -> R) -> R { cx.update(|_, app| f(app)) } diff --git a/crates/postium-ui/src/i18n_tables.rs b/crates/postium-ui/src/i18n_tables.rs index 591eb2ca..33b75022 100644 --- a/crates/postium-ui/src/i18n_tables.rs +++ b/crates/postium-ui/src/i18n_tables.rs @@ -78,6 +78,16 @@ pub static ZH: &[(&str, &str)] = &[ ("email.loadImages", "邮件含远程图片(可能泄露已读状态),点击加载"), ("email.alwaysLoadImages", "始终加载"), ("email.selectionCopied", "已复制所选内容"), + ("app.closeDialogTitle", "关闭窗口"), + ("app.closeDialogText", "要让 Postium 保持在系统托盘运行,还是退出程序?"), + ("app.closeRemember", "记住我的选择"), + ("app.closeToTray", "最小化到托盘"), + ("app.closeQuit", "退出程序"), + ("app.closeCancel", "取消"), + ("settings.closeBehavior", "关闭窗口时"), + ("settings.closeAsk", "每次询问"), + ("settings.closeTray", "最小化到托盘"), + ("settings.closeQuit", "退出程序"), ("mailMenu.openLink", "打开链接"), ("mailMenu.copyLink", "复制链接地址"), ("mailMenu.copyImage", "复制图片"), @@ -296,6 +306,16 @@ pub static EN: &[(&str, &str)] = &[ ("email.loadImages", "This email contains remote images (may leak read status), click to load"), ("email.alwaysLoadImages", "Always load"), ("email.selectionCopied", "Selection copied"), + ("app.closeDialogTitle", "Close Window"), + ("app.closeDialogText", "Keep Postium running in the system tray, or quit?"), + ("app.closeRemember", "Remember my choice"), + ("app.closeToTray", "Minimize to Tray"), + ("app.closeQuit", "Quit"), + ("app.closeCancel", "Cancel"), + ("settings.closeBehavior", "When closing window"), + ("settings.closeAsk", "Ask every time"), + ("settings.closeTray", "Minimize to tray"), + ("settings.closeQuit", "Quit"), ("mailMenu.openLink", "Open Link"), ("mailMenu.copyLink", "Copy Link Address"), ("mailMenu.copyImage", "Copy Image"), diff --git a/crates/postium-ui/src/main.rs b/crates/postium-ui/src/main.rs index f708383a..e892faac 100644 --- a/crates/postium-ui/src/main.rs +++ b/crates/postium-ui/src/main.rs @@ -60,6 +60,11 @@ fn main() { .run(move |cx| { gpui_kit::init(cx); postium_editor::init(cx); + // 窗口全关后应用驻留(线上反馈⑤:关闭到托盘)——非 macOS 的 + // QuitMode::Default 在最后一个窗口关闭时直接退出进程(托盘 + // 一并带走)。改 Explicit:仅显式 cx.quit() 退出(托盘菜单/ + // 关闭行为=退出)。 + cx.set_quit_mode(gpui_kit::QuitMode::Explicit); cx.set_global(i18n::I18nGlobal { lang: i18n::Lang::Zh }); app::open_main_window(api, Some(sync_rx), cx); // 截图模式:不激活应用(不抢用户焦点) diff --git a/crates/postium-ui/src/tray.rs b/crates/postium-ui/src/tray.rs index 7d639490..33ea5e68 100644 --- a/crates/postium-ui/src/tray.rs +++ b/crates/postium-ui/src/tray.rs @@ -21,6 +21,27 @@ struct TrayActions { static ACTIONS_ID: u32 = 1; +/// 托盘「显示窗口」/左键单击共享:主窗口存活 → 激活置前;已关闭(关闭到 +/// 托盘)→ 重建主窗口。 +fn show_main_window(api: &Arc, cx: &mut App) { + let shell_alive = cx + .try_global::() + .and_then(|main| main.0.upgrade()) + .is_some(); + if shell_alive { + if let Some(handle) = cx.active_window() { + let _ = handle.update(cx, |_, window, _| { + window.activate_window(); + }); + } + } else { + let api = api.clone(); + cx.defer(move |cx| { + crate::app::open_main_window(api, None, cx); + }); + } +} + /// 装配托盘并启动事件消费循环。 /// /// 托盘是可选能力:Linux 无 appindicator/无会话总线等环境下 @@ -71,15 +92,13 @@ fn setup_tray_inner( let menu_rx = MenuEvent::receiver(); let tray_rx = tray_icon::TrayIconEvent::receiver(); loop { - // 左键单击托盘 → 显示主窗口 + // 左键单击托盘 → 显示主窗口(与菜单「显示窗口」同逻辑——线上 + // 反馈⑤前左键只激活 active_window,主窗口销毁(关闭到托盘)后 + // 点左键无响应) while let Ok(event) = tray_rx.try_recv() { if let tray_icon::TrayIconEvent::Click { button: tray_icon::MouseButton::Left, .. } = event { cx.update(|cx| { - if let Some(handle) = cx.active_window() { - let _ = handle.update(cx, |_, window, _| { - window.activate_window(); - }); - } + show_main_window(&api, cx); }); } } @@ -88,23 +107,7 @@ fn setup_tray_inner( match id { "show" => { cx.update(|cx| { - // 主窗口存活 → 激活置前;已关闭(X)→ 重建主窗口 - let shell_alive = cx - .try_global::() - .and_then(|main| main.0.upgrade()) - .is_some(); - if shell_alive { - if let Some(handle) = cx.active_window() { - let _ = handle.update(cx, |_, window, _| { - window.activate_window(); - }); - } - } else { - let api = api.clone(); - cx.defer(move |cx| { - crate::app::open_main_window(api, None, cx); - }); - } + show_main_window(&api, cx); }); } "compose" => { diff --git a/crates/postium-ui/src/ui_state.rs b/crates/postium-ui/src/ui_state.rs index 65067c5c..d7cbe99e 100644 --- a/crates/postium-ui/src/ui_state.rs +++ b/crates/postium-ui/src/ui_state.rs @@ -18,6 +18,41 @@ pub struct UiState { /// 侧 reducer 初始值为 !0(true),其 native 存储默认未证实,此处 /// 取保守拦截默认。 pub auto_download_mail_images: Option, + /// 关闭主窗口行为(线上反馈⑤):`"tray"` = 最小化到托盘(窗口销毁、 + /// 应用驻留),`"quit"` = 退出程序;缺省 None = 每次关闭时弹窗询问 + /// (弹窗勾选「记住我的选择」或设置页切换后写入)。 + pub close_behavior: Option, +} + +/// 关闭主窗口行为(线上反馈⑤)。 +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum CloseBehavior { + /// 每次关闭时弹窗询问(缺省;持久化形态为字段缺省 None)。 + Ask, + /// 最小化到托盘:窗口销毁、应用驻留(QuitMode::Explicit 下无窗口 + /// 不退出),托盘「显示窗口」重建。 + ToTray, + /// 退出程序(保存窗口状态后 cx.quit)。 + Quit, +} + +impl CloseBehavior { + /// 持久化串 ↔ 枚举(未知串按 Ask 容错)。 + pub fn from_persisted(s: &str) -> Self { + match s { + "tray" => CloseBehavior::ToTray, + "quit" => CloseBehavior::Quit, + _ => CloseBehavior::Ask, + } + } + + fn as_persisted(self) -> Option<&'static str> { + match self { + CloseBehavior::Ask => None, + CloseBehavior::ToTray => Some("tray"), + CloseBehavior::Quit => Some("quit"), + } + } } impl UiState { @@ -62,6 +97,23 @@ pub fn normalize_sender(sender: &str) -> String { email.trim().to_ascii_lowercase() } +/// 读当前关闭主窗口行为(缺省 Ask;未知串容错为 Ask)。 +pub fn close_behavior() -> CloseBehavior { + CloseBehavior::from_persisted( + &load().close_behavior.unwrap_or_default(), + ) +} + +/// 写关闭主窗口行为(读改写整份 ui-state.json,Ask 清除记忆)。 +pub fn set_close_behavior(behavior: CloseBehavior) { + let mut state = load(); + let next = behavior.as_persisted().map(str::to_string); + if state.close_behavior != next { + state.close_behavior = next; + save(&state); + } +} + /// 记住发件人已放行远程图片(读改写整份 ui-state.json——theme/lang 等其余 /// 字段原样保留;重复记忆幂等)。写盘失败静默(读侧 load 已宽容降级)。 pub fn remember_remote_image_sender(sender: &str) { diff --git a/crates/postium-ui/src/views/settings.rs b/crates/postium-ui/src/views/settings.rs index e15ddf6d..7048f487 100644 --- a/crates/postium-ui/src/views/settings.rs +++ b/crates/postium-ui/src/views/settings.rs @@ -989,6 +989,7 @@ impl Render for SettingsView { ) .child(render_theme_row(self, cx)) .child(render_language_row(cx)) + .child(render_close_behavior_row(cx)) .into_any_element(), SettingsSection::Accounts => v_flex() .p_5() @@ -1932,6 +1933,53 @@ fn render_language_row(cx: &mut Context) -> impl IntoElement { ) .child(seg) } + +/// 关闭窗口行为行(线上反馈⑤):Power 图标 + 三段(每次询问/最小化到托盘/ +/// 退出程序),点击即持久化 ui-state.json。 +fn render_close_behavior_row(cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + let current = crate::ui_state::close_behavior(); + let mut seg = h_flex().gap_1().p(px(2.)).rounded(px(8.)).border_1().border_color(theme.border); + for (key, behavior, label) in [ + ("close-ask", crate::ui_state::CloseBehavior::Ask, t("settings.closeAsk")), + ("close-tray", crate::ui_state::CloseBehavior::ToTray, t("settings.closeTray")), + ("close-quit", crate::ui_state::CloseBehavior::Quit, t("settings.closeQuit")), + ] { + let sel = current == behavior; + let selector = key.to_string(); + seg = seg.child( + div() + .id(key) + .debug_selector(move || selector.clone()) + .px(px(10.)) + .py(px(4.)) + .rounded(px(6.)) + .cursor_pointer() + .text_size(px(12.)) + .when(sel, |d| d.bg(theme.accent).text_color(theme.accent_foreground)) + .when(!sel, |d| { + d.text_color(theme.muted_foreground) + .hover(|s| s.bg(theme.accent.opacity(0.12))) + }) + .child(label) + .on_click(cx.listener(move |_: &mut SettingsView, _: &ClickEvent, _: &mut Window, cx: &mut Context| { + crate::ui_state::set_close_behavior(behavior); + cx.notify(); + })), + ); + } + h_flex() + .items_center() + .child( + h_flex() + .items_center() + .gap_2() + .flex_1() + .child(gpui_kit::component::Icon::new(IconName::Power).size_4().text_color(theme.muted_foreground)) + .child(div().text_size(px(13.)).child(t("settings.closeBehavior"))), + ) + .child(seg) +} /// 同步完成后刷新主窗口的邮件列表(经全局主壳注册表;设置窗口触发)。 fn refresh_main_email_lists(api: &Arc, cx: &mut gpui_kit::AsyncApp) { let _ = cx.update(|app: &mut App| { diff --git a/crates/postium-ui/src/views/title_bar.rs b/crates/postium-ui/src/views/title_bar.rs index 9a744931..29aeae14 100644 --- a/crates/postium-ui/src/views/title_bar.rs +++ b/crates/postium-ui/src/views/title_bar.rs @@ -54,6 +54,8 @@ pub fn render( let muted_fg = theme.muted_foreground; let secondary_hover = theme.secondary_hover; let maximized = window.is_maximized(); + // 关闭按钮分流需要主壳实体(弹窗询问态挂在 AppShell 上) + let shell_handle = cx.entity(); // 选中邮件时标题栏居中显示邮件主题;无选中时中间留空 let subject = shell .detail @@ -127,8 +129,9 @@ pub fn render( secondary_hover, cx, )) - // 关闭:保存窗口状态后销毁窗口(程序驻留托盘,「显示窗口」重建主窗口; - // 退出走托盘菜单)。销毁需异步(事件分发栈上同步移除自身窗口不安全)。 + // 关闭:按关闭行为分流(线上反馈⑤)——托盘驻留(销毁窗口、应用 + // 驻留,「显示窗口」重建)/ 退出程序 / 每次询问(弹窗,勾选记住后 + // 不再问)。销毁需异步(事件分发栈上同步移除自身窗口不安全)。 .child( div() .id("win-close") @@ -140,13 +143,13 @@ pub fn render( .justify_center() .text_color(theme.foreground) .hover(move |s| s.bg(theme.danger).text_color(theme.danger_foreground)) - .on_mouse_down(MouseButton::Left, |_, window, cx| { - crate::window_state::save(window); - let handle = window.window_handle(); - cx.spawn(async move |cx| { - let _ = handle.update(cx, |_, window, _| window.remove_window()); - }) - .detach(); + .on_mouse_down(MouseButton::Left, { + let shell = shell_handle.clone(); + move |_, window, cx| { + let _ = shell.update(cx, |shell, cx| { + shell.request_close(window, cx); + }); + } }) .child(gpui_kit::component::Icon::new(IconName::WindowClose).size_3p5()), ) From bd0b361779749aa577dbeb2d423a88887a786f6d Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 22:21:01 +0800 Subject: [PATCH 12/20] =?UTF-8?q?feat(ui):=20=E5=90=AF=E5=8A=A8=E9=A2=84?= =?UTF-8?q?=E8=BD=BD=E9=A6=96=E5=B1=8F=E6=95=B0=E6=8D=AE=E2=80=94=E2=80=94?= =?UTF-8?q?=E4=B8=BB=E7=AA=97=E5=8F=A3=E6=89=93=E5=BC=80=E5=8D=B3=E6=9C=89?= =?UTF-8?q?=E5=86=85=E5=AE=B9=EF=BC=88=E7=BA=BF=E4=B8=8A=E5=8F=8D=E9=A6=88?= =?UTF-8?q?=E2=91=A5=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:首屏数据(账号列表 + 每账号文件夹统计/标签 + 收件箱首页,1+2N+1 条查询)全部经单条 tokio_rusqlite 连接 FIFO 排队——窗口先渲染空白,查询回填后才出数据(启动期与迁移/写入竞争时约两秒)。 修复:open_main_window 在开窗前 block_on 预载(此时尚无窗口,不冻结任何 UI),PreloadedHome 注入 store 种子——AccountsStore::with_preloaded / EmailsStore::seeded_inbox(版本号从 1 起,宿主首帧即构建列表视图),首帧即有侧栏与收件箱内容。空预载(无账号/查询失败)回退懒加载原路径(e2e 全部同路径不受影响);托盘重建主窗口同受益(重建即带新数据)。预载耗时入日志(后续性能观察锚点)。 e2e:preloaded_shell_first_frame_has_data——只 draw 不 park(懒加载任务未执行)断言首帧数据来自种子注入。80×2 并发 + 23 套件全绿。 --- crates/postium-ui/src/app.rs | 104 +++++++++++++++++-- crates/postium-ui/src/e2e_mail_menu_tests.rs | 38 +++++++ crates/postium-ui/src/stores/accounts.rs | 12 +++ crates/postium-ui/src/stores/emails.rs | 22 +++- 4 files changed, 168 insertions(+), 8 deletions(-) diff --git a/crates/postium-ui/src/app.rs b/crates/postium-ui/src/app.rs index 3bdd6de7..a6ad6cab 100644 --- a/crates/postium-ui/src/app.rs +++ b/crates/postium-ui/src/app.rs @@ -76,12 +76,79 @@ pub(crate) fn window_title_for( } } +/// 启动预载首屏数据(线上反馈⑥):主窗口打开前取入内存,首帧即有侧栏 +/// 账号/统计与收件箱列表——免「窗口空白约两秒等查询回填」(全部查询经 +/// 单条 tokio_rusqlite 连接 FIFO,启动期与其他写入竞争时首屏回填更慢)。 +/// +/// 空结果(无账号/查询失败)等价 [`PreloadedHome::default`],构造侧回退 +/// 懒加载路径,行为与预载前一致。 +pub(crate) struct PreloadedHome { + pub groups: Vec, + pub inbox: Option, +} + +impl Default for PreloadedHome { + fn default() -> Self { + Self { + groups: Vec::new(), + inbox: None, + } + } +} + +/// 预载查询:与 AccountsStore::reload / EmailsStore 首次 navigate 完全 +/// 同序列(账号 → 每账号统计/标签 → 收件箱首页)。 +pub(crate) async fn preload_home(api: &Arc) -> PreloadedHome { + use crate::stores::emails::PAGE_LIMIT; + let accounts = api.list_accounts().await.unwrap_or_default(); + let mut groups = Vec::with_capacity(accounts.len()); + for account in accounts { + let stats = api + .get_folder_stats(account.id) + .await + .unwrap_or_else(|e| { + tracing::warn!(target: "postium::ui", id = account.id, "预载文件夹统计失败: {e}"); + Vec::new() + }); + let labels = api.list_labels(account.id).await.unwrap_or_else(|e| { + tracing::warn!(target: "postium::ui", id = account.id, "预载标签失败: {e}"); + Vec::new() + }); + groups.push(crate::stores::accounts::AccountNode { + account, + stats, + labels, + }); + } + let inbox = api + .list_emails_by_category_for_all_accounts( + postium_core::service::email_service::EmailCategory::Inbox, + 0, + PAGE_LIMIT, + false, + ) + .await + .ok(); + PreloadedHome { groups, inbox } +} + /// 打开主窗口。 /// /// `sync_rx` 为主窗口的同步事件接收端;`None` 时(托盘重建已关闭的 /// 主窗口)使用空通道占位——后台调度的消费循环随旧窗口销毁,重建窗口 /// 不再接收调度事件(同步状态以列表轮询刷新为准)。 pub fn open_main_window(api: Arc, sync_rx: Option, cx: &mut App) { + // 启动预载(线上反馈⑥):窗口出现即带数据。此时尚无窗口,block_on + // 不冻结任何 UI;预载耗时入日志(后续性能观察锚点)。 + let preload_started = std::time::Instant::now(); + let preload = crate::runtime::runtime().block_on(preload_home(&api)); + tracing::info!( + target: "postium::ui", + "启动预载完成:账号组 {} / 收件箱首页 {} 封({:?})", + preload.groups.len(), + preload.inbox.as_ref().map(|r| r.emails.len()).unwrap_or(0), + preload_started.elapsed() + ); let sync_rx = sync_rx .unwrap_or_else(|| crate::stores::sync::sync_event_channel().1); let mut options = match crate::window_state::saved_bounds() { @@ -105,7 +172,7 @@ pub fn open_main_window(api: Arc, sync_rx: Option, cx: &mu ..Default::default() }); let (_handle, shell_view) = gpui_kit::open_window(options, cx, |window, cx| { - cx.new(|cx| AppShell::new(api, sync_rx, window, cx)) + cx.new(|cx| AppShell::new_with_preload(api, sync_rx, preload, window, cx)) }) .expect("打开主窗口失败"); // 注册全局弱引用(窗口关闭后自动失效) @@ -165,6 +232,18 @@ impl AppShell { sync_rx: SyncEventRx, window: &mut Window, cx: &mut Context, + ) -> Self { + Self::new_with_preload(api, sync_rx, PreloadedHome::default(), window, cx) + } + + /// [`Self::new`] 的预载形态(线上反馈⑥):主窗口打开前已取好的首屏 + /// 数据直接注入 store,首帧即有内容;空预载回退懒加载(e2e 同路径)。 + pub(crate) fn new_with_preload( + api: Arc, + sync_rx: SyncEventRx, + preload: PreloadedHome, + window: &mut Window, + cx: &mut Context, ) -> Self { // 恢复持久化偏好(默认暗色,与旧版一致;system 跟随系统外观) let ui = crate::ui_state::load(); @@ -226,17 +305,28 @@ impl AppShell { } }); - let accounts = init_accounts_store(&api, cx); + // 启动预载注入(线上反馈⑥):有种子 → 首帧即有数据(免 reload/ + // navigate 异步回填的空白窗口);空种子 → 懒加载原路径。 + let accounts = if preload.groups.is_empty() { + init_accounts_store(&api, cx) + } else { + cx.new(|_cx| crate::stores::accounts::AccountsStore::with_preloaded(preload.groups)) + }; let sidebar = cx.new(|_cx| Sidebar { accounts: accounts.clone(), current: NavTarget::AllInbox, }); - let emails = cx.new(|cx| { - let mut store = EmailsStore::new(cx); - store.navigate(NavTarget::AllInbox, &api, cx); - store - }); + let emails = match preload.inbox { + Some(resp) if !resp.emails.is_empty() => { + cx.new(|_cx| EmailsStore::seeded_inbox(resp)) + } + _ => cx.new(|cx| { + let mut store = EmailsStore::new(cx); + store.navigate(NavTarget::AllInbox, &api, cx); + store + }), + }; let detail = cx.new(|cx| DetailStore::new(cx)); // 同步事件消费(core 返回的接收端)+ 后台调度器 diff --git a/crates/postium-ui/src/e2e_mail_menu_tests.rs b/crates/postium-ui/src/e2e_mail_menu_tests.rs index a11f3f4e..6e57e614 100644 --- a/crates/postium-ui/src/e2e_mail_menu_tests.rs +++ b/crates/postium-ui/src/e2e_mail_menu_tests.rs @@ -646,3 +646,41 @@ fn settings_close_behavior_persists(cx: &mut gpui_pre::TestAppContext) { // 收尾归零(Ask 清除记忆,防污染进程内后续测试) crate::ui_state::set_close_behavior(crate::ui_state::CloseBehavior::Ask); } + +/// 启动预载种子(线上反馈⑥):注入预载数据的 AppShell **首帧**即有账号组 +/// 与收件箱列表——只 draw 不 park(懒加载的异步任务尚未执行),证明数据 +/// 来自种子注入而非异步回填。 +#[gpui_pre::test] +fn preloaded_shell_first_frame_has_data(cx: &mut gpui_pre::TestAppContext) { + cx.dispatcher.allow_parking(); + let dir = tempfile::tempdir().unwrap(); + crate::e2e_tests::force_e2e_data_dir(); + let (api, sync_rx) = crate::e2e_tests::boot(dir.path()); + + // 预载查询(与 open_main_window 同函数):e2e 种子账号应取到非空数据 + let preload = + crate::runtime::runtime().block_on(crate::app::preload_home(&api)); + assert!(!preload.groups.is_empty(), "种子账号应预载出账号组"); + let inbox_len = preload.inbox.as_ref().map(|r| r.emails.len()).unwrap_or(0); + assert!(inbox_len > 0, "种子 INBOX 应预载出首页邮件"); + + let (shell, cx) = cx.add_window_view(|window, cx| { + crate::e2e_tests::setup(cx); + crate::app::AppShell::new_with_preload(api, sync_rx, preload, window, cx) + }); + // 只 draw 不 run_until_parked:懒加载 spawn 尚未跑,store 数据只能来自种子 + cx.update(|window, cx| window.draw(cx).clear(cx)); + let (groups, emails) = cx.update(|_window: &mut gpui_kit::Window, app: &mut gpui_kit::App| { + let shell_ref = shell.read(app); + ( + shell_ref.accounts.read(app).groups.len(), + shell_ref.emails.read(app).emails.len(), + ) + }); + assert!(groups > 0, "首帧账号组应来自种子(实际 {groups})"); + assert!(emails > 0, "首帧收件箱列表应来自种子(实际 {emails})"); + assert!( + !cx.update(|_w: &mut gpui_kit::Window, app: &mut gpui_kit::App| shell.read(app).emails.read(app).loading), + "种子路径不应处于 loading 态" + ); +} diff --git a/crates/postium-ui/src/stores/accounts.rs b/crates/postium-ui/src/stores/accounts.rs index 3c17e58f..3ae74786 100644 --- a/crates/postium-ui/src/stores/accounts.rs +++ b/crates/postium-ui/src/stores/accounts.rs @@ -25,6 +25,18 @@ pub struct AccountsStore { pending_reload: bool, } +impl AccountsStore { + /// 启动预载种子构造(线上反馈⑥):groups 已在主窗口打开前取好——首帧 + /// 侧栏即有账号/文件夹统计,免「窗口空白等 reload 回填」。 + pub fn with_preloaded(groups: Vec) -> Self { + Self { + groups, + loading: false, + pending_reload: false, + } + } +} + #[derive(Clone, Copy)] pub enum AccountsEvent { Reloaded, diff --git a/crates/postium-ui/src/stores/emails.rs b/crates/postium-ui/src/stores/emails.rs index f3c71883..44c43f8e 100644 --- a/crates/postium-ui/src/stores/emails.rs +++ b/crates/postium-ui/src/stores/emails.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use gpui_kit::{Context, EventEmitter}; use postium_core::api::CoreApi; -use postium_core::service::email_service::{EmailCategory, EmailDto}; +use postium_core::service::email_service::{EmailCategory, EmailDto, EmailListResponse}; use crate::nav::NavTarget; use crate::runtime::spawn_tokio; @@ -69,6 +69,26 @@ impl EmailsStore { } } + /// 启动预载种子构造(线上反馈⑥):AllInbox 首页已在主窗口打开前取好 + /// ——首帧列表即有数据,免「窗口空白两秒等查询回填」。版本号从 1 起 + /// (宿主初始 0 → 首帧即按新数据构建列表视图)。 + pub fn seeded_inbox(resp: EmailListResponse) -> Self { + Self { + nav: NavTarget::AllInbox, + emails: resp.emails, + total: resp.total, + page: 0, + loading: false, + selected: None, + selected_version: 0, + list_version: 1, + nav_version: 1, + unread_only: false, + search_query: None, + load_gen: 0, + } + } + /// 导航变化时重置并装载第一页(退出搜索上下文)。 pub fn navigate(&mut self, nav: NavTarget, api: &Arc, cx: &mut Context) { self.nav = nav; From 9bfcd268453ae120f9ea6d3b90025802b66915df Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 22:35:43 +0800 Subject: [PATCH 13/20] =?UTF-8?q?build(oauth):=20=E5=87=AD=E6=8D=AE?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=BF=9B=E7=A8=8B=E7=8E=AF=E5=A2=83=E5=8F=98?= =?UTF-8?q?=E9=87=8F=E6=B3=A8=E5=85=A5=E2=80=94=E2=80=94CI=20=E7=BB=8F=20G?= =?UTF-8?q?itHub=20secrets=20=E7=BC=96=E8=AF=91=E6=9C=9F=E5=8F=AF=E8=BE=BE?= =?UTF-8?q?=EF=BC=88=E7=BA=BF=E4=B8=8A=E5=8F=8D=E9=A6=88=E2=91=A6=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit build.rs 原仅读 .env 文件:无该文件的构建环境(CI runner)OAuth2 凭据缺失。新增进程 env 回退(文件值优先,GOOGLE/MICROSOFT _CLIENT_ID/_CLIENT_SECRET 四键);.env 缺失不再提前返回(空内容继续走回退);缺失告警改查注入结果集合(原实现查进程 env,本地 .env 注入成功也误报)。 凭据已设入 spartajet/postium-mail 的 Actions secrets(四键);test.yml 构建/测试两步与 nightly/release 的发布构建步骤注入对应 secrets。已本地三态验证:无 .env 无 env → 降级告警不阻断;无 .env 带 env → rustc-env 注入成功;.env 存在 → 文件注入优先。 --- .github/workflows/nightly.yml | 6 +++++ .github/workflows/release.yml | 6 +++++ .github/workflows/test.yml | 12 ++++++++++ crates/postium-core/build.rs | 43 +++++++++++++++++++++++++---------- 4 files changed, 55 insertions(+), 12 deletions(-) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 04e92129..ee8d21bd 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -120,6 +120,12 @@ jobs: - name: Build release binary run: cargo build --release --target ${{ matrix.target }} -p postium-ui + env: + GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }} + GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }} + MICROSOFT_CLIENT_ID: ${{ secrets.MICROSOFT_CLIENT_ID }} + MICROSOFT_CLIENT_SECRET: ${{ secrets.MICROSOFT_CLIENT_SECRET }} + # ── 打包为原生安装包(版本号取自 workspace Cargo.toml)── - name: Resolve version diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c62f3aa8..33606525 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -118,6 +118,12 @@ jobs: - name: Build release binary run: cargo build --release --target ${{ matrix.target }} -p postium-ui + env: + GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }} + GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }} + MICROSOFT_CLIENT_ID: ${{ secrets.MICROSOFT_CLIENT_ID }} + MICROSOFT_CLIENT_SECRET: ${{ secrets.MICROSOFT_CLIENT_SECRET }} + # ── 打包为原生安装包(版本号取自 workspace Cargo.toml)── - name: Resolve version diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cc9bfd91..fe7a079c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -37,10 +37,22 @@ jobs: - name: Cache Rust uses: Swatinem/rust-cache@v2 + # OAuth2 凭据经 secrets 注入构建期(线上反馈⑦:build.rs 进程 env + # 回退——无 .env 文件的 CI 也能编译出带凭据的二进制) - name: Build workspace run: cargo build --workspace + env: + GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }} + GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }} + MICROSOFT_CLIENT_ID: ${{ secrets.MICROSOFT_CLIENT_ID }} + MICROSOFT_CLIENT_SECRET: ${{ secrets.MICROSOFT_CLIENT_SECRET }} # 单独跑应用二进制构建产物检查(可选发布前置) # 全部测试(含 postium-ui 的 GPUI E2E,headless 无需显示服务器) - name: Run all tests run: cargo test --workspace + env: + GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }} + GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }} + MICROSOFT_CLIENT_ID: ${{ secrets.MICROSOFT_CLIENT_ID }} + MICROSOFT_CLIENT_SECRET: ${{ secrets.MICROSOFT_CLIENT_SECRET }} diff --git a/crates/postium-core/build.rs b/crates/postium-core/build.rs index 49623712..09703b79 100644 --- a/crates/postium-core/build.rs +++ b/crates/postium-core/build.rs @@ -34,12 +34,14 @@ fn main() { println!("cargo:rerun-if-changed={}", env_file.display()); println!("cargo:rerun-if-changed=build.rs"); - let Ok(content) = std::fs::read_to_string(&env_file) else { - // 没有 .env 不视为错误:编译可继续,OAuth2 启动时由 - // ensure_credentials 给出带指引的明确错误 - eprintln!("build.rs: 未找到 .env(从 {} 向上查找)", manifest_dir.display()); - return; - }; + // 文件已注入的凭据键(进程 env 回退的去重 + 缺失告警判定依据) + let mut injected_keys = std::collections::HashSet::new(); + // 没有 .env 不视为错误(编译可继续,OAuth2 启动时由 ensure_credentials + // 给出带指引的明确错误)——空内容继续走进程 env 回退(CI 路径) + let content = std::fs::read_to_string(&env_file).unwrap_or_else(|_| { + eprintln!("build.rs: 未找到 .env(从 {} 向上查找),尝试进程环境变量", manifest_dir.display()); + String::new() + }); for (line_no, raw) in content.lines().enumerate() { let line = raw.trim(); @@ -68,16 +70,33 @@ fn main() { // 仅注入凭据类键,避免 .env 里的无关变量泄漏进构建环境 if key.ends_with("_CLIENT_ID") || key.ends_with("_CLIENT_SECRET") { println!("cargo:rustc-env={key}={value}"); + injected_keys.insert(key.to_string()); } } - // 编译期静默凭据是易错点:没有注入任何 *_CLIENT_ID 时给出醒目提示 - let injected_any = [ - "MICROSOFT_CLIENT_ID", + // 进程环境变量回退(CI 路径,线上反馈⑦):无 .env 文件的构建环境 + // (GitHub Actions 等)经 secrets 注入的 env 变量兜底——文件值优先, + // 文件未提供的凭据键查进程 env。凭据不回显日志。 + for key in [ "GOOGLE_CLIENT_ID", - ] - .iter() - .any(|k| std::env::var(k).map(|v| !v.is_empty()).unwrap_or(false)); + "GOOGLE_CLIENT_SECRET", + "MICROSOFT_CLIENT_ID", + "MICROSOFT_CLIENT_SECRET", + ] { + if !injected_keys.contains(key) + && let Ok(value) = std::env::var(key) + && !value.is_empty() + { + println!("cargo:rustc-env={key}={value}"); + injected_keys.insert(key.to_string()); + } + } + + // 编译期静默凭据是易错点:没有注入任何 *_CLIENT_ID 时给出醒目提示 + // (查注入结果集合——原实现查进程 env,.env 注入成功也误报告警) + let injected_any = ["MICROSOFT_CLIENT_ID", "GOOGLE_CLIENT_ID"] + .iter() + .any(|k| injected_keys.contains(*k)); if !injected_any { eprintln!( "build.rs: 工作区根 .env 中未找到有效的 OAuth2 客户端 ID\n\ From 4b40b83dabc57197e4e6b4b508ac9dd21b220cb3 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 22:49:45 +0800 Subject: [PATCH 14/20] =?UTF-8?q?build(oauth):=20=E5=87=AD=E6=8D=AE?= =?UTF-8?q?=E7=BC=BA=E5=A4=B1=E5=91=8A=E8=AD=A6=E6=94=B9=20cargo:warning?= =?UTF-8?q?=E2=80=94=E2=80=94CI=20=E6=97=A5=E5=BF=97=E5=8F=AF=E8=A7=82?= =?UTF-8?q?=E6=B5=8B=E6=B3=A8=E5=85=A5=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit eprintln 不进 cargo 常规输出,CI 上无法判断凭据是否注入;改 cargo:warning 后:CI 构建日志出现该警告=未注入,无警告=secrets 注入成功(值不回显)。移除遗留的 exit 压制写法。 --- crates/postium-core/build.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/postium-core/build.rs b/crates/postium-core/build.rs index 09703b79..72988aac 100644 --- a/crates/postium-core/build.rs +++ b/crates/postium-core/build.rs @@ -5,7 +5,6 @@ //! `.env` 不进版本库(见 .gitignore);模板见 `.env.example`。 use std::path::PathBuf; -use std::process::exit; fn main() { // 从本 crate 目录向上逐级查找 .env(约定放工作区根) @@ -98,12 +97,10 @@ fn main() { .iter() .any(|k| injected_keys.contains(*k)); if !injected_any { - eprintln!( - "build.rs: 工作区根 .env 中未找到有效的 OAuth2 客户端 ID\n\ - (需要 MICROSOFT_CLIENT_ID / GOOGLE_CLIENT_ID)。\n\ - OAuth2 登录将在启动授权时返回明确错误;密码型登录不受影响。" + // cargo:warning:进编译日志(CI 可观测「凭据未注入」——值不回显)。 + // 不视为构建失败:保持其他功能可构建/可测试。 + println!( + "cargo:warning=build.rs: 未注入任何 OAuth2 客户端 ID(需要 MICROSOFT_CLIENT_ID / GOOGLE_CLIENT_ID,来源 .env 文件或环境变量)。OAuth2 登录将在启动授权时报错;密码型登录不受影响" ); - // 不 exit(1):保持其他功能可构建/可测试 - let _ = exit; } } From ea73709249d2ba1b3a5c668903743142c35b75d1 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 23:09:30 +0800 Subject: [PATCH 15/20] =?UTF-8?q?fix(ci):=20=E6=A0=87=E8=AE=B0=E5=BF=AB?= =?UTF-8?q?=E7=85=A7=20.txt=20=E9=94=81=E5=AE=9A=20LF=E2=80=94=E2=80=94Win?= =?UTF-8?q?dows=20runner=20autocrlf=20=E8=BD=AC=E6=8D=A2=E8=87=B4=E5=AD=97?= =?UTF-8?q?=E8=8A=82=E7=BA=A7=E6=AF=94=E5=AF=B9=E8=AF=AF=E6=8A=A5=EF=BC=88?= =?UTF-8?q?PR=20#13=20=E5=AE=9E=E6=B5=8B=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitattributes b/.gitattributes index 75c8aa8f..591b499a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,6 @@ crates/postium-html/tests/fixtures/snapshots/*.json text eol=lf # fixture 语料同样固定 LF,保证管线输入跨平台一致(空白折叠语义不受影响,双保险) crates/postium-html/tests/fixtures/*.html text eol=lf +# 标记序列化快照(markers.rs 逐字节比对):Windows runner checkout 转 CRLF +# 会与 '\n' join 的序列化产物不一致(PR #13 CI 实测踩中) +crates/postium-html/tests/fixtures/markers/*.txt text eol=lf From 4bc68860866310cd0d37110bda496662d765028c Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Tue, 17 Nov 2026 23:51:39 +0800 Subject: [PATCH 16/20] =?UTF-8?q?fix(sync):=20INBOX=20=E5=A4=A7=E5=B0=8F?= =?UTF-8?q?=E5=86=99=E5=8F=98=E4=BD=93=E5=8F=8C=E5=86=99=E2=80=94=E2=80=94?= =?UTF-8?q?=E5=90=8C=E4=B8=80=E5=B0=81=E9=82=AE=E4=BB=B6=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E5=87=BA=E7=8E=B0=E4=B8=A4=E6=9D=A1=EF=BC=88=E7=BA=BF=E4=B8=8A?= =?UTF-8?q?=E5=8F=8D=E9=A6=88=E2=91=A7=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:IMAP 服务器 LIST 返回的收件箱名形态不一(163/Outlook 实测小写 inbox),全量 SyncNow 按 LIST 原名落库;IDLE 定向同步按保留名 INBOX 落库——(account_id, folder, uid) 唯一键大小写敏感,同一封新邮件双行,AllInbox 聚合两种形态都命中 → 列表每封两次。用户库实测:inbox 7486 行 + INBOX 575 行,576 组真重复。 修复三层:①normalize_imap_folder(RFC 3501 §5.1 INBOX 大小写不敏感保留名,规范形态大写)——引擎 discover_folders/sync_one_folder(写入+sync_state 键)、service resolve 出口与 list_emails 原名入口(查询)双侧统一。②幂等迁移 merge_inbox_folder_case_variants:emails/sync_state 每 (account,uid) 组保留最小 id 行(浏览历史/附件缓存多挂先行),变体删除+改名(attachments 级联兜底);库副本演练:删 576 改名 6910,残留 2 组为已发送+收件箱的合法多文件夹存在。③迁移单测(双形态合并/独行改名/幂等重跑)。工作区 23 套件全绿。 --- crates/postium-core/src/api.rs | 4 +- crates/postium-core/src/domain/folders/mod.rs | 38 ++++ crates/postium-core/src/engine/actor.rs | 18 +- .../src/infrastructure/storage/database.rs | 171 ++++++++++++++++++ .../postium-core/src/service/email_service.rs | 10 +- 5 files changed, 235 insertions(+), 6 deletions(-) diff --git a/crates/postium-core/src/api.rs b/crates/postium-core/src/api.rs index 30e8933f..8e292586 100644 --- a/crates/postium-core/src/api.rs +++ b/crates/postium-core/src/api.rs @@ -219,7 +219,9 @@ impl CoreApi { page: usize, limit: usize, ) -> Result { - self.emails.list(account_id, folder, page, limit).await + // INBOX 保留名归一(线上反馈⑧):原名精确匹配入口与库内规范形态对齐 + let folder = crate::domain::folders::normalize_imap_folder(folder); + self.emails.list(account_id, &folder, page, limit).await } pub async fn list_emails_by_category( diff --git a/crates/postium-core/src/domain/folders/mod.rs b/crates/postium-core/src/domain/folders/mod.rs index ce19a5c2..4db4d874 100644 --- a/crates/postium-core/src/domain/folders/mod.rs +++ b/crates/postium-core/src/domain/folders/mod.rs @@ -11,3 +11,41 @@ pub mod special_use; pub use category::FolderCategory; pub use registry::{FolderRegistry, RemoteFolder}; pub use special_use::SpecialUseFlag; + +/// IMAP 文件夹名归一(RFC 3501 §5.1:`INBOX` 是大小写不敏感的保留名, +/// 规范形态大写)。 +/// +/// 落库与查询的统一出口(线上反馈⑧):不同 IMAP 服务器 LIST 返回的收件箱 +/// 形态不一(163/Outlook 实测 `inbox` 小写、保留名常作 `INBOX`),若按 +/// 原名入库,`(account_id, folder, uid)` 唯一键把同一封邮件判成两条 +/// (全量同步写 LIST 原名、IDLE 定向同步写保留名 → 双行)。所有写入 +/// emails/sync_state 的 folder 值与按名查询的入参都必须先过本函数; +/// 其余文件夹名保持服务器原名(大小写有语义的服务器存在,不盲归一)。 +pub fn normalize_imap_folder(name: &str) -> String { + if name.eq_ignore_ascii_case("INBOX") { + "INBOX".to_string() + } else { + name.to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inbox_variants_normalize_to_canonical() { + for variant in ["INBOX", "inbox", "Inbox", "iNbOx"] { + assert_eq!(normalize_imap_folder(variant), "INBOX"); + } + } + + #[test] + fn non_inbox_folders_keep_original_form() { + // 大小写有语义的服务器存在(如 macOS Server 的 "Sent" vs "sent"): + // 仅 INBOX 保留名归一 + for kept in ["&XfJT0ZAB-", "Sent Messages", "[Gmail]/All Mail", "Archive"] { + assert_eq!(normalize_imap_folder(kept), kept); + } + } +} diff --git a/crates/postium-core/src/engine/actor.rs b/crates/postium-core/src/engine/actor.rs index e433dd02..2f4a8dba 100644 --- a/crates/postium-core/src/engine/actor.rs +++ b/crates/postium-core/src/engine/actor.rs @@ -408,15 +408,23 @@ impl AccountEngine { folder: Option, db: DbConn, ) -> Result, MailError> { - let Some(listed) = folder.map(|name| vec![name]) else { + // INBOX 保留名归一(线上反馈⑧):LIST 原名(163/Outlook 实测小写 + // `inbox`)与 IDLE 定向同步的保留名(`INBOX`)会以不同 folder 值 + // 落库——同一封邮件双行。同步目标统一规范形态后,写入与 + // sync_state 键都单形态。 + let Some(listed) = folder.map(|name| { + vec![crate::domain::folders::normalize_imap_folder(&name)] + }) else { let listed = self .pool .with_control(&|s| Box::pin(async move { s.session.list_folders().await })) .await?; + let mut seen = std::collections::HashSet::new(); let targets: Vec = listed .iter() .filter(|f| !f.no_select) - .map(|f| f.name.clone()) + .map(|f| crate::domain::folders::normalize_imap_folder(&f.name)) + .filter(|name| seen.insert(name.clone())) .collect(); // 标准类别回写(沿用旧 dispatcher:供侧栏分类 / get_folder_stats 解析)。 @@ -470,8 +478,10 @@ impl AccountEngine { target: &str, ) -> Result { let account_id = self.account.id; - let local = local_sync_state_from_db(&db, account_id, target).await?; - let target = target.to_string(); + // 双保险:INBOX 保留名归一(discover_folders 已归一,定向入口直调 + // 时兜底——sync_state 与 emails 的 folder 键保持单形态) + let target = crate::domain::folders::normalize_imap_folder(target); + let local = local_sync_state_from_db(&db, account_id, &target).await?; // with_control 闭包为 Fn(失败重建重试会再次调用):捕获值在闭包体内 // clone 后再移入 async 块 diff --git a/crates/postium-core/src/infrastructure/storage/database.rs b/crates/postium-core/src/infrastructure/storage/database.rs index 1d07c8c4..46125236 100644 --- a/crates/postium-core/src/infrastructure/storage/database.rs +++ b/crates/postium-core/src/infrastructure/storage/database.rs @@ -73,6 +73,7 @@ impl DbConn { conn.execute_batch(SCHEMA_SQL)?; migrate_sync_state_history_columns(conn)?; migrate_sync_state_highest_modseq_column(conn)?; + merge_inbox_folder_case_variants(conn)?; Ok(()) }) .await @@ -192,6 +193,108 @@ fn migrate_sync_state_highest_modseq_column(conn: &rusqlite::Connection) -> rusq Ok(()) } +/// 合并 INBOX 大小写变体行(线上反馈⑧,幂等迁移)。 +/// +/// 背景:IMAP 全量同步按 LIST 原名落库(163/Outlook 实测小写 `inbox`), +/// IDLE 定向同步按保留名 `INBOX` 落库——`(account_id, folder, uid)` 唯一键 +/// 大小写敏感,同一封邮件双行(列表每封显示两次)。写入/查询侧已统一走 +/// [`crate::domain::folders::normalize_imap_folder`],本迁移把存量归一: +/// +/// - `emails`:每个 `(account_id, uid)` 组保留 id 最小的行(浏览历史/已读/ +/// 附件缓存多数挂在先行上,attachments 级联删除兜底),其余变体行删除, +/// 保留行 folder 改为规范形态 `INBOX`; +/// - `sync_state`:同法保留最小 id 行并归一(变体高水位丢失可接受——下轮 +/// 同步按 UID 增量重拉一次,无数据损失)。 +fn merge_inbox_folder_case_variants(conn: &mut rusqlite::Connection) -> rusqlite::Result<()> { + // 快速幂等出口:无非规范变体即空转 + let variant_emails: i64 = conn.query_row( + "SELECT COUNT(*) FROM emails WHERE folder <> 'INBOX' AND folder = 'inbox'", + [], + |row| row.get(0), + )?; + let variant_state: i64 = conn.query_row( + "SELECT COUNT(*) FROM sync_state WHERE folder <> 'INBOX' AND folder = 'inbox'", + [], + |row| row.get(0), + )?; + if variant_emails == 0 && variant_state == 0 { + return Ok(()); + } + + let tx = conn.transaction()?; + // 1) 删除同 (account, uid) 组内非最小 id 的 inbox 变体行 + let removed_emails = tx.execute( + "DELETE FROM emails + WHERE folder = 'inbox' + AND EXISTS ( + SELECT 1 FROM emails e2 + WHERE e2.account_id = emails.account_id + AND e2.uid = emails.uid + AND e2.id < emails.id + )", + [], + )?; + // 2) 删除保留行若为变体时将冲突的 INBOX 行去掉(inbox 行 id 更小的组): + // 组内 inbox 行保留 → 删同组 id 更大的 INBOX 行 + let removed_upper = tx.execute( + "DELETE FROM emails + WHERE folder = 'INBOX' + AND EXISTS ( + SELECT 1 FROM emails e2 + WHERE e2.account_id = emails.account_id + AND e2.uid = emails.uid + AND e2.folder = 'inbox' + AND e2.id < emails.id + )", + [], + )?; + // 3) 剩余 inbox 变体行(该组最早行)改名为规范形态 + let renamed_emails = tx.execute( + "UPDATE emails SET folder = 'INBOX' WHERE folder = 'inbox'", + [], + )?; + // sync_state 同法 + let removed_state = tx.execute( + "DELETE FROM sync_state + WHERE folder = 'inbox' + AND EXISTS ( + SELECT 1 FROM sync_state s2 + WHERE s2.account_id = sync_state.account_id + AND s2.id < sync_state.id + AND (s2.folder = 'inbox' OR s2.folder = 'INBOX') + )", + [], + )?; + let removed_state_upper = tx.execute( + "DELETE FROM sync_state + WHERE folder = 'INBOX' + AND EXISTS ( + SELECT 1 FROM sync_state s2 + WHERE s2.account_id = sync_state.account_id + AND s2.folder = 'inbox' + AND s2.id < sync_state.id + )", + [], + )?; + let renamed_state = tx.execute( + "UPDATE sync_state SET folder = 'INBOX' WHERE folder = 'inbox'", + [], + )?; + tx.commit()?; + + tracing::info!( + "迁移:INBOX 大小写变体合并完成——emails 删除 {}+{} 行 / 改名 {} 行;\ + sync_state 删除 {}+{} 行 / 改名 {} 行", + removed_emails, + removed_upper, + renamed_emails, + removed_state, + removed_state_upper, + renamed_state, + ); + Ok(()) +} + /// 检查指定名称的索引是否存在(用于迁移前的幂等判断)。 /// /// 查询 `sqlite_master` 中 `type='index'` 且名称匹配的记录,行数 > 0 即存在。 @@ -446,4 +549,72 @@ mod tests { .unwrap(); assert_eq!(tables.len(), 4, "联系人四表应存在: {tables:?}"); } + + /// INBOX 大小写变体合并(线上反馈⑧):双形态同 UID → 保留最小 id 行、 + /// folder 归一 INBOX;仅小写 → 改名;sync_state 同法;幂等重跑零变化。 + #[tokio::test] + async fn inbox_case_variants_merge_to_single_canonical_row() { + let db = DbConn::open_in_memory_for_test().await.unwrap(); + // 账号 1:双形态同 UID(inbox id 小 / INBOX id 大 → 保留 inbox 行改名) + // 账号 2:仅小写形态 + db.call(|conn| { + conn.execute("INSERT INTO accounts (email, name, provider, created_at, updated_at) VALUES ('a@t', 'A', 'custom', 0, 0), ('b@t', 'B', 'custom', 0, 0)", [])?; + for (acc, folder, uid, subj) in [ + (1, "inbox", 100, "first-path"), + (1, "INBOX", 100, "idle-path"), + (2, "inbox", 200, "solo"), + ] { + conn.execute( + "INSERT INTO emails (account_id, folder, uid, sender_email, recipient_emails, subject, is_deleted, sent_at, received_at, created_at, updated_at) + VALUES (?1, ?2, ?3, 's@t', 'r@t', ?4, 0, 1000, 1000, 0, 0)", + rusqlite::params![acc, folder, uid, subj], + )?; + } + conn.execute( + "INSERT INTO sync_state (account_id, folder, synced_at) VALUES (1, 'inbox', 1), (1, 'INBOX', 2)", + [], + )?; + super::merge_inbox_folder_case_variants(conn) + }) + .await + .unwrap(); + + let rows: Vec<(i32, String, i32, String)> = db + .call(|conn| { + Ok(conn + .prepare("SELECT account_id, folder, uid, subject FROM emails ORDER BY account_id")? + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))? + .collect::>>()?) + }) + .await + .unwrap(); + assert_eq!( + rows, + vec![ + (1, "INBOX".into(), 100, "first-path".into()), + (2, "INBOX".into(), 200, "solo".into()), + ], + "变体组保留最小 id 行且归一 INBOX;独行仅改名" + ); + let states: Vec = db + .call(|conn| { + Ok(conn + .prepare("SELECT folder FROM sync_state ORDER BY id")? + .query_map([], |r| r.get(0))? + .collect::>>()?) + }) + .await + .unwrap(); + assert_eq!(states, vec!["INBOX".to_string()], "sync_state 单形态"); + + // 幂等:重跑无变化 + db.call(|conn| super::merge_inbox_folder_case_variants(conn)) + .await + .unwrap(); + let count: i64 = db + .call(|conn| conn.query_row("SELECT COUNT(*) FROM emails", [], |r| r.get(0))) + .await + .unwrap(); + assert_eq!(count, 2, "幂等重跑不得再删/改行"); + } } diff --git a/crates/postium-core/src/service/email_service.rs b/crates/postium-core/src/service/email_service.rs index d7bbcfb7..0ac2509b 100644 --- a/crates/postium-core/src/service/email_service.rs +++ b/crates/postium-core/src/service/email_service.rs @@ -1214,7 +1214,15 @@ async fn resolve_category_folders_for_account( Some(cat) => cat, None => return Ok(Vec::new()), }; - Ok(registry.resolve(cat)) + // INBOX 保留名归一(线上反馈⑧):库里 folder 值统一规范形态(引擎写入 + // 侧 + 存量迁移),查询侧同口径才能命中 + let mut seen = std::collections::HashSet::new(); + Ok(registry + .resolve(cat) + .into_iter() + .map(|name| crate::domain::folders::normalize_imap_folder(&name)) + .filter(|name| seen.insert(name.clone())) + .collect()) } // ═════════════════════════════════════════════════════════════════════════ From 5a53090b7c44bd5061de5964abe2e4ad1baae980 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Wed, 18 Nov 2026 00:13:29 +0800 Subject: [PATCH 17/20] =?UTF-8?q?fix(log):=20=E5=8E=8B=E5=88=B6=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E7=A7=BB=E9=99=A4=E5=90=8E=E7=9A=84=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E6=BF=80=E6=B4=BB=E5=9B=9E=E8=B0=83=E5=99=AA=E9=9F=B3=EF=BC=88?= =?UTF-8?q?window=20not=20found=EF=BC=8C=E7=BA=BF=E4=B8=8A=E5=8F=8D?= =?UTF-8?q?=E9=A6=88=E2=91=A8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实机复现验证:关闭到托盘(remove_window)后 ERROR 'handling active status change ... window not found' 为 gpui-pre 平台回调在窗口已移除后仍到达的日志噪音——QuitMode::Explicit 下进程持续驻留(自动化探针 50s+ 存活),不导致退出。按文件判定压制(log 桥接同 directx_devices 先例)。 --- crates/postium-core/src/sys/log.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/postium-core/src/sys/log.rs b/crates/postium-core/src/sys/log.rs index 44506963..1ead26e1 100644 --- a/crates/postium-core/src/sys/log.rs +++ b/crates/postium-core/src/sys/log.rs @@ -6,9 +6,12 @@ /// 已知无害噪音(按源文件路径压制): /// - `directx_devices.rs`:无 D3D 调试层机器上的 DXGI debug 探测失败 /// (log 宏桥接记录,EnvFilter 的 target 过滤对其不生效,故按 file 判定) +/// - gpui-pre `window.rs`:窗口 remove 后平台激活回调仍到达("window not +/// found" ERROR)——关闭到托盘(窗口销毁、应用驻留)的必经噪音,实机 +/// 复现验证进程驻留正常(线上反馈⑨) fn is_known_noise(file: Option<&str>) -> bool { match file { - Some(f) => f.contains("directx_devices.rs"), + Some(f) => f.contains("directx_devices.rs") || (f.contains("gpui-pre") && f.contains("window.rs")), None => false, } } From dfc2f9d38238c49bcf6982ac1f0e2bc9f67c7435 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Wed, 18 Nov 2026 10:46:00 +0800 Subject: [PATCH 18/20] =?UTF-8?q?fix(tray):=20=E5=9B=BE=E6=A0=87=E8=BF=9B?= =?UTF-8?q?=E7=A8=8B=E7=BA=A7=E6=8C=81=E6=9C=89=E2=80=94=E2=80=94=E4=B8=BB?= =?UTF-8?q?=E7=AA=97=E5=8F=A3=E9=94=80=E6=AF=81=E4=B8=8D=E5=86=8D=E8=BF=9E?= =?UTF-8?q?=E5=B8=A6=E7=A7=BB=E9=99=A4=E6=89=98=E7=9B=98=E5=9B=BE=E6=A0=87?= =?UTF-8?q?=EF=BC=88=E7=BA=BF=E4=B8=8A=E5=8F=8D=E9=A6=88=E2=91=A8=E7=BB=AD?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:TrayIcon 挂在 AppShell._tray 字段,而 AppShell 是主窗口根视图——「最小化到托盘」remove_window 销毁窗口即 drop 实体,TrayIcon::Drop 触发 Shell_NotifyIcon(NIM_DELETE),图标消失(进程与 App 级轮询任务存活——所以后台在跑但托盘空了)。旧版因 QuitMode bug 从未真正驻留,该缺陷从未暴露。 修复:图标移入 tray 模块 thread_local 进程级持有(Windows TrayIcon 含裸 HWND 非 Send/Sync,须与消息泵同线程——static 不可用,thread_local 恰合且随主线程终结析构);setup_tray 幂等(主窗口重建复用图标);事件轮询任务 CAS 保证只 spawn 一次;AppShell._tray 字段退役,TRAY_ALIVE 语义不变。清理 TrayActions/ACTIONS_ID 死代码。80 e2e + 23 套件全绿。 --- crates/postium-ui/src/app.rs | 9 ++-- crates/postium-ui/src/tray.rs | 81 +++++++++++++++++++++++++++-------- 2 files changed, 67 insertions(+), 23 deletions(-) diff --git a/crates/postium-ui/src/app.rs b/crates/postium-ui/src/app.rs index a6ad6cab..90c6856b 100644 --- a/crates/postium-ui/src/app.rs +++ b/crates/postium-ui/src/app.rs @@ -208,8 +208,6 @@ pub struct AppShell { pub nav: NavTarget, /// 系统外观观察订阅(保持存活) _appearance_sub: Option, - /// 托盘句柄(保持存活) - _tray: Option, pub(crate) calendar_view: Option>, pub(crate) contacts_view: Option>, workflow_view: Option>, @@ -502,8 +500,10 @@ impl AppShell { }) .detach(); - let _tray = crate::tray::setup_tray(api.clone(), sync_store.clone(), cx); - if _tray.is_some() { + // 托盘图标由 tray 模块进程级持有(线上反馈⑨续:此前挂在本实体 + // 字段上,主窗口销毁即随实体 drop → 图标消失);此处只装配并 + // 记录可用性(关闭行为判定用) + if crate::tray::setup_tray(api.clone(), sync_store.clone(), cx) { TRAY_ALIVE.store(true, std::sync::atomic::Ordering::Relaxed); } @@ -524,7 +524,6 @@ impl AppShell { search_gen: 0, nav: NavTarget::AllInbox, _appearance_sub: appearance_sub, - _tray, calendar_view: None, contacts_view: None, workflow_view: None, diff --git a/crates/postium-ui/src/tray.rs b/crates/postium-ui/src/tray.rs index 33ea5e68..ecabf63d 100644 --- a/crates/postium-ui/src/tray.rs +++ b/crates/postium-ui/src/tray.rs @@ -10,16 +10,21 @@ use tray_icon::{TrayIcon, TrayIconBuilder}; use crate::stores::sync::SyncStore; -#[allow(dead_code)] -struct TrayActions { - #[allow(dead_code)] - show: u32, - compose: u32, - sync: u32, - quit: u32, + +thread_local! { + /// 托盘图标**进程级持有**(线上反馈⑨续):此前图标挂在 AppShell 的 + /// `_tray` 字段上——「最小化到托盘」销毁主窗口时 AppShell 实体一并 + /// drop,TrayIcon::Drop 即 Shell_NotifyIcon(NIM_DELETE),图标随之消失 + /// (进程与轮询任务是 App 级的所以活着)。thread_local 而非 static: + /// Windows TrayIcon 含裸 HWND 非 Send/Sync,且须与消息泵同线程;随 + /// 主线程终结(进程退出)析构,跨主窗口重建幂等复用。 + static TRAY_HOLD: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } -static ACTIONS_ID: u32 = 1; +/// 事件轮询任务只启动一次(主窗口重建时 setup_tray 幂等复用图标,轮询 +/// 不得重复 spawn——静态 channel 单消费者语义)。 +static TRAY_CONSUMER_STARTED: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); /// 托盘「显示窗口」/左键单击共享:主窗口存活 → 激活置前;已关闭(关闭到 /// 托盘)→ 重建主窗口。 @@ -42,7 +47,11 @@ fn show_main_window(api: &Arc, cx: &mut App) { } } -/// 装配托盘并启动事件消费循环。 +/// 装配托盘并启动事件消费循环(幂等:图标已持有则直接复用——主窗口 +/// 重建路径反复调用)。 +/// +/// 返回托盘是否可用(供关闭行为判定:无托盘环境真关闭,否则程序退出 +/// 只能走托盘菜单)。 /// /// 托盘是可选能力:Linux 无 appindicator/无会话总线等环境下 /// tray-icon 内部会 panic(毒化其全局 Lazy),此处兜底捕获, @@ -51,15 +60,22 @@ pub fn setup_tray( api: Arc, sync_store: gpui_kit::Entity, cx: &mut App, -) -> Option { +) -> bool { + if TRAY_HOLD.with(|t| t.borrow().is_some()) { + return true; + } let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { setup_tray_inner(api, sync_store, cx) })); match result { - Ok(tray) => tray, + Ok(Some(tray)) => { + TRAY_HOLD.with(|t| *t.borrow_mut() = Some(tray)); + true + } + Ok(None) => false, Err(payload) => { tracing::warn!("托盘初始化失败(无托盘环境属预期):{payload:?}"); - None + false } } } @@ -86,8 +102,41 @@ fn setup_tray_inner( .with_icon(icon) .build(); - // 事件消费:UI 线程轮询(菜单事件量极小,250ms 足够) - let api = api.clone(); + // 事件消费:UI 线程轮询(菜单事件量极小,250ms 足够)。幂等:图标 + // 进程级复用后 setup_tray 可能再次到达,轮询任务只启动一次。 + if TRAY_CONSUMER_STARTED + .compare_exchange( + false, + true, + std::sync::atomic::Ordering::AcqRel, + std::sync::atomic::Ordering::Acquire, + ) + .is_err() + { + tracing::debug!("托盘事件轮询已启动,跳过重复 spawn"); + } else { + spawn_tray_consumer(api.clone(), sync_store, cx); + } + + match tray { + Ok(t) => { + tracing::info!("系统托盘已就绪"); + Some(t) + } + Err(e) => { + tracing::warn!("托盘构建失败:{e}"); + None + } + } +} + +/// 托盘菜单/点击事件轮询(App 级任务:不随主窗口生灭——关闭到托盘后 +/// 依然消费事件)。 +fn spawn_tray_consumer( + api: Arc, + sync_store: gpui_kit::Entity, + cx: &mut App, +) { cx.spawn(async move |cx| { let menu_rx = MenuEvent::receiver(); let tray_rx = tray_icon::TrayIconEvent::receiver(); @@ -152,10 +201,6 @@ fn setup_tray_inner( } }) .detach(); - - let _ = ACTIONS_ID; - tracing::info!("系统托盘已就绪"); - tray.ok() } /// 加载托盘图标:Windows 用 ICO 多尺寸路径;其他平台解码内嵌 PNG 为 RGBA。 From a73ea61a5e0d81b75f6c7ddc8350dea0e8ad3909 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Wed, 18 Nov 2026 14:51:01 +0800 Subject: [PATCH 19/20] =?UTF-8?q?fix(windows):=20release=20=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E6=97=A0=E6=8E=A7=E5=88=B6=E5=8F=B0=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=20+=20=E6=97=A5=E5=BF=97=E8=90=BD=E7=9B=98=EF=BC=88=E7=BA=BF?= =?UTF-8?q?=E4=B8=8A=E5=8F=8D=E9=A6=88=E2=91=A9=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GUI 应用默认 console 子系统,启动即弹黑窗。修复:main.rs 顶部 #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]——release 无控制台(PE 头 subsystem=2 已验证),debug 保留控制台供开发看 stderr。 无控制台后日志不可见 → 新增文件日志:setup_logging(logs_dir) 写 ~/.postium/logs/postium.log(tracing-appender 非阻塞 writer 不拖慢 UI 线程;WorkerGuard 返回调用方全程持有——此前 mem::forget 导致缓冲不 flush 实测 0 字节)。文件无 ANSI 色彩、debug 双写控制台+文件;release 过滤器放宽到 INFO(文件无刷屏负担,启动迁移/预载耗时等运维日志可查)。 release 实机验证:PE subsystem=2 + postium.log 912 字节完整落盘(含启动预载耗时 634ms——旧版两秒空白的量化锚点)。23 套件全绿。 --- Cargo.lock | 59 +++++++++++++++++++++++------- Cargo.toml | 1 + crates/postium-core/Cargo.toml | 1 + crates/postium-core/src/sys/log.rs | 40 ++++++++++++++++---- crates/postium-ui/src/main.rs | 13 ++++++- 5 files changed, 91 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b8a6a5eb..e680f3e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1781,7 +1781,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.3", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1819,7 +1819,7 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" dependencies = [ - "libloading 0.7.4", + "libloading 0.8.9", ] [[package]] @@ -2044,7 +2044,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5014,7 +5014,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png 0.18.1", "thiserror 2.0.21", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5212,7 +5212,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6368,6 +6368,7 @@ dependencies = [ "tokio-test", "tokio-util", "tracing", + "tracing-appender", "tracing-subscriber", "url", "utf7-imap", @@ -6746,7 +6747,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -7395,7 +7396,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8049,7 +8050,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -8118,7 +8119,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -8292,6 +8293,12 @@ dependencies = [ "zeno", ] +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + [[package]] name = "syn" version = "1.0.109" @@ -8486,7 +8493,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8598,6 +8605,7 @@ dependencies = [ "powerfmt", "serde_core", "time-core", + "time-macros", ] [[package]] @@ -8606,6 +8614,16 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -8947,6 +8965,19 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror 2.0.21", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.31" @@ -9015,7 +9046,7 @@ dependencies = [ "once_cell", "png 0.18.1", "thiserror 2.0.21", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -9069,7 +9100,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -9816,7 +9847,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -10459,7 +10490,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" dependencies = [ "cfg-if", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e53330d8..d0a12a7d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,4 +26,5 @@ serde_json = "1" chrono = { version = "0.4", features = ["serde"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "registry", "fmt", "ansi"] } +tracing-appender = "0.2" async-trait = "0.1" diff --git a/crates/postium-core/Cargo.toml b/crates/postium-core/Cargo.toml index f52eb649..6b9af6a0 100644 --- a/crates/postium-core/Cargo.toml +++ b/crates/postium-core/Cargo.toml @@ -16,6 +16,7 @@ chrono.workspace = true thiserror.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["registry", "env-filter", "fmt", "ansi"] } +tracing-appender = { workspace = true } async-trait.workspace = true specta = { version = "=2.0.0-rc.24", features = ["chrono", "derive"] } diff --git a/crates/postium-core/src/sys/log.rs b/crates/postium-core/src/sys/log.rs index 1ead26e1..21af2e90 100644 --- a/crates/postium-core/src/sys/log.rs +++ b/crates/postium-core/src/sys/log.rs @@ -16,7 +16,9 @@ fn is_known_noise(file: Option<&str>) -> bool { } } -pub fn setup_logging() { +/// 初始化日志。返回 non-blocking writer 的 [`WorkerGuard`]——**调用方必须 +/// 在整个进程生命周期持有**(drop 即停 flush worker,缓冲区日志丢失)。 +pub fn setup_logging(logs_dir: std::path::PathBuf) -> tracing_appender::non_blocking::WorkerGuard { use tracing_subscriber::EnvFilter; use tracing_subscriber::Layer as _; use tracing_subscriber::layer::SubscriberExt; @@ -47,9 +49,12 @@ pub fn setup_logging() { } #[cfg(not(debug_assertions))] { - // release 默认 WARN;同样压制 html5ever 的 RcDom 局限告警 - // (foster parenting,线上反馈④——见 dev 分支注释) - EnvFilter::new("warn,html5ever=error") + // release:无控制台(windows_subsystem),日志只落文件——文件 + // 无刷屏负担,级别放宽到 INFO(启动迁移/预载耗时等运维日志 + // 可查);依赖噪音压制与 dev 分支同口径 + EnvFilter::new( + "info,gpui_pre=warn,gpui_pre_windows=warn,tao=warn,globset=warn,reqwest=warn,hyper_util=warn,html5ever=error,markup5ever=warn,selectors=warn", + ) } }); @@ -61,10 +66,31 @@ pub fn setup_logging() { .with_ansi(true) .with_filter(tracing_subscriber::filter::filter_fn(|meta| { !is_known_noise(meta.file()) - })); + })) + .with_filter(filter.clone()); + + // 文件日志(线上反馈⑩):release 构建无控制台(windows_subsystem), + // 日志必须落盘才可查——`~/.postium/logs/postium.log`(单文件追加, + // tracing-appender 非阻塞 writer:写盘不拖慢 UI 线程;guard 返回调用 + // 方持有,进程退出时 flush 缓冲)。debug 双写(控制台 + 文件),release + // 仅文件。文件无 ANSI 色彩。 + let (file_writer, guard) = tracing_appender::non_blocking( + tracing_appender::rolling::never(logs_dir, "postium.log"), + ); + let file_layer = tracing_subscriber::fmt::layer() + .with_target(false) + .with_thread_ids(false) + .with_file(true) + .with_line_number(true) + .with_ansi(false) + .with_writer(file_writer) + .with_filter(tracing_subscriber::filter::filter_fn(|meta| { + !is_known_noise(meta.file()) + })) + .with_filter(filter); - let layered = fmt_layer.with_filter(filter); - tracing_subscriber::registry().with(layered).init(); + tracing_subscriber::registry().with(fmt_layer).with(file_layer).init(); + guard } #[cfg(test)] diff --git a/crates/postium-ui/src/main.rs b/crates/postium-ui/src/main.rs index e892faac..59ec5226 100644 --- a/crates/postium-ui/src/main.rs +++ b/crates/postium-ui/src/main.rs @@ -1,4 +1,12 @@ //! Postium Mail 应用入口:数据目录 → 核心服务装配 → GPUI 主窗口。 +//! +//! Windows 子系统(线上反馈⑩):release 构建设为 `windows`——不分配控制台 +//! 窗口(GUI 应用默认 console 子系统会随启动弹黑窗)。debug 保留控制台 +//! 便于开发期看 stderr 日志;两配置的日志都同时落 +//! `~/.postium/logs/postium.log`(滚动文件,见 sys/log.rs)。 + +// 位置必须在所有 items 之前(crate 级内部属性) +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod app; mod i18n; @@ -34,14 +42,15 @@ pub fn resolve_data_dir() -> PathBuf { } fn main() { - postium_core::setup_logging(); + let data_dir = resolve_data_dir(); + // 日志 flush worker 的 guard 必须全程持有(drop 即停 flush,缓冲丢失) + let _log_guard = postium_core::setup_logging(data_dir.join("logs")); tracing::info!("Postium Mail (GPUI) 启动中..."); // --screenshot :为 Craft Anything 构建检查输出截图后退出 let screenshot = screenshot::init_from_args(); let screenshot_mode = screenshot.is_some(); - let data_dir = resolve_data_dir(); let e2e = std::env::var("POSTIUM_E2E").ok().as_deref() == Some("1"); let e2e_truth = std::env::var("POSTIUM_E2E_TRUTH").ok().as_deref() == Some("1"); From 98516e222d76b8b2d2bd40252de8bda03eea3d65 Mon Sep 17 00:00:00 2001 From: "Dr.Guo" Date: Wed, 18 Nov 2026 15:07:20 +0800 Subject: [PATCH 20/20] =?UTF-8?q?feat(app):=20=E5=8D=95=E5=AE=9E=E4=BE=8B?= =?UTF-8?q?=E2=80=94=E2=80=94=E7=AC=AC=E4=BA=8C=E5=AE=9E=E4=BE=8B=E5=94=A4?= =?UTF-8?q?=E9=86=92=E6=97=A2=E6=9C=89=E5=AE=9E=E4=BE=8B=E5=90=8E=E9=80=80?= =?UTF-8?q?=E5=87=BA=EF=BC=88=E7=BA=BF=E4=B8=8A=E5=8F=8D=E9=A6=88=E2=91=AA?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 通道:本机回环 TCP 握手(跨平台、零新依赖、无 win32 unsafe,避开 OAuth 端口 36279)。首个实例 bind 端口成为 Primary;后续实例 bind 失败 → 连接发送魔串,Primary 回 ACK 并经事件循环 show_main_window(存活激活置前 / 关闭到托盘则重建)——第二实例在重量级装配(CoreApi::init/数据库/引擎)之前退出,不碰库。握手带确认与 800ms 超时(端口被无关占用不误伤对方也绝不挂死);show_main_window 迁至 app.rs 供托盘/单实例双路共享;握手 ACK 不 shutdown(Both)(立即 RST 会吞掉客户端未读 ACK)。 实机双实例验证:第二实例「唤醒握手成功,本实例退出」exit=0,Primary 持续运行。23 套件全绿。 --- crates/postium-ui/src/app.rs | 55 +++++++++++++++++++++ crates/postium-ui/src/main.rs | 13 ++++- crates/postium-ui/src/single_instance.rs | 61 ++++++++++++++++++++++++ crates/postium-ui/src/tray.rs | 17 +------ 4 files changed, 129 insertions(+), 17 deletions(-) create mode 100644 crates/postium-ui/src/single_instance.rs diff --git a/crates/postium-ui/src/app.rs b/crates/postium-ui/src/app.rs index 90c6856b..397c05af 100644 --- a/crates/postium-ui/src/app.rs +++ b/crates/postium-ui/src/app.rs @@ -224,6 +224,61 @@ pub struct AppShell { status_bar: Option>, } +/// 显示主窗口(共享出口:托盘「显示窗口」/左键单击/单实例唤醒):主窗口 +/// 存活 → 激活置前;已关闭(关闭到托盘)→ 重建主窗口。 +pub(crate) fn show_main_window(api: &Arc, cx: &mut App) { + let shell_alive = cx + .try_global::() + .and_then(|main| main.0.upgrade()) + .is_some(); + if shell_alive { + if let Some(handle) = cx.active_window() { + let _ = handle.update(cx, |_, window, _| { + window.activate_window(); + }); + } + } else { + let api = api.clone(); + cx.defer(move |cx| { + open_main_window(api, None, cx); + }); + } +} + +/// 单实例 Primary 消费循环(main 接线):tokio 侧 accept+握手应答(阻塞 IO +/// 不进 gpui 执行器),gpui 侧消费握手事件 → 显示/重建主窗口(跨进程唤醒)。 +pub(crate) fn spawn_show_listener( + mut listener: std::net::TcpListener, + api: Arc, + cx: &mut App, +) { + let (tx, rx) = smol::channel::unbounded::<()>(); + crate::runtime::runtime().spawn(async move { + use std::io::{Read as _, Write as _}; + loop { + let Ok((mut sock, _)) = listener.accept() else { + break; // listener 失效(理论不发生:进程级持有) + }; + let _ = sock.set_read_timeout(Some(std::time::Duration::from_millis(800))); + let _ = sock.set_write_timeout(Some(std::time::Duration::from_millis(800))); + let mut buf = [0u8; crate::single_instance::MAGIC.len()]; + if sock.read_exact(&mut buf).is_err() || &buf != crate::single_instance::MAGIC { + continue; + } + let _ = sock.write_all(crate::single_instance::ACK); + // 不 shutdown(Both):立即 RST 会吞掉客户端未读的 ACK;让连接 + // 随 socket drop 正常关闭(FIN,客户端已读缓冲仍可取) + let _ = tx.send(()).await; + } + }); + cx.spawn(async move |cx| { + while let Ok(()) = rx.recv().await { + let _ = cx.update(|app| show_main_window(&api, app)); + } + }) + .detach(); +} + impl AppShell { pub(crate) fn new( api: Arc, diff --git a/crates/postium-ui/src/main.rs b/crates/postium-ui/src/main.rs index 59ec5226..c26d8c88 100644 --- a/crates/postium-ui/src/main.rs +++ b/crates/postium-ui/src/main.rs @@ -13,6 +13,7 @@ mod i18n; mod nav; mod notify; mod runtime; +mod single_instance; mod screenshot; mod sound; mod ui_state; @@ -51,6 +52,12 @@ fn main() { let screenshot = screenshot::init_from_args(); let screenshot_mode = screenshot.is_some(); + // 单实例(线上反馈⑪):第二实例唤醒既有实例后退出——不碰数据库/引擎 + let show_listener = match single_instance::acquire() { + single_instance::Role::Primary(listener) => Some(listener), + single_instance::Role::Secondary => return, + }; + let e2e = std::env::var("POSTIUM_E2E").ok().as_deref() == Some("1"); let e2e_truth = std::env::var("POSTIUM_E2E_TRUTH").ok().as_deref() == Some("1"); @@ -75,7 +82,11 @@ fn main() { // 关闭行为=退出)。 cx.set_quit_mode(gpui_kit::QuitMode::Explicit); cx.set_global(i18n::I18nGlobal { lang: i18n::Lang::Zh }); - app::open_main_window(api, Some(sync_rx), cx); + app::open_main_window(api.clone(), Some(sync_rx), cx); + // 单实例唤醒消费:第二实例握手 → 显示/重建主窗口 + if let Some(listener) = show_listener { + app::spawn_show_listener(listener, api, cx); + } // 截图模式:不激活应用(不抢用户焦点) if screenshot_mode { cx.activate(false); diff --git a/crates/postium-ui/src/single_instance.rs b/crates/postium-ui/src/single_instance.rs new file mode 100644 index 00000000..1feba845 --- /dev/null +++ b/crates/postium-ui/src/single_instance.rs @@ -0,0 +1,61 @@ +//! 单实例(线上反馈⑪):第二个实例启动时唤醒既有实例(显示/重建主窗口) +//! 后自行退出。 +//! +//! 通道:本机回环 TCP 握手(跨平台、零新依赖、无 win32 unsafe)—— +//! 首个实例绑定 [`PORT`] 成为 Primary 并持有 listener;后续实例 bind 失败 +//! → 连接该端口发送 [`MAGIC`],Primary 回 [`ACK`] 并经事件循环调 +//! [`crate::app::show_main_window`](主窗口存活激活置前 / 已关闭到托盘则 +//! 重建)。握手有确认与超时:端口被无关程序占用时不误伤对方也绝不挂死。 +//! +//! 检查时机在重量级装配(CoreApi::init)之前——第二实例不碰数据库/引擎。 + +use std::io::{Read as _, Write as _}; + + + +/// 单实例握手端口(本机回环)。避开 OAuth 回调端口 36279。 +const PORT: u16 = 45917; +/// 握手魔串(第二实例 → 首实例)。 +pub(crate) const MAGIC: &[u8] = b"postium-show\r\n"; +/// 确认串(首实例 → 第二实例)。 +pub(crate) const ACK: &[u8] = b"postium-ok\r\n"; + +/// [`acquire`] 的结果。 +pub enum Role { + /// 本实例是首个:持有监听 socket(主窗口打开后交给 + /// [`spawn_show_listener`] 消费)。 + Primary(std::net::TcpListener), + /// 已有实例在运行(已发送唤醒信号,调用方应立即退出)。 + Secondary, +} + +/// 尝试成为 Primary;端口被占(已有实例或无关占用)时执行唤醒握手并返回 +/// [`Role::Secondary`]。 +pub fn acquire() -> Role { + match std::net::TcpListener::bind(("127.0.0.1", PORT)) { + Ok(listener) => Role::Primary(listener), + Err(_) => { + let woken = signal_existing(); + tracing::info!( + target: "postium::ui", + "单实例:已有实例运行(唤醒握手{}),本实例退出", + if woken { "成功" } else { "无应答" } + ); + Role::Secondary + } + } +} + +/// 连接既有实例发送唤醒信号(带 800ms 超时——绝不挂死启动路径)。 +fn signal_existing() -> bool { + let Ok(mut sock) = std::net::TcpStream::connect(("127.0.0.1", PORT)) else { + return false; + }; + let _ = sock.set_read_timeout(Some(std::time::Duration::from_millis(800))); + let _ = sock.set_write_timeout(Some(std::time::Duration::from_millis(800))); + if sock.write_all(MAGIC).is_err() { + return false; + } + let mut ack = [0u8; ACK.len()]; + sock.read_exact(&mut ack).is_ok() && &ack == ACK +} diff --git a/crates/postium-ui/src/tray.rs b/crates/postium-ui/src/tray.rs index ecabf63d..0c2c3446 100644 --- a/crates/postium-ui/src/tray.rs +++ b/crates/postium-ui/src/tray.rs @@ -29,22 +29,7 @@ static TRAY_CONSUMER_STARTED: std::sync::atomic::AtomicBool = /// 托盘「显示窗口」/左键单击共享:主窗口存活 → 激活置前;已关闭(关闭到 /// 托盘)→ 重建主窗口。 fn show_main_window(api: &Arc, cx: &mut App) { - let shell_alive = cx - .try_global::() - .and_then(|main| main.0.upgrade()) - .is_some(); - if shell_alive { - if let Some(handle) = cx.active_window() { - let _ = handle.update(cx, |_, window, _| { - window.activate_window(); - }); - } - } else { - let api = api.clone(); - cx.defer(move |cx| { - crate::app::open_main_window(api, None, cx); - }); - } + crate::app::show_main_window(api, cx); } /// 装配托盘并启动事件消费循环(幂等:图标已持有则直接复用——主窗口