Compare commits

..
71 changed files with 1317 additions and 3391 deletions
-3
View File
@@ -18,7 +18,4 @@ jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
Generated
+2 -12
View File
@@ -1248,7 +1248,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c)",
"craft-tiff",
"quick-xml 0.41.0",
"serde",
]
@@ -1401,15 +1401,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1#6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -7292,6 +7283,7 @@ name = "wordcraft-doc"
version = "0.18.1"
dependencies = [
"base64 0.23.1",
"craft-codepage",
"log",
"proptest",
"serde",
@@ -7340,7 +7332,6 @@ dependencies = [
"chrono",
"craft-font-catalog",
"craft-font-store",
"craft-mime",
"craft-proof",
"craft-zip",
"encoding_rs",
@@ -7416,7 +7407,6 @@ name = "wordcraft-geom"
version = "0.18.1"
dependencies = [
"craft-image-codecs",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1)",
"image",
"serde",
]
+1 -3
View File
@@ -36,6 +36,7 @@ wordcraft-mcp = { path = "crates/mcp" }
wordcraft-zotero = { path = "crates/zotero" }
wordcraft-control-key = { path = "crates/control-key" }
wordcraft-ui-egui = { path = "crates/ui-egui" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
# foundation
@@ -68,7 +69,6 @@ brotli-decompressor = "5"
vello_cpu = "0.2"
image = { version = "0.25", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
@@ -123,8 +123,6 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data
[workspace.lints.rust]
unsafe_code = "forbid"
# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation.
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }
[workspace.lints.clippy]
cognitive_complexity = "deny"
+1 -6
View File
File diff suppressed because one or more lines are too long
+4 -40
View File
@@ -369,11 +369,8 @@ mod tests {
impl Conn {
fn open(port: u16) -> Self {
Self::open_within(port, Duration::from_secs(5))
}
fn open_within(port: u16, read_timeout: Duration) -> Self {
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(read_timeout)).unwrap();
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
Self(BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
@@ -391,24 +388,7 @@ mod tests {
/// The server closed the connection.
fn closed(&mut self) -> bool {
let mut r = String::new();
closed_by_peer(self.0.read_line(&mut r))
}
}
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
/// which is how Windows can deliver a close when the writer had nothing to read back (the
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
/// not UTF-8, leaves the connection open.
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
match read {
Ok(n) => n == 0,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
matches!(self.0.read_line(&mut r), Ok(0))
}
}
@@ -493,29 +473,13 @@ mod tests {
assert!(rx.try_recv().is_err());
}
#[test]
fn only_closure_errors_mean_the_peer_closed() {
use std::io::{Error, ErrorKind};
assert!(closed_by_peer(Ok(0)), "end of stream");
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
}
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
// Not UTF-8, a timeout or a would-block leave the socket open.
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
}
}
#[test]
fn a_silent_connection_is_closed() {
let (port, rx) = boot_with(Duration::from_millis(300));
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
let mut quiet = Conn::open(port);
let t0 = Instant::now();
assert!(quiet.closed());
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
assert!(t0.elapsed() < Duration::from_secs(3));
// After an authorised request the connection may stay idle.
let mut busy = Conn::open(port);
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
+1
View File
@@ -16,6 +16,7 @@ workspace = true
test-support = []
[dependencies]
craft-codepage = { workspace = true }
wordcraft-geom = { workspace = true }
base64 = { workspace = true }
log = { workspace = true }
+44 -337
View File
@@ -1,345 +1,52 @@
//! Windows-1252 (the byte encoding legacy Word text pieces use) and the other single-byte Windows
//! code pages RTF files name with `\ansicpg` or a font's `\fcharset` (Cyrillic 1251, Central
//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai), Mac OS Roman
//! (10000, RTF `\mac`), and the East Asian multibyte code pages (932 Shift-JIS, 936 GBK, 949 UHC,
//! 950 Big5), whose bytes decode as runs rather than one at a time.
//! Legacy character decoding delegates to craft-codepage; document fallback policy stays here.
pub use craft_codepage::{
MAC_ROMAN_CODE_PAGE, MULTIBYTE_CODE_PAGES, OEM_CODE_PAGES, SINGLE_BYTE_CODE_PAGES, cp1252, is_multibyte_code_page, multibyte_encoding_name,
oem_byte, windows_byte,
};
/// Windows-1252 code points for 0x80..=0x9F.
const CP1252: [u16; 32] = [
0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
];
/// One Windows-1252 byte as a char.
pub fn cp1252(b: u8) -> char {
if (0x80..0xA0).contains(&b) {
CP1252.get((b - 0x80) as usize).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}')
} else {
b as char
}
/// Word's supported single-byte document code pages (symbol-font policy is separate).
pub fn is_byte_code_page(cp: u16) -> bool {
SINGLE_BYTE_CODE_PAGES.contains(&cp) || OEM_CODE_PAGES.contains(&cp) || cp == MAC_ROMAN_CODE_PAGE
}
/// Windows-874 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP874: [u16; 128] = [
0x20AC, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2026, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0E01, 0x0E02, 0x0E03,
0x0E04, 0x0E05, 0x0E06, 0x0E07, 0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F, 0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15,
0x0E16, 0x0E17, 0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F, 0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27,
0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F, 0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39,
0x0E3A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x0E3F, 0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B,
0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F, 0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57, 0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0xFFFD, 0xFFFD,
0xFFFD, 0xFFFD,
];
/// Windows-1250 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1250: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, 0x00A0, 0x02C7, 0x02D8, 0x0141,
0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7,
0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E,
0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB,
0x011B, 0x00ED, 0x00EE, 0x010F, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD,
0x0163, 0x02D9,
];
/// Windows-1251 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1251: [u16; 128] = [
0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, 0x0452, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, 0x00A0, 0x040E, 0x045E, 0x0408,
0x00A4, 0x0490, 0x00A6, 0x00A7, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5,
0x00B6, 0x00B7, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429,
0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B,
0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D,
0x044E, 0x044F,
];
/// Windows-1253 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1253: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0385, 0x0386, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0xFFFD, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5,
0x00B6, 0x00B7, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9,
0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB,
0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD,
0x03CE, 0xFFFD,
];
/// Windows-1254 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1254: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9,
0x00DA, 0x00DB, 0x00DC, 0x0130, 0x015E, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB,
0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131,
0x015F, 0x00FF,
];
/// Windows-1255 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1255: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x00A1, 0x00A2, 0x00A3,
0x20AA, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7,
0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF, 0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0xFFFD,
0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB,
0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E,
0x200F, 0xFFFD,
];
/// Windows-1256 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1256: [u16; 128] = [
0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688, 0x06AF, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA, 0x00A0, 0x060C, 0x00A2, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F, 0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627,
0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7, 0x0637, 0x0638,
0x0639, 0x063A, 0x0640, 0x0641, 0x0642, 0x0643, 0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB,
0x0649, 0x064A, 0x00EE, 0x00EF, 0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7, 0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E,
0x200F, 0x06D2,
];
/// Windows-1257 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1257: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0x00A8, 0x02C7, 0x00B8, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0x00AF, 0x02DB, 0xFFFD, 0x00A0, 0xFFFD, 0x00A2, 0x00A3,
0x00A4, 0xFFFD, 0x00A6, 0x00A7, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112,
0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7, 0x0172, 0x0141,
0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113, 0x010D, 0x00E9, 0x017A, 0x0117,
0x0123, 0x0137, 0x012B, 0x013C, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C,
0x017E, 0x02D9,
];
/// Windows-1258 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1258: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF, 0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7, 0x00D8, 0x00D9,
0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB,
0x0301, 0x00ED, 0x00EE, 0x00EF, 0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0,
0x20AB, 0x00FF,
];
/// Mac OS Roman (code page 10000, RTF `\mac`) code points for 0x80..=0xFF, with the euro sign at
/// 0xDB (Mac OS 8.5 and later).
const MAC_ROMAN: [u16; 128] = [
0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, 0x00EA, 0x00EB,
0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, 0x2020, 0x00B0, 0x00A2, 0x00A3,
0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5,
0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB,
0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178,
0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE,
0x00CF, 0x00CC, 0x00D3, 0x00D4, 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD,
0x02DB, 0x02C7,
];
/// IBM PC (OEM) code page 437 code points for 0x80..=0xFF (the Unicode Consortium's CP437
/// mapping file).
const CP437: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4,
0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2,
0x25A0, 0x00A0,
];
/// OEM code page 850 (DOS Latin-1, Western European) code points for 0x80..=0xFF (the Unicode
/// Consortium's CP850 mapping file).
const CP850: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518,
0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9,
0x00FD, 0x00DD, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2,
0x25A0, 0x00A0,
];
/// OEM code page 852 (DOS Latin-2, Central European) code points for 0x80..=0xFF (the Unicode Consortium's CP852
/// mapping file).
const CP852: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, 0x00C9, 0x0139,
0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518,
0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170,
0x00FD, 0x00DD, 0x0163, 0x00B4, 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159,
0x25A0, 0x00A0,
];
/// OEM code page 866 (DOS Cyrillic) code points for 0x80..=0xFF (the Unicode Consortium's CP866
/// mapping file).
const CP866: [u16; 128] = [
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421,
0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433,
0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B,
0x044C, 0x044D, 0x044E, 0x044F, 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4,
0x25A0, 0x00A0,
];
/// OEM code page 737 (DOS Greek) code points for 0x80..=0xFF (the Unicode Consortium's CP737
/// mapping file).
const CP737: [u16; 128] = [
0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3,
0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC,
0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388,
0x0389, 0x038A, 0x038C, 0x038E, 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2,
0x25A0, 0x00A0,
];
/// OEM code page 857 (DOS Turkish; U+FFFD where the byte is unassigned) code points for 0x80..=0xFF (the Unicode Consortium's CP857
/// mapping file).
const CP857: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0xFFFD, 0x00CD, 0x00CE, 0x00CF, 0x2518,
0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0xFFFD, 0x00D7, 0x00DA, 0x00DB, 0x00D9,
0x00EC, 0x00FF, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0xFFFD, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2,
0x25A0, 0x00A0,
];
/// The glyphs the OEM code pages show for 0x01..=0x1F (smileys, card suits, arrows), as
/// Windows' Alt+numpad entry produces them rather than the control characters.
const OEM_GLYPHS: [u16; 31] = [
0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195,
0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC,
];
/// The OEM code pages [`oem_byte`] decodes.
pub const OEM_CODE_PAGES: [u16; 6] = [437, 737, 850, 852, 857, 866];
/// One byte of an OEM code page in [`OEM_CODE_PAGES`] (any other code page reads as 437) as a
/// char, with the graphic glyphs for 0x01..=0x1F and 0x7F (⌂); 0x00 stays NUL.
pub fn oem_byte(code_page: u16, b: u8) -> char {
let table: &[u16; 128] = match code_page {
737 => &CP737,
850 => &CP850,
852 => &CP852,
857 => &CP857,
866 => &CP866,
_ => &CP437,
};
let u = match b {
0x01..=0x1F => OEM_GLYPHS.get(usize::from(b - 1)).copied(),
0x7F => Some(0x2302),
0x80..=0xFF => table.get(usize::from(b - 0x80)).copied(),
_ => Some(u16::from(b)),
};
u.and_then(|u| char::from_u32(u32::from(u))).unwrap_or('\u{FFFD}')
/// Decode document text without applying OEM control glyphs or symbol-font remapping.
pub fn code_page_byte(cp: u16, b: u8) -> char {
if b >= 0x80 && OEM_CODE_PAGES.contains(&cp) { oem_byte(cp, b) } else { windows_byte(cp, b) }
}
/// The single-byte Windows code pages [`windows_byte`] decodes (1252 included).
pub const SINGLE_BYTE_CODE_PAGES: [u16; 10] = [874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258];
/// Mac OS Roman, RTF's `\mac` character set.
pub const MAC_ROMAN_CODE_PAGE: u16 = 10000;
/// One byte of a single-byte code page as a char: a Windows one in [`SINGLE_BYTE_CODE_PAGES`] or
/// Mac OS Roman ([`MAC_ROMAN_CODE_PAGE`]); any other code page reads as Windows-1252.
pub fn windows_byte(code_page: u16, b: u8) -> char {
let table: &[u16; 128] = match code_page {
874 => &CP874,
1250 => &CP1250,
1251 => &CP1251,
1253 => &CP1253,
1254 => &CP1254,
1255 => &CP1255,
1256 => &CP1256,
1257 => &CP1257,
1258 => &CP1258,
MAC_ROMAN_CODE_PAGE => &MAC_ROMAN,
_ => return cp1252(b),
};
if b < 0x80 {
return b as char;
}
table.get(usize::from(b - 0x80)).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}')
/// Whether Word's document import accepts this encoding.
pub fn is_text_code_page(cp: u16) -> bool {
is_byte_code_page(cp) || is_multibyte_code_page(cp)
}
/// Whether [`code_page_byte`] decodes `code_page`: a Windows one ([`SINGLE_BYTE_CODE_PAGES`]), an
/// OEM (DOS) one ([`OEM_CODE_PAGES`]) or Mac OS Roman. Document formats (RTF) name all three.
pub fn is_byte_code_page(code_page: u16) -> bool {
SINGLE_BYTE_CODE_PAGES.contains(&code_page) || OEM_CODE_PAGES.contains(&code_page) || code_page == MAC_ROMAN_CODE_PAGE
}
/// A byte of 8-bit document text in `code_page` (see [`is_byte_code_page`]) as a char. Below 0x80
/// it is ASCII in every code page (text, so an OEM page's glyphs for control codes don't apply).
pub fn code_page_byte(code_page: u16, b: u8) -> char {
if b >= 0x80 && OEM_CODE_PAGES.contains(&code_page) { oem_byte(code_page, b) } else { windows_byte(code_page, b) }
}
/// The East Asian multibyte code pages a document format names with `\ansicpg` or a font's `\cpg`:
/// 932 Shift-JIS (Japanese), 936 GBK (Simplified Chinese), 949 UHC (Korean) and 950 Big5
/// (Traditional Chinese).
pub const MULTIBYTE_CODE_PAGES: [u16; 4] = [932, 936, 949, 950];
/// Whether `code_page` is one of the East Asian multibyte code pages ([`MULTIBYTE_CODE_PAGES`]):
/// its bytes decode as a run, a lead byte together with its trail byte.
pub fn is_multibyte_code_page(code_page: u16) -> bool {
multibyte_encoding_name(code_page).is_some()
}
/// The WHATWG encoding name of an East Asian multibyte code page (see [`MULTIBYTE_CODE_PAGES`]),
/// for `encoding_rs::Encoding::for_label`; `None` for the single-byte code pages, whose bytes
/// decode one at a time, and anything else.
pub fn multibyte_encoding_name(code_page: u16) -> Option<&'static str> {
Some(match code_page {
932 => "shift_jis",
936 => "gbk",
949 => "euc-kr",
950 => "big5",
_ => return None,
})
}
/// Whether a document format can name `code_page` for its text: a single-byte Windows, DOS or Mac
/// one ([`is_byte_code_page`]) or an East Asian multibyte one ([`is_multibyte_code_page`]).
pub fn is_text_code_page(code_page: u16) -> bool {
is_byte_code_page(code_page) || is_multibyte_code_page(code_page)
}
/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern
/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949,
/// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950… `None` for the ANSI and default
/// charsets (the document's code page applies) and symbol fonts.
/// Preserve Word's existing symbol-font selection policy, not the shared symbol extension.
pub fn charset_code_page(charset: i32) -> Option<u16> {
Some(match charset {
77 => MAC_ROMAN_CODE_PAGE,
128 => 932,
129 => 949,
134 => 936,
136 => 950,
161 => 1253,
162 => 1254,
163 => 1258,
177 => 1255,
178 => 1256,
186 => 1257,
204 => 1251,
222 => 874,
238 => 1250,
254 | 255 => 437,
_ => return None,
})
if charset == 2 { None } else { craft_codepage::charset_code_page(charset) }
}
#[cfg(test)]
#[allow(dead_code)]
#[path = "encoding_legacy_tests.rs"]
mod legacy;
#[cfg(test)]
mod parity {
use super::*;
#[test]
fn every_supported_byte_and_fallback_matches_original() {
let pages = [0, 42, 437, 737, 850, 852, 857, 866, 874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 10000, 9999, u16::MAX];
for cp in pages {
for b in 0..=u8::MAX {
assert_eq!(windows_byte(cp, b), legacy::windows_byte(cp, b), "windows {cp}/{b}");
assert_eq!(oem_byte(cp, b), legacy::oem_byte(cp, b), "oem {cp}/{b}");
assert_eq!(code_page_byte(cp, b), legacy::code_page_byte(cp, b), "text {cp}/{b}");
assert_eq!(cp1252(b), legacy::cp1252(b));
}
}
for cp in 0..=u16::MAX {
assert_eq!(is_byte_code_page(cp), legacy::is_byte_code_page(cp));
assert_eq!(is_text_code_page(cp), legacy::is_text_code_page(cp));
assert_eq!(multibyte_encoding_name(cp), legacy::multibyte_encoding_name(cp));
}
for charset in -1..=256 {
assert_eq!(charset_code_page(charset), legacy::charset_code_page(charset));
}
}
}
#[cfg(test)]
+428
View File
@@ -0,0 +1,428 @@
// Frozen pre-cutover implementation, test-only parity oracle. Original authors retained in file history.
//! Windows-1252 (the byte encoding legacy Word text pieces use) and the other single-byte Windows
//! code pages RTF files name with `\ansicpg` or a font's `\fcharset` (Cyrillic 1251, Central
//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai), Mac OS Roman
//! (10000, RTF `\mac`), and the East Asian multibyte code pages (932 Shift-JIS, 936 GBK, 949 UHC,
//! 950 Big5), whose bytes decode as runs rather than one at a time.
/// Windows-1252 code points for 0x80..=0x9F.
const CP1252: [u16; 32] = [
0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
];
/// One Windows-1252 byte as a char.
pub fn cp1252(b: u8) -> char {
if (0x80..0xA0).contains(&b) {
CP1252.get((b - 0x80) as usize).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}')
} else {
b as char
}
}
/// Windows-874 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP874: [u16; 128] = [
0x20AC, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2026, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0E01, 0x0E02, 0x0E03,
0x0E04, 0x0E05, 0x0E06, 0x0E07, 0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F, 0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15,
0x0E16, 0x0E17, 0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F, 0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27,
0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F, 0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39,
0x0E3A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x0E3F, 0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B,
0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F, 0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57, 0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0xFFFD, 0xFFFD,
0xFFFD, 0xFFFD,
];
/// Windows-1250 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1250: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, 0x00A0, 0x02C7, 0x02D8, 0x0141,
0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7,
0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E,
0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB,
0x011B, 0x00ED, 0x00EE, 0x010F, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD,
0x0163, 0x02D9,
];
/// Windows-1251 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1251: [u16; 128] = [
0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, 0x0452, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, 0x00A0, 0x040E, 0x045E, 0x0408,
0x00A4, 0x0490, 0x00A6, 0x00A7, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5,
0x00B6, 0x00B7, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429,
0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B,
0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D,
0x044E, 0x044F,
];
/// Windows-1253 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1253: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x0385, 0x0386, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0xFFFD, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5,
0x00B6, 0x00B7, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9,
0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB,
0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD,
0x03CE, 0xFFFD,
];
/// Windows-1254 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1254: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9,
0x00DA, 0x00DB, 0x00DC, 0x0130, 0x015E, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB,
0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131,
0x015F, 0x00FF,
];
/// Windows-1255 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1255: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x00A0, 0x00A1, 0x00A2, 0x00A3,
0x20AA, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7,
0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF, 0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0xFFFD,
0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB,
0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E,
0x200F, 0xFFFD,
];
/// Windows-1256 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1256: [u16; 128] = [
0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688, 0x06AF, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA, 0x00A0, 0x060C, 0x00A2, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F, 0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627,
0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7, 0x0637, 0x0638,
0x0639, 0x063A, 0x0640, 0x0641, 0x0642, 0x0643, 0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB,
0x0649, 0x064A, 0x00EE, 0x00EF, 0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7, 0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E,
0x200F, 0x06D2,
];
/// Windows-1257 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1257: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0xFFFD, 0x201E, 0x2026, 0x2020, 0x2021, 0xFFFD, 0x2030, 0xFFFD, 0x2039, 0xFFFD, 0x00A8, 0x02C7, 0x00B8, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0xFFFD, 0x2122, 0xFFFD, 0x203A, 0xFFFD, 0x00AF, 0x02DB, 0xFFFD, 0x00A0, 0xFFFD, 0x00A2, 0x00A3,
0x00A4, 0xFFFD, 0x00A6, 0x00A7, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112,
0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7, 0x0172, 0x0141,
0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113, 0x010D, 0x00E9, 0x017A, 0x0117,
0x0123, 0x0137, 0x012B, 0x013C, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C,
0x017E, 0x02D9,
];
/// Windows-1258 code points for 0x80..=0xFF (U+FFFD where the byte is unassigned).
const CP1258: [u16; 128] = [
0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0xFFFD, 0x2039, 0x0152, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2018,
0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0xFFFD, 0x203A, 0x0153, 0xFFFD, 0xFFFD, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3,
0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5,
0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF, 0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7, 0x00D8, 0x00D9,
0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB,
0x0301, 0x00ED, 0x00EE, 0x00EF, 0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0,
0x20AB, 0x00FF,
];
/// Mac OS Roman (code page 10000, RTF `\mac`) code points for 0x80..=0xFF, with the euro sign at
/// 0xDB (Mac OS 8.5 and later).
const MAC_ROMAN: [u16; 128] = [
0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, 0x00EA, 0x00EB,
0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, 0x2020, 0x00B0, 0x00A2, 0x00A3,
0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5,
0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB,
0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178,
0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE,
0x00CF, 0x00CC, 0x00D3, 0x00D4, 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD,
0x02DB, 0x02C7,
];
/// IBM PC (OEM) code page 437 code points for 0x80..=0xFF (the Unicode Consortium's CP437
/// mapping file).
const CP437: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4,
0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2,
0x25A0, 0x00A0,
];
/// OEM code page 850 (DOS Latin-1, Western European) code points for 0x80..=0xFF (the Unicode
/// Consortium's CP850 mapping file).
const CP850: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518,
0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9,
0x00FD, 0x00DD, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2,
0x25A0, 0x00A0,
];
/// OEM code page 852 (DOS Latin-2, Central European) code points for 0x80..=0xFF (the Unicode Consortium's CP852
/// mapping file).
const CP852: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, 0x00C9, 0x0139,
0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518,
0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170,
0x00FD, 0x00DD, 0x0163, 0x00B4, 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159,
0x25A0, 0x00A0,
];
/// OEM code page 866 (DOS Cyrillic) code points for 0x80..=0xFF (the Unicode Consortium's CP866
/// mapping file).
const CP866: [u16; 128] = [
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421,
0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433,
0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B,
0x044C, 0x044D, 0x044E, 0x044F, 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4,
0x25A0, 0x00A0,
];
/// OEM code page 737 (DOS Greek) code points for 0x80..=0xFF (the Unicode Consortium's CP737
/// mapping file).
const CP737: [u16; 128] = [
0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3,
0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC,
0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388,
0x0389, 0x038A, 0x038C, 0x038E, 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2,
0x25A0, 0x00A0,
];
/// OEM code page 857 (DOS Turkish; U+FFFD where the byte is unassigned) code points for 0x80..=0xFF (the Unicode Consortium's CP857
/// mapping file).
const CP857: [u16; 128] = [
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0xFFFD, 0x00CD, 0x00CE, 0x00CF, 0x2518,
0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0xFFFD, 0x00D7, 0x00DA, 0x00DB, 0x00D9,
0x00EC, 0x00FF, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0xFFFD, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2,
0x25A0, 0x00A0,
];
/// The glyphs the OEM code pages show for 0x01..=0x1F (smileys, card suits, arrows), as
/// Windows' Alt+numpad entry produces them rather than the control characters.
const OEM_GLYPHS: [u16; 31] = [
0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195,
0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC,
];
/// The OEM code pages [`oem_byte`] decodes.
pub const OEM_CODE_PAGES: [u16; 6] = [437, 737, 850, 852, 857, 866];
/// One byte of an OEM code page in [`OEM_CODE_PAGES`] (any other code page reads as 437) as a
/// char, with the graphic glyphs for 0x01..=0x1F and 0x7F (⌂); 0x00 stays NUL.
pub fn oem_byte(code_page: u16, b: u8) -> char {
let table: &[u16; 128] = match code_page {
737 => &CP737,
850 => &CP850,
852 => &CP852,
857 => &CP857,
866 => &CP866,
_ => &CP437,
};
let u = match b {
0x01..=0x1F => OEM_GLYPHS.get(usize::from(b - 1)).copied(),
0x7F => Some(0x2302),
0x80..=0xFF => table.get(usize::from(b - 0x80)).copied(),
_ => Some(u16::from(b)),
};
u.and_then(|u| char::from_u32(u32::from(u))).unwrap_or('\u{FFFD}')
}
/// The single-byte Windows code pages [`windows_byte`] decodes (1252 included).
pub const SINGLE_BYTE_CODE_PAGES: [u16; 10] = [874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258];
/// Mac OS Roman, RTF's `\mac` character set.
pub const MAC_ROMAN_CODE_PAGE: u16 = 10000;
/// One byte of a single-byte code page as a char: a Windows one in [`SINGLE_BYTE_CODE_PAGES`] or
/// Mac OS Roman ([`MAC_ROMAN_CODE_PAGE`]); any other code page reads as Windows-1252.
pub fn windows_byte(code_page: u16, b: u8) -> char {
let table: &[u16; 128] = match code_page {
874 => &CP874,
1250 => &CP1250,
1251 => &CP1251,
1253 => &CP1253,
1254 => &CP1254,
1255 => &CP1255,
1256 => &CP1256,
1257 => &CP1257,
1258 => &CP1258,
MAC_ROMAN_CODE_PAGE => &MAC_ROMAN,
_ => return cp1252(b),
};
if b < 0x80 {
return b as char;
}
table.get(usize::from(b - 0x80)).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}')
}
/// Whether [`code_page_byte`] decodes `code_page`: a Windows one ([`SINGLE_BYTE_CODE_PAGES`]), an
/// OEM (DOS) one ([`OEM_CODE_PAGES`]) or Mac OS Roman. Document formats (RTF) name all three.
pub fn is_byte_code_page(code_page: u16) -> bool {
SINGLE_BYTE_CODE_PAGES.contains(&code_page) || OEM_CODE_PAGES.contains(&code_page) || code_page == MAC_ROMAN_CODE_PAGE
}
/// A byte of 8-bit document text in `code_page` (see [`is_byte_code_page`]) as a char. Below 0x80
/// it is ASCII in every code page (text, so an OEM page's glyphs for control codes don't apply).
pub fn code_page_byte(code_page: u16, b: u8) -> char {
if b >= 0x80 && OEM_CODE_PAGES.contains(&code_page) { oem_byte(code_page, b) } else { windows_byte(code_page, b) }
}
/// The East Asian multibyte code pages a document format names with `\ansicpg` or a font's `\cpg`:
/// 932 Shift-JIS (Japanese), 936 GBK (Simplified Chinese), 949 UHC (Korean) and 950 Big5
/// (Traditional Chinese).
pub const MULTIBYTE_CODE_PAGES: [u16; 4] = [932, 936, 949, 950];
/// Whether `code_page` is one of the East Asian multibyte code pages ([`MULTIBYTE_CODE_PAGES`]):
/// its bytes decode as a run, a lead byte together with its trail byte.
pub fn is_multibyte_code_page(code_page: u16) -> bool {
multibyte_encoding_name(code_page).is_some()
}
/// The WHATWG encoding name of an East Asian multibyte code page (see [`MULTIBYTE_CODE_PAGES`]),
/// for `encoding_rs::Encoding::for_label`; `None` for the single-byte code pages, whose bytes
/// decode one at a time, and anything else.
pub fn multibyte_encoding_name(code_page: u16) -> Option<&'static str> {
Some(match code_page {
932 => "shift_jis",
936 => "gbk",
949 => "euc-kr",
950 => "big5",
_ => return None,
})
}
/// Whether a document format can name `code_page` for its text: a single-byte Windows, DOS or Mac
/// one ([`is_byte_code_page`]) or an East Asian multibyte one ([`is_multibyte_code_page`]).
pub fn is_text_code_page(code_page: u16) -> bool {
is_byte_code_page(code_page) || is_multibyte_code_page(code_page)
}
/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern
/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949,
/// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950… `None` for the ANSI and default
/// charsets (the document's code page applies) and symbol fonts.
pub fn charset_code_page(charset: i32) -> Option<u16> {
Some(match charset {
77 => MAC_ROMAN_CODE_PAGE,
128 => 932,
129 => 949,
134 => 936,
136 => 950,
161 => 1253,
162 => 1254,
163 => 1258,
177 => 1255,
178 => 1256,
186 => 1257,
204 => 1251,
222 => 874,
238 => 1250,
254 | 255 => 437,
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn single_byte_code_pages() {
let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| windows_byte(cp, b)).collect::<String>();
assert_eq!(decode(1251, &[0xD1, 0xF7, 0xE5, 0xF2, 0x20, 0xB9]), "Счет №");
assert_eq!(decode(1251, &[0xA8, 0xB8]), "Ёё");
assert_eq!(decode(1250, &[0xA3, 0xF3, 0x9F]), "Łóź");
assert_eq!(decode(1253, &[0xC1, 0xE2]), "Αβ");
assert_eq!(decode(1252, &[0x80, 0xE9]), "ێ");
assert_eq!(decode(9999, &[0xE9]), "é");
// Mac OS Roman (#1653): accents, the euro sign at 0xDB, typographic quotes.
assert_eq!(decode(10000, &[0x80, 0x8E, 0xDB, 0xF1, 0xF2, 0xF3, 0xD2, 0xD3, 0x41]), "Äé€ÒÚÛ“”A");
assert_eq!(charset_code_page(77), Some(10000));
assert_eq!(charset_code_page(254), Some(437));
assert_eq!(charset_code_page(255), Some(437));
assert_eq!(charset_code_page(204), Some(1251));
assert_eq!(charset_code_page(0), None);
for cp in SINGLE_BYTE_CODE_PAGES {
for b in 0..=255u8 {
let _ = windows_byte(cp, b);
}
}
}
#[test]
fn windows_1255_holam_haser_for_vav() {
assert_eq!(windows_byte(1255, 0xCA), '\u{05BA}');
}
/// #1653: one decoder for document text in any code page RTF names: Windows, DOS or Mac.
#[test]
fn document_text_in_windows_dos_and_mac_code_pages() {
let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| code_page_byte(cp, b)).collect::<String>();
assert_eq!(decode(437, &[0x82, 0xA0, 0x41, 0x01]), "éáA\u{1}", "DOS text; ASCII stays ASCII");
assert_eq!(decode(850, &[0x9D, 0xE9]), "ØÚ");
assert_eq!(decode(10000, &[0x8E]), "é");
assert_eq!(decode(1251, &[0xC4]), "Д");
for cp in [437, 850, 866, 1250, 1252, 10000] {
assert!(is_byte_code_page(cp), "{cp}");
}
assert!(!is_byte_code_page(932) && !is_byte_code_page(0) && !SINGLE_BYTE_CODE_PAGES.contains(&10000));
}
/// #1653: the East Asian charsets and code pages RTF names are multibyte: their bytes decode
/// as runs (a lead byte and its trail byte together), not one at a time.
#[test]
fn east_asian_code_pages_are_multibyte() {
assert_eq!(charset_code_page(128), Some(932), "Japanese");
assert_eq!(charset_code_page(129), Some(949), "Korean");
assert_eq!(charset_code_page(134), Some(936), "Simplified Chinese");
assert_eq!(charset_code_page(136), Some(950), "Traditional Chinese");
assert_eq!(charset_code_page(255), Some(437), "OEM is single-byte");
assert_eq!(MULTIBYTE_CODE_PAGES, [932, 936, 949, 950]);
for cp in MULTIBYTE_CODE_PAGES {
assert!(is_multibyte_code_page(cp) && is_text_code_page(cp), "{cp}");
assert!(!is_byte_code_page(cp) && !SINGLE_BYTE_CODE_PAGES.contains(&cp), "{cp}");
assert!(multibyte_encoding_name(cp).is_some(), "{cp}");
}
assert!(is_text_code_page(1251) && is_text_code_page(437) && is_text_code_page(10000));
assert!(!is_text_code_page(0) && !is_text_code_page(9999));
}
#[test]
fn oem_code_pages() {
let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| oem_byte(cp, b)).collect::<String>();
assert_eq!(decode(437, &[0x82, 0xE9, 0x01, 0x7F]), "éΘ☺⌂");
assert_eq!(decode(850, &[0x9B, 0xE9]), "øÚ");
assert_eq!(decode(852, &[0xA5, 0x88, 0xBE, 0xA9]), "ąłżę");
assert_eq!(decode(866, &[0x8F, 0xE0, 0xA8, 0xA2, 0xA5, 0xE2, 0xF0, 0xFC]), "ПриветЁ№");
assert_eq!(decode(737, &[0x80, 0x99, 0xE0]), "Αβω");
assert_eq!(decode(857, &[0x8D, 0x98, 0xA6, 0x9F]), "ıİĞş");
assert_eq!(oem_byte(857, 0xD5), '\u{FFFD}', "unassigned in 857");
assert_eq!(decode(9999, &[0xE9]), "Θ", "unknown pages read as 437");
for cp in OEM_CODE_PAGES {
for b in 0..=255u8 {
let _ = oem_byte(cp, b);
}
}
}
}
+2 -2
View File
@@ -94,8 +94,8 @@ pub use settings::{
COMPAT_MODE_CURRENT, CoreProps, CustomProp, DEFAULT_GRID, DEFAULT_HYPHENATION_ZONE, LEGACY_COMPAT_MODE, OdfLayout, PagePicture, Settings, Source,
THEME_COLORS, Watermark, Zoom, ZoomFit,
};
pub(crate) use text_walk::walk_between;
pub use text_walk::{PARA_WALK_DEPTH, count_chars, count_chars_no_spaces, count_words};
pub(crate) use text_walk::{PARA_WALK_DEPTH, walk_between};
pub use text_walk::{count_chars, count_chars_no_spaces, count_words};
/// A document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn count_chars_no_spaces(s: &str) -> usize {
}
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
pub const PARA_WALK_DEPTH: usize = 16;
pub(crate) const PARA_WALK_DEPTH: usize = 16;
/// The note and text box stories an object shows, for `Document::reachable`.
pub(crate) fn notes_and_boxes(o: &InlineObject) -> Vec<(u32, &'static [PartKind])> {
-1
View File
@@ -15,7 +15,6 @@ workspace = true
test-support = []
[dependencies]
craft-mime.workspace = true
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
+12 -25
View File
@@ -172,9 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("edit.formatPainter", "Format Painter", "Home › Clipboard", painter).params(r#"{"sticky"?: bool}"#).pure(),
CommandSpec::new("edit.copyFormat", "Copy Formatting", "Home › Clipboard", |s, _| {
// One format buffer, as in Word: Copy Formatting replaces an armed Format Painter.
s.painter = None;
s.copied_format = Some(picked_format(s));
painter_pick(s);
sel_result(s)
})
.key(copy_format_shortcut(cfg!(target_arch = "wasm32")))
@@ -834,21 +832,11 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
sel_result(s)
}
/// The character and paragraph formatting at the start of the selection.
fn picked_format(s: &Session) -> (wordcraft_doc::props::CharProps, wordcraft_doc::props::ParaProps) {
fn painter_pick(s: &mut Session) {
let f = s.sel.ordered().0;
// A symbol's own font isn't formatting to paint onto text.
// Formatting only: not the source's hyperlink or revision marks (#5616).
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol().formatting()).unwrap_or_default();
let para = s.doc.para_at(&f).map(|p| p.props.clone().formatting()).unwrap_or_default();
(chr, para)
}
fn painter_pick(s: &mut Session) {
let (chr, para) = picked_format(s);
// One format buffer, as in Word: the pick is also what the next Paste Formatting applies,
// and stays after the brush is used up or cancelled.
s.copied_format = Some((chr.clone(), para.clone()));
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol()).unwrap_or_default();
let para = s.doc.para_at(&f).map(|p| p.props.clone()).unwrap_or_default();
s.painter = Some((chr, para, false));
}
@@ -864,14 +852,9 @@ fn painter(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"active": true}))
}
/// Apply the format painter's formatting to the selection, or else what Copy Formatting picked
/// up (which stays for the next Paste Formatting).
/// Apply the format painter's formatting to the selection.
fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
let (chr, para, sticky) = match (s.painter.clone(), s.copied_format.clone()) {
(Some(brush), _) => brush,
(None, Some((chr, para))) => (chr, para, true),
(None, None) => return Err(CmdError::Failed("no formatting copied".into())),
};
let Some((chr, para, sticky)) = s.painter.clone() else { return Err(CmdError::Failed("no formatting copied".into())) };
let (a, b) = s.sel.ordered();
if a == b {
// No selection: apply paragraph formatting (and word formatting like Word).
@@ -881,11 +864,15 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
// Word selection includes trailing spaces; a painter click formats just the word,
// matching the ordinary collapsed-caret formatting target.
let word_end = pp.text.get(x..y).map(|word| x + word.trim_end().len()).unwrap_or(y);
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = c.cleared().overlaid(&chr))?;
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = chr.cleared().overlaid(&chr))?;
}
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
} else {
s.doc.format_range(&a, &b, &|c| *c = c.cleared().overlaid(&chr))?;
s.doc.format_range(&a, &b, &|c| {
let link = c.link.clone();
*c = c.cleared().overlaid(&chr);
c.link = link;
})?;
if a.path != b.path || a.off == 0 {
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
}
+16 -1
View File
@@ -71,7 +71,22 @@ pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
Some(out)
}
pub use craft_mime::transfer::base64 as base64_encode;
pub fn base64_encode(b: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
for ch in b.chunks(3) {
let n =
(ch.first().copied().unwrap_or(0) as u32) << 16 | (ch.get(1).copied().unwrap_or(0) as u32) << 8 | ch.get(2).copied().unwrap_or(0) as u32;
for i in 0..4 {
if i <= ch.len() {
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
pub(crate) fn picture(s: &mut Session, v: &Value) -> CmdResult {
let bytes = if let Some(d) = p::str(v, "data") {
-19
View File
@@ -415,22 +415,3 @@ fn local_civil_date_follows_the_utc_offset() {
assert!(crate::cmd::local_offset_secs(unix).abs() <= 26 * 3600);
}
}
#[test]
fn shared_base64_preserves_command_payload_bytes() {
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
assert_eq!(super::objects::base64_encode(plain.as_bytes()), encoded);
}
let bytes: Vec<u8> = (0..513).map(|i| (i % 256) as u8).collect();
for len in 0..=bytes.len() {
let encoded = super::objects::base64_encode(&bytes[..len]);
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
assert!(!encoded.contains(['\r', '\n']));
assert_eq!(super::objects::base64_decode(&encoded), Some(bytes[..len].to_vec()));
}
assert_eq!(super::objects::base64_encode(&[251, 255, 255]), "+///");
// The existing decoder intentionally accepts URL-safe symbols, whitespace and optional padding.
assert_eq!(super::objects::base64_decode("-___"), Some(vec![251, 255, 255]));
assert_eq!(super::objects::base64_decode("Z g\n"), Some(b"f".to_vec()));
assert_eq!(super::objects::base64_decode("!!!!"), None);
}
+1 -3
View File
@@ -431,8 +431,7 @@ enum HoleMode {
/// run formatting and paragraph formatting outside the ranges `author` may edit, in every story,
/// and the formatting of every table, row and cell that holds any of that protected content, and what
/// reaches the whole document: page setup, the document defaults and the existing styles
/// (applying a style may add one), the glossary's building blocks, the document's settings and
/// its metadata.
/// (applying a style may add one), the document's settings and its metadata.
pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &str) -> bool {
// Protection can't change mid-command (`protection_lifted` guards undo and redo).
let mode = if Some("forms") == before.settings.protection.as_deref() { HoleMode::Controls } else { HoleMode::Perms(author.into()) };
@@ -445,7 +444,6 @@ pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &st
&& before.settings == after.settings
&& before.core == after.core
&& before.custom_props == after.custom_props
&& before.glossary == after.glossary
&& comments_unchanged(before, after)
&& lists_unchanged(before, after)
&& sources_unchanged(before, after)
-17
View File
@@ -428,23 +428,6 @@ fn the_post_check_compares_the_settings_and_the_metadata() {
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged document isn't unchanged");
}
/// The glossary's building blocks reach the whole document, so the post-check compares them.
#[test]
fn the_post_check_compares_the_glossary() {
use wordcraft_doc::{BuildingBlock, CharProps, Paragraph};
let mut before = Document::from_text("Some text.");
before.glossary.push(BuildingBlock {
name: "g".into(),
blocks: vec![wordcraft_doc::para_block(Paragraph::with_text("Block", Default::default()))],
..Default::default()
});
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged glossary is unchanged");
let mut after = before.clone();
after.glossary[0].blocks[0] =
wordcraft_doc::para_block(Paragraph::with_text("Block", CharProps { lang: Some("fr-FR".into()), ..Default::default() }));
assert!(!super::outside_unchanged(&before, &after, "someone"), "a relanguaged building block is a change");
}
/// Read only, no exceptions: going to a header the document doesn't have doesn't create
/// one, and loading or filtering recipients doesn't rewrite the merge fields' shown results
/// (both used to change the document from a non-mutating command, #1327).
+3 -86
View File
@@ -1,5 +1,4 @@
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
use wordcraft_doc::CharProps;
/// Options › Language › Set as default: only the saved default proofing language (what future
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
@@ -15,19 +14,8 @@ pub(super) fn preferred_language(s: &mut Session, v: &Value) -> CmdResult {
/// Set Proofing Language: the selection's language and "do not check spelling or grammar",
/// or (`default`) the document's default and the saved language for future blank documents;
/// `detect` is the per-user detection preference.
/// Nothing at all sets US English, as before. `scope: "document"` sets it for every story.
/// Nothing at all sets US English, as before.
pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
// Checked first, so a bad scope changes nothing (not even the detect preference).
let whole_document = match v.get("scope") {
None | Some(Value::Null) => false,
Some(Value::String(t)) if t == "selection" => false,
Some(Value::String(t)) if t == "document" => true,
Some(other) => return Err(CmdError::Params(format!("`scope` must be \"selection\" or \"document\", not {other}"))),
};
// Protection leaves only its exceptions editable, so the whole document can't be one.
if whole_document && let Some(mode) = s.doc.settings.protection.as_deref() {
return Err(CmdError::Disabled(format!("review.language: stop protection ({mode}) before changing the whole document's proofing language")));
}
let lang = match p::str(v, "lang") {
Some(t) => Some(
wordcraft_proof::lang::normalize_tag(t)
@@ -57,91 +45,20 @@ pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
if lang.is_none() && no_proof.is_none() {
return Ok(json!({"detect": s.prefs.detect_language}));
}
let change = |c: &mut CharProps| {
let result = crate::cmd::format::apply(s, &|c| {
if let Some(l) = &lang {
c.lang = Some(l.clone());
}
if let Some(np) = no_proof {
c.no_proof = Some(np);
}
};
let result = if whole_document {
let glossary_skipped = set_document_props(s, &change)?;
// The same caret/selection result as the selection path (the selection is untouched).
let mut r = sel_result(s)?;
if let Some(m) = r.as_object_mut() {
m.insert("scope".into(), json!("document"));
if glossary_skipped {
m.insert("glossarySkipped".into(), json!(true));
}
}
r
} else {
crate::cmd::format::apply(s, &change)?
};
})?;
if p::bool(v, "default") == Some(true) {
s.prefs.default_language = lang;
}
Ok(result)
}
/// Apply `f` to the character formatting of every story of the document (Language dialog, "Apply
/// to the whole document"): text and paragraph marks of the body, headers, footers, notes,
/// comments, text boxes (all `Document::parts`), table cells, and the glossary's building blocks.
/// The selection is untouched; formatting waiting for typing follows.
///
/// Glossary blocks are left alone while Track Changes and Track Formatting are both on: tracked
/// formatting (`fmt_revisions::record`) compares only the body and the parts, so a glossary change
/// would be an untracked edit. So those blocks keep their old language while tracking; the caller
/// reports it (`glossarySkipped`). Returns whether the glossary was skipped.
fn set_document_props(s: &mut Session, f: &dyn Fn(&mut CharProps)) -> Result<bool, CmdError> {
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
for story in stories {
for path in s.doc.para_paths(story) {
let para = s.doc.para_mut(story, &path)?;
let len = para.len();
para.format(0, len, f)?;
f(&mut para.mark);
para.touch();
}
}
let skipped = s.doc.settings.track_changes && s.prefs.markup.track_formatting;
if !skipped {
for block in &mut s.doc.glossary {
format_blocks(&mut block.blocks, f, 0);
}
}
if let Some(pend) = s.pending.as_mut() {
f(pend);
}
Ok(skipped)
}
/// [`set_document_props`] for a block list outside any story (depth-limited like `para_paths`).
fn format_blocks(blocks: &mut wordcraft_doc::Blocks, f: &dyn Fn(&mut CharProps), depth: usize) {
if depth > wordcraft_doc::PARA_WALK_DEPTH {
return;
}
for blk in blocks.iter_mut() {
match Arc::make_mut(blk) {
wordcraft_doc::Block::Para(p) => {
let len = p.len();
// A range inside the paragraph can't fail; the mark is formatted regardless.
let _ = p.format(0, len, f);
f(&mut p.mark);
p.touch();
}
wordcraft_doc::Block::Table(t) => {
for row in &mut t.rows {
for cell in &mut row.cells {
format_blocks(&mut cell.blocks, f, depth + 1);
}
}
}
}
}
}
pub(super) fn macros(s: &mut Session, v: &Value) -> CmdResult {
if let Some(d) = v.get("define") {
let name = d.get("name").and_then(Value::as_str).unwrap_or("Macro").to_string();
+1 -1
View File
@@ -340,7 +340,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
.params(r#"{"format": "decimal|upperRoman|lowerLetter…", "text"?: "%1.", "start"?: n}"#),
CommandSpec::new("review.language", "Language", "Review › Language", language).params(
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents), "scope"?: "selection" (default) | "document" (every run and paragraph mark of every story: body, headers, footers, notes, comments, text boxes, tables, glossary (skipped while Track Changes and Track Formatting are on); one undo step, selection unchanged; returns the caret, "scope":"document" and "glossarySkipped":true when the glossary was skipped)}"#,
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents)}"#,
),
CommandSpec::new("review.language.preferred", "Set as Default Language", "File › Options › Language", preferred_language)
.params(r#"{"lang": "en-US|en-GB|pl-PL|nl-NL|…" (BCP 47)} — only the saved default proofing language, what future blank documents are written in, as Options › Language › Set as default does; the open document, the selection and the undo history don't change. Returns {"preferred": tag}."#)
-147
View File
@@ -903,150 +903,3 @@ fn inspect_removals_work_when_the_document_does_not_track_changes() {
assert!(!text.contains("Hidden"), "the hidden text is still there: {text}");
assert!(text.contains("Visible text."), "{text}");
}
/// #3518: every run and paragraph mark of a story, as (story, path, lang, noProof) rows.
fn proofing_rows(s: &Session) -> Vec<(StoryRef, Option<String>, Option<bool>)> {
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
let mut out = Vec::new();
for st in stories {
for path in s.doc.para_paths(st) {
let Some(p) = s.doc.para(st, &path) else { continue };
out.push((st, p.mark.lang.clone(), p.mark.no_proof));
out.extend(p.runs.iter().map(|r| (st, r.props.lang.clone(), r.props.no_proof)));
}
}
out
}
/// A document with its text in German in the body, a table cell, a header, a footnote, a comment
/// and a text box, as a Word DOCX keeps a `w:lang` on each run, plus a glossary entry.
fn multi_story_doc() -> Session {
use wordcraft_doc::{Block, BuildingBlock, CharProps, Paragraph, PartKind, Table};
let de = || CharProps { lang: Some("de-DE".into()), ..Default::default() };
let blk = |t: &str| Arc::new(Block::Para(Paragraph::with_text(t, de())));
let mut d = Document::from_text("Guten Tag");
d.body = vec![blk("Guten Tag")];
let mut t = Table::new(1, 2, 200.0);
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) {
c.blocks = vec![blk("Zelle")];
}
d.body.push(Arc::new(Block::Table(t)));
d.body.push(blk("Ende"));
for kind in [PartKind::Header, PartKind::Footnote, PartKind::Comment, PartKind::TextBox] {
d.add_part(kind, vec![blk("Teil")]);
}
d.glossary.push(BuildingBlock { name: "g".into(), blocks: vec![blk("Baustein")], ..Default::default() });
Session::new(d)
}
#[test]
fn language_scope_document_sets_every_story() {
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
let (sel, before) = (s.sel.clone(), s.doc.clone());
let rows = proofing_rows(&s);
assert!(rows.len() >= 10 && rows.iter().any(|r| r.1.as_deref() == Some("de-DE")));
s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
// Runs that had their own language, the paragraph marks and the empty cell: all French.
let rows = proofing_rows(&s);
assert!(rows.iter().all(|r| r.1.as_deref() == Some("fr-FR")), "{rows:?}");
for kind_story in s.doc.parts.keys() {
assert!(rows.iter().any(|r| r.0 == StoryRef::Part(*kind_story)));
}
assert!(s.doc.plain_text(StoryRef::Body).contains("Zelle"));
let g = &s.doc.glossary[0].blocks;
assert_eq!(g[0].as_para().map(|p| p.runs[0].props.lang.clone()), Some(Some("fr-FR".into())));
assert_eq!(g[0].as_para().map(|p| p.mark.lang.clone()), Some(Some("fr-FR".into())));
// The selection stays; the document is modified.
assert_eq!(s.sel, sel);
assert!(s.doc != before);
// One undo restores everything.
s.run("edit.undo", &json!({})).unwrap();
assert!(s.doc == before);
assert_eq!(s.sel, sel);
}
#[test]
fn language_scope_document_no_proof_and_pending() {
let mut s = multi_story_doc();
s.run("review.language", &json!({"noProof": true, "scope": "document"})).unwrap();
assert!(proofing_rows(&s).iter().all(|r| r.2 == Some(true)));
// The language itself wasn't asked for and stays.
assert!(proofing_rows(&s).iter().any(|r| r.1.as_deref() == Some("de-DE")));
// Formatting waiting for typing follows.
s.run("format.bold", &json!({})).unwrap();
s.run("review.language", &json!({"lang": "pl-PL", "scope": "document"})).unwrap();
assert_eq!(s.pending.as_ref().and_then(|p| p.lang.as_deref()), Some("pl-PL"));
}
/// Document scope returns the caret/selection like the selection path, plus the scope.
#[test]
fn language_scope_document_returns_the_selection_result() {
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
assert_eq!(out["scope"], "document");
assert_eq!(out["anchor"], crate::cmd::pos_json(&s.sel.anchor), "{out}");
assert_eq!(out["focus"], crate::cmd::pos_json(&s.sel.focus), "{out}");
}
/// Tracked formatting records only the body and parts, so while it is on the glossary (outside
/// any story) is left alone instead of changing untracked; with tracking off it changes.
#[test]
fn language_scope_document_skips_glossary_while_tracking_formatting() {
let gloss = |s: &Session| s.doc.glossary[0].blocks[0].as_para().map(|p| (p.runs[0].props.lang.clone(), p.mark.lang.clone()));
let mut s = multi_story_doc();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("review.trackingOptions", &json!({"trackFormatting": true})).unwrap();
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
assert_eq!(out["glossarySkipped"], true, "{out}");
assert_eq!(gloss(&s), Some((Some("de-DE".into()), Some("de-DE".into()))));
assert!(proofing_rows(&s).iter().all(|r| r.1.as_deref() == Some("fr-FR")));
assert!(s.doc.revisions.iter().any(|r| r.kind == wordcraft_doc::RevisionKind::Format), "the body change is tracked");
let mut s = multi_story_doc();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("review.trackingOptions", &json!({"trackFormatting": false})).unwrap();
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
assert!(out.get("glossarySkipped").is_none(), "{out}");
assert_eq!(gloss(&s), Some((Some("fr-FR".into()), Some("fr-FR".into()))));
}
#[test]
fn language_default_scope_is_selection_only() {
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
s.run("review.language", &json!({"lang": "fr-FR"})).unwrap();
let rows = proofing_rows(&s);
assert!(rows.iter().any(|r| r.1.as_deref() == Some("fr-FR")));
assert!(rows.iter().filter(|r| r.1.as_deref() == Some("fr-FR")).count() < rows.len() / 2);
let mut s = multi_story_doc();
s.run("select.text", &json!({"text": "Guten"})).unwrap();
s.run("review.language", &json!({"lang": "fr-FR", "scope": "selection"})).unwrap();
assert_eq!(proofing_rows(&s), rows);
}
#[test]
fn language_bad_scope_is_a_params_error() {
let mut s = multi_story_doc();
let before = s.doc.clone();
for bad in [json!("everything"), json!(1), json!(true), json!(["document"])] {
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": bad})).unwrap_err();
assert!(matches!(e, CmdError::Params(_)), "{e:?}");
}
assert!(s.doc == before);
assert!(s.prefs.detect_language);
}
/// Document scope is refused under editing protection, before anything changes.
#[test]
fn language_document_scope_is_refused_under_protection() {
for mode in ["readOnly", "comments", "forms"] {
let mut s = multi_story_doc();
s.doc.settings.protection = Some(mode.into());
let before = s.doc.clone();
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": "document"})).unwrap_err();
assert!(matches!(e, CmdError::Disabled(_)), "{mode}: {e:?}");
assert!(s.doc == before, "{mode}: nothing changed");
assert!(s.prefs.detect_language, "{mode}: the detect preference is untouched");
}
}
-4
View File
@@ -88,10 +88,6 @@ pub struct Session {
pub initials: String,
/// Format painter: copied formatting waiting to be applied (and whether it stays on).
pub painter: Option<(CharProps, wordcraft_doc::props::ParaProps, bool)>,
/// Formatting picked up by Copy Formatting (Mod+Shift+C): Paste Formatting applies it as often
/// as asked, as in Word, until the next Copy Formatting. A Format Painter pick is stored here
/// as well.
pub copied_format: Option<(CharProps, wordcraft_doc::props::ParaProps)>,
/// Last message for the status bar / agents.
pub status: String,
/// Headers/footers `insert.createHeader`/`insert.createFooter` made for a page that had none
-1
View File
@@ -259,7 +259,6 @@ impl Session {
author: _,
initials: _,
painter: _,
copied_format: _,
// What the drawn window knows of the others: its front end sets it as it draws.
windows: _,
status: _,
-1
View File
@@ -109,7 +109,6 @@ impl Session {
author: "WordCraft User".into(),
initials: String::new(),
painter: None,
copied_format: None,
status: String::new(),
new_header_parts,
hf_return,
-1
View File
@@ -92,7 +92,6 @@ impl Session {
author: _,
initials: _,
painter: _,
copied_format: _,
status: _,
// Headers just created to edit: closing checks they still exist and are empty.
new_header_parts: _,
-170
View File
@@ -13472,173 +13472,3 @@ fn resolving_away_an_empty_paragraph_with_a_section_break_keeps_the_next_paragra
assert_eq!(s.doc.last_section.margin_left, 72.0, "{cmd}: the following section's setup stays");
}
}
/// #5616: Copy Formatting's formatting stays for every Paste Formatting, as in Word; it doesn't
/// arm the one-shot Format Painter brush.
#[test]
fn copied_formatting_pastes_again_and_again() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
assert!(s.painter.is_none());
for word in ["one", "two"] {
run(&mut s, "select.text", json!({"text": word}));
run(&mut s, "edit.pasteFormat", json!({}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true), "{word}");
}
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Bold one two");
}
/// #5616: Copy Formatting and the Format Painter share one format buffer: each replaces the other,
/// so a used-up brush never hands over to older copied formatting.
#[test]
fn copy_formatting_and_the_format_painter_replace_each_other() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.formatPainter", json!({}));
assert!(s.painter.is_some());
run(&mut s, "edit.copyFormat", json!({}));
assert!(s.painter.is_none(), "Copy Formatting clears an armed brush");
assert!(s.copied_format.is_some());
run(&mut s, "edit.formatPainter", json!({}));
assert!(s.painter.is_some());
run(&mut s, "select.text", json!({"text": "one"}));
run(&mut s, "edit.pasteFormat", json!({}));
assert!(s.painter.is_none(), "a used-up brush is gone");
assert!(s.copied_format.is_some(), "its pick stays for Paste Formatting");
}
/// #5616: arming and cancelling the Format Painter leaves Copy Formatting's pick; a brush's pick
/// is what Paste Formatting applies next.
#[test]
fn cancelling_the_format_painter_keeps_the_copied_formatting() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
run(&mut s, "edit.formatPainter", json!({}));
run(&mut s, "edit.formatPainter", json!({}));
assert!(s.painter.is_none());
run(&mut s, "select.text", json!({"text": "one"}));
run(&mut s, "edit.pasteFormat", json!({}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
// A brush picked from plain text replaces the bold pick.
run(&mut s, "select.text", json!({"text": "two"}));
run(&mut s, "edit.formatPainter", json!({}));
run(&mut s, "select.text", json!({"text": "Bold"}));
run(&mut s, "edit.pasteFormat", json!({}));
assert_ne!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
}
/// #5616: copied formatting carries no tracked paragraph formatting or numbering change.
#[test]
fn copied_paragraph_formatting_carries_no_tracked_changes() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "one\ntwo"}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "one"}));
run(&mut s, "para.alignCenter", json!({}));
run(&mut s, "review.trackChanges", json!({"value": false}));
run(&mut s, "select.text", json!({"text": "one"}));
let f = s.sel.focus.clone();
assert!(s.doc.para_at(&f).unwrap().props.fmt_change.is_some(), "the source paragraph has a tracked formatting change");
run(&mut s, "edit.copyFormat", json!({}));
let (_, para) = s.copied_format.clone().unwrap();
assert!(para.fmt_change.is_none() && para.num_change.is_none());
run(&mut s, "select.text", json!({"text": "two"}));
run(&mut s, "edit.pasteFormat", json!({}));
let f = s.sel.focus.clone();
let p = s.doc.para_at(&f).unwrap().props.clone();
assert!(p.fmt_change.is_none() && p.num_change.is_none());
}
/// #5616: copied formatting carries no hyperlink or revision marks, even into a collapsed caret.
#[test]
fn copied_formatting_carries_no_hyperlink() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "source target"}));
run(&mut s, "select.text", json!({"text": "source"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
run(&mut s, "select.text", json!({"text": "so"}));
run(&mut s, "edit.copyFormat", json!({}));
let (chr, _) = s.copied_format.clone().unwrap();
assert_eq!(chr.bold, Some(true));
assert!(chr.link.is_none() && chr.ins.is_none() && chr.del.is_none() && chr.fmt_change.is_none());
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "select.collapse", json!({}));
run(&mut s, "caret.left", json!({}));
run(&mut s, "edit.pasteFormat", json!({}));
let f = s.sel.focus.clone();
let link = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).link.clone());
assert_eq!(link, Some(None), "the target didn't become a link");
}
/// #5616: Paste Formatting at a bare caret keeps the word's own hyperlink and tracked insertion.
#[test]
fn a_caret_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "source target"}));
run(&mut s, "select.text", json!({"text": "source"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
run(&mut s, "select.collapse", json!({}));
run(&mut s, "caret.right", json!({}));
run(&mut s, "edit.pasteFormat", json!({}));
let at_caret = |s: &Session| {
let f = s.sel.focus.clone();
s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone()).unwrap_or_default()
};
let c = at_caret(&s);
assert!(c.link.is_some(), "the target kept its hyperlink");
assert_eq!(c.bold, Some(true));
// A tracked insertion stays tracked.
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "text.insert", json!({"text": " added"}));
run(&mut s, "review.trackChanges", json!({"value": false}));
run(&mut s, "caret.left", json!({}));
assert!(at_caret(&s).ins.is_some(), "the insertion is tracked before");
run(&mut s, "edit.pasteFormat", json!({}));
assert!(at_caret(&s).ins.is_some(), "Paste Formatting kept the insertion mark");
}
/// #5616: Paste Formatting over a selection keeps the target's hyperlink and tracked marks too.
#[test]
fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
let mut s = s();
run(&mut s, "document.setText", json!({"text": "source target"}));
run(&mut s, "select.text", json!({"text": "source"}));
run(&mut s, "format.bold", json!({}));
run(&mut s, "edit.copyFormat", json!({}));
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
run(&mut s, "select.text", json!({"text": "target"}));
run(&mut s, "edit.pasteFormat", json!({}));
let (a, _) = s.sel.ordered();
let c = s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default();
assert!(c.link.is_some(), "the target kept its hyperlink");
assert_eq!(c.bold, Some(true));
// A tracked insertion selected as a range stays tracked.
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "text.insert", json!({"text": " added"}));
run(&mut s, "review.trackChanges", json!({"value": false}));
run(&mut s, "select.text", json!({"text": "added"}));
let at_start = |s: &Session| {
let (a, _) = s.sel.ordered();
s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default()
};
assert!(at_start(&s).ins.is_some(), "the insertion is tracked before");
run(&mut s, "edit.pasteFormat", json!({}));
let c = at_start(&s);
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
assert_eq!(c.bold, Some(true));
}
+1 -2
View File
@@ -10,10 +10,9 @@ workspace = true
[features]
# Picture decoding within a memory budget (`picture`), for the crates that decode pictures.
image = ["dep:image", "dep:craft-image-codecs", "dep:craft-tiff"]
image = ["dep:image", "dep:craft-image-codecs"]
[dependencies]
craft-image-codecs = { workspace = true, optional = true }
craft-tiff = { workspace = true, optional = true }
image = { workspace = true, optional = true }
serde = { workspace = true }
+20 -24
View File
@@ -1,4 +1,5 @@
//! WordCraft geometry and units.
//!
//! Layout works in **points** (1/72 inch, `f32`). File formats use other units: OOXML uses
//! twentieths of a point (twips) for most lengths, half-points for font sizes, eighths of a point
//! for borders and English Metric Units (EMU, 914 400 per inch) for drawings. The conversions live
@@ -24,32 +25,26 @@ pub const EMU_PER_PT: f32 = 12_700.0;
pub const PT_PER_CM: f32 = 72.0 / 2.54;
/// Twips → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn twips(v: i64) -> f32 {
v as f32 / TWIPS_PER_PT
}
/// Points → twips (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_twips(pt: f32) -> i64 {
finite(pt * TWIPS_PER_PT).round() as i64
}
/// EMU → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn emu(v: i64) -> f32 {
v as f32 / EMU_PER_PT
}
/// Points → EMU (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_emu(pt: f32) -> i64 {
(f64::from(finite(pt)) * f64::from(EMU_PER_PT)).round() as i64
(finite(pt) as f64 * EMU_PER_PT as f64).round() as i64
}
/// Half-points (OOXML font sizes) → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn half_points(v: i64) -> f32 {
v as f32 / 2.0
}
/// Points → half-points (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_half_points(pt: f32) -> i64 {
(finite(pt) * 2.0).round() as i64
}
@@ -128,7 +123,8 @@ pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
"cm" => PT_PER_CM,
"mm" => PT_PER_CM / 10.0,
"pt" | "pts" | "point" | "points" => 1.0,
"pi" | "pc" | "pica" | "picas" | "li" | "line" | "lines" => 12.0,
"pi" | "pc" | "pica" | "picas" => 12.0,
"li" | "line" | "lines" => 12.0,
"px" => 0.75,
_ => return None,
};
@@ -202,7 +198,7 @@ pub fn normalize_degrees(deg: f32) -> f32 {
}
/// How a drawing is turned about its centre: mirrored first (`flip_h` left to right, `flip_v` top
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as `DrawingML`'s `a:xfrm`
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as DrawingML's `a:xfrm`
/// `flipH`, `flipV` and `rot` say (ECMA-376 §20.1.7.6).
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Spin {
@@ -223,7 +219,7 @@ impl Spin {
}
/// The linear part (a, b, c, d: x' = a·x + c·y, y' = b·x + d·y).
fn linear(self) -> [f32; 4] {
fn linear(&self) -> [f32; 4] {
let r = normalize_degrees(self.deg).to_radians();
let (s, c) = r.sin_cos();
let fx = if self.flip_h { -1.0 } else { 1.0 };
@@ -241,17 +237,17 @@ impl Spin {
/// Where point (`x`, `y`) goes when turned about (`cx`, `cy`).
pub fn apply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
let (relative_x, relative_y) = (x - cx, y - cy);
(cx + x_from_x * relative_x + x_from_y * relative_y, cy + y_from_x * relative_x + y_from_y * relative_y)
let [a, b, c, d] = self.linear();
let (u, v) = (x - cx, y - cy);
(cx + a * u + c * v, cy + b * u + d * v)
}
/// The point that [`Spin::apply`] takes to (`x`, `y`).
pub fn unapply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
// The linear part is orthogonal: its inverse is its transpose.
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
let (relative_x, relative_y) = (x - cx, y - cy);
(cx + x_from_x * relative_x + y_from_x * relative_y, cy + x_from_y * relative_x + y_from_y * relative_y)
let [a, b, c, d] = self.linear();
let (u, v) = (x - cx, y - cy);
(cx + a * u + b * v, cy + c * u + d * v)
}
/// The axis-aligned box `r` covers once turned about its centre.
@@ -262,10 +258,10 @@ impl Spin {
/// The width and height of the box a `w` × `h` rectangle covers once turned.
pub fn extent(&self, w: f32, h: f32) -> (f32, f32) {
let (width, height) = (finite(w).abs(), finite(h).abs());
let radians = normalize_degrees(self.deg).to_radians();
let (sine, cosine) = (radians.sin().abs(), radians.cos().abs());
(width * cosine + height * sine, width * sine + height * cosine)
let (w, h) = (finite(w).abs(), finite(h).abs());
let r = normalize_degrees(self.deg).to_radians();
let (s, c) = (r.sin().abs(), r.cos().abs());
(w * c + h * s, w * s + h * c)
}
/// This spin applied inside `outer` (a group member's own spin within its group's): the one
@@ -347,11 +343,11 @@ mod tests {
#[test]
fn unit_round_trips() {
assert_eq!(twips(1440).to_bits(), 72.0f32.to_bits());
assert_eq!(twips(1440), 72.0);
assert_eq!(to_twips(72.0), 1440);
assert_eq!(emu(914_400).to_bits(), 72.0f32.to_bits());
assert_eq!(emu(914_400), 72.0);
assert_eq!(to_emu(72.0), 914_400);
assert_eq!(half_points(24).to_bits(), 12.0f32.to_bits());
assert_eq!(half_points(24), 12.0);
assert_eq!(to_half_points(10.5), 21);
assert_eq!(to_twips(f32::NAN), 0);
}
@@ -433,7 +429,7 @@ mod tests {
assert!(a.intersects(&b));
assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 15.0, 15.0));
assert!(a.contains(Point::new(5.0, 5.0)));
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w.to_bits(), 0.0f32.to_bits());
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w, 0.0);
assert_eq!(a.inset(1.0, 2.0, 3.0, 4.0), Rect::new(1.0, 2.0, 6.0, 4.0));
}
+33 -29
View File
@@ -20,9 +20,9 @@ pub enum Refusal {
NotAPicture,
/// A kind of picture that is never decoded, because its decoder can't be held to a budget.
Unsupported(&'static str),
/// Decoding would exceed the memory budget or size arithmetic overflowed.
/// Decoding it would take more memory than the budget.
TooLarge { width: u32, height: u32 },
/// The header or data is damaged, or the decoder rejects the input.
/// The header or the data is damaged.
Broken(String),
}
@@ -179,19 +179,11 @@ pub struct Probe<'a> {
}
/// TIFF compressions decoded within the caller's limits: none, CCITT Group 4, LZW, Deflate (both
/// codes) and `PackBits`. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
/// codes) and PackBits. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
/// default limits, whatever size the TIFF declares, so such a TIFF is not decoded (#3645).
const TIFF_COMPRESSIONS: [u16; 6] = [1, 4, 5, 8, 32946, 32773];
/// Read a picture's header: PNG, JPEG, GIF, WebP, BMP or TIFF.
///
/// # Errors
///
/// Returns `Refusal::NotAPicture` for an unsupported format, `Refusal::Unsupported` for a TIFF
/// whose compression cannot be read or budgeted (including truncation that prevents reading
/// its compression metadata), `Refusal::TooLarge`
/// on size arithmetic overflow, and `Refusal::Broken` for other header or inspection errors,
/// including TIFF errors after compression metadata is accepted.
pub fn probe(bytes: &[u8]) -> Result<Probe<'_>, Refusal> {
let codec_fmt = detect(bytes).ok_or(Refusal::NotAPicture)?;
let format = from_codec_format(codec_fmt).ok_or(Refusal::NotAPicture)?;
@@ -295,11 +287,6 @@ fn dib_to_bmp(dib: &[u8]) -> Vec<u8> {
/// Read a DIB's header: a BMP without its 14-byte file header, as the Windows clipboard holds
/// one (`CF_DIB`, `CF_DIBV5`). Its layout is first made the one the decoder reads (see
/// [`dib_layout`]).
///
/// # Errors
///
/// Returns `Refusal::Broken` for an invalid DIB header and `Refusal::TooLarge` on size arithmetic
/// overflow.
pub fn probe_dib(dib: Vec<u8>) -> Result<Probe<'static>, Refusal> {
let dib = dib_layout(dib);
let bmp = dib_to_bmp(&dib);
@@ -362,12 +349,6 @@ impl Probe<'_> {
/// Decode, refused before anything is allocated when the peak would pass `budget` bytes. The
/// decoder is held to the header's size and to `budget` as well.
///
/// # Errors
///
/// Returns `Refusal::TooLarge` when the picture does not fit `budget` or the decoder
/// exceeds its limits, `Refusal::NotAPicture` for an unsupported format, and
/// `Refusal::Broken` for other decoding or pixel-conversion errors.
pub fn decode(&self, budget: u64) -> Result<DynamicImage, Refusal> {
if !self.fits(budget) {
return Err(Refusal::TooLarge { width: self.width, height: self.height });
@@ -383,10 +364,6 @@ impl Probe<'_> {
}
/// [`probe`], then [`Probe::decode`] within `budget` bytes.
///
/// # Errors
///
/// Returns the probing or decoding `Refusal`; see [`probe`] and [`Probe::decode`].
pub fn decode(bytes: &[u8], budget: u64) -> Result<DynamicImage, Refusal> {
probe(bytes)?.decode(budget)
}
@@ -539,7 +516,36 @@ fn worst_coefficients(bytes: &[u8]) -> u64 {
/// tag is missing. None when the header can't be read, or when the tag appears more than once:
/// the decoder keeps the last copy, so a harmless first one must not hide a JPEG one after it.
fn tiff_compression(bytes: &[u8]) -> Option<u16> {
craft_tiff::probe::first_image_compression(bytes)
let le = match bytes.get(..4)? {
b"II*\0" => true,
b"MM\0*" => false,
_ => return None,
};
let u16_at = |at: usize| -> Option<u16> {
let b = [*bytes.get(at)?, *bytes.get(at.checked_add(1)?)?];
Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
};
let u32_at = |at: usize| -> Option<u32> {
let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?;
Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
};
let ifd = usize::try_from(u32_at(4)?).ok()?;
let mut found = None;
for i in 0..usize::from(u16_at(ifd)?) {
let entry = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?;
if u16_at(entry)? != 259 {
continue;
}
if found.is_some() || u32_at(entry.checked_add(4)?)? != 1 {
return None;
}
found = Some(match u16_at(entry.checked_add(2)?)? {
3 => u16_at(entry.checked_add(8)?)?,
4 => u16::try_from(u32_at(entry.checked_add(8)?)?).ok()?,
_ => return None,
});
}
Some(found.unwrap_or(1))
}
/// A DIB with a V4 or V5 header in the layout the decoder reads. A 32-bit one whose alpha mask
@@ -716,7 +722,6 @@ mod tests {
let mut s = vec![8];
s.extend(h.to_be_bytes());
s.extend(w.to_be_bytes());
#[expect(clippy::cast_possible_truncation, reason = "These fixtures contain at most four three-byte component records.")]
s.push((comps.len() / 3) as u8);
s.extend(comps);
s
@@ -731,7 +736,6 @@ mod tests {
// A marker walk over SOI, an APP0 segment, SOF2, then the scan.
let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2];
let f = sof(64, 64, &[1, 0x11, 0]);
#[expect(clippy::cast_possible_truncation, reason = "This fixture's nine-byte frame header and length field fit u16.")]
jpeg.extend(((f.len() + 2) as u16).to_be_bytes());
jpeg.extend(&f);
jpeg.extend([0xFF, 0xDA]);
+10 -22
View File
@@ -9,7 +9,7 @@ pub const MAX_RASTER_PIXELS: u64 = 100_000_000;
/// Bytes of a `w`×`h` RGBA8 raster, None on overflow.
pub fn rgba_bytes(w: u32, h: u32) -> Option<u64> {
u64::from(w).checked_mul(u64::from(h))?.checked_mul(4)
(w as u64).checked_mul(h as u64)?.checked_mul(4)
}
/// Whether a `w`×`h` RGBA8 raster fits `budget` bytes.
@@ -29,34 +29,22 @@ pub fn decode_fits(w: u32, h: u32, budget: u64) -> bool {
/// premultiplied copy, so the peak is the larger of `native + 4` and `8` bytes a pixel.
pub fn decode_peak_fits(w: u32, h: u32, native: u64, budget: u64) -> bool {
let per_pixel = native.saturating_add(4).max(8);
w > 0 && h > 0 && u64::from(w).checked_mul(u64::from(h)).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
w > 0 && h > 0 && (w as u64).checked_mul(h as u64).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
}
/// `w`×`h` shrunk (aspect kept, each side at least 1) until it holds at most `max_pixels`.
pub fn fit_pixels(w: u32, h: u32, max_pixels: u64) -> (u32, u32) {
let (w, h) = (w.max(1), h.max(1));
let max_pixels = max_pixels.max(1);
let area = u64::from(w) * u64::from(h);
let area = w as u64 * h as u64;
if area <= max_pixels {
return (w, h);
}
#[expect(clippy::cast_precision_loss, reason = "Floating point only approximates the scale; the integer clamps below enforce every bound.")]
let scale = (max_pixels as f64 / area as f64).sqrt();
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
)]
let new_height = ((f64::from(h) * scale) as u64).clamp(1, u64::from(h));
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
)]
let new_width = ((f64::from(w) * scale) as u64).clamp(1, u64::from(w)).min(max_pixels / new_height).max(1);
let new_height = new_height.min(max_pixels / new_width).max(1);
#[expect(clippy::cast_possible_truncation, reason = "Both dimensions are clamped to their original u32 values above.")]
(new_width as u32, new_height as u32)
let f = (max_pixels as f64 / area as f64).sqrt();
let nh = ((h as f64 * f) as u64).clamp(1, h as u64);
let nw = ((w as f64 * f) as u64).clamp(1, w as u64).min(max_pixels / nh).max(1);
let nh = nh.min(max_pixels / nw).max(1);
(nw as u32, nh as u32)
}
#[cfg(test)]
@@ -90,9 +78,9 @@ mod tests {
fn fit_pixels_keeps_normal_sizes_and_shrinks_huge_ones() {
assert_eq!(fit_pixels(612, 792, MAX_RASTER_PIXELS), (612, 792));
let (w, h) = fit_pixels(16_000, 16_000, 1_000_000);
assert!(u64::from(w) * u64::from(h) <= 1_000_000 && w >= 900, "{w}x{h}");
assert!(w as u64 * h as u64 <= 1_000_000 && w >= 900, "{w}x{h}");
let (w, h) = fit_pixels(16_000, 1, 100);
assert!(u64::from(w) * u64::from(h) <= 100 && h == 1, "{w}x{h}");
assert!(w as u64 * h as u64 <= 100 && h == 1, "{w}x{h}");
assert_eq!(fit_pixels(0, 5, 10).0, 1);
}
}
+5 -11
View File
@@ -718,18 +718,12 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
// (#4250). Inline objects go with their own line.
let first = l0 == 0;
let late = at.late.filter(|l| !l.placed.is_empty());
// A later piece looks only at its own lines and those holding the anchors of the late floats
// it draws, in order: walking every line of the paragraph for each piece made a paragraph of
// many pages quadratic (#6757).
let (piece, mut late_lines) =
if first { (0..pl.lines.len(), Vec::new()) } else { (l0..l1.min(pl.lines.len()), late.map(LateFloats::lines_here).unwrap_or_default()) };
late_lines.retain(|li| !piece.contains(li));
late_lines.sort_unstable();
late_lines.dedup();
let (before, after) = late_lines.split_at(late_lines.partition_point(|li| *li < piece.start));
for li in before.iter().copied().chain(piece).chain(after.iter().copied()) {
crate::work::steps(1);
let late_lines = late.map(LateFloats::lines_here).unwrap_or_default();
for li in 0..pl.lines.len() {
let in_piece = (l0..l1).contains(&li);
if !in_piece && !first && !late_lines.contains(&li) {
continue;
}
let Some(line) = pl.lines.get(li) else { continue };
for k in line.c0..line.c1 {
let Some(c) = pl.clusters.get(k) else { continue };
+3 -7
View File
@@ -292,13 +292,9 @@ fn hf_text_at(p: &Page, id: u32, x: f32, y: f32) -> bool {
_ => None,
})
.any(|(para, l0, l1, lx, ly)| {
let Some(first) = para.lines.get(*l0) else { return false };
// Each line has its own band and extent: lines beside a float are shorter than the
// ones above them, and a click on a long line past a short one's end is still text.
(*l0..*l1).filter_map(|li| para.lines.get(li)).any(|l| {
let top = ly + l.top - first.top;
y >= top - 2.0 && y <= top + l.height + 2.0 && x >= lx + l.left - 40.0 && x <= lx + l.right + 40.0
})
let (Some(first), Some(last)) = (para.lines.get(*l0), para.lines.get(l1.checked_sub(1).unwrap_or(0))) else { return false };
let bottom = ly + last.top + last.height - first.top;
y >= *ly - 2.0 && y <= bottom + 2.0 && x >= *lx - 40.0 && x <= lx + last.right + 40.0
})
}
-88
View File
@@ -914,7 +914,6 @@ fn long_word_beside_a_float(n: usize) -> Document {
/// A word with no break opportunity in it: measuring the word for every line it takes scanned
/// the whole paragraph each time, so the layout was quadratic in the word's length.
#[test]
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
fn a_long_unbreakable_word_lays_out_in_linear_time() {
let (t1, tk, ratio) = layout_time_ratio(long_word_beside_a_float, 50_000, &LayoutOptions::default());
eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}");
@@ -1135,7 +1134,6 @@ fn long_word_with_alternating_advances_beside_a_float(n: usize) -> Document {
/// A word whose advances alternate in sign lays out in linear time: the measurement that asks
/// whether it would fit the full line must not walk the word again for every line it takes.
#[test]
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
fn a_word_with_alternating_advances_lays_out_in_linear_time() {
let (t1, tk, ratio) = layout_time_ratio(long_word_with_alternating_advances_beside_a_float, 50_000, &LayoutOptions::default());
eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}");
@@ -7841,7 +7839,6 @@ fn a_no_break_space_before_a_slash_still_holds() {
}
#[test]
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
fn unequal_formats_lay_out_in_linear_time() {
crate::test_fonts();
// Runs whose formats never compare equal (NaN spacing from a hostile file) each get a style;
@@ -15447,88 +15444,3 @@ fn turned_cell_float_keeps_its_along_text_offset() {
assert!((confined.y - reference.y).abs() < 0.01, "{direction:?}: {confined:?} vs {reference:?}");
}
}
/// A header paragraph beside a Square float on its last lines only: those lines are shorter than
/// the first. A click on the first line past the short last line's end is still on the header's
/// text, so a Behind Text picture under it is not grabbed there (#5601 review).
#[test]
fn header_text_covers_the_whole_width_of_a_wrapped_first_line() {
use wordcraft_doc::para::{Anchor, Float, Wrap};
let text = "Header words that wrap across the whole line and carry on over several lines of the header \
paragraph so there are three lines here and the last one is cut short by the float beside it";
let mut d = Document::new();
let id =
d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, Default::default()))]);
d.last_section.headers.default = Some(id);
let at = |off| Pos::new(wordcraft_doc::StoryRef::Part(id), wordcraft_doc::Path(vec![0]), off);
// The Square float narrows the lines below the first two, on the right.
let square = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 300.0, y: 30.0, ..Default::default() };
d.insert_object(&at(0), rect_shape(160.0, 80.0, square), &Default::default()).unwrap();
// The Behind Text picture lies under the first line, past where the last line ends.
let behind = Float { wrap: Wrap::BehindText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 340.0, y: 0.0, ..Default::default() };
d.insert_object(&at(0), rect_shape(120.0, 20.0, behind), &Default::default()).unwrap();
let l = lay(&d);
let page = &l.pages[0];
let lines: Vec<_> = page
.header
.iter()
.filter_map(|it| match it {
Placed::Lines { para, l0, l1, x, y, .. } => {
Some((*x, *y, (*l0..*l1).filter_map(|i| para.lines.get(i)).map(|l| (l.top, l.height, l.right)).collect::<Vec<_>>()))
}
_ => None,
})
.collect();
let (x, y, ls) = lines.first().expect("header lines").clone();
let (first, last) = (ls.first().expect("first"), ls.last().expect("last"));
assert!(last.2 + 40.0 < first.2 - 20.0, "the last line is shorter than the first: {ls:?}");
let (px, py) = (x + first.2 - 15.0, y + first.0 + first.1 / 2.0);
assert!(l.object_at_in(0, px, py, 0.0, wordcraft_doc::StoryRef::Part(id)).is_none(), "on the first line's text, not the picture: {lines:?}");
}
/// `Line::left`/`right` are the edges available to a line, not where its ink sits: a centred or
/// right-aligned header line covers the Behind Text picture across its whole band, so a click in
/// the empty space beside its text is still on the header text. Beyond the band (an indent, or
/// beside a float) and 40pt of slack the picture is hit (#5601 review).
#[test]
fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
use wordcraft_doc::Align;
use wordcraft_doc::para::{Anchor, Float, Wrap};
for align in [Align::Center, Align::Right] {
let mut d = Document::new();
let mut p = wordcraft_doc::Paragraph::with_text("Header", Default::default());
p.props.align = Some(align);
p.props.indent_left = Some(150.0);
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(p)]);
d.last_section.headers.default = Some(id);
let story = wordcraft_doc::StoryRef::Part(id);
let at = Pos::new(story, wordcraft_doc::Path(vec![0]), 0);
// A Behind Text picture across the whole text width, level with the header line.
let behind = Float { wrap: Wrap::BehindText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 0.0, y: 0.0, ..Default::default() };
d.insert_object(&at, rect_shape(460.0, 20.0, behind), &Default::default()).unwrap();
let l = lay(&d);
let (x, y, left, right, height, ink0) = l.pages[0]
.header
.iter()
.find_map(|it| match it {
Placed::Lines { para, l0, x, y, .. } => {
para.lines.get(*l0).and_then(|ln| Some((*x, *y, ln.left, ln.right, ln.height, *ln.xs.first()?)))
}
_ => None,
})
.expect("header line");
// `left`/`right` are the band edges available to the line, not the ink extent.
assert!((left - 150.0).abs() < 0.5, "{align:?}: the band's left edge is the indent: {left}");
assert!(ink0 > left + 100.0, "{align:?}: the ink starts well inside the band: ink {ink0}, band left {left}");
let ym = y + height / 2.0;
let hit = |px: f32| l.object_at_in(0, px, ym, 0.0, story).is_some();
// Inside the band, wherever the centred or right-aligned ink sits: header text.
assert!(!hit(x + left + 5.0), "{align:?}: the band's left end is text");
assert!(!hit(x + (left + right) / 2.0), "{align:?}: the band's middle is text");
// Between the indent and the ink is still the text band, not the picture.
assert!(!hit(x + left + 160.0), "{align:?}: between the indent and the ink is text");
// Within 40pt of the band's left end is still text; further left the picture is hit.
assert!(!hit(x + left - 30.0), "{align:?}: within 40pt left of the band is text");
assert!(hit(x + left - 60.0), "{align:?}: beyond 40pt left of the band the picture is hit");
}
}
-16
View File
@@ -223,22 +223,6 @@ fn selecting_a_long_endnote_takes_linear_time() {
assert_linear_steps("endnote selection", 20, laid, |(d, l, (a, b))| drop(std::hint::black_box(l.selection_rects(d, a, b, 0))));
}
/// One paragraph of `n` lines (a line break after each word), so it runs over many pages.
fn many_lines(n: usize) -> Document {
let mut d = Document::from_text("");
d.body = vec![wordcraft_doc::para_block(Paragraph::with_text(&"x\n".repeat(n), CharProps::default()))];
d
}
/// The piece of a long paragraph on each page looked through every line of the paragraph for the
/// pictures and shapes to draw with it (#6757).
#[test]
fn a_paragraph_over_many_pages_lays_out_in_linear_time() {
let pages = lay(&many_lines(SCALE * 400), &LayoutOptions::default()).pages.len();
assert!(pages > 40, "the paragraph runs over many pages: {pages}");
assert_layout_linear("a paragraph over many pages", 400, many_lines, &LayoutOptions::default());
}
/// A table of `n` rows of 60 cells, each row exactly half a point high, so every cell clips its
/// (empty) paragraph and the whole table fits on the first page.
fn clipped_table(n: usize) -> Document {
-6
View File
@@ -58,9 +58,7 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
@@ -106,7 +104,6 @@ impl WordApp {
clipboard_published: false,
printing: Default::default(),
print_feedback_seen: None,
print_gen: 0,
integrated_titlebar: false,
mac_titlebar: chrome::MacTitleBar::default(),
updates_rt: updates_ui::Runtime::default(),
@@ -181,9 +178,7 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
@@ -502,7 +497,6 @@ impl WordApp {
if !self.ui.backstage {
backstage::forget_open_error(&ctx);
backstage::forget_save_as_error(&ctx);
self.export_error.clear();
}
self.paint_window(ui, &ctx, t);
if !moved(self) {
+2 -4
View File
@@ -145,9 +145,7 @@ impl WordApp {
// Web: saving and exporting become downloads.
if self.services.download.is_some() && matches!(id, "file.save" | "file.saveAs" | "file.exportPdf" | "file.exportPng") {
let name = params.get("path").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| self.web_save_name(id));
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
let name = if id == "file.exportPdf" && !name.ends_with(".pdf") { format!("{name}.pdf") } else { name };
// A save with a password encrypts this and later saves (`file.save`'s `password`).
if matches!(id, "file.save" | "file.saveAs")
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
@@ -777,7 +775,7 @@ impl WordApp {
json!({"dir": dir})
}
// The built-in file browser (#576), for when the system's file dialog doesn't show up
// (desktop only): `purpose` is document (default), picture, recipients, save or export. A system
// (desktop only): `purpose` is document (default), picture, recipients or save. A system
// dialog still waiting for an answer is given up as cancelled.
#[cfg(not(target_arch = "wasm32"))]
"ui.fileBrowser" => {
-7
View File
@@ -320,8 +320,6 @@ impl WordApp {
return;
}
self.print_feedback_seen = self.printing.message.clone();
// A new message: what any window said before no longer stands for it.
self.print_gen = self.print_gen.wrapping_add(1);
let Some(message @ (printing::Feedback::Submitted(_) | printing::Feedback::Failed(_) | printing::Feedback::WorkerStopped)) =
self.printing.message.clone()
else {
@@ -336,11 +334,6 @@ impl WordApp {
self.ui.backstage = false;
self.canvas.want_focus = true;
}
// Said only where the status bar is drawn: not under File's other pages, and a failure on
// the Print page is the page's to show.
if !self.ui.backstage {
self.print_memo.said = Some(self.print_gen);
}
}
/// Files dropped on the native window. Raw input is taken only in the first UI pass: a
-5
View File
@@ -759,11 +759,6 @@ fn save_as_page(app: &mut WordApp, ui: &mut Ui) {
if ui.button(egui::RichText::new(tl!("Browse…")).font(medium(14.0))).clicked() {
app.save_as_dialog();
}
// Linux and the BSDs (#3535): WordCraft's own browser when the system dialog doesn't appear.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
if ui.button(egui::RichText::new(tl!("Browse in WordCraft…")).font(medium(14.0))).clicked() {
let _ = app.run("ui.fileBrowser", json!({"purpose": "save"}));
}
// A Word template in the user templates folder, which File › New lists under Personal (#2852).
ui.add_space(8.0);
if ui
-174
View File
@@ -859,77 +859,6 @@ fn save_as_page_shows_browse_and_no_open_list() {
assert!(h.query_by_label("Recent").is_none(), "Save As has no list that opens documents");
}
/// #3467, #3535: a system dialog that never shows up doesn't leave Save As stuck: Browse in
/// WordCraft… gives it up and saves through WordCraft's own browser.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn save_as_saves_in_wordcraft_when_the_system_dialog_never_shows() {
// A host that takes every request and never answers, like a portal that shows nothing.
let senders: std::rc::Rc<std::cell::RefCell<Vec<std::sync::mpsc::Sender<crate::FileDialogAnswer>>>> = Default::default();
let keep = senders.clone();
let services = Services {
file_dialog: Some(Box::new(move |_| {
let (tx, rx) = std::sync::mpsc::channel();
keep.borrow_mut().push(tx);
rx
})),
..Default::default()
};
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-builtin-save-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
a.run("text.insert", json!({"text": "Saved past a silent portal"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "saveAs"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
h.get_by_label("Browse…").click();
h.run_steps(4);
assert!(h.state().file_dialog.is_some(), "the system dialog was asked for and never answered");
h.get_by_label("Browse in WordCraft…").click();
h.run_steps(4);
let a = h.state_mut();
assert!(a.file_dialog.is_none(), "the silent system dialog is given up");
let b = a.file_browser.open.as_mut().expect("WordCraft's own browser is open");
b.navigate(dir.clone());
b.name = "kept".into();
let crate::file_browser::Step::Pick(path) = b.accept() else { panic!("picked") };
a.close_file_browser(Some(path));
let saved = dir.join("kept.docx");
assert_eq!(a.session.path.as_deref(), Some(saved.as_path()));
let back = wordcraft_engine::io::open_path(&saved).unwrap();
assert!(back.plain_text(wordcraft_doc::StoryRef::Body).contains("Saved past a silent portal"));
let _ = std::fs::remove_dir_all(&dir);
}
/// #3535: File › Export offers WordCraft's own browser as well, for its formats.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn export_page_offers_wordcrafts_own_browser() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
h.get_by_label("Browse in WordCraft…").click();
h.run_steps(4);
let b = h.state().file_browser.open.as_ref().expect("WordCraft's own browser is open");
assert!(matches!(&b.after, crate::file_dialogs::AfterPick::Export { ext } if ext == "pdf"));
}
#[test]
fn backstage_save_navigates_to_save_as_when_unnamed() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
@@ -1363,106 +1292,3 @@ fn rtl_template_titles_are_right_aligned() {
wide_text_right,
);
}
/// A refused Word XML export (the typed name's `.xml` twin already exists) is said on the Export
/// page itself: Backstage hides the status bar, so the person would otherwise see nothing.
#[test]
fn export_refusal_shows_on_the_export_page() {
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-export-error-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
let err = h.state_mut().finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
h.run_steps(4);
assert!(h.state().ui.backstage, "still on the Export page");
assert!(err.contains("letter.xml already exists"), "{err}");
h.get_by_label(err.as_str());
assert_eq!(std::fs::read_to_string(dir.join("letter.xml")).unwrap(), "taken", "nothing replaced");
let _ = std::fs::remove_dir_all(&dir);
}
/// A refused Word XML export (the typed name's `.xml` twin already exists) is said on the Export
/// page itself: Backstage hides the status bar, so the person would otherwise see nothing.
#[test]
fn export_refusal_shows_on_the_print_page() {
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-print-export-error-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "print"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
let err = h.state_mut().finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
h.run_steps(4);
assert!(h.state().ui.backstage, "still on the Print page");
assert!(err.contains("letter.xml already exists"), "{err}");
h.get_by_label(err.as_str());
assert_eq!(std::fs::read_to_string(dir.join("letter.xml")).unwrap(), "taken", "nothing replaced");
let _ = std::fs::remove_dir_all(&dir);
}
/// A cancelled export dialog drops an earlier refusal: it is not news any more.
#[test]
fn cancelling_an_export_clears_its_page_error() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.export_error = "old refusal".into();
a.finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, None).unwrap();
assert!(a.export_error.is_empty());
}
/// The export error belongs to the window that refused the export: another window running a
/// frame outside Backstage must not erase it while this one still shows the Export page.
#[test]
fn export_error_belongs_to_its_window() {
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-export-two-windows-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
// Window A (this one) is refused; window B is another window's state, outside Backstage.
let mut b = crate::window_ui::WindowUi::new(a.session.document_id());
let err = a.finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
assert_eq!(a.export_error, err);
// B's frame: swap its state in, run frames outside Backstage, swap back.
a.swap_window(&mut b);
assert!(!a.ui.backstage && a.export_error.is_empty(), "B has its own, empty, error");
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
h.run_steps(4);
h.state_mut().swap_window(&mut b);
assert!(h.state().ui.backstage, "A is still on the Export page");
assert_eq!(h.state().export_error, err, "B's frames left A's message alone");
let _ = std::fs::remove_dir_all(&dir);
}
-16
View File
@@ -253,18 +253,6 @@ pub struct CanvasState {
pub(crate) v_pressed: bool,
/// The modifiers last held with Mod, for a Mod+V whose Mod is released before V.
pub(crate) paste_mods: Option<egui::Modifiers>,
/// The modifiers a paste event is read with: those of Mod+V's press or a Mod change, until an
/// unrelated key, a pointer press or a focus change. (`paste_mods` also serves the release path.)
pub(crate) paste_event_mods: Option<egui::Modifiers>,
/// On the web, Mod+Shift+V pasted formatting from its key press: the browser's paste event
/// that follows is the same keystroke and pastes nothing (#5616). Any other key press clears it.
pub(crate) ignore_next_paste: bool,
/// When `ignore_next_paste` was set (input time, seconds): the browser's paired paste comes
/// with the key, so the wait ends after `PASTE_WAIT` and a later paste isn't dropped.
pub(crate) paste_wait_since: Option<f64>,
/// The platform sends a paste event after Mod+Shift+V's key (a browser does; a desktop shell
/// doesn't). Only then does the key leave a paste event to ignore or to let paste text.
pub(crate) paste_event_follows_chord: bool,
/// Draw Table or Eraser is on (`table_pen`): presses draw instead of moving the caret.
pub table_tool: Option<crate::table_pen::TableTool>,
/// The Draw Table stroke (or eraser press) in progress.
@@ -448,10 +436,6 @@ impl Default for CanvasState {
pasted: false,
v_pressed: false,
paste_mods: None,
paste_event_mods: None,
ignore_next_paste: false,
paste_wait_since: None,
paste_event_follows_chord: cfg!(target_arch = "wasm32"),
swallow_text: false,
ime_join_text: None,
ime_reset: false,
+48 -215
View File
@@ -635,12 +635,12 @@ fn multi_click_drag_extends_by_units() {
for _ in 0..6 {
h.step();
}
let screen = |h: &mut H, pos: Pos| {
let screen = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: Pos| {
let c = h.state_mut().session.layout().caret(&pos).expect("caret");
page_to_screen(h.state_mut(), c.page, c.x + 1.0, c.top + c.height / 2.0).expect("on screen")
};
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let multi_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
let multi_drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, clicks: usize| {
h.event(Event::PointerMoved(from));
for i in 0..clicks {
h.event(button(from, true));
@@ -871,7 +871,7 @@ fn clicking_vertical_scrollbar_track_advances_one_screen() {
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut H, at: Pos2| {
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(button(at, true));
@@ -939,7 +939,7 @@ fn clicking_vertical_scrollbar_track_advances_one_screen_in_rtl() {
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut H, at: Pos2| {
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(button(at, true));
@@ -1002,7 +1002,7 @@ fn clicking_thin_vertical_scrollbar_track_advances_one_screen() {
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut H, at: Pos2| {
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(button(at, true));
@@ -1195,11 +1195,11 @@ fn ctrl_drag_copies_an_object() {
for _ in 0..6 {
h.step();
}
let objects = |h: &mut H| {
let objects = |h: &mut egui_kittest::Harness<'_, WordApp>| {
let doc = &h.state().session.doc;
doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).map_or(0, |p| p.objects.len())
};
let xs = |h: &mut H| {
let xs = |h: &mut egui_kittest::Harness<'_, WordApp>| {
let mut v: Vec<i32> = Vec::new();
for x in (0..600).step_by(50) {
if h.state_mut().session.layout().find_object(0, |o| (o.rect.x - x as f32).abs() < 0.5).is_some() {
@@ -1208,7 +1208,7 @@ fn ctrl_drag_copies_an_object() {
}
v
};
let drag = |h: &mut H, mods: Modifiers| {
let drag = |h: &mut egui_kittest::Harness<'_, WordApp>, mods: Modifiers| {
let from = page_to_screen(h.state_mut(), 0, 250.0, 330.0).expect("on screen");
let to = page_to_screen(h.state_mut(), 0, 400.0, 330.0).expect("on screen");
h.event(Event::ModifiersChanged(mods));
@@ -1257,19 +1257,19 @@ fn selection_bar_clicks_select_lines() {
h.step();
}
// A point in the left margin beside the line `li` lines below the one holding `pos`.
let margin = |h: &mut H, pos: Pos, li: f32| {
let margin = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: Pos, li: f32| {
let c = h.state_mut().session.layout().caret(&pos).expect("caret");
page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height * (li + 0.5)).expect("on screen")
};
let line_start = |h: &mut H, at: Pos2| {
let line_start = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
let (rects, scale) = (h.state().canvas.page_rects.clone(), h.state().canvas.scale);
let layout = h.state_mut().session.layout();
let (pg, x, y) = page_at(&rects, &layout, scale, at).expect("page");
layout.selection_bar_at(pg, x, y).expect("in the selection bar")
};
let span = |h: &mut H, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
let span = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
let clicks_drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, clicks: usize| {
h.event(Event::PointerMoved(from));
for i in 0..clicks {
h.event(button(from, true));
@@ -1288,7 +1288,7 @@ fn selection_bar_clicks_select_lines() {
h.step();
}
};
let pause = |h: &mut H| {
let pause = |h: &mut egui_kittest::Harness<'_, WordApp>| {
for _ in 0..40 {
h.step();
}
@@ -1361,7 +1361,7 @@ fn selection_bar_of_a_right_to_left_paragraph_is_on_the_right() {
let y = c.top + c.height / 2.0;
let right = page_to_screen(h.state_mut(), c.page, (body_x + page_w) / 2.0, y).expect("on screen");
let left = page_to_screen(h.state_mut(), c.page, 30.0, y).expect("on screen");
let click = |h: &mut H, at: Pos2| {
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
h.event(Event::PointerMoved(at));
h.step();
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
@@ -1408,7 +1408,7 @@ fn an_armed_format_painter_changes_the_pointer() {
let c = h.state_mut().session.layout().caret(&Pos::body(0, 6)).expect("caret");
let over_text = page_to_screen(h.state_mut(), c.page, c.x, c.top + c.height / 2.0).expect("on screen");
let over_bar = page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height / 2.0).expect("on screen");
let pointer_after = |h: &mut H, cmd: Option<&str>| {
let pointer_after = |h: &mut egui_kittest::Harness<'_, WordApp>, cmd: Option<&str>| {
if let Some(cmd) = cmd {
h.state_mut().run(cmd, json!({})).unwrap();
}
@@ -1493,7 +1493,7 @@ fn an_empty_comment_balloon_deletes() {
for _ in 0..6 {
h.step();
}
let click = |h: &mut H, at: egui::Pos2| {
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: egui::Pos2| {
h.event(egui::Event::PointerMoved(at));
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.step();
@@ -2137,7 +2137,7 @@ fn double_click_margin_creates_header_and_footer() {
for _ in 0..6 {
h.step();
}
let double_click = |h: &mut H, at: Pos2| {
let double_click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
h.event(Event::PointerMoved(at));
for _ in 0..2 {
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
@@ -2150,7 +2150,7 @@ fn double_click_margin_creates_header_and_footer() {
h.step();
}
};
let kind = |h: &H| part_kind(h.state(), h.state().session.sel.focus.story);
let kind = |h: &egui_kittest::Harness<'_, WordApp>| part_kind(h.state(), h.state().session.sel.focus.story);
let page = h.state_mut().session.layout().pages[0].clone();
assert!(page.header_story.is_none() && page.footer_story.is_none());
let (x, top, bottom) = (page.body.x + 20.0, page.body.y / 2.0, (page.body.bottom() + page.h) / 2.0);
@@ -2250,7 +2250,7 @@ fn double_click_switches_between_header_and_footer() {
for _ in 0..6 {
h.step();
}
let double_click = |h: &mut H, at: Pos2| {
let double_click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
h.event(Event::PointerMoved(at));
for _ in 0..2 {
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
@@ -2262,7 +2262,7 @@ fn double_click_switches_between_header_and_footer() {
h.step();
}
};
let kind = |h: &H| part_kind(h.state(), h.state().session.sel.focus.story);
let kind = |h: &egui_kittest::Harness<'_, WordApp>| part_kind(h.state(), h.state().session.sel.focus.story);
let page = h.state_mut().session.layout().pages[0].clone();
let (x, top, bottom) = (page.body.x + 20.0, page.body.y / 2.0, (page.body.bottom() + page.h) / 2.0);
let head_at = page_to_screen(h.state_mut(), 0, x, top).expect("top margin on screen");
@@ -2885,7 +2885,7 @@ fn control_click_on_macos_opens_the_context_menu() {
h.step();
let ctrl = egui::Modifiers { ctrl: true, ..Default::default() };
// The events winit delivers for a Control-click, through the app's input hook as eframe runs it.
let send = |h: &mut H, events: Vec<egui::Event>| {
let send = |h: &mut egui_kittest::Harness<'_, WordApp>, events: Vec<egui::Event>| {
let mut raw = egui::RawInput { events, ..Default::default() };
let ctx = h.ctx.clone();
h.state_mut().raw_input_hook(&ctx, &mut raw);
@@ -2973,10 +2973,7 @@ fn drag_floating_picture(wrap: &str, header: bool, preselect: bool) {
for _ in 0..3 {
h.step();
}
// In the header the picture lies over the body area, clear of the header's own text, so a
// click on it selects it (Word); in the body a click still reaches the text behind it.
let picked = wordcraft_engine::cmd::objects::object_selection(&h.state().session).is_some();
assert_eq!(picked, header, "a click selects the header's picture, but only edits the body's text");
assert!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).is_none(), "a click still selects text");
if preselect {
let end = Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() };
h.state_mut().run("select.range", json!({"anchor": pos, "focus": end})).unwrap();
@@ -3141,7 +3138,7 @@ fn right_clicking_a_link_hides_the_hover_tooltip() {
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
h.event(egui::Event::PointerMoved(at));
steps(&mut h, 2);
let tips = |h: &H| h.query_all_by_label_contains("Click to follow link").count();
let tips = |h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by_label_contains("Click to follow link").count();
assert!(tips(&h) > 0, "hovering the link shows its target");
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() });
@@ -3174,7 +3171,7 @@ fn a_handled_press_skips_the_link_tooltip() {
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
h.event(Event::PointerMoved(at));
steps(&mut h, 2);
let tips = |h: &H| h.query_all_by_label_contains("Click to follow link").count();
let tips = |h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by_label_contains("Click to follow link").count();
assert!(tips(&h) > 0, "hovering the link shows its target");
h.event(Event::ModifiersChanged(Modifiers::COMMAND));
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::COMMAND });
@@ -4032,13 +4029,13 @@ fn ruler_tab_gestures_are_primary_only_and_cancellable() {
h.step();
}
let area = h.state().canvas.canvas_rect.expect("the canvas is laid out");
let ruler_x = |h: &mut H, d: f32| {
let ruler_x = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| {
let body_x = h.state_mut().session.layout().pages[0].body.x;
page_to_screen(h.state_mut(), 0, body_x + d, 0.0).expect("on screen").x
};
let on_ruler = |h: &mut H, d: f32| pos2(ruler_x(h, d), area.min.y - 7.0);
let on_ruler = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| pos2(ruler_x(h, d), area.min.y - 7.0);
let button = |at: Pos2, b: PointerButton, pressed: bool| Event::PointerButton { pos: at, button: b, pressed, modifiers: Default::default() };
let drag_events = |h: &mut H, from: Pos2, to: Pos2, b: PointerButton| {
let drag_events = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, b: PointerButton| {
h.event(Event::PointerMoved(from));
h.event(button(from, b, true));
h.step();
@@ -4051,7 +4048,7 @@ fn ruler_tab_gestures_are_primary_only_and_cancellable() {
h.step();
}
};
let stops_of = |h: &H, block: usize| {
let stops_of = |h: &egui_kittest::Harness<'_, WordApp>, block: usize| {
let s = &h.state().session;
let para = s.doc.para_at(&Pos::body(block, 0)).expect("a paragraph");
s.doc.styles.resolve_para(&para.props).tabs.iter().map(|t| (t.pos, t.align)).collect::<Vec<_>>()
@@ -4137,13 +4134,13 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
}
let area = h.state().canvas.canvas_rect.expect("the canvas is laid out");
// The middle of the ruler's strip, over a point `d` points from the paragraph's start.
let on_ruler = |h: &mut H, d: f32| {
let on_ruler = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| {
let body_x = h.state_mut().session.layout().pages[0].body.x;
let x = page_to_screen(h.state_mut(), 0, body_x + d, 0.0).expect("on screen").x;
pos2(x, area.min.y - 7.0)
};
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let click = |h: &mut H, at: Pos2| {
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
h.event(Event::PointerMoved(at));
h.event(button(at, true));
h.step();
@@ -4156,7 +4153,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
h.step();
}
};
let drag = |h: &mut H, from: Pos2, to: Pos2| {
let drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2| {
h.event(Event::PointerMoved(from));
h.event(button(from, true));
h.step();
@@ -4169,7 +4166,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
h.step();
}
};
let stops = |h: &H| {
let stops = |h: &egui_kittest::Harness<'_, WordApp>| {
let s = &h.state().session;
let para = s.doc.para_at(&s.sel.focus).expect("a paragraph");
s.doc.styles.resolve_para(&para.props).tabs.iter().map(|t| (t.pos, t.align)).collect::<Vec<_>>()
@@ -4256,7 +4253,8 @@ fn space_and_enter_on_the_canvas_do_not_interrupt_ime() {
}
assert!(h.state().canvas.focused, "the canvas takes focus when the window opens");
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let ime_interrupted = |h: &H| h.output().platform_output.ime.as_ref().map(|ime| ime.should_interrupt_composition);
let ime_interrupted =
|h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|ime| ime.should_interrupt_composition);
h.event(key(egui::Key::Space));
h.event(egui::Event::Text(" ".into()));
h.step();
@@ -4342,7 +4340,7 @@ fn the_caret_follows_the_input_method_cursor_in_the_composition() {
for _ in 0..8 {
h.step();
}
let ime_x = |h: &H| h.output().platform_output.ime.as_ref().map(|ime| ime.cursor_rect.min.x);
let ime_x = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|ime| ime.cursor_rect.min.x);
let start = ime_x(&h).expect("the canvas places the candidate window");
let mut compose = |range: Option<std::ops::Range<usize>>| {
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほん".into(), active_range_chars: range }));
@@ -4388,8 +4386,10 @@ fn ime_descriptor_reports_visible_logical_text_and_exact_cause() {
}
h.state_mut().session.sel = wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 2));
h.step();
let text = |h: &H| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).map(|p| p.text.clone());
let cause = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
let text = |h: &egui_kittest::Harness<'_, WordApp>| {
h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).map(|p| p.text.clone())
};
let cause = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
assert_eq!(text(&h), Some("ab".into()), "the committed text is available");
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "に".into(), active_range_chars: None }));
h.step();
@@ -4433,7 +4433,8 @@ fn ime_descriptor_hides_tracked_deletions_and_preserves_reversed_selection() {
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 2), focus: wordcraft_doc::Pos::body(0, 7) };
h.step();
let payload = |h: &H| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).cloned();
let payload =
|h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).cloned();
let p = payload(&h).expect("the visible text is available");
assert_eq!(p.text, "abcd");
assert_eq!(p.cursor, 4);
@@ -4459,10 +4460,10 @@ fn ime_byte_deletion_preserves_the_selection_and_earns_input_method() {
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 3), focus: wordcraft_doc::Pos::body(0, 1) };
h.step();
let cause = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
let cause = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
h.event(egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 1 }));
h.step();
let body = |h: &H| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim_end().to_string();
let body = |h: &egui_kittest::Harness<'_, WordApp>| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim_end().to_string();
assert_eq!(body(&h), "bc", "the selected text is preserved");
assert_eq!(h.state().session.sel.anchor.off, 2, "the selection anchor moved with the erased prefix");
assert_eq!(h.state().session.sel.focus.off, 0);
@@ -4509,7 +4510,7 @@ fn ime_generation_changes_on_document_replacement_but_not_on_caret_motion() {
for _ in 0..8 {
h.step();
}
let generation = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let generation = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let first = generation(&h).expect("an IME context");
h.state_mut().run("caret.right", json!({})).unwrap();
h.step();
@@ -4714,7 +4715,7 @@ fn ime_generation_changes_on_undo_and_version_restore() {
for _ in 0..8 {
h.step();
}
let generation = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let generation = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
let first = generation(&h).expect("an IME context");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.step();
@@ -5013,7 +5014,9 @@ fn ime_equation_byte_delete_drops_only_its_immediate_replacement() {
for _ in 0..8 {
h.step();
}
let linear = |h: &mut H| h.state_mut().run("equation.get", json!({})).unwrap()["linear"].as_str().unwrap_or_default().to_string();
let linear = |h: &mut egui_kittest::Harness<'_, WordApp>| {
h.state_mut().run("equation.get", json!({})).unwrap()["linear"].as_str().unwrap_or_default().to_string()
};
// Harness::event steps each queued event in a separate frame. Insert the complete
// protocol replacement into RawInput to exercise a single native input batch.
h.input_mut().events.extend([
@@ -5385,176 +5388,6 @@ fn a_long_comment_balloon_paints_only_its_first_ten_rows() {
}
}
/// A Behind Text header picture: while editing the header a click on it selects it wherever no
/// header text covers it (far down over the body, or in the band clear of the text), as in Word;
/// over the header text the click edits the text. From the body a click there is body text.
#[test]
fn header_picture_clear_of_header_text_is_selected_while_editing_the_header() {
// Far down the page, over the body.
header_picture_click(false, 200.0, 400.0, Some((300.0, f32::MAX)), true);
// In the header band, below the header's text line.
header_picture_click(false, 300.0, 56.0, Some((50.0, 72.0)), true);
// Over the header's text, at its start: the click goes to the text.
header_picture_click(false, 72.0, 36.0, None, false);
}
/// The same for a footer, which is a `StoryRef::Part` like the header.
#[test]
fn footer_picture_clear_of_footer_text_is_selected_while_editing_the_footer() {
header_picture_click(true, 200.0, 400.0, Some((300.0, f32::MAX)), true);
}
/// Dragging a header picture that no header text covers moves it, rather than starting the
/// deferred drag-over-text path.
#[test]
fn dragging_a_header_picture_clear_of_header_text_moves_it() {
let (mut h, pos, rect) = header_picture_app(false, 200.0, 400.0, 1);
edit_story(&mut h, false, 0);
let at = picture_point(&h, 0, rect);
h.event(egui::Event::PointerMoved(at));
h.event(pointer_button(at, egui::PointerButton::Primary, true));
h.step();
let to = at + egui::vec2(60.0, 30.0);
for p in [at + egui::vec2(20.0, 10.0), to] {
h.event(egui::Event::PointerMoved(p));
h.step();
}
h.event(pointer_button(to, egui::PointerButton::Primary, false));
steps(&mut h, 3);
let moved = h.state_mut().session.layout().object(&pos, 0).unwrap().rect;
assert!(moved.x > rect.x + 10.0 && moved.y > rect.y + 5.0, "the picture moved with the drag: {rect:?} -> {moved:?}");
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "and stays selected");
}
/// A right-click on the header picture repeated on page 2 while editing the header on page 1
/// selects that copy: the frame and handles belong on page 2, not the page last edited.
#[test]
fn right_clicking_a_repeated_header_picture_selects_it_on_its_own_page() {
let (mut h, pos, _) = header_picture_app(false, 200.0, 400.0, 2);
edit_story(&mut h, false, 0);
assert_eq!(h.state().session.page_hint, 0, "editing the header on page 1");
let rect = h.state_mut().session.layout().object(&pos, 1).unwrap().rect;
assert_eq!(h.state_mut().session.layout().object(&pos, 1).unwrap().page, 1, "the picture is repeated on page 2");
let at = picture_point(&h, 1, rect);
press(&mut h, at, egui::PointerButton::Secondary);
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "the right-click selected it");
assert_eq!(h.state().session.page_hint, 1, "its frame is drawn on the page clicked");
}
/// The same for a left-click: it selects the page-2 copy and moves the frame there, not the copy
/// on page 1 that was being edited.
#[test]
fn left_clicking_a_repeated_header_picture_selects_it_on_its_own_page() {
let (mut h, pos, _) = header_picture_app(false, 200.0, 400.0, 2);
edit_story(&mut h, false, 0);
assert_eq!(h.state().session.page_hint, 0, "editing the header on page 1");
let rect = h.state_mut().session.layout().object(&pos, 1).unwrap().rect;
assert_eq!(h.state_mut().session.layout().object(&pos, 1).unwrap().page, 1, "the picture is repeated on page 2");
let at = picture_point(&h, 1, rect);
press(&mut h, at, egui::PointerButton::Primary);
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "the left-click selected it");
assert_eq!(h.state().session.page_hint, 1, "its frame is drawn on the page clicked");
}
fn pointer_button(pos: egui::Pos2, button: egui::PointerButton, pressed: bool) -> egui::Event {
egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() }
}
/// Moves to `at`, presses and releases `button` there and lets the frames settle.
fn press(h: &mut H, at: egui::Pos2, button: egui::PointerButton) {
h.event(egui::Event::PointerMoved(at));
h.event(pointer_button(at, button, true));
h.step();
h.event(pointer_button(at, button, false));
steps(h, 3);
}
/// Near the top-left corner of the picture's `rect` on `page`: on the header text line when the
/// picture is placed over it.
fn picture_point(h: &H, page: usize, rect: wordcraft_geom::Rect) -> egui::Pos2 {
let scale = h.state().canvas.scale;
crate::frame::to_screen(h.state().canvas.page_rects[page], scale, rect).min + egui::vec2(10.0, 6.0) * scale
}
/// Starts editing the header (or footer) of `page` and lets the frames settle.
fn edit_story(h: &mut H, footer: bool, page: usize) {
let command = if footer { "insert.editFooter" } else { "insert.editHeader" };
h.state_mut().run(command, json!({"page": page})).unwrap();
// Entering the footer scrolls the page to it: wait until the page stops moving.
let (mut last, mut still) = (h.state().canvas.page_rects[0], 0);
for _ in 0..600 {
h.step();
let now = h.state().canvas.page_rects[0];
still = if now == last { still + 1 } else { 0 };
last = now;
if still >= 10 {
break;
}
}
}
/// A body-mode window on a document of `pages` pages whose header (or footer) holds text and a
/// 160pt Behind Text picture at (`x`, `y`) on the page. Returns it, the picture's position and
/// its first-page rectangle.
fn header_picture_app(footer: bool, x: f32, y: f32, pages: usize) -> (H, Pos, wordcraft_geom::Rect) {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
for _ in 1..pages {
a.run("insert.pageBreak", json!({})).unwrap();
}
a.run(if footer { "insert.editFooter" } else { "insert.editHeader" }, json!({})).unwrap();
a.run("text.insert", json!({"text": if footer { "Footer" } else { "Header" }})).unwrap();
let mut png = Vec::new();
let img = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 255]));
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
a.run("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png), "width": 160})).unwrap();
let pos = wordcraft_engine::cmd::objects::selected(&a.session).unwrap().0;
a.run("arrange.bounds", json!({"x": x, "y": y})).unwrap();
a.run("arrange.wrap", json!({"wrap": "behindText"})).unwrap();
let rect = a.session.layout().object(&pos, 0).unwrap().rect;
a.run("insert.closeHeader", json!({})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
// Zoomed out so the whole page is on screen and entering the footer scrolls nothing.
h.state_mut().run("view.zoom", json!({"value": 40})).unwrap();
steps(&mut h, 20);
(h, pos, rect)
}
/// Puts a Behind Text header (or footer) picture at (`x`, `y`), checks its top lies within `band`
/// (when given), clicks near its top-left corner from the body and then while editing, and checks
/// the second click selects it (`selects`) or leaves the caret in the text; a right-click picks it
/// only where the click does, so the context menu (Reset Picture, Wrap Text) acts on it.
fn header_picture_click(footer: bool, x: f32, y: f32, band: Option<(f32, f32)>, selects: bool) {
let (mut h, pos, rect) = header_picture_app(footer, x, y, 1);
if let Some((lo, hi)) = band {
assert!(rect.y >= lo && rect.y < hi, "the picture sits where the case wants it: {rect:?}");
}
let at = picture_point(&h, 0, rect);
let picked = |h: &H| wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p);
press(&mut h, at, egui::PointerButton::Primary);
assert!(picked(&h).is_none(), "from the body the picture isn't selectable");
assert_eq!(h.state().session.sel.focus.story, StoryRef::Body);
edit_story(&mut h, footer, 0);
press(&mut h, at, egui::PointerButton::Primary);
if selects {
assert_eq!(picked(&h), Some(pos.clone()), "while editing a click on its picture selects it ({x}, {y})");
} else {
assert_eq!(picked(&h), None, "over the text the click edits the text ({x}, {y})");
assert!(matches!(h.state().session.sel.focus.story, StoryRef::Part(_)), "still in the header or footer");
}
h.state_mut().session.sel = wordcraft_engine::Selection::caret(Pos { off: 0, ..pos.clone() });
press(&mut h, at, egui::PointerButton::Secondary);
assert_eq!(picked(&h), selects.then(|| pos.clone()), "a right-click picks the picture only where a click does ({x}, {y})");
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
h.step();
}
/// #1961 review: what a picture draws must be in its page's fingerprint itself. Reset Picture on
/// one never edited keeps its media and clears only its corrections and crop, and undo puts them
/// back; the anchor paragraph's layout pointer also moves then, but only as long as the old
+1 -15
View File
@@ -225,21 +225,7 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) {
let held = (app.file_browser_open() || app.colors.is_some()).then(|| ctx.input_mut(|i| std::mem::take(&mut i.events)));
let shown = place_dialog(ctx, id, window).show(ctx, |ui| {
ui.set_min_width(340.0);
// Scrolls only when the last frame's body was taller than the screen.
let room = (ui.ctx().content_rect().height() - 110.0).max(160.0);
let key = id.with("body_height");
let tall = ui.ctx().data(|data| data.get_temp::<f32>(key)).is_some_and(|h| h > room);
let mut content = |ui: &mut egui::Ui| {
let top = ui.cursor().min.y;
close = crate::rtl::root(ui, |ui| body(app, ui, &mut d));
let height = ui.min_rect().max.y - top;
ui.ctx().data_mut(|data| data.insert_temp(key, height));
};
if tall {
egui::ScrollArea::vertical().max_height(room).auto_shrink([true, true]).show(ui, content);
} else {
content(ui);
}
close = crate::rtl::root(ui, |ui| body(app, ui, &mut d));
});
if let Some(events) = held {
ctx.input_mut(|i| i.events = events);
@@ -1,4 +1,4 @@
use super::{MeasureExt, Serialize, Ui, Value, WordApp, buttons, fit_size, json, run, unit, vec2};
use super::{MeasureExt, Serialize, Ui, Value, WordApp, buttons, fit_size, heading, json, run, unit, vec2};
// ---------------------------------------------------------------------------------------------
// Size
@@ -163,49 +163,46 @@ pub(super) fn size_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SizeForm) -> bool
let changed = r.cell(|ui| ui.add(field.update_while_editing(false)).labelled_by(name.id).changed());
(changed && v != was).then_some(v)
};
crate::widgets::section(ui, tl!("Size"), |ui| {
crate::rtl::Table::new("size_lengths").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(h) = length(r, "Height:", f.height) {
f.set_height(h);
}
if let Some(w) = length(r, "Width:", f.width) {
f.set_width(w);
}
});
heading(ui, "Size");
crate::rtl::Table::new("size_lengths").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(h) = length(r, "Height:", f.height) {
f.set_height(h);
}
if let Some(w) = length(r, "Width:", f.width) {
f.set_width(w);
}
});
});
crate::widgets::section(ui, tl!("Scale"), |ui| {
let (sw, sh) = f.scale();
crate::rtl::Table::new("size_scale").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(p) = percent(r, "Height:", sh) {
f.set_scale_height(p);
}
if let Some(w) = percent(r, "Width:", sw) {
f.set_scale_width(w);
}
});
heading(ui, "Scale");
let (sw, sh) = f.scale();
crate::rtl::Table::new("size_scale").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
if let Some(p) = percent(r, "Height:", sh) {
f.set_scale_height(p);
}
if let Some(w) = percent(r, "Width:", sw) {
f.set_scale_width(w);
}
});
ui.checkbox(&mut f.lock, tl!("Lock aspect ratio"));
ui.add_enabled_ui(f.original.is_some(), |ui| ui.checkbox(&mut f.relative, tl!("Relative to original picture size")));
});
ui.checkbox(&mut f.lock, tl!("Lock aspect ratio"));
ui.add_enabled_ui(f.original.is_some(), |ui| ui.checkbox(&mut f.relative, tl!("Relative to original picture size")));
if let Some((w, h)) = f.uncropped {
crate::widgets::section(ui, tl!("Original size"), |ui| {
ui.horizontal(|ui| {
ui.label(format!("{} {}", tl!("Height:"), crate::options::length(h)));
heading(ui, "Original size");
ui.horizontal(|ui| {
ui.label(format!("{} {}", tl!("Height:"), crate::options::length(h)));
ui.add_space(12.0);
ui.label(format!("{} {}", tl!("Width:"), crate::options::length(w)));
if let Some((pw, ph)) = f.pixels {
ui.add_space(12.0);
ui.label(format!("{} {}", tl!("Width:"), crate::options::length(w)));
if let Some((pw, ph)) = f.pixels {
ui.add_space(12.0);
let (pw, ph) = (pw.to_string(), ph.to_string());
ui.weak(crate::i18n::fmt(tl!("{width} × {height} pixels"), &[("width", &pw), ("height", &ph)]));
}
ui.add_space(12.0);
if ui.button(tl!("Reset")).clicked() {
f.reset();
}
});
let (pw, ph) = (pw.to_string(), ph.to_string());
ui.weak(crate::i18n::fmt(tl!("{width} × {height} pixels"), &[("width", &pw), ("height", &ph)]));
}
ui.add_space(12.0);
if ui.button(tl!("Reset")).clicked() {
f.reset();
}
});
}
let (ok, cancel) = buttons(ui, "OK", true);
@@ -271,12 +268,11 @@ pub(super) fn page_numbers_ui(app: &mut WordApp, ui: &mut Ui, f: &mut PageNumber
ui.selectable_value(&mut f.format, v.to_string(), l);
}
});
crate::widgets::section(ui, tl!("Page numbering"), |ui| {
ui.radio_value(&mut f.cont, true, tl!("Continue from previous section"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.cont, false, tl!("Start at:"));
ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(1..=100_000));
});
heading(ui, "Page numbering");
ui.radio_value(&mut f.cont, true, tl!("Continue from previous section"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.cont, false, tl!("Start at:"));
ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(1..=100_000));
});
let (ok, cancel) = buttons(ui, "OK", true);
if ok {
@@ -1,4 +1,4 @@
use super::{ENVELOPE_SIZES, LABEL_PRODUCTS, Serialize, Ui, Value, WordApp, buttons, json, run};
use super::{ENVELOPE_SIZES, LABEL_PRODUCTS, Serialize, Ui, Value, WordApp, buttons, heading, json, run};
// ---------------------------------------------------------------------------------------------
// Envelopes
@@ -163,16 +163,15 @@ pub(super) fn labels_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LabelsForm) -> b
});
});
let (rows, cols) = LABEL_PRODUCTS.get(f.product).map_or((1, 1), |p| (p.rows, p.cols));
crate::widgets::section(ui, tl!("Print"), |ui| {
ui.radio_value(&mut f.single, false, tl!("Full page of the same label"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.single, true, tl!("Single label"));
ui.add_enabled_ui(f.single, |ui| {
ui.label(tl!("Row:"));
ui.add(egui::DragValue::new(&mut f.row).range(1..=rows));
ui.label(tl!("Column:"));
ui.add(egui::DragValue::new(&mut f.col).range(1..=cols));
});
heading(ui, "Print");
ui.radio_value(&mut f.single, false, tl!("Full page of the same label"));
ui.horizontal(|ui| {
ui.radio_value(&mut f.single, true, tl!("Single label"));
ui.add_enabled_ui(f.single, |ui| {
ui.label(tl!("Row:"));
ui.add(egui::DragValue::new(&mut f.row).range(1..=rows));
ui.label(tl!("Column:"));
ui.add(egui::DragValue::new(&mut f.col).range(1..=cols));
});
});
f.row = f.row.clamp(1, rows.max(1));
@@ -118,25 +118,23 @@ impl SortForm {
}
pub(super) fn sort_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SortForm) -> bool {
crate::widgets::section(ui, tl!("Sort by"), |ui| {
ui.horizontal(|ui| {
craft_ui::ComboBox::from_id_salt("sort_column").selected_text(f.column_label(f.column)).width(180.0).show_ui(ui, |ui| {
for i in 0..f.headers.len() {
let label = f.column_label(i);
ui.selectable_value(&mut f.column, i, label);
}
});
crate::rtl::vertical(ui, |ui| {
ui.radio_value(&mut f.descending, false, tl!("Ascending"));
ui.radio_value(&mut f.descending, true, tl!("Descending"));
});
heading(ui, "Sort by");
ui.horizontal(|ui| {
craft_ui::ComboBox::from_id_salt("sort_column").selected_text(f.column_label(f.column)).width(180.0).show_ui(ui, |ui| {
for i in 0..f.headers.len() {
let label = f.column_label(i);
ui.selectable_value(&mut f.column, i, label);
}
});
crate::rtl::vertical(ui, |ui| {
ui.radio_value(&mut f.descending, false, tl!("Ascending"));
ui.radio_value(&mut f.descending, true, tl!("Descending"));
});
});
crate::widgets::section(ui, tl!("My list has"), |ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.header, true, tl!("Header row"));
ui.radio_value(&mut f.header, false, tl!("No header row"));
});
heading(ui, "My list has");
ui.horizontal(|ui| {
ui.radio_value(&mut f.header, true, tl!("Header row"));
ui.radio_value(&mut f.header, false, tl!("No header row"));
});
let (ok, cancel) = buttons(ui, "OK", true);
if ok {
@@ -382,42 +380,39 @@ impl TextToTableForm {
pub(super) fn text_to_table_ui(app: &mut WordApp, ui: &mut Ui, f: &mut TextToTableForm) -> bool {
let before = (f.separator.clone(), f.other_char.clone(), f.columns);
crate::widgets::section(ui, tl!("Table size"), |ui| {
crate::rtl::Table::new("text_to_table").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of columns:")));
r.cell(|ui| ui.add(egui::DragValue::new(&mut f.columns).range(1..=63)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of rows:")));
r.cell(|ui| ui.label(f.rows.to_string()));
});
heading(ui, "Table size");
crate::rtl::Table::new("text_to_table").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of columns:")));
r.cell(|ui| ui.add(egui::DragValue::new(&mut f.columns).range(1..=63)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number of rows:")));
r.cell(|ui| ui.label(f.rows.to_string()));
});
});
crate::widgets::section(ui, tl!("AutoFit behavior"), |ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.autofit, "initial".to_string(), tl!("Initial column width:"));
ui.add_enabled(f.autofit == "initial", egui::TextEdit::singleline(&mut f.width).desired_width(72.0));
});
ui.radio_value(&mut f.autofit, "contents".to_string(), tl!("AutoFit to contents"));
ui.radio_value(&mut f.autofit, "window".to_string(), tl!("AutoFit to window"));
heading(ui, "AutoFit behavior");
ui.horizontal(|ui| {
ui.radio_value(&mut f.autofit, "initial".to_string(), tl!("Initial column width:"));
ui.add_enabled(f.autofit == "initial", egui::TextEdit::singleline(&mut f.width).desired_width(72.0));
});
crate::widgets::section(ui, tl!("Separate text at"), |ui| {
crate::rtl::Table::new("text_to_table_sep").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "paragraph".to_string(), tl!("Paragraphs")));
r.cell(|ui| ui.radio_value(&mut f.separator, "comma".to_string(), tl!("Commas")));
});
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "tab".to_string(), tl!("Tabs")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.separator, "other".to_string(), tl!("Other:"));
let edit = ui.add(egui::TextEdit::singleline(&mut f.other_char).char_limit(1).desired_width(24.0));
if edit.changed() {
f.separator = "other".into();
}
});
ui.radio_value(&mut f.autofit, "contents".to_string(), tl!("AutoFit to contents"));
ui.radio_value(&mut f.autofit, "window".to_string(), tl!("AutoFit to window"));
heading(ui, "Separate text at");
crate::rtl::Table::new("text_to_table_sep").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "paragraph".to_string(), tl!("Paragraphs")));
r.cell(|ui| ui.radio_value(&mut f.separator, "comma".to_string(), tl!("Commas")));
});
t.row(|r| {
r.cell(|ui| ui.radio_value(&mut f.separator, "tab".to_string(), tl!("Tabs")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.separator, "other".to_string(), tl!("Other:"));
let edit = ui.add(egui::TextEdit::singleline(&mut f.other_char).char_limit(1).desired_width(24.0));
if edit.changed() {
f.separator = "other".into();
}
});
});
});
@@ -208,14 +208,7 @@ fn language_dialog_default_survives_a_restart() {
use egui_kittest::kittest::Queryable;
let mut a = app();
a.ui.language = "en".into();
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(LanguageForm {
lang: "fr-FR".into(),
no_proof: false,
detect: false,
whole_document: false,
initial: ("fr-FR".into(), false),
proof_touched: false,
}))));
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(LanguageForm { lang: "fr-FR".into(), no_proof: false, detect: false }))));
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
app.logic(&ui.ctx().clone());
@@ -239,143 +232,6 @@ fn language_dialog_default_survives_a_restart() {
assert_eq!(LanguageForm::read(&b).lang, "fr-FR");
}
/// #3518: ticking "Apply to the whole document" makes OK send `scope: "document"`; unticked sends none.
#[test]
fn language_dialog_whole_document_checkbox_sends_scope() {
use egui_kittest::kittest::Queryable;
let f = LanguageForm {
lang: "fr-FR".into(),
no_proof: false,
detect: false,
whole_document: false,
initial: ("fr-FR".into(), false),
proof_touched: false,
};
assert!(f.params().get("scope").is_none());
assert_eq!(LanguageForm { whole_document: true, ..f.clone() }.params()["scope"], "document");
let mut a = app();
a.ui.language = "en".into();
let para = wordcraft_doc::Paragraph::with_text("Header", Default::default());
let header = a.session.doc.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(wordcraft_doc::Block::Para(para))]);
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(f))));
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
a,
);
h.run_steps(3);
h.get_by_label("Apply to the whole document").click();
h.run_steps(3);
h.get_by_label("OK").click();
h.run_steps(3);
// The header, which the caret isn't in, took the language.
let doc = &h.state().session.doc;
let hp = doc.para(wordcraft_doc::StoryRef::Part(header), &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(hp.runs.first().and_then(|r| r.props.lang.as_deref()), Some("fr-FR"));
}
/// "Plain text, then a Do-not-check run", the caret in the plain text.
fn proofing_mix_app() -> WordApp {
let mut a = app();
a.run("text.insert", json!({"text": "Plain code"})).unwrap();
a.run("select.text", json!({"text": "code"})).unwrap();
a.run("review.language", json!({"lang": "de-DE", "noProof": true})).unwrap();
a.run("select.text", json!({"text": "Plain"})).unwrap();
a.run("review.language", json!({"lang": "en-US", "noProof": false})).unwrap();
a.run("select.text", json!({"text": "Plain"})).unwrap();
a
}
fn run_proofing(a: &mut WordApp, text: &str) -> (Option<String>, Option<bool>) {
a.run("select.text", json!({"text": text})).unwrap();
let st = a.run("format.state", json!({})).unwrap();
(st["lang"].as_str().map(String::from), st["noProof"].as_bool())
}
/// #3518: whole-document OK sends only what the user changed.
#[test]
fn language_dialog_whole_document_sends_only_changes() {
// Changing only the language leaves the Do-not-check run alone.
let mut a = proofing_mix_app();
let mut f = LanguageForm::read(&a);
f.whole_document = true;
f.lang = "en-GB".into();
let p = f.params();
assert!(p.get("noProof").is_none());
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("en-GB".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-GB".into()), Some(false)));
// Changing only Do-not-check leaves each run's language alone.
let mut a = proofing_mix_app();
let mut f = LanguageForm::read(&a);
f.whole_document = true;
f.no_proof = true;
f.proof_touched = true;
let p = f.params();
assert!(p.get("lang").is_none());
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("de-DE".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-US".into()), Some(true)));
// No edits: the caret's language, no noProof (never the engine's en-US default).
let mut a = proofing_mix_app();
let mut f = LanguageForm::read(&a);
f.lang = "fr-FR".into();
f.initial.0 = "fr-FR".into();
f.whole_document = true;
let p = f.params();
assert_eq!(p["lang"], "fr-FR");
assert!(p.get("noProof").is_none());
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("fr-FR".into()), Some(true)));
// Selection mode is unchanged: both are sent.
f.whole_document = false;
assert_eq!(f.params()["noProof"], false);
}
/// #3518: a ticked Do-not-check box the user did not change (the caret sits in a no-proof run)
/// is not sent, so a language-only whole-document apply leaves other runs' proofing state alone.
#[test]
fn language_dialog_whole_document_unchanged_no_proof_is_not_sent() {
let mut a = proofing_mix_app();
a.run("select.text", json!({"text": "code"})).unwrap();
let mut f = LanguageForm::read(&a);
assert!(f.no_proof && f.initial.1);
f.whole_document = true;
f.lang = "en-GB".into();
let p = f.params();
assert!(p.get("noProof").is_none(), "{p}");
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "code"), (Some("en-GB".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-GB".into()), Some(false)));
}
/// #3518: with the caret in a no-proof run, ticking the whole-document box and clicking Do not
/// check off and on again (ending ticked) still marks the whole document no-proof.
#[test]
fn language_dialog_whole_document_retoggled_no_proof_is_sent() {
let mut a = proofing_mix_app();
a.run("select.text", json!({"text": "code"})).unwrap();
let mut f = LanguageForm::read(&a);
assert!(f.no_proof && f.initial.1 && !f.proof_touched);
f.whole_document = true;
for _ in 0..2 {
f.no_proof = !f.no_proof;
f.proof_touched = true;
}
assert!(f.no_proof);
let p = f.params();
assert_eq!(p["noProof"], true, "{p}");
assert!(p.get("lang").is_none(), "{p}");
a.run("review.language", p).unwrap();
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-US".into()), Some(true)));
assert_eq!(run_proofing(&mut a, "code"), (Some("de-DE".into()), Some(true)));
}
/// #407: Envelopes starts from the selected address; Add to Document puts an envelope
/// section before the letter without asking to save (nothing is replaced).
#[test]
@@ -320,16 +320,6 @@ pub struct LanguageForm {
pub lang: String,
pub no_proof: bool,
pub detect: bool,
/// "Apply to the whole document": OK sends `scope: "document"` (every story), not the selection.
pub whole_document: bool,
/// The language and Do-not-check state the dialog opened with, to tell what the user changed.
#[serde(skip)]
pub initial: (String, bool),
/// The Do-not-check box was clicked (even back to where it started). A whole-document OK sends
/// `noProof` only then: the caret's value alone says nothing about runs that differ elsewhere,
/// but a click is a request to mark the whole document that way (#3518).
#[serde(skip)]
pub proof_touched: bool,
}
impl LanguageForm {
@@ -338,36 +328,12 @@ impl LanguageForm {
let style = s.doc.para_at(&s.sel.focus).and_then(|p| p.props.style.as_deref());
let here = s.doc.styles.resolve_char(style, &s.typing_props());
let lang = here.lang.unwrap_or_else(|| "en-US".into());
LanguageForm {
initial: (lang.clone(), here.no_proof),
lang,
no_proof: here.no_proof,
detect: s.prefs.detect_language,
whole_document: false,
proof_touched: false,
}
LanguageForm { lang, no_proof: here.no_proof, detect: s.prefs.detect_language }
}
/// `review.language` parameters for OK.
pub fn params(&self) -> Value {
if !self.whole_document {
return json!({"lang": self.lang, "noProof": self.no_proof, "detect": self.detect});
}
// Whole document: the caret's values must not flatten what differs elsewhere, so send only
// what was changed. With no edits at all the language goes (never the engine's en-US default).
let (lang_changed, proof_touched) = (self.lang != self.initial.0, self.proof_touched);
let mut v = json!({"scope": "document", "detect": self.detect});
if let Some(m) = v.as_object_mut() {
if lang_changed || !proof_touched {
m.insert("lang".into(), json!(self.lang));
}
// Only a clicked box is sent: the caret's value untouched says nothing about runs that
// differ elsewhere, and resending it would flatten them.
if proof_touched {
m.insert("noProof".into(), json!(self.no_proof));
}
}
v
json!({"lang": self.lang, "noProof": self.no_proof, "detect": self.detect})
}
}
@@ -377,7 +343,7 @@ pub(super) fn language_name(tag: &str) -> String {
}
pub(super) fn language_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LanguageForm) -> bool {
ui.label(if f.whole_document { tl!("Mark the whole document as:") } else { tl!("Mark selected text as:") });
ui.label(tl!("Mark selected text as:"));
let list = crate::ribbon::language_list(&f.lang);
egui::Frame::NONE.stroke(egui::Stroke::new(1.0, crate::theme::Tokens::get(ui.ctx()).border_strong)).inner_margin(4.0).show(ui, |ui| {
egui::ScrollArea::vertical().max_height(220.0).min_scrolled_height(220.0).show(ui, |ui| {
@@ -392,11 +358,8 @@ pub(super) fn language_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LanguageForm)
});
});
ui.add_space(4.0);
if ui.checkbox(&mut f.no_proof, tl!("Do not check spelling or grammar")).clicked() {
f.proof_touched = true;
}
ui.checkbox(&mut f.no_proof, tl!("Do not check spelling or grammar"));
ui.checkbox(&mut f.detect, tl!("Detect language automatically"));
ui.checkbox(&mut f.whole_document, tl!("Apply to the whole document"));
ui.add_space(4.0);
let set_default = ui.button(tl!("Set As Default")).clicked();
if set_default && run(app, "review.language", json!({"lang": f.lang, "default": true, "detect": f.detect})) {
+58 -59
View File
@@ -534,70 +534,69 @@ const MOVE_TO_MARKS: &[(&str, &str)] = &[
/// Track Changes Options. Returns true to close.
pub fn track_options(app: &mut WordApp, ui: &mut Ui, f: &mut TrackForm) -> bool {
let theme = app.session.doc.settings.theme_colors.clone();
crate::widgets::section(ui, tl!("Show"), |ui| {
crate::rtl::Table::new("tco_show").columns(2).spacing(vec2(16.0, 4.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.comments, tl!("Comments")));
r.cell(|ui| ui.checkbox(&mut f.ink, tl!("Ink")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.insertions_deletions, tl!("Insertions and Deletions")));
r.cell(|ui| ui.checkbox(&mut f.formatting, tl!("Formatting")));
});
let heading = |ui: &mut Ui, s: &str| {
ui.add_space(4.0);
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
};
heading(ui, "Show");
crate::rtl::Table::new("tco_show").columns(2).spacing(vec2(16.0, 4.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.comments, tl!("Comments")));
r.cell(|ui| ui.checkbox(&mut f.ink, tl!("Ink")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.insertions_deletions, tl!("Insertions and Deletions")));
r.cell(|ui| ui.checkbox(&mut f.formatting, tl!("Formatting")));
});
});
crate::widgets::section(ui, tl!("Balloons"), |ui| {
for (v, l) in [
("revisions", "Show revisions in balloons"),
("inline", "Show all revisions inline"),
("commentsAndFormatting", "Show only comments and formatting in balloons"),
] {
ui.radio_value(&mut f.balloons, v.to_string(), tl!(l));
}
});
crate::widgets::section(ui, tl!("Comments"), |ui| {
for (v, l) in [("margin", "In the margin"), ("selected", "Only for the selected text")] {
ui.radio_value(&mut f.comment_display, v.to_string(), tl!(l));
}
});
crate::widgets::section(ui, tl!("Advanced"), |ui| {
crate::rtl::Table::new("tco_advanced").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Insertions:")));
r.cell(|ui| choice(ui, "tco_ins", &mut f.insert_mark, INSERT_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.insert_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Deletions:")));
r.cell(|ui| choice(ui, "tco_del", &mut f.delete_mark, DELETE_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.delete_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Changed lines:")));
r.cell(|ui| {
choice(
ui,
"tco_bar",
&mut f.changed_lines,
&[("outside", "Outside border"), ("left", "Left border"), ("right", "Right border"), ("none", "None")],
)
});
r.cell(|ui| color(ui, &theme, &mut f.changed_lines_color, "Automatic", Some(wordcraft_layout::display::CHANGE_BAR)));
heading(ui, "Balloons");
for (v, l) in [
("revisions", "Show revisions in balloons"),
("inline", "Show all revisions inline"),
("commentsAndFormatting", "Show only comments and formatting in balloons"),
] {
ui.radio_value(&mut f.balloons, v.to_string(), tl!(l));
}
heading(ui, "Comments");
for (v, l) in [("margin", "In the margin"), ("selected", "Only for the selected text")] {
ui.radio_value(&mut f.comment_display, v.to_string(), tl!(l));
}
heading(ui, "Advanced");
crate::rtl::Table::new("tco_advanced").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Insertions:")));
r.cell(|ui| choice(ui, "tco_ins", &mut f.insert_mark, INSERT_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.insert_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Deletions:")));
r.cell(|ui| choice(ui, "tco_del", &mut f.delete_mark, DELETE_MARKS));
r.cell(|ui| color(ui, &theme, &mut f.delete_color, "By author", None));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Changed lines:")));
r.cell(|ui| {
choice(
ui,
"tco_bar",
&mut f.changed_lines,
&[("outside", "Outside border"), ("left", "Left border"), ("right", "Right border"), ("none", "None")],
)
});
r.cell(|ui| color(ui, &theme, &mut f.changed_lines_color, "Automatic", Some(wordcraft_layout::display::CHANGE_BAR)));
});
});
crate::widgets::section(ui, tl!("Moves"), |ui| {
crate::rtl::Table::new("tco_moves").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved from:")));
r.cell(|ui| choice(ui, "tco_move_from", &mut f.move_from_mark, DELETE_MARKS));
r.cell(|ui| ui.push_id("tco_move_from_color", |ui| color(ui, &theme, &mut f.move_from_color, "By author", None)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved to:")));
r.cell(|ui| choice(ui, "tco_move_to", &mut f.move_to_mark, MOVE_TO_MARKS));
r.cell(|ui| ui.push_id("tco_move_to_color", |ui| color(ui, &theme, &mut f.move_to_color, "By author", None)));
});
heading(ui, "Moves");
crate::rtl::Table::new("tco_moves").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved from:")));
r.cell(|ui| choice(ui, "tco_move_from", &mut f.move_from_mark, DELETE_MARKS));
r.cell(|ui| ui.push_id("tco_move_from_color", |ui| color(ui, &theme, &mut f.move_from_color, "By author", None)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Moved to:")));
r.cell(|ui| choice(ui, "tco_move_to", &mut f.move_to_mark, MOVE_TO_MARKS));
r.cell(|ui| ui.push_id("tco_move_to_color", |ui| color(ui, &theme, &mut f.move_to_color, "By author", None)));
});
});
ui.add_space(4.0);
+74 -72
View File
@@ -8,6 +8,7 @@ use serde::Serialize;
use serde_json::{Value, json};
use crate::WordApp;
use crate::theme::semibold;
/// Number formats notes offer: OOXML name and a sample (not translated). The Format Page Numbers
/// dialog offers the same list (#1113).
@@ -79,83 +80,84 @@ fn choice(ui: &mut Ui, id: &str, value: &mut String, options: &[(&str, &str)], t
/// Footnote and Endnote. Returns true to close.
pub fn note_options(app: &mut WordApp, ui: &mut Ui, f: &mut NoteForm) -> bool {
crate::widgets::section(ui, tl!("Location"), |ui| {
let mut convert = None;
crate::rtl::grid(ui, egui::Grid::new("notes_location").num_columns(2).spacing(vec2(10.0, 6.0)), |ui| {
ui.radio_value(&mut f.endnote, false, tl!("Footnotes"));
ui.add_enabled_ui(!f.endnote, |ui| {
choice(ui, "notes_fpos", &mut f.pos[0], &[("pageBottom", "Bottom of Page"), ("beneathText", "Below text")], true);
});
ui.end_row();
ui.radio_value(&mut f.endnote, true, tl!("Endnotes"));
ui.add_enabled_ui(f.endnote, |ui| {
choice(ui, "notes_epos", &mut f.pos[1], &[("sectEnd", "End of section"), ("docEnd", "End of document")], true);
});
ui.end_row();
ui.label("");
ui.menu_button(format!("{}…", tl!("Convert")), |ui| {
crate::rtl::root(ui, |ui| {
for (to, l) in
[("endnote", "Footnotes to endnotes"), ("footnote", "Endnotes to footnotes"), ("swap", "Swap footnotes and endnotes")]
{
if ui.button(tl!(l)).clicked() {
convert = Some(to);
ui.close();
}
}
})
});
ui.end_row();
let heading = |ui: &mut Ui, s: &str| {
ui.add_space(4.0);
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
};
heading(ui, "Location");
let mut convert = None;
crate::rtl::grid(ui, egui::Grid::new("notes_location").num_columns(2).spacing(vec2(10.0, 6.0)), |ui| {
ui.radio_value(&mut f.endnote, false, tl!("Footnotes"));
ui.add_enabled_ui(!f.endnote, |ui| {
choice(ui, "notes_fpos", &mut f.pos[0], &[("pageBottom", "Bottom of Page"), ("beneathText", "Below text")], true);
});
if let Some(to) = convert
&& let Err(e) = app.run("references.convertNotes", json!({ "to": to }))
{
app.status(e);
}
ui.end_row();
ui.radio_value(&mut f.endnote, true, tl!("Endnotes"));
ui.add_enabled_ui(f.endnote, |ui| {
choice(ui, "notes_epos", &mut f.pos[1], &[("sectEnd", "End of section"), ("docEnd", "End of document")], true);
});
ui.end_row();
ui.label("");
ui.menu_button(format!("{}…", tl!("Convert")), |ui| {
crate::rtl::root(ui, |ui| {
for (to, l) in [("endnote", "Footnotes to endnotes"), ("footnote", "Endnotes to footnotes"), ("swap", "Swap footnotes and endnotes")]
{
if ui.button(tl!(l)).clicked() {
convert = Some(to);
ui.close();
}
}
})
});
ui.end_row();
});
crate::widgets::section(ui, tl!("Format"), |ui| {
let k = usize::from(f.endnote);
crate::rtl::Table::new("notes_format").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number format")));
r.cell(|ui| {
if let Some(v) = f.fmt.get_mut(k) {
choice(ui, "notes_fmt", v, &FORMATS, false);
}
});
if let Some(to) = convert
&& let Err(e) = app.run("references.convertNotes", json!({ "to": to }))
{
app.status(e);
}
heading(ui, "Format");
let k = usize::from(f.endnote);
crate::rtl::Table::new("notes_format").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Number format")));
r.cell(|ui| {
if let Some(v) = f.fmt.get_mut(k) {
choice(ui, "notes_fmt", v, &FORMATS, false);
}
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Custom mark:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.mark).desired_width(60.0).char_limit(10)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Custom mark:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.mark).desired_width(60.0).char_limit(10)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Start at:")));
r.cell(|ui| {
if let Some(v) = f.start.get_mut(k) {
ui.add(egui::DragValue::new(v).range(1..=32_767).speed(0.2));
}
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Start at:")));
r.cell(|ui| {
if let Some(v) = f.start.get_mut(k) {
ui.add(egui::DragValue::new(v).range(1..=32_767).speed(0.2));
}
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Numbering")));
r.cell(|ui| {
if let Some(v) = f.restart.get_mut(k) {
let each_page: &[(&str, &str)] = if f.endnote { &[] } else { &[("eachPage", "Restart Each Page")] };
let options: Vec<(&str, &str)> = [("continuous", "Continuous numbering"), ("eachSect", "Restart Each Section")]
.into_iter()
.chain(each_page.iter().copied())
.collect();
choice(ui, "notes_restart", v, &options, true);
}
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Numbering")));
r.cell(|ui| {
if let Some(v) = f.restart.get_mut(k) {
let each_page: &[(&str, &str)] = if f.endnote { &[] } else { &[("eachPage", "Restart Each Page")] };
let options: Vec<(&str, &str)> = [("continuous", "Continuous numbering"), ("eachSect", "Restart Each Section")]
.into_iter()
.chain(each_page.iter().copied())
.collect();
choice(ui, "notes_restart", v, &options, true);
}
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Apply to:")));
r.cell(|ui| {
let mut scope = if f.whole { "document" } else { "section" }.to_string();
choice(ui, "notes_scope", &mut scope, &[("document", "Whole document"), ("section", "This section")], true);
f.whole = scope == "document";
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Apply to:")));
r.cell(|ui| {
let mut scope = if f.whole { "document" } else { "section" }.to_string();
choice(ui, "notes_scope", &mut scope, &[("document", "Whole document"), ("section", "This section")], true);
f.whole = scope == "document";
});
});
});
@@ -1,4 +1,4 @@
use super::common::{LEADERS, choice, leader_char, sample};
use super::common::{LEADERS, choice, heading, leader_char, sample};
use super::shell::{Next, go};
use super::{FieldCode, RefsDialog, Serialize, Ui, Value, WordApp, buttons, json, vec2};
@@ -161,43 +161,40 @@ impl MarkForm {
/// Draws the index-entry fields and page, cross-reference or bookmark-range options, with Mark
/// and Mark All running `references.markEntry`.
pub(super) fn mark_ui(app: &mut WordApp, ui: &mut Ui, f: &mut MarkForm) -> Next {
crate::widgets::section(ui, tl!("Index"), |ui| {
crate::rtl::Table::new("xe").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let entry_label = r.cell(|ui| ui.label(tl!("Main entry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.entry).desired_width(220.0)).labelled_by(entry_label.id));
});
t.row(|r| {
let subentry_label = r.cell(|ui| ui.label(tl!("Subentry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.subentry).desired_width(220.0)).labelled_by(subentry_label.id));
});
heading(ui, "Index");
crate::rtl::Table::new("xe").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let entry_label = r.cell(|ui| ui.label(tl!("Main entry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.entry).desired_width(220.0)).labelled_by(entry_label.id));
});
t.row(|r| {
let subentry_label = r.cell(|ui| ui.label(tl!("Subentry:")));
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.subentry).desired_width(220.0)).labelled_by(subentry_label.id));
});
});
crate::widgets::section(ui, tl!("Options"), |ui| {
ui.horizontal(|ui| {
let see_label = ui.radio_value(&mut f.option, "see".to_string(), tl!("Cross-reference:"));
ui.add_enabled(f.option == "see", egui::TextEdit::singleline(&mut f.see).desired_width(160.0)).labelled_by(see_label.id);
});
ui.radio_value(&mut f.option, "page".to_string(), tl!("This page"));
ui.horizontal(|ui| {
let bookmark_label =
ui.add_enabled_ui(!f.bookmarks.is_empty(), |ui| ui.radio_value(&mut f.option, "range".to_string(), tl!("Pages of bookmark:"))).inner;
ui.add_enabled_ui(f.option == "range", |ui| {
let opts: Vec<(String, &str)> = f.bookmarks.iter().map(|b| (b.clone(), b.as_str())).collect();
let combo = craft_ui::ComboBox::from_id_salt("xe_bm").selected_text(f.bookmark.clone()).width(140.0).show_ui(ui, |ui| {
for (v, l) in &opts {
ui.selectable_value(&mut f.bookmark, v.clone(), *l);
}
});
combo.response.labelled_by(bookmark_label.id);
heading(ui, "Options");
ui.horizontal(|ui| {
let see_label = ui.radio_value(&mut f.option, "see".to_string(), tl!("Cross-reference:"));
ui.add_enabled(f.option == "see", egui::TextEdit::singleline(&mut f.see).desired_width(160.0)).labelled_by(see_label.id);
});
ui.radio_value(&mut f.option, "page".to_string(), tl!("This page"));
ui.horizontal(|ui| {
let bookmark_label =
ui.add_enabled_ui(!f.bookmarks.is_empty(), |ui| ui.radio_value(&mut f.option, "range".to_string(), tl!("Pages of bookmark:"))).inner;
ui.add_enabled_ui(f.option == "range", |ui| {
let opts: Vec<(String, &str)> = f.bookmarks.iter().map(|b| (b.clone(), b.as_str())).collect();
let combo = craft_ui::ComboBox::from_id_salt("xe_bm").selected_text(f.bookmark.clone()).width(140.0).show_ui(ui, |ui| {
for (v, l) in &opts {
ui.selectable_value(&mut f.bookmark, v.clone(), *l);
}
});
combo.response.labelled_by(bookmark_label.id);
});
});
crate::widgets::section(ui, tl!("Page number style"), |ui| {
ui.horizontal(|ui| {
ui.checkbox(&mut f.bold, tl!("Bold"));
ui.checkbox(&mut f.italic, tl!("Italic"));
});
heading(ui, "Page number style");
ui.horizontal(|ui| {
ui.checkbox(&mut f.bold, tl!("Bold"));
ui.checkbox(&mut f.italic, tl!("Italic"));
});
if !f.message.is_empty() {
ui.label(egui::RichText::new(&f.message).small());
+215 -232
View File
@@ -122,130 +122,128 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
};
let sample_props =
font_sample_props(app, sample_paper(app), font, size, color, (*bold, *italic, *underline, *strike), (*small_caps, *caps, *hidden), *spacing);
crate::widgets::section(ui, "", |ui| {
crate::rtl::Table::new("fontdlg").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
// Word's two font boxes when East Asian text is in use: the Latin text font and
// the Asian text font, each with its own list (type to find a font).
let prev = app.previews.font_preview_fn();
if *asian {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Asian text font:")));
r.cell(|ui| {
let fams = app.previews.east_asian_families();
let stored = app.previews.font_stored(font_ea);
let latin = app.previews.font_stored(font);
let warning = app.east_asian_font_box_warning(&stored, &latin);
if let Some(f) = font_box(ui, ("fontdlg_asian", font_ea.as_str()), &fams, &*prev, warning.as_deref()) {
if f == crate::widgets::ADD_FONT {
let _ = app.run("font.add", json!({}));
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
let _ = app.run("font.loadSystem", json!({}));
} else {
*font_ea = f;
}
}
});
});
}
crate::rtl::Table::new("fontdlg").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
// Word's two font boxes when East Asian text is in use: the Latin text font and
// the Asian text font, each with its own list (type to find a font).
let prev = app.previews.font_preview_fn();
if *asian {
t.row(|r| {
r.cell(|ui| ui.label(if *asian { tl!("Latin text font:") } else { tl!("Font:") }));
r.cell(|ui| ui.label(tl!("Asian text font:")));
r.cell(|ui| {
let fams = app.previews.families();
let stored = app.previews.font_stored(font);
let warning = app.font_dialog_warning(&stored);
if let Some(f) = font_box(ui, ("fontdlg_font", font.as_str()), &fams, &*prev, warning.as_deref()) {
let fams = app.previews.east_asian_families();
let stored = app.previews.font_stored(font_ea);
let latin = app.previews.font_stored(font);
let warning = app.east_asian_font_box_warning(&stored, &latin);
if let Some(f) = font_box(ui, ("fontdlg_asian", font_ea.as_str()), &fams, &*prev, warning.as_deref()) {
if f == crate::widgets::ADD_FONT {
let _ = app.run("font.add", json!({}));
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
let _ = app.run("font.loadSystem", json!({}));
} else {
*font = f;
*font_ea = f;
}
}
});
});
t.row(|r| {
let size_label = r.cell(|ui| ui.label(tl!("Size:")));
r.cell(|ui| ui.text_edit_singleline(size).labelled_by(size_label.id));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Font color:")));
r.cell(|ui| {
let theme = app.session.doc.settings.theme_colors.clone();
color_field(ui, &theme, color, "Automatic", "auto");
});
});
t.row(|r| {
let spacing_label = r.cell(|ui| ui.label(tl!("Spacing (pt):")));
r.cell(|ui| ui.add(egui::DragValue::new(spacing).speed(0.1).range(-20.0..=20.0)).labelled_by(spacing_label.id));
});
t.row(|r| {
let label = tl!("Kerning for fonts:");
r.cell(|ui| match kern {
Some(on) => {
ui.checkbox(on, label);
}
None => {
if ui.add(egui::Checkbox::new(&mut false, label).indeterminate(true)).clicked() {
*kern = Some(true);
}
}
});
r.cell(|ui| {
ui.horizontal(|ui| {
let enabled = *kern == Some(true);
let field = egui::DragValue::new(kern_at).speed(0.5).range(1.0..=1638.0).max_decimals(1);
// The number comes first in the reading order, then "points and above"; a left-to-right
// row in a right-to-left interface runs the other way, so there the label is first.
if crate::rtl::on() && !crate::rtl::flows(ui) {
let points_label = ui.label(tl!("Points and above"));
ui.add_enabled(enabled, field).labelled_by(points_label.id);
} else {
let points = ui.add_enabled(enabled, field);
let points_label = ui.label(tl!("Points and above"));
points.labelled_by(points_label.id);
}
});
});
});
});
});
crate::widgets::section(ui, tl!("Effects"), |ui| {
crate::rtl::Table::new("fx").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(bold, tl!("Bold")));
r.cell(|ui| ui.checkbox(italic, tl!("Italic")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(underline, tl!("Underline")));
r.cell(|ui| ui.checkbox(strike, tl!("Strikethrough")));
});
t.row(|r| {
// Superscript and Subscript exclude each other: the one just ticked wins.
let was_sup = *sup;
r.cell(|ui| ui.checkbox(sup, tl!("Superscript")));
r.cell(|ui| ui.checkbox(sub, tl!("Subscript")));
if *sup && *sub {
if was_sup {
*sup = false;
}
t.row(|r| {
r.cell(|ui| ui.label(if *asian { tl!("Latin text font:") } else { tl!("Font:") }));
r.cell(|ui| {
let fams = app.previews.families();
let stored = app.previews.font_stored(font);
let warning = app.font_dialog_warning(&stored);
if let Some(f) = font_box(ui, ("fontdlg_font", font.as_str()), &fams, &*prev, warning.as_deref()) {
if f == crate::widgets::ADD_FONT {
let _ = app.run("font.add", json!({}));
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
let _ = app.run("font.loadSystem", json!({}));
} else {
*sub = false;
*font = f;
}
}
});
t.row(|r| {
r.cell(|ui| ui.checkbox(small_caps, tl!("Small caps")));
r.cell(|ui| ui.checkbox(caps, tl!("All caps")));
});
t.row(|r| {
let size_label = r.cell(|ui| ui.label(tl!("Size:")));
r.cell(|ui| ui.text_edit_singleline(size).labelled_by(size_label.id));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Font color:")));
r.cell(|ui| {
let theme = app.session.doc.settings.theme_colors.clone();
color_field(ui, &theme, color, "Automatic", "auto");
});
t.row(|r| {
r.cell(|ui| ui.checkbox(hidden, tl!("Hidden")));
});
t.row(|r| {
let spacing_label = r.cell(|ui| ui.label(tl!("Spacing (pt):")));
r.cell(|ui| ui.add(egui::DragValue::new(spacing).speed(0.1).range(-20.0..=20.0)).labelled_by(spacing_label.id));
});
t.row(|r| {
let label = tl!("Kerning for fonts:");
r.cell(|ui| match kern {
Some(on) => {
ui.checkbox(on, label);
}
None => {
if ui.add(egui::Checkbox::new(&mut false, label).indeterminate(true)).clicked() {
*kern = Some(true);
}
}
});
r.cell(|ui| {
ui.horizontal(|ui| {
let enabled = *kern == Some(true);
let field = egui::DragValue::new(kern_at).speed(0.5).range(1.0..=1638.0).max_decimals(1);
// The number comes first in the reading order, then "points and above"; a left-to-right
// row in a right-to-left interface runs the other way, so there the label is first.
if crate::rtl::on() && !crate::rtl::flows(ui) {
let points_label = ui.label(tl!("Points and above"));
ui.add_enabled(enabled, field).labelled_by(points_label.id);
} else {
let points = ui.add_enabled(enabled, field);
let points_label = ui.label(tl!("Points and above"));
points.labelled_by(points_label.id);
}
});
});
});
});
// Live preview of the chosen font/size/colour/effects.
crate::widgets::section(ui, tl!("Preview"), |ui| {
font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden);
ui.separator();
ui.label(egui::RichText::new(tl!("Effects")).font(semibold(12.5)));
crate::rtl::Table::new("fx").columns(2).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(bold, tl!("Bold")));
r.cell(|ui| ui.checkbox(italic, tl!("Italic")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(underline, tl!("Underline")));
r.cell(|ui| ui.checkbox(strike, tl!("Strikethrough")));
});
t.row(|r| {
// Superscript and Subscript exclude each other: the one just ticked wins.
let was_sup = *sup;
r.cell(|ui| ui.checkbox(sup, tl!("Superscript")));
r.cell(|ui| ui.checkbox(sub, tl!("Subscript")));
if *sup && *sub {
if was_sup {
*sup = false;
} else {
*sub = false;
}
}
});
t.row(|r| {
r.cell(|ui| ui.checkbox(small_caps, tl!("Small caps")));
r.cell(|ui| ui.checkbox(caps, tl!("All caps")));
});
t.row(|r| {
r.cell(|ui| ui.checkbox(hidden, tl!("Hidden")));
});
});
// Live preview of the chosen font/size/colour/effects.
ui.separator();
ui.label(egui::RichText::new(tl!("Preview")).small().weak());
font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden);
let (ok, cancel) = buttons(ui, tl!("OK"));
if ok {
apply_font(app, d);
@@ -283,92 +281,86 @@ fn paragraph_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ui.add_space(6.0);
match *tab {
0 => {
crate::widgets::section(ui, tl!("General"), |ui| {
ui.horizontal(|ui| {
ui.label(tl!("Direction:"));
// Neither while the selected paragraphs differ.
let blank = mixed.contains("bidi");
for (value, text) in [(true, tl!("Right-to-left")), (false, tl!("Left-to-right"))] {
if ui.radio(!blank && *rtl == value, text).clicked() {
*rtl = value;
mixed.remove("bidi");
ui.label(egui::RichText::new(tl!("General")).font(semibold(12.5)));
ui.horizontal(|ui| {
ui.label(tl!("Direction:"));
// Neither while the selected paragraphs differ.
let blank = mixed.contains("bidi");
for (value, text) in [(true, tl!("Right-to-left")), (false, tl!("Left-to-right"))] {
if ui.radio(!blank && *rtl == value, text).clicked() {
*rtl = value;
mixed.remove("bidi");
}
}
});
const ALIGNS: [(&str, &str); 4] = [("left", "Left"), ("center", "Center"), ("right", "Right"), ("justify", "Justify")];
ui.horizontal(|ui| {
let align_label = ui.label(tl!("Alignment:"));
let shown =
if mixed.contains("align") { "" } else { ALIGNS.iter().find(|(v, _)| v == align).map_or(align.as_str(), |(_, l)| tl!(l)) };
let combo = craft_ui::ComboBox::from_id_salt("para_align").selected_text(shown).show_ui(ui, |ui| {
for (v, l) in ALIGNS {
if ui.selectable_value(align, v.to_string(), tl!(l)).clicked() {
mixed.remove("align");
}
}
});
const ALIGNS: [(&str, &str); 4] = [("left", "Left"), ("center", "Center"), ("right", "Right"), ("justify", "Justify")];
ui.horizontal(|ui| {
let align_label = ui.label(tl!("Alignment:"));
let shown =
if mixed.contains("align") { "" } else { ALIGNS.iter().find(|(v, _)| v == align).map_or(align.as_str(), |(_, l)| tl!(l)) };
let combo = craft_ui::ComboBox::from_id_salt("para_align").selected_text(shown).show_ui(ui, |ui| {
for (v, l) in ALIGNS {
if ui.selectable_value(align, v.to_string(), tl!(l)).clicked() {
mixed.remove("align");
}
}
});
combo.response.labelled_by(align_label.id);
combo.response.labelled_by(align_label.id);
});
ui.label(egui::RichText::new(tl!("Indentation")).font(semibold(12.5)));
// Mirrored indents are the inside and outside ones (they swap on even pages).
let (l_label, r_label) = if opts[0] { ("Inside:", "Outside:") } else { ("Left:", "Right:") };
crate::rtl::Table::new("ind").columns(4).show(ui, |t| {
t.row(|r| {
let left_label = r.cell(|ui| ui.label(tl!(l_label)));
r.cell(|ui| para_number(ui, left, ParaNumber::Length, "left", mixed, &left_label));
let right_label = r.cell(|ui| ui.label(tl!(r_label)));
r.cell(|ui| para_number(ui, right, ParaNumber::Length, "right", mixed, &right_label));
});
t.row(|r| {
let first_label = r.cell(|ui| ui.label(tl!("First line:")));
r.cell(|ui| para_number(ui, first, ParaNumber::Length, "indentFirst", mixed, &first_label));
});
});
crate::widgets::section(ui, tl!("Indentation"), |ui| {
// Mirrored indents are the inside and outside ones (they swap on even pages).
let (l_label, r_label) = if opts[0] { ("Inside:", "Outside:") } else { ("Left:", "Right:") };
crate::rtl::Table::new("ind").columns(4).show(ui, |t| {
t.row(|r| {
let left_label = r.cell(|ui| ui.label(tl!(l_label)));
r.cell(|ui| para_number(ui, left, ParaNumber::Length, "left", mixed, &left_label));
let right_label = r.cell(|ui| ui.label(tl!(r_label)));
r.cell(|ui| para_number(ui, right, ParaNumber::Length, "right", mixed, &right_label));
});
t.row(|r| {
let first_label = r.cell(|ui| ui.label(tl!("First line:")));
r.cell(|ui| para_number(ui, first, ParaNumber::Length, "indentFirst", mixed, &first_label));
});
para_check(ui, &mut opts[0], tl!("Mirror indents"), "mirrorIndents", mixed);
ui.label(egui::RichText::new(tl!("Spacing")).font(semibold(12.5)));
crate::rtl::Table::new("sp").columns(4).show(ui, |t| {
t.row(|r| {
let before_label = r.cell(|ui| ui.label(tl!("Before:")));
r.cell(|ui| para_number(ui, before, ParaNumber::Points, "spaceBefore", mixed, &before_label));
let line_label = r.cell(|ui| ui.label(tl!("Line spacing:")));
r.cell(|ui| para_number(ui, line, ParaNumber::Lines, "lineSpacing", mixed, &line_label));
});
para_check(ui, &mut opts[0], tl!("Mirror indents"), "mirrorIndents", mixed);
});
crate::widgets::section(ui, tl!("Spacing"), |ui| {
crate::rtl::Table::new("sp").columns(4).show(ui, |t| {
t.row(|r| {
let before_label = r.cell(|ui| ui.label(tl!("Before:")));
r.cell(|ui| para_number(ui, before, ParaNumber::Points, "spaceBefore", mixed, &before_label));
let line_label = r.cell(|ui| ui.label(tl!("Line spacing:")));
r.cell(|ui| para_number(ui, line, ParaNumber::Lines, "lineSpacing", mixed, &line_label));
});
t.row(|r| {
let after_label = r.cell(|ui| ui.label(tl!("After:")));
r.cell(|ui| para_number(ui, after, ParaNumber::Points, "spaceAfter", mixed, &after_label));
});
t.row(|r| {
let after_label = r.cell(|ui| ui.label(tl!("After:")));
r.cell(|ui| para_number(ui, after, ParaNumber::Points, "spaceAfter", mixed, &after_label));
});
});
para_check(ui, &mut opts[1], tl!("Don't add space between paragraphs of the same style"), "contextualSpacing", mixed);
}
1 => {
crate::widgets::section(ui, tl!("Line and Page Breaks"), |ui| {
para_check(ui, widow, tl!("Widow/Orphan control"), "widowControl", mixed);
para_check(ui, keep_next, tl!("Keep with next"), "keepNext", mixed);
para_check(ui, keep_lines, tl!("Keep lines together"), "keepLines", mixed);
para_check(ui, page_break, tl!("Page break before"), "pageBreakBefore", mixed);
});
crate::widgets::section(ui, tl!("Formatting exceptions"), |ui| {
para_check(ui, &mut opts[2], tl!("Suppress line numbers"), "suppressLineNumbers", mixed);
para_check(ui, &mut opts[3], tl!("Don't hyphenate"), "suppressHyphens", mixed);
});
ui.label(egui::RichText::new(tl!("Line and Page Breaks")).font(semibold(12.5)));
para_check(ui, widow, tl!("Widow/Orphan control"), "widowControl", mixed);
para_check(ui, keep_next, tl!("Keep with next"), "keepNext", mixed);
para_check(ui, keep_lines, tl!("Keep lines together"), "keepLines", mixed);
para_check(ui, page_break, tl!("Page break before"), "pageBreakBefore", mixed);
ui.label(egui::RichText::new(tl!("Formatting exceptions")).font(semibold(12.5)));
para_check(ui, &mut opts[2], tl!("Suppress line numbers"), "suppressLineNumbers", mixed);
para_check(ui, &mut opts[3], tl!("Don't hyphenate"), "suppressHyphens", mixed);
}
_ => {
let [kinsoku, word_wrap, overflow, top_line, de, dn] = asian;
crate::widgets::section(ui, tl!("Line breaking"), |ui| {
para_check(ui, kinsoku, tl!("Apply Asian line-breaking rules (kinsoku)"), "kinsoku", mixed);
// The model's flag is "wrap whole words"; the box offers the opposite.
let mut mid_word = !*word_wrap;
para_check(ui, &mut mid_word, tl!("Allow Latin text to wrap in the middle of a word"), "wordWrap", mixed);
*word_wrap = !mid_word;
para_check(ui, overflow, tl!("Allow hanging punctuation"), "overflowPunct", mixed);
});
crate::widgets::section(ui, tl!("Character Spacing"), |ui| {
para_check(ui, top_line, tl!("Compress punctuation at the start of a line"), "topLinePunct", mixed);
para_check(ui, de, tl!("Add space between Asian and Latin text"), "autoSpaceDE", mixed);
para_check(ui, dn, tl!("Add space between Asian text and numbers"), "autoSpaceDN", mixed);
});
ui.label(egui::RichText::new(tl!("Line breaking")).font(semibold(12.5)));
para_check(ui, kinsoku, tl!("Apply Asian line-breaking rules (kinsoku)"), "kinsoku", mixed);
// The model's flag is "wrap whole words"; the box offers the opposite.
let mut mid_word = !*word_wrap;
para_check(ui, &mut mid_word, tl!("Allow Latin text to wrap in the middle of a word"), "wordWrap", mixed);
*word_wrap = !mid_word;
para_check(ui, overflow, tl!("Allow hanging punctuation"), "overflowPunct", mixed);
ui.label(egui::RichText::new(tl!("Character Spacing")).font(semibold(12.5)));
para_check(ui, top_line, tl!("Compress punctuation at the start of a line"), "topLinePunct", mixed);
para_check(ui, de, tl!("Add space between Asian and Latin text"), "autoSpaceDE", mixed);
para_check(ui, dn, tl!("Add space between Asian text and numbers"), "autoSpaceDN", mixed);
}
}
ui.add_space(6.0);
@@ -627,66 +619,57 @@ fn page_setup_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
else {
return false;
};
crate::widgets::section(ui, tl!("Margins"), |ui| {
crate::rtl::Table::new("ps").columns(4).show(ui, |t| {
t.row(|r| {
let top_label = r.cell(|ui| ui.label(tl!("Top:")));
r.cell(|ui| ui.add(margin(top)).labelled_by(top_label.id));
let bottom_label = r.cell(|ui| ui.label(tl!("Bottom:")));
r.cell(|ui| ui.add(margin(bottom)).labelled_by(bottom_label.id));
});
t.row(|r| {
let left_label = r.cell(|ui| ui.label(if *mirror { tl!("Inside:") } else { tl!("Left:") }));
r.cell(|ui| ui.add(margin(left)).labelled_by(left_label.id));
let right_label = r.cell(|ui| ui.label(if *mirror { tl!("Outside:") } else { tl!("Right:") }));
r.cell(|ui| ui.add(margin(right)).labelled_by(right_label.id));
});
ui.label(egui::RichText::new(tl!("Margins")).font(semibold(12.5)));
crate::rtl::Table::new("ps").columns(4).show(ui, |t| {
t.row(|r| {
let top_label = r.cell(|ui| ui.label(tl!("Top:")));
r.cell(|ui| ui.add(margin(top)).labelled_by(top_label.id));
let bottom_label = r.cell(|ui| ui.label(tl!("Bottom:")));
r.cell(|ui| ui.add(margin(bottom)).labelled_by(bottom_label.id));
});
t.row(|r| {
let left_label = r.cell(|ui| ui.label(if *mirror { tl!("Inside:") } else { tl!("Left:") }));
r.cell(|ui| ui.add(margin(left)).labelled_by(left_label.id));
let right_label = r.cell(|ui| ui.label(if *mirror { tl!("Outside:") } else { tl!("Right:") }));
r.cell(|ui| ui.add(margin(right)).labelled_by(right_label.id));
});
});
crate::widgets::section(ui, tl!("Orientation"), |ui| {
ui.horizontal(|ui| {
ui.radio_value(landscape, false, tl!("Portrait"));
ui.radio_value(landscape, true, tl!("Landscape"));
ui.label(egui::RichText::new(tl!("Orientation")).font(semibold(12.5)));
ui.horizontal(|ui| {
ui.radio_value(landscape, false, tl!("Portrait"));
ui.radio_value(landscape, true, tl!("Landscape"));
});
ui.label(egui::RichText::new(tl!("Pages")).font(semibold(12.5)));
ui.checkbox(mirror, tl!("Mirror margins"));
page_paper_group(ui, paper, landscape, paper_custom);
ui.label(egui::RichText::new(tl!("Document Grid")).font(semibold(12.5)));
ui.horizontal_wrapped(|ui| {
ui.radio_value(&mut grid.0, 0, tl!("No grid"));
ui.radio_value(&mut grid.0, 1, tl!("Lines only"));
ui.radio_value(&mut grid.0, 2, tl!("Lines and characters"));
ui.radio_value(&mut grid.0, 3, tl!("Text snaps to characters"));
});
crate::rtl::Table::new("ps_grid").columns(4).show(ui, |t| {
t.row(|r| {
let chars_label = r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::Label::new(tl!("Characters per line:"))));
r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::DragValue::new(&mut grid.2).range(1..=1000).clip_text(true)).labelled_by(chars_label.id));
let lines_label = r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::Label::new(tl!("Lines per page:"))));
r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::DragValue::new(&mut grid.1).range(1..=1000).clip_text(true)).labelled_by(lines_label.id));
});
});
crate::widgets::section(ui, tl!("Pages"), |ui| {
ui.checkbox(mirror, tl!("Mirror margins"));
page_paper_group(ui, paper, landscape, paper_custom);
});
crate::widgets::section(ui, tl!("Document Grid"), |ui| {
ui.horizontal_wrapped(|ui| {
ui.radio_value(&mut grid.0, 0, tl!("No grid"));
ui.radio_value(&mut grid.0, 1, tl!("Lines only"));
ui.radio_value(&mut grid.0, 2, tl!("Lines and characters"));
ui.radio_value(&mut grid.0, 3, tl!("Text snaps to characters"));
});
crate::rtl::Table::new("ps_grid").columns(4).show(ui, |t| {
t.row(|r| {
let chars_label = r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::Label::new(tl!("Characters per line:"))));
r.cell(|ui| {
ui.add_enabled(grid.0 >= 2, egui::DragValue::new(&mut grid.2).range(1..=1000).clip_text(true)).labelled_by(chars_label.id)
});
let lines_label = r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::Label::new(tl!("Lines per page:"))));
r.cell(|ui| {
ui.add_enabled(grid.0 >= 1, egui::DragValue::new(&mut grid.1).range(1..=1000).clip_text(true)).labelled_by(lines_label.id)
});
});
});
ui.horizontal(|ui| {
ui.label(tl!("Section direction:"));
ui.radio_value(rtl, false, tl!("Left-to-right"));
ui.radio_value(rtl, true, tl!("Right-to-left"));
});
if !message.is_empty() {
ui.label(egui::RichText::new(message.as_str()).small().color(ui.visuals().error_fg_color));
}
page_valign_combo(ui, valign);
});
crate::widgets::section(ui, tl!("Headers and footers"), |ui| {
// Word's Page Setup › Layout: a title page without the page number (#1230).
ui.checkbox(odd_even, tl!("Different Odd & Even Pages"));
ui.checkbox(first_page, tl!("Different First Page"));
ui.horizontal(|ui| {
ui.label(tl!("Section direction:"));
ui.radio_value(rtl, false, tl!("Left-to-right"));
ui.radio_value(rtl, true, tl!("Right-to-left"));
});
if !message.is_empty() {
ui.label(egui::RichText::new(message.as_str()).small().color(ui.visuals().error_fg_color));
}
page_valign_combo(ui, valign);
// Word's Page Setup › Layout: a title page without the page number (#1230).
ui.label(egui::RichText::new(tl!("Headers and footers")).font(semibold(12.5)));
ui.checkbox(odd_even, tl!("Different Odd & Even Pages"));
ui.checkbox(first_page, tl!("Different First Page"));
let (mut ok, cancel) = buttons(ui, tl!("OK"));
if ok {
// Everything OK changes is one undo step; a refused command applies nothing.
+69 -72
View File
@@ -1,5 +1,5 @@
use super::chrome::buttons;
use super::{MeasureExt, Sense, Serialize, Tokens, Ui, Value, WordApp, json, vec2};
use super::{MeasureExt, Sense, Serialize, Tokens, Ui, Value, WordApp, json, semibold, vec2};
/// The Custom tab of File › Info › Properties › Advanced Properties (#2982): the document's
/// custom properties, edited as a working copy. OK sends the whole difference from what the
@@ -385,88 +385,85 @@ pub(super) fn table_properties(ui: &mut Ui, f: &mut TableForm) {
fn len(v: &mut f32, lo: f32, unit: wordcraft_geom::Unit) -> egui::DragValue<'_> {
egui::DragValue::new(v).speed(0.01).range(lo..=22.0).measure(unit).max_decimals(2)
}
crate::widgets::section(ui, tl!("Table"), |ui| {
crate::rtl::Table::new("tp_table").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.width_on, len(&mut f.width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("left", "Left"), ("center", "Center"), ("right", "Right")] {
ui.radio_value(&mut f.align, v.to_string(), tl!(l));
}
});
let heading = |ui: &mut Ui, s: &str| {
ui.add_space(4.0);
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
};
heading(ui, "Table");
crate::rtl::Table::new("tp_table").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.width_on, len(&mut f.width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("left", "Left"), ("center", "Center"), ("right", "Right")] {
ui.radio_value(&mut f.align, v.to_string(), tl!(l));
}
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Indent from left:")));
r.cell(|ui| {
ui.add_enabled(
f.align == "left",
egui::DragValue::new(&mut f.indent).speed(0.01).range(-11.0..=22.0).measure(unit).max_decimals(2),
)
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Indent from left:")));
r.cell(|ui| {
ui.add_enabled(f.align == "left", egui::DragValue::new(&mut f.indent).speed(0.01).range(-11.0..=22.0).measure(unit).max_decimals(2))
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Table direction:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.rtl, false, tl!("Left-to-right"));
ui.radio_value(&mut f.rtl, true, tl!("Right-to-left"));
});
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Table direction:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut f.rtl, false, tl!("Left-to-right"));
ui.radio_value(&mut f.rtl, true, tl!("Right-to-left"));
});
});
heading(ui, "Row");
crate::rtl::Table::new("tp_row").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let specify = r.cell(|ui| ui.checkbox(&mut f.row_height_on, tl!("Specify height:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.add_enabled(f.row_height_on, len(&mut f.row_height, 0.02, unit));
ui.add_enabled_ui(f.row_height_on, |ui| {
let rule = craft_ui::ComboBox::from_id_salt("tp_rule")
.selected_text(tl!(if f.row_exact { "Exactly" } else { "At least" }))
.show_ui(ui, |ui| {
ui.selectable_value(&mut f.row_exact, false, tl!("At least"));
ui.selectable_value(&mut f.row_exact, true, tl!("Exactly"));
});
// A screen reader names the rule by the box it belongs to.
rule.response.labelled_by(specify.id);
});
});
});
});
});
crate::widgets::section(ui, tl!("Row"), |ui| {
crate::rtl::Table::new("tp_row").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
let specify = r.cell(|ui| ui.checkbox(&mut f.row_height_on, tl!("Specify height:")));
r.cell(|ui| {
ui.horizontal(|ui| {
ui.add_enabled(f.row_height_on, len(&mut f.row_height, 0.02, unit));
ui.add_enabled_ui(f.row_height_on, |ui| {
let rule = craft_ui::ComboBox::from_id_salt("tp_rule")
.selected_text(tl!(if f.row_exact { "Exactly" } else { "At least" }))
.show_ui(ui, |ui| {
ui.selectable_value(&mut f.row_exact, false, tl!("At least"));
ui.selectable_value(&mut f.row_exact, true, tl!("Exactly"));
});
// A screen reader names the rule by the box it belongs to.
rule.response.labelled_by(specify.id);
});
});
});
});
});
super::paragraph::para_check(ui, &mut f.allow_break, tl!("Allow row to break across pages"), "allowBreak", &mut f.mixed);
super::paragraph::para_check(ui, &mut f.header_row, tl!("Repeat as header row on each page"), "headerRow", &mut f.mixed);
});
crate::widgets::section(ui, tl!("Column"), |ui| {
crate::rtl::Table::new("tp_col").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Preferred width:")));
r.cell(|ui| ui.add(len(&mut f.column_width, 0.1, unit)));
});
super::paragraph::para_check(ui, &mut f.allow_break, tl!("Allow row to break across pages"), "allowBreak", &mut f.mixed);
super::paragraph::para_check(ui, &mut f.header_row, tl!("Repeat as header row on each page"), "headerRow", &mut f.mixed);
heading(ui, "Column");
crate::rtl::Table::new("tp_col").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.label(tl!("Preferred width:")));
r.cell(|ui| ui.add(len(&mut f.column_width, 0.1, unit)));
});
});
crate::widgets::section(ui, tl!("Cell"), |ui| {
crate::rtl::Table::new("tp_cell").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.cell_width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.cell_width_on, len(&mut f.cell_width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Vertical alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("top", "Top"), ("center", "Center"), ("bottom", "Bottom")] {
ui.radio_value(&mut f.valign, v.to_string(), tl!(l));
}
});
heading(ui, "Cell");
crate::rtl::Table::new("tp_cell").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
t.row(|r| {
r.cell(|ui| ui.checkbox(&mut f.cell_width_on, tl!("Preferred width:")));
r.cell(|ui| ui.add_enabled(f.cell_width_on, len(&mut f.cell_width, 0.1, unit)));
});
t.row(|r| {
r.cell(|ui| ui.label(tl!("Vertical alignment:")));
r.cell(|ui| {
ui.horizontal(|ui| {
for (v, l) in [("top", "Top"), ("center", "Center"), ("bottom", "Bottom")] {
ui.radio_value(&mut f.valign, v.to_string(), tl!(l));
}
});
});
});
-21
View File
@@ -1868,27 +1868,6 @@ fn the_custom_properties_dialog_leaves_imported_non_text_properties_alone() {
assert_eq!(kinds, [("Status", "lpwstr"), ("Count", "i4")], "Cancel leaves the imported property as it was");
}
/// A tall dialog on a short screen stays inside it and scrolls.
#[test]
fn a_tall_dialog_fits_a_short_screen() {
let mut app = app_with("Some text");
app.dialog = Dialog::open("pageSetup", &mut app);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 360.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
for _ in 0..4 {
h.step();
}
let id = egui::Id::unique(("dialog", "Page Setup"));
let rect = h.ctx.memory(|m| m.area_rect(id)).expect("the dialog is open");
assert!(rect.height() <= 360.5, "the dialog is {}pt tall on a 360pt screen", rect.height());
}
/// #3859: a dialog is modal, as in Word. While Font is open, typing (from the frame it opens),
/// Mod+O and a click on File reach nothing behind it, and the dialog itself still works. Find
/// and Replace is modeless: with it open, File still opens.
+7 -193
View File
@@ -12,7 +12,6 @@ use std::path::{Path, PathBuf};
use egui::{Align2, Rect, Sense, Ui, pos2, vec2};
use crate::file_dialogs::{AfterPick, FileDialogRequest, open_filters};
use crate::print_page::{EXPORT_FORMATS, export_file_ext, export_name, is_document_ext};
use crate::theme::{Tokens, regular};
use crate::{WordApp, icons};
@@ -139,8 +138,6 @@ pub(crate) struct FileBrowser {
/// The file types, as (label, extensions).
filters: Vec<(String, Vec<String>)>,
filter: usize,
/// Exporting: the format behind each type, which `after` follows; empty otherwise.
exports: Vec<String>,
listing: Result<Listing, String>,
/// The highlighted entry.
selected: Option<PathBuf>,
@@ -161,15 +158,6 @@ impl FileBrowser {
(name.clone(), f)
}
};
// Exporting (#3535): File › Export's formats are the types, starting on the one asked for.
let (filters, filter, exports) = match &after {
AfterPick::Export { ext } => (
EXPORT_FORMATS.iter().map(|&(l, f)| (l.to_string(), vec![export_file_ext(f).to_string()])).collect(),
EXPORT_FORMATS.iter().position(|&(_, f)| f == ext.as_str()).unwrap_or(0),
EXPORT_FORMATS.iter().map(|&(_, f)| f.to_string()).collect(),
),
_ => (filters, 0, Vec::new()),
};
let mut b = FileBrowser {
req,
after,
@@ -178,8 +166,7 @@ impl FileBrowser {
location: String::new(),
name,
filters,
filter,
exports,
filter: 0,
listing: Ok(Listing::default()),
selected: None,
note: Note::None,
@@ -202,16 +189,6 @@ impl FileBrowser {
self.note = Note::None;
}
/// A type was chosen: when exporting it is the format, and the name's export extension follows it.
fn type_changed(&mut self) {
let Some(format) = self.exports.get(self.filter).cloned() else { return };
// Only a known document extension is replaced; `notes.v2` keeps its `.v2`.
if Path::new(&self.name).extension().and_then(|e| e.to_str()).is_some_and(is_document_ext) {
self.name = export_name(&self.name, &format);
}
self.after = AfterPick::Export { ext: format };
}
fn up(&mut self) {
if let Some(parent) = self.dir.parent().map(Path::to_path_buf) {
self.navigate(parent);
@@ -219,8 +196,8 @@ impl FileBrowser {
}
/// OK: a highlighted folder, or a typed folder, is opened; otherwise the typed name is the
/// pick. Save adds the chosen type's extension to a name without one (an export replaces a
/// known document extension with the type's) and asks once more before replacing a file; Open wants a file that exists.
/// pick. Save adds the chosen type's extension to a name without one and asks once more
/// before replacing a file; Open wants a file that exists.
pub(crate) fn accept(&mut self) -> Step {
if let Some(dir) = self.selected.take().filter(|p| p.is_dir()) {
self.navigate(dir);
@@ -241,11 +218,7 @@ impl FileBrowser {
Step::Stay
}
FileDialogRequest::Save { .. } => {
if let AfterPick::Export { ext } = &self.after {
// The chosen type is the format: its extension replaces a known document
// extension on the name, and is added to any other.
path = PathBuf::from(export_name(&path.to_string_lossy(), ext));
} else if path.extension().is_none()
if path.extension().is_none()
&& let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*")
{
path.set_extension(ext);
@@ -300,11 +273,10 @@ impl WordApp {
self.file_browser.open = Some(Box::new(FileBrowser::new(req, after, start, unavailable)));
}
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save,
/// export), even when a system dialog was asked for and never showed up (it is given up as cancelled).
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save),
/// even when a system dialog was asked for and never showed up (it is given up as cancelled).
pub(crate) fn browse_builtin(&mut self, purpose: &str) {
// An export that was waiting on the system dialog keeps its format.
let pending = self.give_up_file_dialog();
self.give_up_file_dialog();
if self.file_browser.open.is_some() {
return;
}
@@ -315,11 +287,6 @@ impl WordApp {
FileDialogRequest::Save { name: self.default_save_name(), dir: None },
AfterPick::SaveAs { after: crate::file_dialogs::AfterSave::Nothing, document: self.session.document_id() },
),
"export" => {
let ext = pending.unwrap_or_else(|| "pdf".into());
let name = format!("{}.{}", self.title_stem(), export_file_ext(&ext));
(FileDialogRequest::Save { name, dir: None }, AfterPick::Export { ext })
}
_ => (FileDialogRequest::Open { purpose: "document".into() }, AfterPick::OpenDocument { document: self.session.document_id() }),
};
self.show_file_browser(req, after, false);
@@ -504,7 +471,6 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option<Option<PathBuf>>
refilter = b.filter != before;
});
if refilter {
b.type_changed();
b.navigate(b.dir.clone());
}
ui.add_space(8.0);
@@ -765,158 +731,6 @@ mod tests {
assert!(crate::keytips::suppressed(&a, &ctx));
}
/// #3535: exporting offers File › Export's formats as the types; the chosen one is the format,
/// the name's extension follows it, and the export writes that format.
#[test]
fn export_types_choose_the_format_and_the_extension() {
let dir = scratch("export");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Exported in WordCraft"})).unwrap();
a.run("ui.fileBrowser", json!({"purpose": "export"})).unwrap();
let b = a.file_browser.open.as_mut().expect("the built-in browser is open");
assert_eq!(b.filters.len(), EXPORT_FORMATS.len());
assert_eq!(b.filters[b.filter].0, "PDF document (*.pdf)");
assert!(b.name.ends_with(".pdf"), "{}", b.name);
b.filter = b.filters.iter().position(|(l, _)| l == "Plain text (*.txt)").unwrap();
b.type_changed();
assert!(b.name.ends_with(".txt"), "{}", b.name);
assert!(matches!(&b.after, AfterPick::Export { ext } if ext == "txt"));
b.navigate(dir.clone());
// A name typed afterwards with another document extension gets the chosen format's instead,
// and a name with an unknown one keeps it.
b.name = "notes.v2".into();
let Step::Pick(v2) = b.accept() else { panic!("picked") };
assert_eq!(v2.file_name().unwrap(), "notes.v2.txt");
b.name = "notes.docx".into();
let Step::Pick(path) = b.accept() else { panic!("picked") };
assert_eq!(path.file_name().unwrap(), "notes.txt");
for (typed, want) in [
("a.PDF", "a.txt"),
("a.htm", "a.txt"),
("a", "a.txt"),
("a.TXT", "a.TXT"),
("sub/a.rtf", "sub/a.txt"),
(".txt", ".txt.txt"),
(".docx", ".docx.txt"),
("sub/.docx", "sub/.docx.txt"),
("a.", "a.txt"),
("a..", "a.txt"),
] {
assert_eq!(crate::print_page::export_name(typed, "txt"), want);
}
a.close_file_browser(Some(path.clone()));
assert!(std::fs::read_to_string(&path).unwrap().contains("Exported in WordCraft"));
// Word 2003 XML starts on its own type, though Word XML writes .xml too.
let req = FileDialogRequest::Save { name: "x.xml".into(), dir: None };
let b = FileBrowser::new(req, AfterPick::Export { ext: crate::print_page::EXPORT_WORD_2003.into() }, dir.clone(), false);
assert_eq!(b.filters[b.filter].0, "Word 2003 XML Document (*.xml)");
let _ = std::fs::remove_dir_all(&dir);
}
/// The OpenDocument template and flat-XML exports are types of their own: the name gets
/// their extension, and the export saves by it.
#[test]
fn export_types_include_the_opendocument_template_and_flat_xml() {
let dir = scratch("export_ott");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Template text"})).unwrap();
for (label, ext) in [("OpenDocument Text Template (*.ott)", "ott"), ("Flat OpenDocument Text (*.fodt)", "fodt")] {
let req = FileDialogRequest::Save { name: "x.pdf".into(), dir: None };
let mut b = FileBrowser::new(req, AfterPick::Export { ext: "pdf".into() }, dir.clone(), false);
b.filter = b.filters.iter().position(|(l, _)| l == label).unwrap();
b.type_changed();
assert_eq!(b.name, format!("x.{ext}"));
b.navigate(dir.clone());
let Step::Pick(path) = b.accept() else { panic!("picked") };
assert_eq!(path, dir.join(format!("x.{ext}")));
a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(path.to_string_lossy().into_owned())).unwrap();
assert!(path.is_file(), "{ext} written");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// An export waiting on a system dialog that never showed up keeps its format when Browse
/// in WordCraft… takes over, instead of starting over on PDF.
#[test]
fn browse_in_wordcraft_keeps_a_pending_exports_format() {
let services = Services {
file_dialog: Some(Box::new(|_req| {
let (tx, rx) = channel();
// The system dialog never answers.
std::mem::forget(tx);
rx
})),
..Default::default()
};
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services);
a.export_dialog("rtf");
assert!(a.file_dialog.is_some(), "waiting on the system dialog");
a.run("ui.fileBrowser", json!({"purpose": "export"})).unwrap();
assert!(a.file_dialog.is_none(), "the system dialog is given up");
let b = a.file_browser.open.as_ref().expect("the built-in browser is open");
assert!(matches!(&b.after, AfterPick::Export { ext } if ext == "rtf"));
assert_eq!(b.filters[b.filter].0, "Rich Text Format (*.rtf)");
assert!(b.name.ends_with(".rtf"), "{}", b.name);
}
/// Word XML chosen as the export type wins over a Word 2003 XML file already at that path,
/// whose format a save by path alone would keep.
#[test]
fn exporting_word_xml_over_a_word_2003_file_writes_word_xml() {
let dir = scratch("export_xml");
let path = dir.join("letter.xml").to_string_lossy().into_owned();
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
a.finish_pick(AfterPick::Export { ext: crate::print_page::EXPORT_WORD_2003.into() }, Some(path.clone())).unwrap();
assert!(std::fs::read_to_string(&path).unwrap().contains("w:wordDocument"));
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(path.clone())).unwrap();
let xml = std::fs::read_to_string(&path).unwrap();
assert!(xml.contains("pkg:package") && !xml.contains("w:wordDocument"), "Word XML, not Word 2003 XML");
let _ = std::fs::remove_dir_all(&dir);
}
/// A system Save dialog lets the user type a name without `.xml`; Word XML export still
/// writes `<name>.xml` (as the built-in browser does) and won't silently replace an existing one.
#[test]
fn exporting_word_xml_to_a_name_without_xml_appends_the_extension() {
let dir = scratch("export_xml_ext");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
let bare = dir.join("letter").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap();
let xml = std::fs::read_to_string(dir.join("letter.xml")).unwrap();
assert!(xml.contains("pkg:package"), "Word XML written at letter.xml");
// A known document extension gives way to .xml; an unknown one stays.
let docx = dir.join("notes.docx").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(docx)).unwrap();
assert!(dir.join("notes.xml").is_file());
let v2 = dir.join("notes.v2").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(v2)).unwrap();
assert!(dir.join("notes.v2.xml").is_file());
// The resulting name already exists: the system dialog never confirmed it, so refuse.
let bare = dir.join("letter").to_string_lossy().into_owned();
assert!(a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(bare)).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
/// A name that is only a known extension (`.docx`) is a stem for `Path::extension`, which the
/// engine's explicit-format guard reads too: exporting Word XML to it must name a real
/// `.xml` file and write it (a bare `.xml` would be refused, writing nothing).
#[test]
fn exporting_word_xml_to_a_dotfile_name_writes_the_file() {
let dir = scratch("export_xml_dotfile");
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
for format in ["xml", crate::print_page::EXPORT_WORD_2003] {
let typed = dir.join(".docx").to_string_lossy().into_owned();
a.finish_pick(AfterPick::Export { ext: format.into() }, Some(typed)).unwrap();
let written = dir.join(".docx.xml");
assert!(std::fs::read_to_string(&written).unwrap().contains(if format == "xml" { "pkg:package" } else { "w:wordDocument" }));
let _ = std::fs::remove_file(&written);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// #3037: an empty folder (or a type filter that matches nothing) says so instead of a blank
/// box; a matching file replaces the hint.
#[test]
+12 -50
View File
@@ -171,17 +171,15 @@ impl WordApp {
}
}
/// Treat the system dialog the host is showing as cancelled, e.g. one that never showed up;
/// returns the format of the export it was for, if any.
/// Treat the system dialog the host is showing as cancelled, e.g. one that never showed up.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn give_up_file_dialog(&mut self) -> Option<String> {
pub(crate) fn give_up_file_dialog(&mut self) {
if let Some(cancel) = &self.services.cancel_file_dialog {
cancel();
}
let d = self.file_dialog.take()?;
let export = if let AfterPick::Export { ext } = &d.after { Some(ext.clone()) } else { None };
let _ = self.finish_pick(d.after, None);
export
if let Some(d) = self.file_dialog.take() {
let _ = self.finish_pick(d.after, None);
}
}
/// The host couldn't show a system dialog (#576): ask in the built-in browser instead, which
@@ -297,40 +295,16 @@ impl WordApp {
Ok(json!({"picked": true}))
}
AfterPick::Export { ext } => {
let Some(mut path) = picked else {
// Cancelled: an earlier refusal is not news any more.
self.clear_export_error();
return Ok(json!({"cancelled": true}));
};
let Some(path) = picked else { return Ok(json!({"cancelled": true})) };
let r = if ext == "png" {
self.run("file.exportPng", json!({"path": path}))
} else if ext == "xml" || ext == crate::print_page::EXPORT_WORD_2003 {
// The engine takes an explicit format only for an .xml path, and a system Save
// dialog lets the user type any name: give it the extension, as the built-in
// browser does (`notes.docx` becomes `notes.xml`, `notes.v2` `notes.v2.xml`).
let named = crate::print_page::export_name(&path, "xml");
if named != path {
path = named;
// The dialog only confirmed the name it was given, not this one.
if std::path::Path::new(&path).exists() {
// Callers drop the result, so say it where the person sees it.
return Err(self.fail_export(format!("{path} already exists; choose another name")));
}
}
// Word XML even over a Word 2003 XML file, which a save by path would keep.
let format = if ext == "xml" { wordcraft_engine::cmd::file::FORMAT_FLAT_OPC } else { crate::print_page::EXPORT_WORD_2003 };
self.run("file.saveAs", json!({"path": path, "format": format}))
} else if ext == crate::print_page::EXPORT_WORD_2003 {
self.run("file.saveAs", json!({"path": path, "format": ext}))
} else {
self.run("file.saveAs", json!({"path": path}))
};
match &r {
Ok(_) => {
self.clear_export_error();
self.status(crate::i18n::fmt(tl!("Exported {path}"), &[("path", &crate::i18n::isolate_path(&path))]));
}
Err(e) => {
self.fail_export(e.clone());
}
if r.is_ok() {
self.status(crate::i18n::fmt(tl!("Exported {path}"), &[("path", &crate::i18n::isolate_path(&path))]));
}
r
}
@@ -409,18 +383,6 @@ impl WordApp {
}
}
/// An export failed or was refused: say so on the status bar and, for the Export page,
/// there too, since Backstage's render loop skips the status bar (callers drop the result).
fn fail_export(&mut self, error: String) -> String {
self.status(error.clone());
self.export_error = error.clone();
error
}
fn clear_export_error(&mut self) {
self.export_error.clear();
}
/// Drop a Save As page error once a later attempt has actually saved.
fn clear_save_as_error(&mut self) {
if let Some(ctx) = self.ctx.clone() {
@@ -474,8 +436,8 @@ impl WordApp {
/// File › Export: ask where to save a copy in this format, then write it.
pub(crate) fn export_dialog(&mut self, ext: &str) {
let name = format!("{}.{}", self.title_stem(), crate::print_page::export_file_ext(ext));
// A refusal or failure is reported by `finish_pick` itself (Export page and status bar).
let file_ext = if ext == crate::print_page::EXPORT_WORD_2003 { "xml" } else { ext };
let name = format!("{}.{file_ext}", self.title_stem());
let _ = self.ask_file(FileDialogRequest::Save { name, dir: None }, AfterPick::Export { ext: ext.to_string() });
}
-33
View File
@@ -465,39 +465,6 @@ fn export_pdf_without_a_path_asks_where_to_save() {
let _ = std::fs::remove_dir_all(&dir);
}
/// An explicit web PDF export keeps an existing PDF suffix regardless of ASCII case.
#[test]
fn web_pdf_export_keeps_an_existing_suffix_in_any_case() {
let downloaded = Rc::new(RefCell::new(Vec::new()));
let captured = downloaded.clone();
let services = Services {
download: Some(Box::new(move |name, bytes| {
captured.borrow_mut().push((name.to_string(), bytes.starts_with(b"%PDF")));
Ok(())
})),
..Default::default()
};
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services);
for (name, expected) in [
("Report.pdf", "Report.pdf"),
("Report.PDF", "Report.PDF"),
("Résumé.PdF", "Résumé.PdF"),
("😀.PDF", "😀.PDF"),
(".hidden.PDF", ".hidden.PDF"),
("Report..PDF", "Report..PDF"),
("é", "é.pdf"),
("😀", "😀.pdf"),
("Report.pdf.exe", "Report.pdf.exe.pdf"),
("Report.PDF", "Report.PDF.pdf"),
("Report.pdf.", "Report.pdf..pdf"),
("Report", "Report.pdf"),
] {
let result = a.execute("file.exportPdf", json!({"path": name})).unwrap();
assert_eq!(result["downloaded"], expected, "{name}");
assert_eq!(downloaded.borrow().last().cloned(), Some((expected.to_string(), true)), "{name}");
}
}
/// Open, Save As and Export PNG from the command search (no path) ask for a file the same way.
#[test]
fn file_commands_without_a_path_ask_for_one() {
+4 -67
View File
@@ -46,8 +46,6 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
interrupted_preedit: std::mem::take(&mut app.canvas.ime_interrupted_preedit),
interrupted_replacement: EquationReplacementDrop::None,
};
let now = ctx.input(|i| i.time);
expire_paste_wait(app, now);
let held = ctx.input(|i| i.modifiers);
if held.command {
app.canvas.paste_mods = Some(held);
@@ -62,8 +60,7 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
continue;
}
note_key_state(app, &e);
if ignored_paste(app, &e)
|| drop_refused_replacement(app, &e, &mut batch)
if drop_refused_replacement(app, &e, &mut batch)
|| prefilter(app, ctx, &e, alt_codes)
|| paste_release(app, &e)
|| equation_event(app, ctx, &e, &mut batch)
@@ -72,27 +69,6 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
}
handle_event(app, ctx, e);
}
if app.canvas.ignore_next_paste && app.canvas.paste_wait_since.is_none() {
app.canvas.paste_wait_since = Some(now);
}
}
/// How long the paste event paired with Mod+Shift+V is waited for. A browser sends it with the
/// key, in the same frame; with no text on the clipboard it sends none at all.
const PASTE_WAIT: f64 = 1.0;
/// Ends a wait for the paired paste event that never came, so a later paste (a browser menu's,
/// say) isn't dropped (#5616).
fn expire_paste_wait(app: &mut WordApp, now: f64) {
if !app.canvas.ignore_next_paste {
app.canvas.paste_wait_since = None;
} else if app.canvas.paste_wait_since.is_some_and(|t| now - t > PASTE_WAIT) {
app.canvas.ignore_next_paste = false;
app.canvas.paste_wait_since = None;
// No key came since the chord (any key ends the wait), so noted modifiers are the
// chord's: a later paste reads the modifiers held then.
app.canvas.paste_event_mods = None;
}
}
/// State carried across the events of one raw batch.
@@ -182,54 +158,20 @@ fn stale_composition(app: &mut WordApp, e: &egui::Event, b: &mut Batch) -> bool
fn note_key_state(app: &mut WordApp, e: &egui::Event) {
// Which presses reached the canvas, and the modifiers held with Mod, in event order: Mod
// can go down and up within one frame, leaving the frame's modifiers without it.
if matches!(e, egui::Event::Key { pressed: true, key, .. } if !is_modifier_key(*key))
|| matches!(e, egui::Event::WindowFocused(_) | egui::Event::PointerButton { pressed: true, .. })
{
app.canvas.ignore_next_paste = false;
}
match &e {
egui::Event::ModifiersChanged(m) => {
app.canvas.paste_event_mods = m.command.then_some(*m);
if m.command {
app.canvas.paste_mods = Some(*m);
}
}
egui::Event::Key { key: Key::V | Key::Paste, pressed: true, modifiers, .. } => {
app.canvas.v_pressed = true;
app.canvas.paste_event_mods = modifiers.command.then_some(*modifiers);
}
egui::Event::ModifiersChanged(m) if m.command => app.canvas.paste_mods = Some(*m),
egui::Event::Key { key: Key::V | Key::Paste, pressed: true, .. } => app.canvas.v_pressed = true,
egui::Event::Key { key, pressed: true, modifiers, .. } if !is_modifier_key(*key) => {
app.canvas.paste_mods = modifiers.command.then_some(*modifiers);
// An unrelated key's modifiers mustn't steer a later keyless paste.
app.canvas.paste_event_mods = None;
}
egui::Event::PointerButton { pressed: true, .. } => app.canvas.paste_event_mods = None,
egui::Event::WindowFocused(_) => {
app.canvas.v_pressed = false;
// A V release lost to a focus change must not swallow a later Mod+V's picture.
app.canvas.pasted = false;
app.canvas.paste_mods = None;
app.canvas.paste_event_mods = None;
}
_ => {}
}
}
/// The browser's paste event that follows a Mod+Shift+V that pasted formatting is the same
/// keystroke: ignored before an equation or a picture-file paste can take it (#5616).
/// With no text on the clipboard eframe sends no paste event, so the wait ends at the next key,
/// pointer press or focus change, or after `PASTE_WAIT`.
fn ignored_paste(app: &mut WordApp, e: &egui::Event) -> bool {
if matches!(e, egui::Event::Paste(_)) && std::mem::take(&mut app.canvas.ignore_next_paste) {
// Not a Mod+V with no text either: the release mustn't paste a picture.
app.canvas.pasted = true;
// Its Mod+Shift is used up too, or a later menu-bar paste would read as Keep Text Only.
app.canvas.paste_event_mods = None;
return true;
}
false
}
/// The replacement paired with a refused equation deletion is dropped.
fn drop_refused_replacement(app: &mut WordApp, e: &egui::Event, b: &mut Batch) -> bool {
// The replacement is the event immediately after the refused deletion: one `Commit`,
@@ -567,15 +509,10 @@ fn handle_event(app: &mut WordApp, ctx: &egui::Context, e: egui::Event) {
egui::Event::Ime(egui::ImeEvent::Commit(text)) => ime_commit(app, text),
egui::Event::Paste(t) => {
// Mod+Alt+V arrives as a paste too (the shell reads the clipboard): Paste Special.
// The modifiers held with Mod in event order: Shift may be up by the frame's end.
app.canvas.paste_mods = None;
let m = app.canvas.paste_event_mods.take().unwrap_or_else(|| ctx.input(|i| i.modifiers));
// A browser sends Mod+Shift+V as a paste too: Keep Text Only, as the key does on the
// desktop (#1537). (egui-winit sends that chord as a key, and Shift+Insert has no Mod.)
let m = ctx.input(|i| i.modifiers);
let id = match (m.alt, m.shift) {
(true, true) => "edit.pasteText",
(true, false) => "edit.pasteSpecial",
(false, true) if m.command => "edit.pasteText",
_ => "edit.paste",
};
let _ = app.run(id, json!({"text": t}));
+1 -26
View File
@@ -132,32 +132,7 @@ pub(super) fn dispatch(app: &mut WordApp, key: Key, m: Modifiers) -> bool {
if m.alt && !crate::widgets::enabled(app, spec.id) {
return false;
}
// Mod+Shift+V pastes the formatting Mod+Shift+C (or the Format Painter) picked up; with
// none picked up it pastes the clipboard as text only, as Word for Windows does (#1537,
// #4943). Another key bound to Paste Formatting only pastes formatting.
let id = if spec.id == "edit.pasteFormat" {
let formatting = app.session.painter.is_some() || app.session.copied_format.is_some();
let chord = key == Key::V && m.command && m.shift && !m.alt;
// A browser sends a paste event after that chord (the desktop doesn't): after
// pasting formatting it's ignored; with none, it pastes the text there, once. A
// rebinding to another key makes no paste event.
let paste_follows = chord && app.canvas.paste_event_follows_chord;
app.canvas.ignore_next_paste = formatting && paste_follows;
// Handled from the canvas's key events: its V release (Shift may go up first, so the
// release reads as plain Mod+V) mustn't paste again through the picture hook. Not
// from `global_shortcuts` (canvas unfocused), where no release is ever seen.
if chord && app.canvas.focused {
app.canvas.pasted = true;
}
app.canvas.paste_wait_since = None;
if !formatting && paste_follows {
return true;
}
if !formatting && chord { "edit.pasteText" } else { spec.id }
} else {
spec.id
};
let _ = app.run(id, json!({}));
let _ = app.run(spec.id, json!({}));
return true;
}
let Some(name) = name else { return false };
-259
View File
@@ -133,124 +133,6 @@ fn only_plain_paste_releases_paste_a_clipboard_picture() {
assert!(!is_paste_special_release(Key::V, m(true, true, true)) && !is_paste_special_release(Key::V, m(true, false, false)));
}
/// #1537: a browser sends Mod+Shift+V as a paste event; it pastes text only, in the destination's
/// formatting, though the clipboard also holds bold HTML. Plain Mod+V keeps the HTML's bold.
#[test]
fn a_mod_shift_paste_event_keeps_text_only() {
for (modifiers, bold) in [(Modifiers::COMMAND | Modifiers::SHIFT, false), (Modifiers::COMMAND, true)] {
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let ctx = egui::Context::default();
mods_frame(&ctx, &mut a, modifiers, vec![egui::Event::Paste("external".into())]);
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "external", "{modifiers:?}");
let state = a.session.run("format.state", &json!({})).unwrap();
assert_eq!(state.get("bold").and_then(serde_json::Value::as_bool) == Some(true), bold, "{modifiers:?}: {state}");
}
}
/// #5616: a browser sends Mod+Shift+V as its key and then a paste event. After Mod+Shift+C the
/// key pastes the formatting and the paste event that follows doesn't replace the text; a later
/// Mod+V still pastes.
#[test]
fn a_paste_event_after_mod_shift_v_pasted_formatting_is_ignored() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.canvas.paste_event_follows_chord = true;
a.run("text.insert", json!({"text": "source target"})).unwrap();
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copyFormat", json!({})).unwrap();
a.run("select.text", json!({"text": "target"})).unwrap();
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord), egui::Event::Paste("clipboard text".into())]);
let body = |a: &WordApp| a.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(body(&a), "source target", "the paste event didn't replace the formatted text");
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(true), "the key pasted the formatting");
mods_frame(&ctx, &mut a, Modifiers::COMMAND, vec![key_event(Key::V, true, Modifiers::COMMAND), egui::Event::Paste("pasted".into())]);
assert_eq!(body(&a), "source pasted", "the next Mod+V pastes");
}
/// #5616: on a desktop, Mod+Shift+V with nothing copied pastes the text; releasing Shift before V
/// leaves the V release as plain Mod+V, which mustn't paste a second time through the picture hook.
/// Likewise after pasting copied formatting.
#[test]
fn mod_shift_v_released_shift_first_pastes_once() {
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
let ctrl = Modifiers { shift: false, ..chord };
for formatting in [false, true] {
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let seen = calls.clone();
let services = crate::Services {
clipboard_picture: Some(Box::new(move || {
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
None
})),
..Default::default()
};
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
a.canvas.paste_event_follows_chord = false;
a.canvas.focused = true;
a.run("text.insert", json!({"text": "source target"})).unwrap();
if formatting {
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copyFormat", json!({})).unwrap();
}
// The clipboard holds "source"; "target" is selected.
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("edit.copy", json!({})).unwrap();
a.run("select.text", json!({"text": "target"})).unwrap();
let ctx = egui::Context::default();
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::ShiftLeft, false, ctrl)]);
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
let body = a.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
assert_eq!(body, if formatting { "source target" } else { "source source" }, "formatting={formatting}");
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0, "formatting={formatting}: the release asked for a picture");
// The release used it up: a later plain Mod+V release still pastes a picture.
assert!(!a.canvas.pasted);
}
}
/// #5616: Mod+Shift+V pressed with the canvas unfocused (after a ribbon click) runs through the
/// global shortcuts, and its V release never reaches the canvas: it mustn't leave a paste marked
/// done that swallows the clipboard picture of a later Mod+V.
#[test]
fn a_global_mod_shift_v_leaves_the_next_mod_v_picture_paste_alone() {
let ctx = egui::Context::default();
let mut a = picture_app();
a.canvas.paste_event_follows_chord = false;
a.canvas.focused = false;
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
let events = vec![egui::Event::ModifiersChanged(chord), key_event(Key::V, true, chord)];
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::shortcuts::global_shortcuts(&mut a, ui.ctx()))
.drop_without_applying_deltas();
assert!(!a.canvas.pasted, "no canvas release is coming to use the mark up");
a.canvas.focused = true;
let ctrl = Modifiers { shift: false, ..chord };
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
assert_eq!(pictures(&mut a), 1);
}
/// #5616: Mod+Shift+V pressed, then focus leaves before V is released: the lost release mustn't
/// swallow a later Mod+V's picture.
#[test]
fn a_focus_change_clears_the_mod_shift_v_paste_mark() {
let ctx = egui::Context::default();
let mut a = picture_app();
a.canvas.paste_event_follows_chord = false;
a.canvas.focused = true;
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
assert!(a.canvas.pasted);
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::WindowFocused(false)]);
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::WindowFocused(true)]);
let ctrl = Modifiers { shift: false, ..chord };
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
assert_eq!(pictures(&mut a), 1);
}
/// An empty document whose clipboard holds a 4 × 4 picture.
fn picture_app() -> WordApp {
use crate::paste_picture::ClipboardPicture;
@@ -272,129 +154,6 @@ fn mods_frame(ctx: &egui::Context, a: &mut WordApp, modifiers: Modifiers, events
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| canvas_events(a, ui.ctx())).drop_without_applying_deltas();
}
/// A source word in bold with Copy Formatting picked up, and "target" selected.
fn copied_bold_app() -> WordApp {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("text.insert", json!({"text": "source target"})).unwrap();
a.run("select.text", json!({"text": "source"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copyFormat", json!({})).unwrap();
a.run("select.text", json!({"text": "target"})).unwrap();
a
}
/// #5616: on a desktop no paste event follows Mod+Shift+V's key, so none is swallowed: a later
/// paste (from a menu, say) pastes.
#[test]
fn a_desktop_paste_after_mod_shift_v_is_not_swallowed() {
let mut a = copied_bold_app();
assert!(!a.canvas.paste_event_follows_chord || cfg!(target_arch = "wasm32"));
a.canvas.paste_event_follows_chord = false;
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
assert!(!a.canvas.ignore_next_paste);
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::Paste("later".into())]);
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "source later");
}
/// #5616: a pointer press ends the wait for the browser's paste event, so a later keyless paste
/// (context menu, touch) isn't swallowed.
#[test]
fn a_pointer_press_ends_the_wait_for_the_ignored_paste() {
let mut a = copied_bold_app();
a.canvas.ignore_next_paste = true;
let ctx = egui::Context::default();
let press =
egui::Event::PointerButton { pos: egui::pos2(5.0, 5.0), button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE };
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![press]);
assert!(!a.canvas.ignore_next_paste);
}
/// #5616: the modifiers noted for a paste are used up by it: a later paste with no Mod held
/// keeps the HTML's formatting instead of reading the stale Mod+Shift.
#[test]
fn a_paste_event_uses_up_the_noted_paste_modifiers() {
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let ctx = egui::Context::default();
mods_frame(&ctx, &mut a, Modifiers::COMMAND | Modifiers::SHIFT, vec![egui::Event::Paste("external".into())]);
assert!(a.canvas.paste_mods.is_none());
a.run("select.all", json!({})).unwrap();
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::Paste("external".into())]);
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(true), "the later paste was a plain paste");
}
/// #5616: the dropped browser paste uses up its Mod+Shift, so a later menu-bar paste with no key
/// or pointer press in between isn't read as Keep Text Only.
#[test]
fn the_ignored_paste_uses_up_its_paste_modifiers() {
let mut a = copied_bold_app();
a.canvas.paste_event_follows_chord = true;
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord), egui::Event::Paste("x".into())]);
assert!(!a.canvas.ignore_next_paste);
assert!(a.canvas.paste_event_mods.is_none());
}
/// #5616: with no text on the clipboard the browser sends no paste event after Mod+Shift+V; the
/// wait for it ends, so a later menu-bar paste with no key or pointer press in between pastes.
#[test]
fn a_menu_bar_paste_after_an_unpaired_mod_shift_v_pastes() {
let mut a = copied_bold_app();
a.canvas.paste_event_follows_chord = true;
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
let frame = |a: &mut WordApp, time: f64, events: Vec<egui::Event>| {
ctx.run_ui(egui::RawInput { time: Some(time), events, ..Default::default() }, |ui| canvas_events(a, ui.ctx())).drop_without_applying_deltas();
};
frame(&mut a, 10.0, vec![egui::Event::ModifiersChanged(chord), key_event(Key::V, true, chord)]);
assert!(a.canvas.ignore_next_paste, "the key waits for its paired paste");
// No Mod release reaches the canvas (the menu bar takes it).
frame(&mut a, 10.5, vec![]);
assert!(a.canvas.ignore_next_paste, "still within the wait");
frame(&mut a, 12.0, vec![]);
assert!(!a.canvas.ignore_next_paste, "the wait is over");
assert!(a.canvas.paste_event_mods.is_none(), "the chord's Mod+Shift is used up");
frame(&mut a, 12.1, vec![egui::Event::Paste("menu".into())]);
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "source menu", "the menu-bar paste pasted");
}
/// #5616: the browser paste event after a formatting paste is dropped before an open equation
/// can type it.
#[test]
fn the_ignored_paste_event_never_reaches_an_open_equation() {
let mut a = copied_bold_app();
a.canvas.paste_event_follows_chord = true;
a.run("insert.equation", json!({"linear": "abc"})).unwrap();
a.canvas.ignore_next_paste = true;
let ctx = egui::Context::default();
let before = a.session.math.clone();
mods_frame(&ctx, &mut a, Modifiers::COMMAND, vec![egui::Event::Paste("zzz".into())]);
assert_eq!(a.session.math, before, "the ignored paste typed nothing into the equation");
assert!(!a.canvas.ignore_next_paste);
}
/// #5616: only Mod+Shift+V leaves a browser paste event; Paste Formatting on another key neither
/// arms the ignore flag nor waits for a paste.
#[test]
fn paste_formatting_on_another_key_leaves_no_paste_to_ignore() {
for formatting in [true, false] {
let mut a = if formatting {
copied_bold_app()
} else {
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default())
};
a.canvas.paste_event_follows_chord = true;
a.session.keymap = wordcraft_engine::keymap::KeyMap::from_value(&json!({"assigned": {"Mod+Alt+P": "edit.pasteFormat"}}));
let m = Modifiers::COMMAND | Modifiers::ALT;
super::shortcuts::dispatch(&mut a, Key::P, m);
assert!(!a.canvas.ignore_next_paste, "formatting={formatting}");
}
}
/// A press or release of `key` with `modifiers`.
fn key_event(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
@@ -1577,24 +1336,6 @@ fn typing_with_smart_art_selected_types_into_an_item() {
assert_eq!(g.items[0].text, "Ada", "one undo step for the typing");
}
/// #5616: modifiers recorded for an unrelated key (Mod+Shift+C) don't steer a later keyless paste,
/// whether Mod was released or is still held with no change event.
#[test]
fn an_unrelated_keys_modifiers_do_not_steer_a_later_paste() {
for mod_still_held in [false, true] {
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let ctx = egui::Context::default();
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::C, true, chord)]);
// Shift released, Mod still held: Mod+C's chord isn't the paste's modifiers.
let after = if mod_still_held { Modifiers::COMMAND } else { Modifiers::NONE };
mods_frame(&ctx, &mut a, after, vec![egui::Event::Paste("external".into())]);
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(true), "held={mod_still_held}: a plain paste keeps the HTML's bold");
}
}
#[test]
fn delete_previous_sentence_shortcut_dispatches_and_can_be_reassigned() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
-8
View File
@@ -656,9 +656,6 @@ pub struct WordApp {
pub clipboard_published: bool,
pub printing: printing::State,
print_feedback_seen: Option<printing::Feedback>,
/// Which job message is current: bumped when a job starts and whenever the message changes,
/// so a window can tell a new result from one it already said even when the text is the same.
print_gen: u64,
pub canvas: canvas::CanvasState,
/// Content control frames, check boxes and lists on the page.
pub controls: content_controls::ControlUi,
@@ -786,13 +783,8 @@ pub struct WordApp {
/// The document's fonts that aren't installed, for the status bar and the font box, and the
/// layout they were read from.
pub missing_fonts: crate::chrome::MissingFontsMemo,
/// This window's refused or failed export, shown on its Export and Print pages; see [`WordApp::fail_export`].
pub export_error: String,
/// The document's [`StatusCounts`] and the key they were computed for; see [`WordApp::cached_status_counts`].
pub status_counts: (u64, StatusCounts),
/// What this window's Print page knows of the last job's message (the viewport and pass it was
/// last drawn in, and the generations of the result it said and holds back); per window.
print_memo: crate::print_page::Memo,
last_autosave: f64,
/// The tab shown before the Equation tab came up (restored when editing ends).
pub(crate) equation_prev_tab: Option<String>,
+4 -16
View File
@@ -407,15 +407,7 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
let _ = app.run("select.addObject", json!({"pos": object.pos()}));
return true;
}
// While editing a header/footer, a click on its Behind Text picture where no header/footer
// text covers it (the plain hit test picked it: down over the body, or clear of the text in
// the band) selects it, as in Word; only over text does the click defer to that text.
// ponytail: headers/footers only; body Behind Text pictures clear of text could do the same.
let clear_of_text = matches!(object.story, StoryRef::Part(_))
&& crate::canvas::page_at(pages, layout, scale, at)
.and_then(|(page, x, y)| layout.object_at_in(page, x, y, EDGE / scale.max(0.01), object.story))
.is_some_and(|o| o.pos() == object.pos());
if pressed && grab == Grab::Move && object.behind() && !clear_of_text && behind_draggable(app, &object) {
if pressed && grab == Grab::Move && object.behind() && behind_draggable(app, &object) {
let (min, picture) = match app.session.doc.para_at(&object.pos()).and_then(|p| p.object_at(object.pos().off)) {
Some(o) => (wordcraft_engine::cmd::objects::min_size(o), matches!(o, InlineObject::Image { .. })),
None => return false,
@@ -439,8 +431,6 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
let pos = object.pos();
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
// A header/footer picture repeats on every page: select the copy clicked, as `select_at` does.
app.session.page_hint = object.page;
let (min, picture) = match selected(app) {
Some((_, o)) => (wordcraft_engine::cmd::objects::min_size(o), matches!(o, InlineObject::Image { .. })),
None => return true,
@@ -611,8 +601,9 @@ fn link_click(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f32,
/// Right-click at `at`: the picture, shape or text box under it becomes the selection (as a click
/// would, without a drag), so the context menu acts on it. Returns whether there was one.
pub fn select_at(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at: Pos2) -> bool {
// While editing a header/footer, `grab_at` looks at its own objects, so its picture is picked
// too and the menu's Reset Picture or Wrap Text acts on it.
if crate::canvas::editing_header_footer(app, layout) {
return false;
}
let Some((object, _)) = grab_at(app, layout, pages, scale, at) else { return false };
let pos = object.pos();
// Already selected (alone or among several picked for Group): keep the selection.
@@ -620,9 +611,6 @@ pub fn select_at(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
}
// A header/footer picture repeats on every page: its frame belongs on the page clicked, not
// the one last edited.
app.session.page_hint = object.page;
true
}
+16 -95
View File
@@ -170,18 +170,6 @@ fn return_prints(ctx: &egui::Context) -> bool {
})
}
/// Per window: what the Print page needs to know about the last job's message.
#[derive(Default)]
pub struct Memo {
/// The viewport and pass the page was last drawn in: a gap means it was just opened.
pass: Option<(egui::ViewportId, u64)>,
/// The generation (`WordApp::print_gen`) of the job result this window has already said, in
/// its status bar or on this page: a result of the same text from a later job is another one.
pub(crate) said: Option<u64>,
/// The generation of the result held back on this opening of the page.
hidden: Option<u64>,
}
/// The Print page: settings on the left, the preview on the right.
pub fn show(app: &mut WordApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
@@ -190,30 +178,6 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
let total = lay.pages.len();
let current = app.session.current_pages(&lay);
app.ui.print.preview = app.ui.print.preview.min(total.saturating_sub(1));
// Opened afresh, the page doesn't repeat how the last job went when this window already said
// it (its status bar, or this page): `printing.message` itself stays, as `ui.printSettings`
// and other windows still report it. What the printers are doing (finding them, none found)
// always shows. Passes are counted per viewport, so the marker is per window.
let here = (ctx.viewport_id(), ctx.cumulative_pass_nr());
let opened = app.print_memo.pass.is_none_or(|(viewport, last)| viewport != here.0 || last.saturating_add(1) < here.1);
app.print_memo.pass = Some(here);
let result = |m: &Option<crate::printing::Feedback>| {
matches!(m, Some(crate::printing::Feedback::Submitted(_) | crate::printing::Feedback::Failed(_) | crate::printing::Feedback::WorkerStopped))
};
let message = app.printing.message.clone();
let generation = app.print_gen;
if opened {
app.print_memo.hidden = (result(&message) && app.print_memo.said == Some(generation)).then_some(generation);
}
// A later message (a job started again, then failed the same way) is shown afresh.
if app.print_memo.hidden != Some(generation) {
app.print_memo.hidden = None;
}
let hide_message = app.print_memo.hidden.is_some();
if !hide_message {
// Shown here, so the next opening needn't repeat it.
app.print_memo.said = result(&message).then_some(generation);
}
let settings = |app: &mut WordApp, ui: &mut Ui| {
{
@@ -242,7 +206,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
}
if native {
if let Some(discover) = &app.services.printers {
crate::printing::show(&mut app.printing, ui, discover, hide_message, |label| crate::i18n::t(label).to_owned());
crate::printing::show(&mut app.printing, ui, discover, |label| crate::i18n::t(label).to_owned());
}
// A job can wait long on a sleeping printer's driver; Cancel frees the page.
if app.printing.busy() && app.services.cancel_print.is_some() && ui.button(tl!("Cancel printing")).clicked() {
@@ -490,71 +454,28 @@ fn preview(app: &mut WordApp, ui: &mut Ui, lay: &DocLayout) {
/// The export "format" of a Word 2003 XML Document: an `.xml` file saved with `format: "wordml2003"`.
pub(crate) const EXPORT_WORD_2003: &str = "wordml2003";
/// The "save a copy" formats as (label, format), also the built-in browser's types when exporting.
pub(crate) const EXPORT_FORMATS: &[(&str, &str)] = &[
("PDF document (*.pdf)", "pdf"),
("Word document (*.docx)", "docx"),
("Word XML Document (*.xml)", "xml"),
("Word 2003 XML Document (*.xml)", EXPORT_WORD_2003),
("OpenDocument Text (*.odt)", "odt"),
("OpenDocument Text Template (*.ott)", "ott"),
("Flat OpenDocument Text (*.fodt)", "fodt"),
("Rich Text Format (*.rtf)", "rtf"),
("Web page (*.html)", "html"),
("Markdown (*.md)", "md"),
("LaTeX (*.tex)", "tex"),
("Plain text (*.txt)", "txt"),
("Page image (*.png)", "png"),
];
/// The file extension an export format writes.
pub(crate) fn export_file_ext(format: &str) -> &str {
if format == EXPORT_WORD_2003 { "xml" } else { format }
}
/// Is `ext` an extension of a document or export type (the Export types, plus the older `.doc`
/// and `.htm`)? Such an extension on a typed name gives way to the chosen type's; any other
/// (`notes.v2`) is part of the name.
pub(crate) fn is_document_ext(ext: &str) -> bool {
["doc", "htm"].iter().any(|e| e.eq_ignore_ascii_case(ext)) || EXPORT_FORMATS.iter().any(|&(_, f)| export_file_ext(f).eq_ignore_ascii_case(ext))
}
/// The name an export to `format` is saved under: the chosen type's extension replaces a known
/// document extension (`notes.docx` as plain text is `notes.txt`) and is added to any other name.
pub(crate) fn export_name(name: &str, format: &str) -> String {
let want = export_file_ext(format);
let path = std::path::Path::new(name);
// A dotfile name (`.docx`) has no extension for `Path::extension`, which the engine's save also
// reads, so it is a stem and gets one (`.docx.xml`); a bare extension would be refused.
match path.extension().and_then(|e| e.to_str()) {
Some(e) if e.eq_ignore_ascii_case(want) => name.to_string(),
Some(e) if is_document_ext(e) => path.with_extension(want).to_string_lossy().into_owned(),
// `a.` has an empty extension: its dot is dropped before the type's is added.
_ => format!("{}.{want}", name.trim_end_matches('.')),
}
}
/// The "save a copy" formats (File › Export, and below the settings on the Print page).
pub fn export_formats(app: &mut WordApp, ui: &mut Ui) {
// A refused or failed export, said here because Backstage hides the status bar (Export and Print pages both draw this).
if !app.export_error.is_empty() {
ui.label(egui::RichText::new(&app.export_error).color(ui.visuals().error_fg_color));
ui.add_space(6.0);
}
for &(label, ext) in EXPORT_FORMATS {
for (label, ext) in [
("PDF document (*.pdf)", "pdf"),
("Word document (*.docx)", "docx"),
("Word XML Document (*.xml)", "xml"),
("Word 2003 XML Document (*.xml)", EXPORT_WORD_2003),
("OpenDocument Text (*.odt)", "odt"),
("OpenDocument Text Template (*.ott)", "ott"),
("Flat OpenDocument Text (*.fodt)", "fodt"),
("Rich Text Format (*.rtf)", "rtf"),
("Web page (*.html)", "html"),
("Markdown (*.md)", "md"),
("LaTeX (*.tex)", "tex"),
("Plain text (*.txt)", "txt"),
("Page image (*.png)", "png"),
] {
if ui.add(egui::Button::new(egui::RichText::new(tl!(label)).font(medium(13.5))).min_size(vec2(320.0, 34.0))).clicked() {
app.export_dialog(ext);
}
ui.add_space(4.0);
}
// Linux and the BSDs (#3535): WordCraft's own browser when the system dialog doesn't appear.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
{
ui.add_space(8.0);
if ui.add(egui::Button::new(egui::RichText::new(tl!("Browse in WordCraft…")).font(medium(13.5))).min_size(vec2(320.0, 34.0))).clicked() {
let _ = app.run("ui.fileBrowser", json!({"purpose": "export"}));
}
}
}
#[cfg(test)]
+3 -4
View File
@@ -23,8 +23,8 @@ pub fn commands(app: &crate::WordApp) -> Vec<serde_json::Value> {
}
/// Builds translated print labels, draws the shared print-settings panel, and shows the current
/// feedback message (unless `hide_message`: this window has already said it).
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, hide_message: bool, translate: impl Fn(&str) -> String) {
/// feedback message.
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate: impl Fn(&str) -> String) {
let labels = Labels {
printer: &translate("Printer"),
select_printer: &translate("Select a printer"),
@@ -38,7 +38,7 @@ pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, hide_mess
grayscale: &translate("Grayscale"),
};
state.show(ui, egui::Id::unique("wordcraft_print_settings"), discover, &labels);
if let Some(message) = state.message.as_ref().filter(|_| !hide_message) {
if let Some(message) = &state.message {
ui.label(feedback(message, translate));
}
}
@@ -243,7 +243,6 @@ pub fn submit(app: &mut crate::WordApp, params: &serde_json::Value) -> Result<se
}
app.printing.begin(submit(bytes, settings, collate, print_options)).map_err(|_| "A print job is already being submitted.".to_owned())?;
app.print_feedback_seen = None;
app.print_gen = app.print_gen.wrapping_add(1);
} else if let Some(print) = &app.services.print {
print(&bytes)?;
}
+3 -181
View File
@@ -3767,148 +3767,6 @@ fn the_print_button_shows_only_with_a_print_hook() {
}
}
/// A Print page with printers found (so it draws the job message), in English.
fn print_page_harness(message: Option<crate::printing::Feedback>) -> egui_kittest::Harness<'static, WordApp> {
let mut a = app();
a.ui.language = "en".into();
a.services.printers = Some(Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = sender.send(vec![printing::Printer { name: "Test queue".into(), label: String::new(), default: true }]);
receiver
}));
a.services.print_native = Some(Box::new(|_, _, _, _| std::sync::mpsc::channel().1));
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
// The page's first drawing starts discovery, which replaces the message: draw it once, leave,
// and let the printers arrive.
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(4);
let _ = h.state_mut().run("ui.backstage", json!({"value": false}));
h.run_steps(3);
set_print_message(&mut h, message);
h.state_mut().print_memo = Default::default();
h
}
/// A job message that arrives without the app's own `print_feedback` acting on it (a submitted job
/// would close the Print page); what the window has said is set by the test.
fn set_print_message(h: &mut egui_kittest::Harness<'_, WordApp>, message: Option<crate::printing::Feedback>) {
h.state_mut().printing.message = message.clone();
h.state_mut().print_feedback_seen = message;
h.state_mut().print_gen += 1;
}
fn leave_and_reopen_print(h: &mut egui_kittest::Harness<'_, WordApp>) {
let _ = h.state_mut().run("ui.backstage", json!({"value": false}));
h.run_steps(2);
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(3);
}
/// Opened again, the Print page doesn't repeat how the last job went when the window already said
/// it (in its status bar), but a failure that comes in while it is open stays, and what the
/// printers are doing (none found) shows each time. The shared message is never cleared, so
/// `ui.printSettings` still reports it.
#[test]
fn the_print_page_opens_without_the_last_jobs_message() {
use crate::printing::Feedback;
use egui_kittest::kittest::Queryable;
let mut h = print_page_harness(Some(Feedback::Submitted("job 7".into())));
// A job went away earlier: its message was said in this window's status bar, and the page closed.
h.state_mut().print_memo.said = Some(h.state().print_gen);
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(4);
assert!(h.query_by_label_contains("job 7").is_none(), "the last job's message isn't repeated");
assert_eq!(h.state().printing.message, Some(Feedback::Submitted("job 7".into())), "but the shared message stays");
// A failure arrives while the page is open, said (by the status bar) in the very frame, so
// only the page being open keeps it showing: wrong reopen detection would hide it.
let failure = Some(Feedback::Failed("no paper".into()));
set_print_message(&mut h, failure.clone());
h.state_mut().print_memo.said = Some(h.state().print_gen);
h.run_steps(3);
assert!(h.query_by_label_contains("no paper").is_some(), "a failure on the open page stays");
leave_and_reopen_print(&mut h);
assert!(h.query_by_label_contains("no paper").is_none(), "reopened, the failure isn't repeated");
assert_eq!(h.state().printing.message, failure, "but it is still the shared message");
set_print_message(&mut h, Some(Feedback::NoPrinters));
leave_and_reopen_print(&mut h);
assert!(h.query_by_label_contains("No printers found").is_some(), "no printers still shows");
}
/// A retry that fails again with the very same text is a new result: it shows, though the window
/// said the same words for the job before.
#[test]
fn a_retry_that_fails_the_same_way_shows_again() {
use crate::printing::Feedback;
use egui_kittest::kittest::Queryable;
let mut h = print_page_harness(None);
// Every job is refused at once, with the same words.
h.state_mut().services.print_native = Some(Box::new(|_, _, _, _| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = sender.send(Err("no paper".to_owned()));
receiver
}));
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(3);
h.state_mut().run("ui.print", json!({})).unwrap();
h.run_steps(3);
assert_eq!(h.state().printing.message, Some(Feedback::Failed("no paper".into())));
assert!(h.query_by_label_contains("no paper").is_some(), "the first failure shows");
leave_and_reopen_print(&mut h);
assert!(h.query_by_label_contains("no paper").is_none(), "reopened, it isn't repeated");
h.state_mut().run("ui.print", json!({})).unwrap();
h.run_steps(3);
assert_eq!(h.state().printing.message, Some(Feedback::Failed("no paper".into())));
assert!(h.query_by_label_contains("no paper").is_some(), "the same failure of a new job shows");
}
/// A result nobody has said yet isn't dropped: a failure that arrived while File showed another
/// page (so no status bar was drawn) shows when Print opens.
#[test]
fn the_print_page_shows_a_result_that_was_never_said() {
use crate::printing::Feedback;
use egui_kittest::kittest::Queryable;
let mut h = print_page_harness(None);
h.state_mut().ui.backstage = true;
h.state_mut().ui.backstage_page = "home".into();
h.run_steps(2);
// Through the app's own `print_feedback` (run each frame), which says it in a status bar that isn't drawn.
h.state_mut().printing.message = Some(Feedback::Failed("no paper".into()));
h.run_steps(3);
assert_eq!(h.state().print_memo.said, None, "File's home page doesn't say it");
let _ = h.state_mut().run("file.print", json!({}));
h.run_steps(4);
assert!(h.query_by_label_contains("no paper").is_some());
}
/// Per window: what one window has said of the last job isn't another window's, and the shared
/// message is the same in both. (The harness draws one viewport, which re-enters a window of its
/// own, so the per-window state is checked where windows swap; `the_print_page_opens_without_the_last_jobs_message`
/// and `the_print_page_shows_a_result_that_was_never_said` show what each state does on the page.)
#[test]
fn the_print_pages_of_two_windows_decide_separately() {
use crate::printing::Feedback;
let failure = Some(Feedback::Failed("no paper".into()));
let mut a = app();
a.printing.message = failure.clone();
let first = a.windows.shown();
a.print_gen = 1;
a.print_memo.said = Some(a.print_gen);
a.new_window();
assert_ne!(first, a.windows.shown());
assert_eq!(a.print_memo.said, None, "the second window never said it, so its page shows it");
assert_eq!(a.printing.message, failure, "the message is shared, and still there");
assert!(a.enter_window(first));
assert_eq!(a.print_memo.said, Some(1), "the first window said it, so its page doesn't repeat it");
assert_eq!(a.printing.message, failure);
}
/// Return on the Print page prints, as in Word, where ⌘P opens on Print as the default
/// button; the document isn't typed into.
#[test]
@@ -4572,8 +4430,7 @@ fn ctrl_shift_c_and_v_copy_and_paste_formatting_not_text() {
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
h.event(key(egui::Key::C, modifiers));
h.step();
assert!(h.state().session.copied_format.is_some(), "{modifiers:?}: Copy Formatting picked up the selection's formatting");
assert!(h.state().session.painter.is_none(), "{modifiers:?}: Copy Formatting doesn't arm the Format Painter brush");
assert!(h.state().session.painter.is_some(), "{modifiers:?}: Copy Formatting picked up the selection's formatting");
assert_eq!(h.state().session.clip_history.len(), clipboard_entries, "{modifiers:?}: Copy Formatting preserved clipboard history");
assert_eq!(h.state().session.clipboard_text, "plain", "{modifiers:?}: the existing clipboard text was preserved");
assert!(copied(&h).is_empty(), "{modifiers:?}: no text reached the system clipboard: {:?}", copied(&h));
@@ -4584,49 +4441,14 @@ fn ctrl_shift_c_and_v_copy_and_paste_formatting_not_text() {
h.event(key(egui::Key::V, modifiers));
h.step();
assert_eq!(bold(&mut h), Some(true), "{modifiers:?}: Paste Formatting made the target bold");
assert!(h.state().session.copied_format.is_some(), "{modifiers:?}: copied formatting stays for the next Paste Formatting");
// Pasted again, as in Word: formatting again, never the clipboard's text (#5616).
h.state_mut().run("caret.docEnd", json!({})).unwrap();
h.state_mut().run("text.insert", json!({"text": " more"})).unwrap();
h.state_mut().run("select.text", json!({"text": "more"})).unwrap();
// It types on in the pasted bold: make it plain first.
h.state_mut().run("format.bold", json!({})).unwrap();
assert_eq!(bold(&mut h), Some(false));
h.event(key(egui::Key::V, modifiers));
h.step();
assert_eq!(bold(&mut h), Some(true), "{modifiers:?}: a second Paste Formatting made the next target bold");
assert_eq!(body_text(h.state()), "Bold plain more", "{modifiers:?}: the second paste left the text alone");
assert!(h.state().session.painter.is_none(), "{modifiers:?}: the non-sticky painter is used up");
assert_eq!(body_text(h.state()), "Bold plain", "{modifiers:?}: pasting formatting left the document text alone");
assert_eq!(h.state().session.clip_history.len(), clipboard_entries, "{modifiers:?}: Paste Formatting preserved clipboard history");
assert_eq!(h.state().session.clipboard_text, "plain", "{modifiers:?}: Paste Formatting preserved the clipboard text");
assert!(copied(&h).is_empty(), "{modifiers:?}: pasting formatting put no text on the system clipboard: {:?}", copied(&h));
}
}
/// #1537/#4943: with no formatting picked up, Ctrl/Cmd+Shift+V pastes the clipboard as text
/// only (Word for Windows): the text arrives in the destination's formatting, not the source's.
#[test]
fn ctrl_shift_v_without_copied_formatting_pastes_text_only() {
let mut a = app();
a.run("text.insert", json!({"text": "Bold plain"})).unwrap();
a.run("select.text", json!({"text": "Bold"})).unwrap();
a.run("format.bold", json!({})).unwrap();
a.run("edit.copy", json!({})).unwrap();
a.run("select.text", json!({"text": "plain"})).unwrap();
// The destination has formatting of its own, so a paste that dropped it would show.
a.run("format.italic", json!({})).unwrap();
assert!(a.session.painter.is_none());
let mut h = harness(a);
h.run_steps(6);
let modifiers = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT;
h.event(egui::Event::Key { key: egui::Key::V, physical_key: None, pressed: true, repeat: false, modifiers });
h.step();
assert_eq!(body_text(h.state()), "Bold Bold", "the clipboard text replaced the selection");
let bold = h.state_mut().run("format.state", json!({})).unwrap().get("bold").and_then(Value::as_bool);
assert_ne!(bold, Some(true), "the pasted text took the destination's formatting, not the copied bold");
let italic = h.state_mut().run("format.state", json!({})).unwrap().get("italic").and_then(Value::as_bool);
assert_eq!(italic, Some(true), "the pasted text kept the destination's italic");
}
/// #1669: with Shift held, Backspace still erases (#707) and Delete cuts the selection, doing
/// nothing without one, as in Word for Windows. (Windows sends Shift+Delete as a Cut; macOS and
/// Linux send the key, which reached no command.)
-1
View File
@@ -27,7 +27,6 @@ pub(crate) use combo::{current_pick, note_hover, set_current_pick, swatch, take_
pub use groups::{command_icon, command_menu, customize_menu_items, group, group_titled, row};
pub use icon_buttons::{
dialog_tabs, icon_button, icon_menu_item, icon_only_button, icon_text_button, icon_text_button_width, icon_text_menu_button, primary_button,
section,
};
#[cfg(test)]
use tooltip::show_hint;
+20 -12
View File
@@ -257,7 +257,7 @@ const ARROW_BORDER: f32 = 1.0;
/// A searching combo's state between frames.
#[derive(Clone, Default)]
struct ComboSearch {
/// The match list is showing (opened via the arrow button or typing in the field).
/// The match list is showing (the user typed since focusing the field).
open: bool,
/// Whether the user has typed or modified the search query.
typed: bool,
@@ -332,16 +332,16 @@ fn consume_arrow_steps(ui: &mut Ui, open: bool, has_focus: bool) -> i32 {
/// - `text`: the current text string in the edit field.
/// - `reveal`: set to `true` when opening or changing search query to scroll the list/highlight into view.
///
/// Clicking the dropdown arrow (`aresp.clicked()`) toggles `s.open`; when opening, it requests focus
/// on `te_id`, resets `typed` and `moved`, sets `*reveal = true`, and selects all text with
/// [`select_all_text`].
/// Clicking the text box (`resp.clicked()`) when the dropdown is closed sets `s.open = true`,
/// `s.typed = false`, `s.moved = false`, `*reveal = true`, and selects all text with [`select_all_text`].
/// Clicking while already open preserves caret positioning for partial edits without re-selecting all text.
/// Gaining focus alone (`resp.gained_focus()` when `!was_open`, such as on Tab navigation) selects all text
/// for typing without opening the 420px dropdown popup, while regaining focus when already open (e.g. after
/// interacting with the popup scrollbar) preserves query text and caret placement without re-selecting all.
/// Clicking the dropdown arrow (`aresp.clicked()`) toggles `s.open`; when opening, it requests focus on `te_id`,
/// resets `typed` and `moved`, sets `*reveal = true`, and selects all text.
/// Changing the text (`resp.changed()`) opens the dropdown with `s.typed = true`, clears `s.highlight`,
/// clears `s.moved`, and sets `*reveal = true`.
/// Gaining focus while closed (`resp.gained_focus() && !was_open`, from an initial click in the field
/// or Tab navigation) selects all text for immediate replacement typing without opening the 420px
/// dropdown popup; subsequent clicks inside the already-focused field and regaining focus while already
/// open (e.g. after interacting with the popup scrollbar) preserve caret placement and query text without
/// re-selecting all.
fn handle_search_interactions(
ui: &mut Ui,
s: &mut ComboSearch,
@@ -352,7 +352,17 @@ fn handle_search_interactions(
reveal: &mut bool,
) {
let was_open = s.open;
if aresp.clicked() {
if resp.clicked() {
if !was_open {
s.open = true;
s.typed = false;
s.moved = false;
*reveal = true;
select_all_text(ui.ctx(), te_id, text);
}
} else if resp.gained_focus() && !was_open {
select_all_text(ui.ctx(), te_id, text);
} else if aresp.clicked() {
if was_open {
s.open = false;
} else {
@@ -369,8 +379,6 @@ fn handle_search_interactions(
s.highlight = None;
s.moved = false;
*reveal = true;
} else if resp.gained_focus() && !was_open {
select_all_text(ui.ctx(), te_id, text);
}
}
@@ -108,41 +108,6 @@ pub fn icon_menu_item(ui: &mut Ui, icon: &str, text: &str, shortcut: &str, min_w
resp
}
/// A dialog section: space above, then a soft rounded panel. The panel
/// holds the heading and, indented under it, the settings. An empty title
/// gives a panel with no heading. A section inside another keeps the fill
/// of its parent and shows only the border.
pub fn section<R>(ui: &mut Ui, title: &str, add: impl FnOnce(&mut Ui) -> R) -> R {
let t = Tokens::get(ui.ctx());
let key = egui::Id::unique("dialog_section_fill");
let parent: Option<Color32> = ui.data(|d| d.get_temp(key));
let fill = parent.unwrap_or_else(|| ui.visuals().window_fill.lerp_to_gamma(t.text, 0.04));
ui.data_mut(|d| d.insert_temp(key, fill));
ui.add_space((f32::from(ui.spacing().window_margin.left) - ui.spacing().item_spacing.y).max(0.0));
let out = egui::Frame::new()
.fill(fill)
.stroke(Stroke::new(1.0, t.border.gamma_multiply(0.6)))
.corner_radius(CornerRadius::same(6))
.inner_margin(egui::Margin::symmetric(10, 8))
.show(ui, |ui| {
ui.set_width(ui.available_width());
if title.is_empty() {
return add(ui);
}
ui.label(egui::RichText::new(title).font(crate::theme::semibold(12.5)));
ui.add_space(2.0);
egui::Frame::new().inner_margin(egui::Margin { left: 12, ..egui::Margin::ZERO }).show(ui, add).inner
})
.inner;
ui.data_mut(|d| match parent {
Some(p) => {
d.insert_temp(key, p);
}
None => d.remove::<Color32>(key),
});
out
}
/// A strip of dialog tabs. The active tab joins the page below it.
/// Returns the index of the tab the user clicked.
pub fn dialog_tabs(ui: &mut Ui, labels: &[String], selected: usize) -> Option<usize> {
+56 -84
View File
@@ -428,134 +428,106 @@ fn clearing_a_font_query_keeps_the_recent_heading_visible() {
}
}
fn font_combo_harness(
id: &'static str,
initial: &str,
fonts: Vec<String>,
recent: Vec<String>,
) -> (egui_kittest::Harness<'static>, std::rc::Rc<std::cell::RefCell<Option<String>>>) {
let picked = std::rc::Rc::new(std::cell::RefCell::new(None));
let current = std::rc::Rc::new(std::cell::RefCell::new(initial.to_string()));
let picked_c = picked.clone();
let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 600.0)).build_ui(move |ui| {
let cur = current.borrow().clone();
if let Some(f) = font_combo_with_recent(ui, id, 150.0, &cur, &fonts, &recent, None) {
*current.borrow_mut() = f.clone();
*picked_c.borrow_mut() = Some(f);
}
});
h.run_steps(2);
(h, picked)
}
fn click_at_separated(h: &mut egui_kittest::Harness<'_>, pos: egui::Pos2) {
h.event(egui::Event::PointerMoved(pos));
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.step();
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
}
/// #6722: clicking on the font text field focuses it and selects all text for immediate
/// replacement typing without opening the 420px dropdown popup; subsequent clicks inside the
/// already-focused field place the caret without re-selecting all; only typing opens the filtered list.
/// #5914: clicking on the font name or dropdown arrow opens the dropdown list with the other fonts
/// (Recently Used Fonts and All Fonts), focuses the field, and selects all text so typing immediately
/// replaces the font name to search for a font, like in Microsoft Word. Also verifies that focus alone
/// (such as on Tab navigation) does not open the 420px dropdown, subsequent clicks preserve cursor placement,
/// and clicking the arrow button toggles the dropdown open and closed.
#[test]
fn clicking_the_font_field_selects_all_without_opening_dropdown() {
fn clicking_the_font_name_or_box_shows_other_fonts_and_selects_all_to_type() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
use std::cell::RefCell;
use std::rc::Rc;
let fonts: Vec<String> = ["Arial", "Courier New", "Georgia", "Times New Roman"].map(String::from).to_vec();
let recent: Vec<String> = ["Courier New"].map(String::from).to_vec();
let (mut h, picked) = font_combo_harness("font_field_test", "Arial", fonts, recent);
let picked = Rc::new(RefCell::new(None));
let current = Rc::new(RefCell::new("Arial".to_string()));
let picked_c = picked.clone();
let current_c = current.clone();
let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 600.0)).build_ui(move |ui| {
let cur = current_c.borrow().clone();
let v = font_combo_with_recent(ui, "font_test", 150.0, &cur, &fonts, &recent, None);
if let Some(f) = v {
*current_c.borrow_mut() = f.clone();
*picked_c.borrow_mut() = Some(f);
}
});
h.run_steps(2);
// Before click: dropdown is closed, font name "Arial" is displayed
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Arial"));
assert!(h.query_by_label("All Fonts").is_none());
// Focus without click (e.g. Tab navigation) selects text without opening the dropdown.
// Focus without click (e.g. keyboard navigation via Tab) selects text but does not open popup
h.get(By::new().role(Role::TextInput)).focus();
h.run_steps(2);
assert!(h.get(By::new().role(Role::TextInput)).is_focused(), "field takes focus on Tab/focus");
assert!(h.query_by_label("All Fonts").is_none(), "focusing without click does not open the 420px dropdown");
// Typing while focused without click replaces the selected text (verifying selection on focus alone)
h.event(egui::Event::Text("g".into()));
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("g"), "typing replaces font name selected on focus alone");
assert!(h.query_by_label("Georgia").is_some(), "typing while focused opens list and filters to matches");
// Cancel out with Escape to restore the initial state
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Arial"));
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes on Escape");
// Click on the unfocused field: focuses and selects all text without opening the dropdown.
// Click on the font name field
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
assert!(h.get(By::new().role(Role::TextInput)).is_focused(), "clicking field focuses it");
assert!(h.query_by_label("Recently Used Fonts").is_none(), "clicking field does not open recently used fonts");
assert!(h.query_by_label("All Fonts").is_none(), "clicking field does not open the dropdown list");
// After click: other fonts show up (Recently Used Fonts and All Fonts)
assert!(h.query_by_label("Recently Used Fonts").is_some(), "recently used fonts should show up on click");
assert!(h.query_by_label("All Fonts").is_some(), "all fonts should show up on click");
// "Courier New" is present in both Recently Used and All Fonts sections
assert_eq!(h.query_all_by_label("Courier New").count(), 2, "the other fonts should show up on click");
assert!(h.query_by_label("Times New Roman").is_some(), "the other fonts should show up on click");
// Typing a letter replaces the selected text and filters the list
h.event(egui::Event::Text("t".into()));
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("t"));
assert!(h.query_by_label("Times New Roman").is_some(), "matching font shows up on typing");
assert!(h.query_by_label("Times New Roman").is_some(), "matching font shows up");
assert_eq!(h.query_all_by_label("Courier New").count(), 0, "non-matching font is filtered out");
// Press Enter to apply the matching font
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(picked.borrow().as_deref(), Some("Times New Roman"));
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes after applying");
assert!(!h.get(By::new().role(Role::TextInput)).is_focused(), "field loses focus after Enter");
// First click selects all without opening; a second click inside the focused field places the
// caret for partial edits instead of re-selecting all. Separate press/release frames match real input.
let field_center = h.get(By::new().role(Role::TextInput)).rect().center();
click_at_separated(&mut h, field_center);
assert!(h.get(By::new().role(Role::TextInput)).is_focused());
assert!(h.query_by_label("All Fonts").is_none(), "first click does not open the dropdown");
click_at_separated(&mut h, field_center);
assert!(h.query_by_label("All Fonts").is_none(), "second click keeps the dropdown closed");
h.event(egui::Event::Text("!".into()));
// Exercise arrow button: clicking the arrow button opens the dropdown, focuses the text edit,
// and selects all text so typing immediately replaces the font name.
let arrow_btn = h.get(By::new().role(Role::Button).label_contains("Font options"));
arrow_btn.click();
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Times New !Roman"));
h.key_press(egui::Key::Backspace);
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Times New Roman"));
assert!(h.query_by_label("Times New Roman").is_some(), "editing the box opens the filtered dropdown");
}
/// #6722: clicking the dropdown arrow opens Recently Used Fonts and All Fonts, focuses the field,
/// and selects all text; clicking inside the field while open preserves caret placement; clicking
/// the arrow again toggles the dropdown closed.
#[test]
fn clicking_the_font_arrow_toggles_dropdown_and_preserves_caret_on_field_click() {
use egui::accesskit::Role;
use egui_kittest::kittest::{By, Queryable};
let fonts: Vec<String> = ["Arial", "Courier New", "Georgia", "Times New Roman"].map(String::from).to_vec();
let recent: Vec<String> = ["Courier New"].map(String::from).to_vec();
let (mut h, _picked) = font_combo_harness("font_arrow_test", "Times New Roman", fonts, recent);
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.run_steps(2);
assert!(h.query_by_label("Recently Used Fonts").is_some(), "recently used fonts show up on arrow click");
assert!(h.query_by_label("All Fonts").is_some(), "all fonts show up on arrow click");
assert_eq!(h.query_all_by_label("Courier New").count(), 2, "the other fonts show up on arrow click");
assert!(h.query_by_label("All Fonts").is_some(), "dropdown opens on arrow click");
assert!(h.get(By::new().role(Role::TextInput)).is_focused(), "text edit has focus after arrow click");
// Clicking the text field while already open preserves caret placement rather than re-selecting all text.
// Clicking the text field while already open preserves caret placement rather than re-selecting all text
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
assert!(h.query_by_label("All Fonts").is_some(), "dropdown remains open on click inside field");
// Typing inserts at the clicked cursor position rather than replacing all text
h.event(egui::Event::Text("!".into()));
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Times New !Roman"));
assert!(egui::Popup::is_any_open(&h.ctx), "dropdown popup stays open even with no matches");
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
// Clicking the arrow button again toggles the dropdown closed
let arrow_btn = h.get(By::new().role(Role::Button).label_contains("Font options"));
arrow_btn.click();
h.run_steps(2);
assert!(!egui::Popup::is_any_open(&h.ctx), "dropdown popup closes on arrow click toggle");
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes on arrow click toggle");
}
@@ -590,10 +562,10 @@ fn uninstalled_current_font_not_in_list_commits_box_text_on_enter_without_replac
h.run_steps(2);
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Calibri"));
// Click dropdown arrow to open the list
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
// Click font name field to open dropdown
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
assert!(h.query_by_label("All Fonts").is_some(), "dropdown opens on arrow click");
assert!(h.query_by_label("All Fonts").is_some(), "dropdown opens on click");
// Press Enter without typing and without moving: commits box text "Calibri", not first recent font
h.key_press(egui::Key::Enter);
@@ -602,9 +574,9 @@ fn uninstalled_current_font_not_in_list_commits_box_text_on_enter_without_replac
assert_eq!(h.get(By::new().role(Role::TextInput)).value().as_deref(), Some("Calibri"));
assert!(h.query_by_label("All Fonts").is_none(), "dropdown closes after Enter");
// Re-open via arrow and move highlight with ArrowDown: now it picks the first font on Enter
// Re-open and move highlight with ArrowDown: now it picks the first font on Enter
*picked.borrow_mut() = None;
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
assert!(h.query_by_label("All Fonts").is_some());
@@ -614,10 +586,10 @@ fn uninstalled_current_font_not_in_list_commits_box_text_on_enter_without_replac
h.run_steps(2);
assert_eq!(picked.borrow().as_deref(), Some("Courier New"), "ArrowDown moves highlight to first available font");
// Re-open via arrow, type partial query "co", lose and regain focus while pointer is over the popup:
// Re-open, type partial query "co", lose and regain focus while pointer is over the popup:
// verify the dropdown stays open and the query is not re-selected.
*picked.borrow_mut() = None;
h.get(By::new().role(Role::Button).label_contains("Font options")).click();
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
h.event(egui::Event::Text("co".into()));
h.run_steps(2);
-10
View File
@@ -39,12 +39,9 @@ pub(crate) struct WindowUi {
pub(crate) seen_full_screen: Option<bool>,
pub(crate) escape_free: bool,
pub(crate) status_counts: (u64, crate::StatusCounts),
pub(crate) print_memo: crate::print_page::Memo,
/// Per window, as each window shows its own layout: one shared list would be read again
/// on every frame of every window.
pub(crate) missing_fonts: crate::chrome::MissingFontsMemo,
/// This window's refused or failed export, shown on its Export and Print pages (Backstage hides the status bar).
pub(crate) export_error: String,
pub(crate) last_autosave: f64,
pub(crate) equation_prev_tab: Option<String>,
pub(crate) smart_art_item: Option<usize>,
@@ -115,9 +112,7 @@ impl WindowUi {
seen_full_screen: None,
escape_free: false,
status_counts: NOT_COUNTED,
print_memo: Default::default(),
missing_fonts: Default::default(),
export_error: String::new(),
last_autosave: 0.0,
equation_prev_tab: None,
smart_art_item: None,
@@ -169,7 +164,6 @@ impl WordApp {
services: _,
printing: _,
print_feedback_seen: _,
print_gen: _,
font_generation: _,
integrated_titlebar: _,
mac_titlebar: _,
@@ -249,9 +243,7 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
@@ -357,9 +349,7 @@ impl WordApp {
seen_full_screen,
escape_free,
status_counts,
print_memo,
missing_fonts,
export_error,
last_autosave,
equation_prev_tab,
smart_art_item,
+1 -1
View File
@@ -84,7 +84,7 @@ let apps move windows, so there Arrange All and Side by Side only resize.
| Method | Params | Result |
|---|---|---|
| `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, capped so a window of at least 900x460 points fits the screen (#4030), a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"\|"export"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576; `export` offers File › Export's formats as its types, #3535), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) |
| `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, capped so a window of at least 900x460 points fits the screen (#4030), a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) |
| `engine.commands` | — | every command: id, label, location, shortcut, params, enabled |
| `document.inspect` | `text?`, `doc?` | blocks (text, style, runs, lists, tables), parts, sections, selection, pages |
| `ui.inspect` | — | UI state, view, dialog, window size, page rects on screen, caret, comment balloons (`balloons`: id + screen rect; `balloon`: the selected one), perf; `windows`: the other windows as the drawn window sees them (`available`, `others`, `sideBySide`, `syncScroll`); `document`: the active document's id; `documents`: the open documents (`id`, `title`, `path`, `dirty`, `active`) |
-1
View File
@@ -198,7 +198,6 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | trivial | Dialog sections improve readability across 13 dialogs; conditional scrolling keeps tall dialogs usable. Ranked gaps and estimates unchanged (#4035, #4038) |
| 2026-11-12 | trivial | Clipboard: a copied picture is published to the system clipboard as PNG, with HTML where the host writes it, and WordCraft's own paste keeps the original fragment; a copy of only shapes stays in WordCraft (#6205). Native external-app paste remains untested. |
| 2026-11-04 | trivial | #4501 refactor regressions restored: per-section header/footer grid, ODT default font, link tooltip (#4683); no ranked gap changed; readiness estimates unchanged |
| 2026-11-08 | trivial | #10 narrowed: a turned inline picture with no recorded effect extent keeps its line to its frame (exchanged near a quarter turn in Word 2013+ layout), cut at the line; gap stays open |
File diff suppressed because one or more lines are too long
+3 -10
View File
File diff suppressed because one or more lines are too long