From 9843e3fb17e44286627b96680550ff0f1147859d Mon Sep 17 00:00:00 2001 From: xianyuli <20537815+xianyuli@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:52:02 +0800 Subject: [PATCH] feat: add readable Unicode previews for properties files Show decoded Unicode escapes in full and split previews, with selection, copying, keyboard navigation, and independent mode preferences. Preserve source text and encoding through preview transitions and saving. Keep save-time cleanup and formatting available for writable sources, and cover read-only files, hex views, reloads, and preview interactions. --- crates/winc-app/src/app.rs | 2 + crates/winc-app/src/app/editor/editing.rs | 22 +- crates/winc-app/src/app/editor/scrollbar.rs | 15 +- crates/winc-app/src/app/input/actions.rs | 30 +- crates/winc-app/src/app/input/context_menu.rs | 2 + .../src/app/input/context_menu/present.rs | 8 + .../src/app/input/context_menu/run.rs | 8 + crates/winc-app/src/app/input/keyboard.rs | 13 + crates/winc-app/src/app/input/mouse/click.rs | 15 +- crates/winc-app/src/app/input/mouse/drag.rs | 7 + crates/winc-app/src/app/input/mouse/target.rs | 31 +- crates/winc-app/src/app/lifecycle/startup.rs | 1 + crates/winc-app/src/app/preview.rs | 12 +- crates/winc-app/src/app/preview/images.rs | 18 +- crates/winc-app/src/app/preview/markdown.rs | 14 +- .../src/app/preview/markdown/scroll.rs | 10 +- crates/winc-app/src/app/preview/properties.rs | 345 +++++++++ .../src/app/preview/properties/selection.rs | 188 +++++ crates/winc-app/src/app/scroll/editor.rs | 30 + crates/winc-app/src/app/scroll/fling.rs | 4 + crates/winc-app/src/app/scroll/target.rs | 13 + crates/winc-app/src/app/snapshot/preview.rs | 2 + .../src/app/snapshot/preview/latex.rs | 4 +- .../src/app/snapshot/preview/properties.rs | 655 ++++++++++++++++++ .../src/app/snapshot/workspace/tabs.rs | 2 +- crates/winc-app/src/app/vim.rs | 1 + crates/winc-app/src/app/workspace/files.rs | 4 +- crates/winc-app/src/layout.rs | 4 + crates/winc-app/src/view/editor.rs | 4 + crates/winc-app/src/view/editor/area.rs | 2 +- crates/winc-app/src/view/editor/picture.rs | 4 + crates/winc-app/src/view/preview.rs | 3 +- .../winc-app/src/view/preview/properties.rs | 103 +++ crates/winc-config/src/state.rs | 12 +- crates/winc-config/src/state/tests.rs | 26 +- crates/winc-editor/src/document.rs | 59 +- crates/winc-editor/src/document/disk.rs | 10 +- .../winc-editor/src/document/disk/save_job.rs | 4 +- .../winc-editor/src/document/indentation.rs | 4 +- crates/winc-editor/src/document/preview.rs | 59 +- crates/winc-editor/src/document/tests.rs | 167 +++++ crates/winc-editor/src/tests.rs | 21 + crates/winc-editor/src/tools/format.rs | 6 +- crates/winc-editor/src/tools/format/tests.rs | 23 + crates/winc-i18n/locales/en-US/preview.ftl | 2 +- crates/winc-i18n/locales/zh-CN/preview.ftl | 2 +- crates/winc-preview/src/lib.rs | 4 +- crates/winc-preview/src/properties.rs | 129 ++++ 48 files changed, 2012 insertions(+), 92 deletions(-) create mode 100644 crates/winc-app/src/app/preview/properties.rs create mode 100644 crates/winc-app/src/app/preview/properties/selection.rs create mode 100644 crates/winc-app/src/app/snapshot/preview/properties.rs create mode 100644 crates/winc-app/src/view/preview/properties.rs create mode 100644 crates/winc-preview/src/properties.rs diff --git a/crates/winc-app/src/app.rs b/crates/winc-app/src/app.rs index b408f0f6..dbefe7fa 100644 --- a/crates/winc-app/src/app.rs +++ b/crates/winc-app/src/app.rs @@ -718,6 +718,8 @@ enum Drag { Hex, /// 在 Markdown 预览中拖选文字(`App::drag_markdown`)。 MarkdownText, + /// 在 Properties 预览中拖选解码后的文字。 + PropertiesText, /// 拖动预览中图片的把手调整大小(`App::drag_image_resize`)。 ImageResize, /// 在表格中拖选单元格(`App::drag_table`)。 diff --git a/crates/winc-app/src/app/editor/editing.rs b/crates/winc-app/src/app/editor/editing.rs index d05be200..d37c47eb 100644 --- a/crates/winc-app/src/app/editor/editing.rs +++ b/crates/winc-app/src/app/editor/editing.rs @@ -470,6 +470,23 @@ impl App { /// 复制选区(`cut` 为 `true` 时剪切);没有选区时操作光标所在的整行。 pub(in crate::app) fn copy(&mut self, cut: bool) { + if self.properties_focused() { + // 与其他只读文字预览相同,剪切只复制,不修改源文档。 + if self.properties_has_selection() { + if let Some(text) = self.properties_selected_text() { + if !text.is_empty() { + self.set_clipboard(text, false); + self.flash(t!("editor-selection-copied")); + } + } else { + self.flash(t!( + "editor-selection-too-large-to-copy", + size = COPY_LIMIT >> 20 + )); + } + } + return; + } // 十六进制视图:复制选中的字节,写成十六进制;只读,不能剪切。 if self.hex_active() { if !cut { @@ -611,7 +628,7 @@ impl App { self.edit_field(|field| field.insert(&content)); } } - Focus::Editor => self.paste_into_editor(), + Focus::Editor if !self.properties_focused() => self.paste_into_editor(), Focus::Tree => self.paste_into_tree(), Focus::Terminal => self.terminal_paste(), _ => {} @@ -645,6 +662,9 @@ impl App { /// /// 文档不可编辑时在状态栏提示原因,不执行命令。 pub(in crate::app) fn run(&mut self, command: Command) { + if self.properties_focused() { + return; + } let page = self.page_lines(); let tab_width = self.editor.active_tab_width(); let lines_before = self.line_count(); diff --git a/crates/winc-app/src/app/editor/scrollbar.rs b/crates/winc-app/src/app/editor/scrollbar.rs index c444ab83..ba6dc56f 100644 --- a/crates/winc-app/src/app/editor/scrollbar.rs +++ b/crates/winc-app/src/app/editor/scrollbar.rs @@ -61,13 +61,17 @@ pub(crate) enum ScrollArea { Table, /// 表格预览的水平滚动条。 TableHorizontal, + /// Properties 预览的竖直滚动条。 + Properties, + /// Properties 预览的水平滚动条。 + PropertiesHorizontal, /// 链接地址和写作命令的补全列表。 Suggest, } impl ScrollArea { /// 全部区域,遍历时用。 - const ALL: [ScrollArea; 20] = [ + const ALL: [ScrollArea; 22] = [ ScrollArea::Editor, ScrollArea::EditorHorizontal, ScrollArea::DiffLeftHorizontal, @@ -87,6 +91,8 @@ impl ScrollArea { ScrollArea::MarkdownToc, ScrollArea::Table, ScrollArea::TableHorizontal, + ScrollArea::Properties, + ScrollArea::PropertiesHorizontal, ScrollArea::Suggest, ]; @@ -112,6 +118,8 @@ impl ScrollArea { ScrollArea::MarkdownToc => Some(Scrollbar::MarkdownToc), ScrollArea::Table => Some(Scrollbar::Table), ScrollArea::TableHorizontal => Some(Scrollbar::TableHorizontal), + ScrollArea::Properties => Some(Scrollbar::Properties), + ScrollArea::PropertiesHorizontal => Some(Scrollbar::PropertiesHorizontal), ScrollArea::Suggest => None, } } @@ -125,6 +133,7 @@ impl ScrollArea { | ScrollArea::TreeHorizontal | ScrollArea::MarkdownTable | ScrollArea::TableHorizontal + | ScrollArea::PropertiesHorizontal ) } } @@ -169,7 +178,7 @@ struct Reveal { } /// 编辑区窗格里的滚动条:拆分后每个窗格各有一份显示状态。 -pub(crate) const PANE_AREAS: [ScrollArea; 11] = [ +pub(crate) const PANE_AREAS: [ScrollArea; 13] = [ ScrollArea::Editor, ScrollArea::EditorHorizontal, ScrollArea::DiffLeftHorizontal, @@ -181,6 +190,8 @@ pub(crate) const PANE_AREAS: [ScrollArea; 11] = [ ScrollArea::MarkdownToc, ScrollArea::Table, ScrollArea::TableHorizontal, + ScrollArea::Properties, + ScrollArea::PropertiesHorizontal, ]; /// 各区域滚动条的显示状态,以及鼠标所在的滚动条。 diff --git a/crates/winc-app/src/app/input/actions.rs b/crates/winc-app/src/app/input/actions.rs index aaa939a5..0bd00f51 100644 --- a/crates/winc-app/src/app/input/actions.rs +++ b/crates/winc-app/src/app/input/actions.rs @@ -9,7 +9,7 @@ use winc_preview::markdown::paragraph::Kind; use super::*; use crate::field::TextField; -use crate::keymap::{Action, Context}; +use crate::keymap::{Action, Context, Group}; use crate::layout::{PanelButton, SearchButton, SettingsPage, SidebarView}; impl App { @@ -23,7 +23,7 @@ impl App { if !self.action_available(action) { return false; } - if action == Copy && self.vim_side_copy() { + if action == Copy && !self.properties_focused() && self.vim_side_copy() { return true; } if let Some(done) = self.diff_edit_action(action) { @@ -70,11 +70,12 @@ impl App { } // Vim 的普通与可视模式下,撤销、重做、复制、剪切、粘贴由 Vim 层按对应的命令执行。 - let vim_keys = if self.vim.is_some() && self.focus == Focus::Editor { - self.vim_equivalent(action) - } else { - None - }; + let vim_keys = + if self.vim.is_some() && self.focus == Focus::Editor && !self.properties_focused() { + self.vim_equivalent(action) + } else { + None + }; match action { ShowCommands => self.toggle_palette(), @@ -207,6 +208,7 @@ impl App { Copy => self.copy(false), Paste => self.paste(), SelectAll if self.markdown_focused() => self.markdown_select_all(), + SelectAll if self.properties_focused() => self.properties_select_all(), SelectAll if self.table_focused() => self.table_select_all(), SelectAll if self.focus == Focus::Tree => { if let Some(ws) = &mut self.editor.workspace { @@ -544,6 +546,20 @@ impl App { /// 命令当前是否可用:属于某个模块的命令只在模块开着时可用。 pub(in crate::app) fn action_available(&self, action: Action) -> bool { + if self.properties_focused() + && !matches!(action, Action::Copy | Action::Cut | Action::SelectAll) + && (action.group() == Group::Edit + || matches!( + action, + Action::FindNext + | Action::FindPrevious + | Action::ReplaceOne + | Action::ReplaceAll + | Action::GitRevertChange + )) + { + return false; + } match action { Action::RunConfiguration if self.editor.root().is_none() => return false, // 编辑提交说明只在日志里可用;其余位置同一个键执行其他命令。 diff --git a/crates/winc-app/src/app/input/context_menu.rs b/crates/winc-app/src/app/input/context_menu.rs index eac540ce..b2e4f555 100644 --- a/crates/winc-app/src/app/input/context_menu.rs +++ b/crates/winc-app/src/app/input/context_menu.rs @@ -937,6 +937,8 @@ pub enum MenuTarget { Editor(DocumentId), /// Markdown 预览(分栏右边,或只看预览时整个编辑区)。 Markdown, + /// Properties 预览中的解码文字。 + Properties(DocumentId), /// 差异标签里的文字:`true` 是右侧(工作区,可以编辑),`false` 是左侧。 Diff(DocumentId, bool), /// 差异标签中两侧的行号栏、逐行追溯一栏。 diff --git a/crates/winc-app/src/app/input/context_menu/present.rs b/crates/winc-app/src/app/input/context_menu/present.rs index f15f503a..49fa9353 100644 --- a/crates/winc-app/src/app/input/context_menu/present.rs +++ b/crates/winc-app/src/app/input/context_menu/present.rs @@ -176,6 +176,8 @@ impl App { MenuTarget::Terminal(block) } else if self.markdown_context_target(x, y) { MenuTarget::Markdown + } else if let Some(id) = self.properties_context_target(x, y) { + MenuTarget::Properties(id) } else if let Some(id) = self.editor_context_target(x, y) { MenuTarget::Editor(id) } else { @@ -301,6 +303,7 @@ impl App { } let id = doc.id; + self.unfocus_properties(); self.focus = Focus::Editor; self.ime.preedit.clear(); Some(id) @@ -517,6 +520,10 @@ impl App { ]); menu } + MenuTarget::Properties(_) => vec![ + MenuEntry::Item(MenuCommand::Copy, self.properties_has_selection()), + MenuEntry::Item(MenuCommand::SelectAll, true), + ], MenuTarget::Markdown => { let mut menu = vec![ MenuEntry::Item(MenuCommand::Copy, self.markdown_selected_text().is_some()), @@ -802,6 +809,7 @@ impl App { | MenuTarget::Diff(..) | MenuTarget::DiffGutter(..) | MenuTarget::Markdown + | MenuTarget::Properties(_) | MenuTarget::LogCommit(_) => Context::Editor, MenuTarget::Terminal(_) | MenuTarget::TerminalTab(_) => Context::Terminal, MenuTarget::SearchResult(..) => Context::Panel, diff --git a/crates/winc-app/src/app/input/context_menu/run.rs b/crates/winc-app/src/app/input/context_menu/run.rs index d192117a..c4308258 100644 --- a/crates/winc-app/src/app/input/context_menu/run.rs +++ b/crates/winc-app/src/app/input/context_menu/run.rs @@ -100,6 +100,14 @@ impl App { } } MenuTarget::Editor(id) => self.run_editor_command(command, id), + MenuTarget::Properties(id) => { + if self.editor.active().map(|doc| doc.id) == Some(id) + && self.properties_focused() + && let Some(action) = command.action() + { + self.run_action(action); + } + } MenuTarget::Markdown => match command { MenuCommand::Cut => self.copy(true), MenuCommand::Copy => self.copy(false), diff --git a/crates/winc-app/src/app/input/keyboard.rs b/crates/winc-app/src/app/input/keyboard.rs index 53ac8352..39666b67 100644 --- a/crates/winc-app/src/app/input/keyboard.rs +++ b/crates/winc-app/src/app/input/keyboard.rs @@ -99,6 +99,7 @@ impl App { // 的按键继续按原有的顺序处理。 // 两步组合键的第二步仍由键位表处理;Vim 没有带 `Alt` 的命令,应用绑定的 `Alt` 组合归应用。 if self.vim.is_some() + && !self.properties_focused() && self.pending_chord.is_none() && !self.alt_shortcut(event, &base) && (self.vim_key_event(event) || self.vim_list_key(&event.logical_key, &base)) @@ -294,6 +295,17 @@ impl App { } return; } + if self.properties_focused() { + if event.logical_key == Key::Named(NamedKey::Escape) { + if self.bars.find.open { + self.close_search(); + } + self.unfocus_properties(); + } else { + self.properties_key(&event.logical_key, cmd); + } + return; + } if self.log_active() { self.log_key(&event.logical_key); return; @@ -1144,6 +1156,7 @@ impl App { pub(in crate::app) fn takes_text(&self) -> bool { match self.focus { Focus::Terminal => self.terminal.tab().is_some_and(|t| t.ended.is_none()), + Focus::Editor if self.properties_focused() => false, Focus::Editor if self .vim_mode() diff --git a/crates/winc-app/src/app/input/mouse/click.rs b/crates/winc-app/src/app/input/mouse/click.rs index 040f0b72..6a9d7681 100644 --- a/crates/winc-app/src/app/input/mouse/click.rs +++ b/crates/winc-app/src/app/input/mouse/click.rs @@ -177,6 +177,13 @@ impl App { self.preview.markdown.focused = false; self.preview.markdown.selection = None; } + if !matches!( + target, + Target::Properties + | Target::Scrollbar(Scrollbar::Properties | Scrollbar::PropertiesHorizontal, _) + ) { + self.unfocus_properties(); + } // 点击的目标由 `target_at` 决定(与悬停同一个顺序);只有点击才有的规则写成前面的 // 分支:快速打开面板开着时点其他位置关掉快速打开面板,正在输入名字时点其他位置 @@ -235,6 +242,7 @@ impl App { Target::MarkdownLink(link) => self.open_markdown_link(link), Target::MarkdownToc(target) => self.press_toc(target), Target::MarkdownText(_) => self.click_markdown(x, y), + Target::Properties => self.click_properties(x, y), Target::ImageHandle => { if let Some(image) = self.image_handle_at(x, y) { self.start_image_resize(image, x); @@ -259,7 +267,12 @@ impl App { } } Target::RulerChange(hunk) => self.go_to_change(hunk), - Target::Scrollbar(bar, grab) => self.grab_scrollbar(bar, grab), + Target::Scrollbar(bar, grab) => { + if matches!(bar, Scrollbar::Properties | Scrollbar::PropertiesHorizontal) { + self.focus_properties(); + } + self.grab_scrollbar(bar, grab); + } Target::Minimap => self.press_minimap(y), Target::Crumb(index) => self.open_crumb_menu(index), Target::Status(item) => self.open_status_menu(item), diff --git a/crates/winc-app/src/app/input/mouse/drag.rs b/crates/winc-app/src/app/input/mouse/drag.rs index af09b7d9..8d2f5934 100644 --- a/crates/winc-app/src/app/input/mouse/drag.rs +++ b/crates/winc-app/src/app/input/mouse/drag.rs @@ -347,6 +347,12 @@ impl App { bar: bar @ (Scrollbar::Table | Scrollbar::TableHorizontal), grab, } => self.drag_table_scrollbar(bar == Scrollbar::TableHorizontal, (x, y), grab), + Drag::Scrollbar { + bar: bar @ (Scrollbar::Properties | Scrollbar::PropertiesHorizontal), + grab, + } => { + self.drag_properties_scrollbar(bar == Scrollbar::PropertiesHorizontal, (x, y), grab) + } Drag::Scrollbar { bar: Scrollbar::PdfStrip, grab, @@ -423,6 +429,7 @@ impl App { Drag::LogText => self.drag_log_text(x, y), Drag::Hex => self.drag_hex(x, y), Drag::MarkdownText => self.drag_markdown(x, y), + Drag::PropertiesText => self.drag_properties(x, y), Drag::ImageResize => self.drag_image_resize(x), Drag::TableCells => self.drag_table(x, y), Drag::Field => { diff --git a/crates/winc-app/src/app/input/mouse/target.rs b/crates/winc-app/src/app/input/mouse/target.rs index c3b5aa67..adee3678 100644 --- a/crates/winc-app/src/app/input/mouse/target.rs +++ b/crates/winc-app/src/app/input/mouse/target.rs @@ -237,7 +237,10 @@ impl App { Target::MarkdownToc(target) => Hover::MarkdownToc(target), Target::MarkdownText(Some(link)) => Hover::MarkdownLinkText(link), Target::ImageHandle => Hover::ImageHandle, - Target::MarkdownText(None) | Target::PdfThumb(_) | Target::Picture => Hover::None, + Target::MarkdownText(None) + | Target::PdfThumb(_) + | Target::Picture + | Target::Properties => Hover::None, Target::PdfTool(tool) => Hover::PdfTool(tool), Target::LatexStatus => Hover::LatexStatus, Target::LatexProblem(line) => Hover::LatexProblem(line), @@ -466,6 +469,9 @@ impl App { None => Target::Terminal, }; } + if self.properties_area_at(x, y) { + return Target::Properties; + } if l.tree.contains(x, y) || self.in_tree_overflow(x, y) { return Target::Tree(self.tree_row_at(y)); } @@ -646,6 +652,21 @@ impl App { } // 预览(分栏时位于右侧,仅预览时占满编辑区)先于编辑区判断,仅预览时两者重叠。 + if self.properties_area_at(x, y) { + let (track, scroll, content) = self.properties_vscrollbar()?; + if x >= track.right() - SCROLLBAR_HIT + && let Some(thumb) = scrollbar_thumb(track, scroll, content) + { + return Some((Scrollbar::Properties, grab(y, thumb.y, thumb.h))); + } + let (track, scroll, content) = self.properties_hscrollbar()?; + if track.contains(x, y) && y >= track.bottom() - SCROLLBAR_HIT { + let thumb = hscrollbar_thumb(track, scroll, content)?; + return Some((Scrollbar::PropertiesHorizontal, grab(x, thumb.x, thumb.w))); + } + return None; + } + let preview = self.preview.markdown.area; // 标题列表覆盖在预览之上,先于预览判断;图钉按钮所在的位置不属于滚动条。 let list = &self.preview.markdown.toc_list; @@ -871,7 +892,11 @@ impl App { || self.over_diff_text(x, y) && x < self.layout.editor.right() - SCROLLBAR_HIT; // 日志详情中可选择的文字上(不含可点击的提交号和文件)显示文本光标。 let in_field = self.field_at(x, y).is_some() - || matches!(self.pointer.drag, Drag::LogText | Drag::MarkdownText) + || matches!( + self.pointer.drag, + Drag::LogText | Drag::MarkdownText | Drag::PropertiesText + ) + || self.properties_area_at(x, y) || (self.preview.markdown.area.contains(x, y) && self.markdown_link_at(x, y).is_none()) || (self.log_active() && crate::layout::hit(&self.hits.log, x, y).is_none() @@ -1018,6 +1043,8 @@ pub(super) enum Target { /// Markdown 预览中可以选择文字的区域;参数为鼠标下的链接(可编辑的预览中单击链接放置 /// 光标,不打开它)。 MarkdownText(Option), + /// Properties 预览的文字区域。 + Properties, /// 可编辑的预览中图片的把手。 ImageHandle, /// 标签,参数为标签下标与是否位于关闭按钮上。 diff --git a/crates/winc-app/src/app/lifecycle/startup.rs b/crates/winc-app/src/app/lifecycle/startup.rs index fc40c527..b85ce6fd 100644 --- a/crates/winc-app/src/app/lifecycle/startup.rs +++ b/crates/winc-app/src/app/lifecycle/startup.rs @@ -114,6 +114,7 @@ impl App { table_layout: Default::default(), split: preview::images::SplitPreview::default(), markdown: preview::markdown::MarkdownPreview::default(), + properties: preview::properties::PropertiesPreview::default(), pdf: preview::pdf::PdfPreview::default(), latex: preview::latex::LatexBuilds::default(), split_share: None, diff --git a/crates/winc-app/src/app/preview.rs b/crates/winc-app/src/app/preview.rs index 9881e513..cf664ee4 100644 --- a/crates/winc-app/src/app/preview.rs +++ b/crates/winc-app/src/app/preview.rs @@ -1,7 +1,8 @@ //! 预览:Markdown(后台解析、滚动、链接和图片)、图片和 SVG(后台解码、分栏预览)、表格(后台 -//! 读取 xlsx、csv)、PDF(渲染线程逐页渲染)、LaTeX(本机的 TeX 编译出 PDF)。 +//! 读取 xlsx、csv)、PDF(渲染线程逐页渲染)、LaTeX(本机的 TeX 编译出 PDF)和 Properties +//! (按可见物理行解码)。 //! -//! 各种预览都在后台线程完成解码、解析和绘制,界面只收结果;排版与绘制在 `view` 模块中完成。 +//! 排版与绘制在 `view` 模块中完成。 use std::path::{Path, PathBuf}; @@ -13,6 +14,7 @@ pub(crate) mod images; pub(crate) mod latex; pub(crate) mod markdown; pub(crate) mod pdf; +pub(crate) mod properties; pub(crate) mod tables; /// 能在浏览器中打开的网页文件的扩展名(小写)。 @@ -53,7 +55,7 @@ impl App { } } -/// 各类预览的状态:图片、表格、分栏、Markdown 与 PDF。 +/// 各类预览的状态。 pub(crate) struct PreviewState { /// 图片预览缩放后的图片缓存。 pub(crate) picture_cache: Option, @@ -69,6 +71,8 @@ pub(crate) struct PreviewState { pub(crate) split: images::SplitPreview, /// Markdown 预览(分栏右侧或仅预览模式)。 pub(crate) markdown: markdown::MarkdownPreview, + /// Properties 预览(分栏右侧或仅预览模式)。 + pub(crate) properties: properties::PropertiesPreview, /// 当前标签的 PDF 预览。 pub(crate) pdf: pdf::PdfPreview, /// LaTeX 文档的编译,各窗格共用。 @@ -87,6 +91,7 @@ pub(crate) struct PanePreview { table_layout: tables::TableLayout, split: images::SplitPreview, markdown: markdown::MarkdownPreview, + properties: properties::PropertiesPreview, pdf: pdf::PdfPreview, } @@ -111,6 +116,7 @@ impl PreviewState { std::mem::swap(&mut self.table_layout, &mut other.table_layout); std::mem::swap(&mut self.split, &mut other.split); std::mem::swap(&mut self.markdown, &mut other.markdown); + std::mem::swap(&mut self.properties, &mut other.properties); std::mem::swap(&mut self.pdf, &mut other.pdf); self.markdown.trade_places(&mut other.markdown); self.pdf.trade_places(&mut other.pdf); diff --git a/crates/winc-app/src/app/preview/images.rs b/crates/winc-app/src/app/preview/images.rs index b14d2f75..adb33ff4 100644 --- a/crates/winc-app/src/app/preview/images.rs +++ b/crates/winc-app/src/app/preview/images.rs @@ -6,8 +6,7 @@ use std::collections::HashSet; use std::sync::{Arc, OnceLock, mpsc}; -use winc_editor::DocumentId; -use winc_editor::{PictureState, PreviewKind, PreviewMode}; +use winc_editor::{Document, DocumentId, PictureState, PreviewKind, PreviewMode}; use winc_preview::image::{self, Picture, Pixels, Source}; use winc_preview::svg; @@ -438,7 +437,14 @@ impl App { pub(in crate::app) fn set_preview_mode(&mut self, mode: PreviewMode) { // 换了显示方式,键盘先回到文字(只看预览时本来就对着预览)。 self.preview.markdown.focused = false; - let top = self.leave_markdown_mode(mode); + if mode == PreviewMode::Preview + && self.bars.find.open + && self.editor.active().is_some_and(Document::is_properties) + { + self.close_search(); + } + let markdown_top = self.leave_markdown_mode(mode).map(f64::from); + let properties_top = self.prepare_properties_mode(mode); let Some(doc) = self.editor.active_mut() else { return; }; @@ -479,9 +485,12 @@ impl App { } self.relayout(); // 从只看预览换回来:文字滚到预览顶上的那一处,不回到换走之前的位置。 - if let Some(line) = top { + if let Some(line) = markdown_top.or(properties_top) { self.scroll_text_to(line); } + if properties_top.is_some() && mode == PreviewMode::Split { + self.remember_properties_source_line(); + } self.request_redraw(); } } @@ -537,6 +546,7 @@ fn preview_key(kind: PreviewKind) -> &'static str { PreviewKind::Markdown => "markdown", PreviewKind::Table => "table", PreviewKind::Latex => "latex", + PreviewKind::Properties => "properties", } } diff --git a/crates/winc-app/src/app/preview/markdown.rs b/crates/winc-app/src/app/preview/markdown.rs index 279ea5c8..bdaced91 100644 --- a/crates/winc-app/src/app/preview/markdown.rs +++ b/crates/winc-app/src/app/preview/markdown.rs @@ -6,6 +6,7 @@ //! (README 中的徽章、截图)在后台用系统的 `curl` 下载到临时目录缓存,关闭联网后显示替代文字。 use crate::app::ScrollTarget; +use crate::app::scroll::editor::{source_row, top_source_line}; use crate::app::scroll::set_scroll_line; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -1272,18 +1273,7 @@ pub(super) fn preview_line(doc: &winc_editor::Document, lines: Option<&LineMap>) /// 返回文字滚动位置的第一个显示行 `doc.scroll_line` 对应的原文行号(小数:自动换行折成 /// 多段的行按段数等分)。 pub(super) fn text_line(doc: &winc_editor::Document) -> f32 { - let row = doc.scroll_line.max(0.0); - let (line, part) = doc.line_and_part(row as usize); - let rows = doc.rows_of(line).max(1) as f64; - line as f32 + ((part as f64 + row.fract()) / rows) as f32 -} - -/// [`text_line`] 的逆运算:返回原文第 `line` 行(小数)对应的显示行。 -fn text_row(doc: &winc_editor::Document, line: f32) -> f64 { - let last = doc.text().line_count().saturating_sub(1); - let whole = (line.max(0.0) as usize).min(last); - let rows = doc.rows_of(whole).max(1) as f64; - doc.row_of(whole) as f64 + f64::from((line - whole as f32).clamp(0.0, 1.0)) * rows + top_source_line(doc) as f32 } /// 网址图片的下载缓存目录,文件名为网址的哈希。 diff --git a/crates/winc-app/src/app/preview/markdown/scroll.rs b/crates/winc-app/src/app/preview/markdown/scroll.rs index b4d45d7c..79cda69e 100644 --- a/crates/winc-app/src/app/preview/markdown/scroll.rs +++ b/crates/winc-app/src/app/preview/markdown/scroll.rs @@ -230,18 +230,10 @@ impl App { return; }; let line = laid.line_of_y(y, doc.text().line_count()); - set_scroll_line(doc, text_row(doc, line).clamp(0.0, max.max(0.0))); + set_scroll_line(doc, source_row(doc, f64::from(line)).clamp(0.0, max)); self.preview.markdown.synced = Some((doc.id, doc.scroll_line, laid.height())); } - /// 滚动文字,使原文第 `line` 行(小数)位于顶部。 - pub(in crate::app) fn scroll_text_to(&mut self, line: f32) { - let max = self.max_scroll_line(); - if let Some(doc) = self.editor.active_mut() { - set_scroll_line(doc, text_row(doc, line).clamp(0.0, max.max(0.0))); - } - } - /// 将预览滚动到文字顶端那一行对应的位置;仅在刚切换为只显示预览后执行一次。 /// /// 位置的计算使用分栏同步滚动的映射。 diff --git a/crates/winc-app/src/app/preview/properties.rs b/crates/winc-app/src/app/preview/properties.rs new file mode 100644 index 00000000..82fce543 --- /dev/null +++ b/crates/winc-app/src/app/preview/properties.rs @@ -0,0 +1,345 @@ +//! Properties 预览的位置和输入。滚动按物理行计,与源代码的折叠、自动换行无关。 + +use std::ops::Range; + +use winc_core::Lines; +use winc_core::text::{MAX_LINE_CHARS, text_cells}; +use winc_editor::{Document, DocumentId, PreviewMode}; +use winc_render::Rect; +use winit::keyboard::{Key, NamedKey}; + +use crate::app::scroll::editor::top_source_line; +use crate::app::{App, Focus}; +use crate::layout::{ + drawn_scroll_line, editor_content_height, editor_max_scroll, hscrollbar_thumb, + scroll_for_thumb, scrollbar_thumb, +}; +use crate::theme::{SCROLLBAR_HIT, TEXT_PAD}; + +mod selection; + +#[derive(Default)] +pub(crate) struct PropertiesPreview { + doc: Option, + revision: Option, + /// 解码后的(物理行,字符列);行数处的位置表示完整文档末尾。 + selection: Option<((usize, usize), (usize, usize))>, + /// 顶部物理行,可为小数。 + pub(crate) top_line: f64, + pub(crate) scroll_x: f32, + pub(crate) max_scroll_x: f32, + /// 最近同步的源代码位置;源代码再次滚动时才带动预览。 + source_line: Option, + pub(in crate::app) focused: bool, + visible: Option, +} + +struct VisibleLines { + revision: u64, + tab_width: usize, + range: Range, + rows: Vec>, + widest: usize, +} + +impl PropertiesPreview { + pub(crate) fn lines(&self) -> impl Iterator { + self.visible + .iter() + .flat_map(|view| view.range.clone().zip(view.rows.iter().map(Vec::as_slice))) + } +} + +impl App { + /// 当前 Properties 预览的区域。分栏在空间不足时只显示源代码。 + pub(crate) fn properties_area(&self) -> Option { + let doc = self.editor.active()?; + if !doc.is_properties() { + return None; + } + let area = match doc.preview_mode() { + PreviewMode::Source => return None, + PreviewMode::Split => self.layout.split, + PreviewMode::Preview => self.layout.editor, + }; + (area.w > 0.0 && area.h > 0.0).then_some(area) + } + + /// 位置 (`x`, `y`) 是否落在 Properties 预览中。 + pub(crate) fn properties_area_at(&self, x: f32, y: f32) -> bool { + self.properties_area() + .is_some_and(|area| area.contains(x, y)) + } + + /// 只看预览时总是把编辑区的输入交给预览;分栏时由最近点击的一侧决定。 + pub(crate) fn properties_focused(&self) -> bool { + self.focus == Focus::Editor + && self.properties_area().is_some() + && self.editor.active().is_some_and(|doc| { + doc.preview_mode() == PreviewMode::Preview + || (self.preview.properties.doc == Some(doc.id) + && self.preview.properties.focused) + }) + } + + /// 在切换模式前记录原来的顶部行。进入预览时使用当前分栏位置或源代码位置, + /// 离开预览时在重新布局源代码后恢复对应的行。 + pub(super) fn prepare_properties_mode(&mut self, mode: PreviewMode) -> Option { + let doc = self.editor.active()?; + let old = doc.preview_mode(); + if old == mode || !doc.is_properties() { + return None; + } + self.settle_editor_glide(); + // 分栏可能因窗口太窄而隐藏,这时没有可沿用或可同步的预览位置。 + let pane_visible = self.properties_area().is_some(); + if pane_visible { + self.prepare_properties(); + } + let doc = self.editor.active()?; + let view = &mut self.preview.properties; + view.focused = false; + view.selection = None; + if old == PreviewMode::Preview { + return Some(view.top_line); + } + let top = top_source_line(doc); + // 从源代码进入分栏或只看预览:右侧跟着左侧当前的阅读位置开始。分栏可见时切到只看 + // 预览沿用分栏已有的位置(上面已经同步过),不重置;分栏因空间不足隐藏时没有可沿用 + // 的位置,同样从源码开始。 + if old == PreviewMode::Source || !pane_visible { + view.show(doc.id, top); + } + view.source_line = Some(top); + None + } + + /// 记下预览带动的源代码位置。折叠处的源代码视口可能比预览提前几行。 + pub(super) fn remember_properties_source_line(&mut self) { + self.preview.properties.source_line = self.editor.active().map(top_source_line); + } + + /// 将位置限制在当前视口内,缓存本屏解码后的行和字宽,供绘制与鼠标共用。 + pub(crate) fn prepare_properties(&mut self) { + let (Some(area), Some(doc)) = (self.properties_area(), self.editor.active()) else { + return; + }; + let lh = self.fonts.line_height; + let lines = doc.text().line_count(); + let max = editor_max_scroll(lines, area.h, lh); + let top = top_source_line(doc); + let view = &mut self.preview.properties; + if view.doc != Some(doc.id) { + view.show(doc.id, top); + } + if view.revision != Some(doc.revision) { + view.revision = Some(doc.revision); + view.selection = None; + } + if view.source_line != Some(top) { + view.top_line = top; + view.source_line = Some(top); + } + view.top_line = view.top_line.clamp(0.0, max); + let scroll = drawn_scroll_line(view.top_line, lh); + let first = scroll.floor() as usize; + let last = (scroll + f64::from(area.h / lh)).ceil() as usize; + let range = first..last.min(lines); + let tab_width = doc.tab_width(self.editor.tab_width); + if view.visible.as_ref().is_none_or(|visible| { + visible.revision != doc.revision + || visible.range != range + || visible.tab_width != tab_width + }) { + let rows: Vec> = range + .clone() + .map(|line| decoded_line(doc, line).chars().collect()) + .collect(); + let widest = rows + .iter() + .map(|chars| text_cells(chars.iter().copied(), 0, tab_width)) + .max() + .unwrap_or(0); + view.visible = Some(VisibleLines { + revision: doc.revision, + tab_width, + range, + rows, + widest, + }); + } + let width = view.visible.as_ref().map_or(0, |visible| visible.widest); + let track = horizontal_track(area); + view.max_scroll_x = (width as f32 * self.metrics.cell + 2.0 * TEXT_PAD - track.w).max(0.0); + view.scroll_x = view.scroll_x.clamp(0.0, view.max_scroll_x); + } + + /// 返回 Properties 预览竖直滚动条的轨道、滚动位置与内容高度,单位为逻辑像素。 + pub(crate) fn properties_vscrollbar(&self) -> Option<(Rect, f32, f32)> { + let area = self.properties_ready()?; + let line_count = self.editor.active()?.text().line_count(); + let lh = self.fonts.line_height; + Some(( + area, + (self.preview.properties.top_line * f64::from(lh)) as f32, + editor_content_height(line_count, area.h, lh), + )) + } + + /// 返回 Properties 预览水平滚动条的轨道、滚动位置与内容宽度,单位为逻辑像素。 + pub(crate) fn properties_hscrollbar(&self) -> Option<(Rect, f32, f32)> { + let area = self.properties_ready()?; + let track = horizontal_track(area); + let view = &self.preview.properties; + Some((track, view.scroll_x, track.w + view.max_scroll_x)) + } + + /// 预览已为当前标签准备好时返回它的区域。 + fn properties_ready(&self) -> Option { + let area = self.properties_area()?; + let doc = self.editor.active()?; + (self.preview.properties.doc == Some(doc.id)).then_some(area) + } + + pub(in crate::app) fn drag_properties_scrollbar( + &mut self, + horizontal: bool, + (x, y): (f32, f32), + grab: f32, + ) { + self.prepare_properties(); + let bar = if horizontal { + self.properties_hscrollbar() + } else { + self.properties_vscrollbar() + }; + let Some((track, _, content)) = bar else { + return; + }; + if horizontal { + if let Some(thumb) = hscrollbar_thumb(track, 0.0, content) { + self.preview.properties.scroll_x = + scroll_for_thumb(track.x, track.w, thumb.w, x, grab, content - track.w); + } + } else if let Some(thumb) = scrollbar_thumb(track, 0.0, content) { + let y = scroll_for_thumb(track.y, track.h, thumb.h, y, grab, content - track.h); + self.scroll_properties_to(f64::from(y) / f64::from(self.fonts.line_height)); + } + self.request_redraw(); + } + + pub(in crate::app) fn scroll_properties_by(&mut self, dx: f32, dy: f32) { + self.settle_editor_glide(); + self.prepare_properties(); + if dx.abs() > dy.abs() { + let view = &mut self.preview.properties; + view.scroll_x = (view.scroll_x - dx).clamp(0.0, view.max_scroll_x); + } else if dy != 0.0 { + let line = self.preview.properties.top_line + - f64::from(dy) / f64::from(self.fonts.line_height); + self.scroll_properties_to(line); + } + } + + /// 预览中的导航键滚动视口,不移动源代码的光标或选区。 + pub(in crate::app) fn properties_key(&mut self, key: &Key, cmd: bool) -> bool { + let Some(area) = self.properties_area().filter(|_| self.properties_focused()) else { + return false; + }; + self.prepare_properties(); + let line = self.preview.properties.top_line; + let page = f64::from((area.h / self.fonts.line_height).floor().max(2.0) - 1.0); + let back = self.pointer.modifiers.shift_key(); + let to = match key { + Key::Named(NamedKey::Home) => 0.0, + Key::Named(NamedKey::End) => f64::MAX, + Key::Named(NamedKey::ArrowUp) if cmd => 0.0, + Key::Named(NamedKey::ArrowDown) if cmd => f64::MAX, + Key::Named(NamedKey::ArrowUp) => line - 1.0, + Key::Named(NamedKey::ArrowDown) => line + 1.0, + Key::Named(NamedKey::PageUp) => line - page, + Key::Named(NamedKey::PageDown) => line + page, + Key::Named(NamedKey::Space) => line + if back { -page } else { page }, + Key::Character(c) if c == " " => line + if back { -page } else { page }, + Key::Named(NamedKey::ArrowLeft | NamedKey::ArrowRight) => { + let right = *key == Key::Named(NamedKey::ArrowRight); + let step = if cmd { + f32::MAX + } else { + self.metrics.cell * 4.0 + }; + self.scroll_properties_by(if right { -step } else { step }, 0.0); + self.request_redraw(); + return true; + } + _ => return false, + }; + self.scroll_properties_to(to); + self.request_redraw(); + true + } + + fn scroll_properties_to(&mut self, line: f64) { + let (Some(area), Some(doc)) = (self.properties_area(), self.editor.active()) else { + return; + }; + let max = editor_max_scroll(doc.text().line_count(), area.h, self.fonts.line_height); + let line = line.clamp(0.0, max); + self.preview.properties.top_line = line; + self.settle_editor_glide(); + self.scroll_text_to(line); + self.remember_properties_source_line(); + self.prepare_properties(); + } + + pub(in crate::app) fn focus_properties(&mut self) { + self.prepare_properties(); + self.preview.properties.focused = true; + self.focus = Focus::Editor; + self.ime.preedit.clear(); + } + + /// 把键盘交回源代码。点击、切换标签等离开预览时调用。 + pub(in crate::app) fn unfocus_properties(&mut self) { + self.preview.properties.focused = false; + self.preview.properties.selection = None; + } +} + +impl PropertiesPreview { + fn show(&mut self, doc: DocumentId, line: f64) { + if self.doc != Some(doc) { + *self = Self { + doc: Some(doc), + ..Self::default() + }; + } + self.top_line = line; + } +} + +fn horizontal_track(area: Rect) -> Rect { + Rect::new(area.x, area.y, (area.w - SCROLLBAR_HIT).max(0.0), area.h) +} + +/// 返回一行的预览文字,按解码后的字符数限制绘制量。 +fn decoded_line(doc: &Document, line: usize) -> String { + // 一个显示字符最多需要两个六字节的 Unicode 转义,额外读一个字符用来判断是否截断。 + const MAX_ENCODED_LINE_BYTES: usize = (MAX_LINE_CHARS + 1) * 12; + let content = doc.text().line_content(line); + let slice = content.slice(); + let prefix = if slice.len_bytes() > MAX_ENCODED_LINE_BYTES { + slice.slice(..slice.byte_to_char(MAX_ENCODED_LINE_BYTES)) + } else { + slice + }; + let mut text = match prefix.as_str() { + Some(text) => winc_preview::properties::decode(text), + None => winc_preview::properties::decode(&prefix.to_string()), + }; + if let Some((end, _)) = text.char_indices().nth(MAX_LINE_CHARS) { + text.truncate(end); + text.push('…'); + } + text +} diff --git a/crates/winc-app/src/app/preview/properties/selection.rs b/crates/winc-app/src/app/preview/properties/selection.rs new file mode 100644 index 00000000..51e229f8 --- /dev/null +++ b/crates/winc-app/src/app/preview/properties/selection.rs @@ -0,0 +1,188 @@ +//! Properties 预览的只读选区。位置属于解码后的行,不写入源文档的选区。 + +use ropey::Rope; +use winc_core::{Lines, movement, text}; +use winc_editor::{COPY_LIMIT, DocumentId}; + +use super::{PropertiesPreview, decoded_line, horizontal_track}; +use crate::app::{App, Drag}; +use crate::layout::drawn_scroll_line; +use crate::theme::TEXT_PAD; + +type Position = (usize, usize); + +impl PropertiesPreview { + /// 按先后顺序返回非空选区的两端。 + pub(crate) fn selection(&self) -> Option<(Position, Position)> { + let (a, b) = self.selection?; + (a != b).then_some((a.min(b), a.max(b))) + } +} + +impl App { + /// 选区是否仍属于当前文档的这一版本。 + pub(in crate::app) fn properties_has_selection(&self) -> bool { + let view = &self.preview.properties; + self.properties_area().is_some() + && self + .editor + .active() + .is_some_and(|doc| view.doc == Some(doc.id) && view.revision == Some(doc.revision)) + && view.selection().is_some() + } + + /// 返回选中的完整解码文字。没有有效选区或超过复制大小上限时返回 `None`。 + /// + /// 绘制行的省略号不属于内容;读取源文档的完整行,保留实际行尾,包括混合行尾。 + pub(crate) fn properties_selected_text(&self) -> Option { + if !self.properties_has_selection() { + return None; + } + let doc = self.editor.active()?; + let ((first, from), (last, to)) = self.preview.properties.selection()?; + let lines = doc.text().line_count(); + let mut selected = String::new(); + for line in first..=last.min(lines - 1) { + let span = doc.text().line_span(line); + let source = doc.text_range(span.start, span.end)?; + let decoded = winc_preview::properties::decode(&source); + let start = if line == first { from } else { 0 }; + let end = if line == last { to } else { usize::MAX }; + let byte_at = |col| { + decoded + .char_indices() + .nth(col) + .map_or(decoded.len(), |(byte, _)| byte) + }; + let part = &decoded[byte_at(start)..byte_at(end)]; + if selected.len() as u64 + part.len() as u64 > COPY_LIMIT { + return None; + } + selected.push_str(part); + } + Some(selected) + } + + /// 全选用文档末尾标记,复制时不受绘制长行的字符上限影响。 + pub(crate) fn properties_select_all(&mut self) { + self.prepare_properties(); + if let Some(doc) = self + .editor + .active() + .filter(|_| self.properties_area().is_some()) + { + self.preview.properties.selection = + (doc.text().end_pos() > 0).then_some(((0, 0), (doc.text().line_count(), 0))); + self.request_redraw(); + } + } + + /// 点击放置选区起点,双击选词,按住 Shift 扩展已有选区。 + pub(in crate::app) fn click_properties(&mut self, x: f32, y: f32) { + self.focus_properties(); + let Some(at) = self.properties_position_at(x, y) else { + return; + }; + let count = self.click_count(x, y); + let shift = self.pointer.modifiers.shift_key(); + let selection = if count >= 2 { + let doc = self.editor.active().unwrap(); + if at.0 < doc.text().line_count() { + let line = Rope::from_str(&decoded_line(doc, at.0)); + let (from, to) = movement::word_at(&line, at.1); + ((at.0, from), (at.0, to.min(text::MAX_LINE_CHARS))) + } else { + (at, at) + } + } else if shift { + ( + self.preview + .properties + .selection + .map_or(at, |(anchor, _)| anchor), + at, + ) + } else { + (at, at) + }; + self.preview.properties.selection = Some(selection); + self.pointer.drag = Drag::PropertiesText; + self.request_redraw(); + } + + /// 拖出预览边缘时滚动,选区始终使用预览自身的坐标。 + pub(in crate::app) fn drag_properties(&mut self, x: f32, y: f32) { + self.prepare_properties(); + if self.preview.properties.selection.is_none() { + self.pointer.drag = Drag::None; + return; + } + let Some(area) = self.properties_area().map(horizontal_track) else { + return; + }; + if y < area.y { + self.scroll_properties_by(0.0, (area.y - y).min(60.0)); + } else if y > area.bottom() { + self.scroll_properties_by(0.0, -(y - area.bottom()).min(60.0)); + } + if x < area.x { + self.scroll_properties_by((area.x - x).min(60.0), 0.0); + } else if x > area.right() { + self.scroll_properties_by(-(x - area.right()).min(60.0), 0.0); + } + self.prepare_properties(); + let x = x.clamp(area.x, area.right().max(area.x)); + let y = y.clamp(area.y, (area.bottom() - 1.0).max(area.y)); + if let Some(at) = self.properties_position_at(x, y) + && let Some((anchor, _)) = self.preview.properties.selection + { + self.preview.properties.selection = Some((anchor, at)); + } + self.request_redraw(); + } + + /// 右键点击预览:取得焦点,保留点中选区,取消点外选区。 + pub(in crate::app) fn properties_context_target( + &mut self, + x: f32, + y: f32, + ) -> Option { + let covered = self.layout.search.contains(x, y) + || (self.bars.goto_input.is_some() && self.prompt_bar().contains(x, y)) + || self.over_corner_card(x, y); + if covered || !self.properties_area_at(x, y) { + return None; + } + self.focus_properties(); + let inside = self.properties_position_at(x, y).is_some_and(|at| { + self.preview + .properties + .selection() + .is_some_and(|(a, b)| (a..=b).contains(&at)) + }); + if !inside { + self.preview.properties.selection = None; + } + self.request_redraw(); + self.editor.active().map(|doc| doc.id) + } + + /// 使用与绘制相同的制表位、组合字符和 emoji 宽度,并吸附到字素边界。 + fn properties_position_at(&self, x: f32, y: f32) -> Option { + let area = self.properties_ready()?; + let doc = self.editor.active()?; + let view = &self.preview.properties; + let scroll = drawn_scroll_line(view.top_line, self.fonts.line_height); + let line = (scroll + f64::from((y - area.y) / self.fonts.line_height)).max(0.0) as usize; + if line >= doc.text().line_count() { + return Some((doc.text().line_count(), 0)); + } + let shown = Rope::from_str(&decoded_line(doc, line)); + let cell = ((x - area.x - TEXT_PAD + view.scroll_x) / self.metrics.cell) + .round() + .max(0.0) as usize; + let col = text::cell_to_col(shown.slice(..), cell, self.editor.active_tab_width()); + let col = movement::snap_to_grapheme(&shown, col.min(text::MAX_LINE_CHARS)); + Some((line, col)) + } +} diff --git a/crates/winc-app/src/app/scroll/editor.rs b/crates/winc-app/src/app/scroll/editor.rs index 1ef123ed..2caa63a1 100644 --- a/crates/winc-app/src/app/scroll/editor.rs +++ b/crates/winc-app/src/app/scroll/editor.rs @@ -70,7 +70,29 @@ impl TopRow { } } +/// 将源代码的顶部显示行换算成物理行号,自动换行折成多段的行按段数等分。 +pub(crate) fn top_source_line(doc: &Document) -> f64 { + let row = doc.scroll_line.max(0.0); + let (line, part) = doc.line_and_part(row as usize); + line as f64 + (part as f64 + row.fract()) / doc.rows_of(line).max(1) as f64 +} + +/// 返回物理行号对应的源代码显示行。折叠内的行映射到折叠处。 +pub(crate) fn source_row(doc: &Document, line: f64) -> f64 { + let last = doc.text().line_count().saturating_sub(1); + let whole = (line.max(0.0) as usize).min(last); + doc.row_of(whole) as f64 + (line - whole as f64).clamp(0.0, 1.0) * doc.rows_of(whole) as f64 +} + impl App { + /// 滚动源代码,使物理行 `line` 位于顶部。 + pub(in crate::app) fn scroll_text_to(&mut self, line: f64) { + let max = self.max_scroll_line(); + if let Some(doc) = self.editor.active_mut() { + set_scroll_line(doc, source_row(doc, line).clamp(0.0, max)); + } + } + /// 返回 `scroll_line` 的最大值(显示行):内容能完整显示时不滚动;否则滚动到底时, /// 最后一行下方留出四成屏高的空白([`OVERSCROLL`](crate::layout::OVERSCROLL))。 pub(in crate::app) fn max_scroll_line(&self) -> f64 { @@ -165,6 +187,14 @@ impl App { /// 上下各留一行余量(顶部有固定行时,留出固定行占用的行数),左右各留 4 个单元格。 /// 选区的任一端处在折叠的块内(查找、转到行、撤销都可能把光标移到折叠处)时,先展开。 pub(in crate::app) fn ensure_caret_visible(&mut self) { + // 只看 Properties 预览时,文档的滚动位置记录阅读位置;隐藏的源代码光标不影响它。 + if self + .editor + .active() + .is_some_and(Document::properties_preview) + { + return; + } let before = self.editor.active().map(|d| d.scroll_line); self.reveal_caret(); if let Some(before) = before { diff --git a/crates/winc-app/src/app/scroll/fling.rs b/crates/winc-app/src/app/scroll/fling.rs index e8e56b85..7e56f4b4 100644 --- a/crates/winc-app/src/app/scroll/fling.rs +++ b/crates/winc-app/src/app/scroll/fling.rs @@ -111,6 +111,10 @@ impl App { f64::from(self.preview.pdf.scroll), f64::from(self.preview.pdf.scroll_x), )), + ScrollTarget::Properties(_) => Some(( + self.preview.properties.top_line, + f64::from(self.preview.properties.scroll_x), + )), _ => self.pane_scroll(target).map(|y| (f64::from(y), 0.0)), } } diff --git a/crates/winc-app/src/app/scroll/target.rs b/crates/winc-app/src/app/scroll/target.rs index 8813b6ba..381b7714 100644 --- a/crates/winc-app/src/app/scroll/target.rs +++ b/crates/winc-app/src/app/scroll/target.rs @@ -54,6 +54,8 @@ pub(crate) enum ScrollTarget { Picture, /// 表格预览。 Table, + /// Properties 预览。 + Properties(DocumentId), /// 编辑区中显示的文档。 Editor(DocumentId), /// 不在任何可滚动的区域上。 @@ -137,6 +139,10 @@ impl App { ScrollTarget::TerminalStrip } else if l.terminal.contains(x, y) { ScrollTarget::Terminal + } else if self.properties_area_at(x, y) + && let Some(doc) = self.editor.active() + { + ScrollTarget::Properties(doc.id) } else if self.preview.markdown.area.contains(x, y) { ScrollTarget::Markdown } else if self.preview.pdf.strip.contains(x, y) { @@ -232,6 +238,13 @@ impl App { ScrollTarget::Pdf => self.scroll_pdf_by(sx, sy), ScrollTarget::Picture => self.scroll_picture_by(sx, sy), ScrollTarget::Table => self.scroll_table(sx, sy, origin), + ScrollTarget::Properties(id) => { + if self.editor.active().is_some_and(|doc| doc.id == id) + && self.properties_area().is_some() + { + self.scroll_properties_by(sx, sy); + } + } ScrollTarget::Editor(id) => self.scroll_editor_by_pixels(id, sx, sy), ScrollTarget::Picker | ScrollTarget::Commit diff --git a/crates/winc-app/src/app/snapshot/preview.rs b/crates/winc-app/src/app/snapshot/preview.rs index 54c60eb0..a436dd23 100644 --- a/crates/winc-app/src/app/snapshot/preview.rs +++ b/crates/winc-app/src/app/snapshot/preview.rs @@ -15,6 +15,7 @@ mod options; mod pdf; #[cfg(any(target_os = "macos", windows))] mod pdf_places; +mod properties; mod reading; mod tables; mod writing; @@ -942,6 +943,7 @@ fn each_kind_of_file_keeps_its_own_preview_mode() { PreviewMode::Source, PreviewMode::Preview, PreviewMode::Source, + PreviewMode::Source, PreviewMode::Source ] ); diff --git a/crates/winc-app/src/app/snapshot/preview/latex.rs b/crates/winc-app/src/app/snapshot/preview/latex.rs index cd09d559..e24eec84 100644 --- a/crates/winc-app/src/app/snapshot/preview/latex.rs +++ b/crates/winc-app/src/app/snapshot/preview/latex.rs @@ -78,7 +78,7 @@ fn latex_previews_read_only_and_scrolls_by_source_lines() { app.set_preview_mode(PreviewMode::Split); settle(&mut app); let line = text.lines().position(|l| l == "\\section{结论}").unwrap(); - app.scroll_text_to(line as f32); + app.scroll_text_to(line as f64); settle(&mut app); let heading = crate::app::preview::markdown::laid::anchor_top(&app, "结论").unwrap(); let scroll = app.preview.markdown.scroll(); @@ -389,7 +389,7 @@ fn real_tex_compiles_and_syncs() { .lines() .position(|l| l.starts_with("Paragraph 25.")) .unwrap(); - app.scroll_text_to(last as f32); + app.scroll_text_to(last as f64); app.advance_previews(); paint(&mut app); let pdf = &app.preview.pdf; diff --git a/crates/winc-app/src/app/snapshot/preview/properties.rs b/crates/winc-app/src/app/snapshot/preview/properties.rs new file mode 100644 index 00000000..7cb7203a --- /dev/null +++ b/crates/winc-app/src/app/snapshot/preview/properties.rs @@ -0,0 +1,655 @@ +//! Properties 预览的测试:三段切换、分栏实时显示、只读预览、滚动和模式记忆。 + +use winc_core::Lines; +use winc_editor::{Command, PreviewKind, PreviewMode}; + +use super::*; + +/// 文件内容:可读的转义、已经是字符的文字、注释、空行和重复的键。 +const SOURCE: &str = "greeting=\\u4F60\\u597D\nfarewell=\\u518D\\u89C1 # \\u6CE8\\u91CA\n\nkey=\\u4E00\nkey=\\u4E8C\nemoji=\\uD83D\\uDE00\nliteral=\\\\u4F60\n"; + +/// 打开写有 [`SOURCE`] 的 `.properties` 文件,等界面画好。 +fn properties(name: &str) -> (App, PathBuf) { + let dir = sample_folder(name); + let path = dir.join("messages_zh.properties"); + std::fs::write(&path, SOURCE).unwrap(); + let mut app = app_with(&path, false); + paint(&mut app); + (app, dir) +} + +/// 点击标签栏上的显示方式,使用与其他预览相同的三段切换。 +fn click_mode(app: &mut App, mode: PreviewMode) { + let [source, split, preview] = crate::layout::preview_segments(app.layout.preview); + let button = match mode { + PreviewMode::Source => source, + PreviewMode::Split => split, + PreviewMode::Preview => preview, + }; + click(app, (button.x + button.w / 2.0, button.y + button.h / 2.0)); + paint(app); +} + +/// 取离屏帧中一行开头的像素。避开窗格边缘、滚动条和顶栏。 +fn row_pixels(app: &App, pane: Rect, row: usize) -> Vec { + let renderer = app.frame.renderer.as_ref().unwrap(); + let image = renderer.image().unwrap(); + let scale = renderer.scale_factor(); + let left = ((pane.x + 8.0) * scale).ceil() as usize; + let right = ((pane.x + pane.w.min(220.0)) * scale) as usize; + let top = ((pane.y + row as f32 * app.fonts.line_height) * scale).ceil() as usize; + let bottom = top + (app.fonts.line_height * scale) as usize; + let stride = image.width as usize; + (top..bottom) + .flat_map(|y| &image.pixels[y * stride + left..y * stride + right]) + .copied() + .collect() +} + +/// 通过平台的标准复制或全选快捷键执行操作。 +fn preview_shortcut(app: &mut App, key: char) -> bool { + use crate::keymap::{KeyCode, Mods, Stroke}; + let mods = if cfg!(target_os = "macos") { + Mods::META + } else { + Mods::CTRL + }; + app.on_shortcut(Stroke { + key: KeyCode::Char(key), + mods, + }) +} + +/// 预览中物理行与显示列交点,使用与文字绘制相同的字体尺寸。 +fn preview_point(app: &App, row: usize, cell: usize) -> (f32, f32) { + let pane = app.properties_area().unwrap(); + ( + pane.x + crate::theme::TEXT_PAD + cell as f32 * app.metrics.cell, + pane.y + (row as f32 + 0.5) * app.fonts.line_height, + ) +} + +#[test] +fn properties_preview_selects_and_copies_decoded_text_with_shortcuts() { + use crate::keymap::Action; + use_vscode_keys(); + + let expected = + "greeting=你好\nfarewell=再见 # 注释\n\nkey=一\nkey=二\nemoji=😀\nliteral=\\\\u4F60\n"; + for mode in [PreviewMode::Preview, PreviewMode::Split] { + let (mut app, dir) = properties(&format!("properties-copy-{mode:?}")); + let original = app.editor.active().unwrap().selection; + click_mode(&mut app, mode); + let origin = preview_point(&app, 0, 0); + click(&mut app, origin); + app.clipboard.copied = Some("unchanged".into()); + assert!(preview_shortcut(&mut app, 'c')); + assert_eq!(app.clipboard.copied.as_deref(), Some("unchanged")); + let revision = app.editor.active().unwrap().revision; + let pane = app.properties_area().unwrap(); + let unselected = row_pixels(&app, pane, 0); + + assert!(preview_shortcut(&mut app, 'a')); + paint(&mut app); + assert_ne!(unselected, row_pixels(&app, pane, 0)); + assert!(preview_shortcut(&mut app, 'c')); + assert_eq!(app.clipboard.copied.as_deref(), Some(expected)); + assert!(preview_shortcut(&mut app, 'x')); + assert_eq!(app.clipboard.copied.as_deref(), Some(expected)); + assert!(app.run_action(Action::ToggleVimMode)); + assert!(preview_shortcut(&mut app, 'c')); + assert_eq!(app.clipboard.copied.as_deref(), Some(expected)); + assert!(!app.action_available(Action::Paste)); + app.run(Command::Insert("unexpected".into())); + + let doc = app.editor.active().unwrap(); + assert_eq!(doc.revision, revision); + assert_eq!(doc.selection, original); + assert!(!doc.is_dirty()); + assert_eq!(doc.text().rope().unwrap().to_string(), SOURCE); + assert_eq!( + std::fs::read_to_string(dir.join("messages_zh.properties")).unwrap(), + SOURCE + ); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[test] +fn properties_preview_drag_selection_and_context_copy_use_display_columns() { + use crate::app::input::context_menu::MenuCommand; + + let (mut app, dir) = properties("properties-drag-copy"); + click_mode(&mut app, PreviewMode::Split); + let start = preview_point(&app, 0, 9); + let end = preview_point(&app, 1, 11); + app.on_mouse_move(start.0, start.1); + app.on_mouse_down(MouseButton::Left); + app.on_mouse_move(end.0, end.1); + app.on_mouse_up(MouseButton::Left); + paint(&mut app); + + let inside = preview_point(&app, 0, 10); + right_click(&mut app, inside); + let commands = menu_commands(&app); + assert!(commands.contains(&(MenuCommand::Copy, true))); + assert!(commands.contains(&(MenuCommand::SelectAll, true))); + app.run_menu_command(MenuCommand::Copy); + assert_eq!(app.clipboard.copied.as_deref(), Some("你好\nfarewell=再")); + right_click(&mut app, inside); + app.run_menu_command(MenuCommand::SelectAll); + right_click(&mut app, inside); + app.run_menu_command(MenuCommand::Copy); + assert!(app.clipboard.copied.as_ref().unwrap().contains("emoji=😀")); + assert_eq!( + app.editor + .active() + .unwrap() + .text() + .rope() + .unwrap() + .to_string(), + SOURCE + ); + click_mode(&mut app, PreviewMode::Preview); + app.notify(NoticeKind::Error, "Test notice"); + paint(&mut app); + let notice = app.hits.notice_card.unwrap(); + assert!(app.properties_area_at(notice.x + notice.w / 2.0, notice.y + notice.h / 2.0)); + assert!( + app.properties_context_target(notice.x + notice.w / 2.0, notice.y + notice.h / 2.0) + .is_none() + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn properties_preview_copy_all_includes_text_beyond_the_render_limit() { + use_vscode_keys(); + let dir = sample_folder("properties-copy-long-line"); + let path = dir.join("long.properties"); + let source = format!("key={}\nnext=\\u597D\n", "\\u4F60".repeat(12_000)); + std::fs::write(&path, &source).unwrap(); + let mut app = app_with(&path, false); + paint(&mut app); + click_mode(&mut app, PreviewMode::Preview); + assert!(preview_shortcut(&mut app, 'a')); + assert!(preview_shortcut(&mut app, 'c')); + assert_eq!( + app.clipboard.copied, + Some(format!("key={}\nnext=好\n", "你".repeat(12_000))) + ); + assert_eq!(std::fs::read_to_string(&path).unwrap(), source); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn properties_preview_selection_handles_tabs_wide_text_and_source_changes() { + use crate::keymap::Action; + use_vscode_keys(); + let dir = sample_folder("properties-copy-columns"); + let path = dir.join("columns.properties"); + let source = "value=\t\\u4F60\\u597D\\uD83D\\uDE00\r\n"; + std::fs::write(&path, source).unwrap(); + let mut app = app_with(&path, false); + paint(&mut app); + click_mode(&mut app, PreviewMode::Split); + let start = preview_point(&app, 0, 8); + let end = preview_point(&app, 0, 14); + app.on_mouse_move(start.0, start.1); + app.on_mouse_down(MouseButton::Left); + app.on_mouse_move(end.0, end.1); + app.on_mouse_up(MouseButton::Left); + assert!(preview_shortcut(&mut app, 'c')); + assert_eq!(app.clipboard.copied.as_deref(), Some("你好😀")); + assert!(preview_shortcut(&mut app, 'a')); + assert!(preview_shortcut(&mut app, 'c')); + assert_eq!(app.clipboard.copied.as_deref(), Some("value=\t你好😀\r\n")); + + // 回到源码一侧修改,旧选区在下一次复制前作废。 + let text = app.layout.text; + let source_at = (text.x + 10.0, text.y + app.fonts.line_height / 2.0); + click(&mut app, source_at); + assert!(app.run_action(Action::SelectAll)); + app.run(Command::Insert("value=\\u4E2D\n".into())); + assert!(app.properties_selected_text().is_none()); + paint(&mut app); + let reader = preview_point(&app, 0, 0); + click(&mut app, reader); + assert!(preview_shortcut(&mut app, 'a')); + assert!(preview_shortcut(&mut app, 'c')); + assert_eq!(app.clipboard.copied.as_deref(), Some("value=中\r\n")); + assert_eq!(std::fs::read_to_string(&path).unwrap(), source); + + click_mode(&mut app, PreviewMode::Source); + assert!(app.run_action(Action::Undo)); + assert_eq!( + app.editor + .active() + .unwrap() + .text() + .rope() + .unwrap() + .to_string(), + source + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 预览显示转义对应的字符,仍是只读的;切回代码后文字、可编辑性和撤销记录都还在,磁盘上的 +/// 文件没有变化。 +#[test] +fn properties_preview_decodes_escapes_and_keeps_the_source() { + let (mut app, dir) = properties("properties-preview"); + let path = dir.join("messages_zh.properties"); + let doc = app.editor.active().unwrap(); + assert_eq!(doc.preview_kind(), Some(PreviewKind::Properties)); + assert_eq!(doc.preview_mode(), PreviewMode::Source); + assert_eq!(app.layout.preview.w, crate::layout::PREVIEW_GROUP_W); + + // 在分栏中改动源码,右侧实际画出的第二行随未保存的修改改变。 + click_mode(&mut app, PreviewMode::Split); + let doc = app.editor.active().unwrap(); + assert_eq!(doc.preview_mode(), PreviewMode::Split); + assert!(doc.shows_text() && !doc.readonly); + assert!(app.layout.split.w > 0.0); + let before = row_pixels(&app, app.layout.split, 1); + app.run_action(crate::keymap::Action::SelectAll); + app.run(Command::Insert( + "greeting=\\u4F60\\u597D\nkey=\\u4E2D\n".into(), + )); + paint(&mut app); + assert!(app.editor.active().unwrap().is_dirty()); + assert_ne!(before, row_pixels(&app, app.layout.split, 1)); + let pane = app.layout.split; + click(&mut app, (pane.x + pane.w / 2.0, pane.y + pane.h / 2.0)); + assert!(!app.action_available(crate::keymap::Action::Paste)); + + // 转义和直接写入的中文在预览中画出相同的字形。 + app.open_search(false); + assert!(app.bars.find.open); + click_mode(&mut app, PreviewMode::Preview); + assert!(!app.bars.find.open); + assert!(!app.action_available(crate::keymap::Action::FindNext)); + let doc = app.editor.active().unwrap(); + assert_eq!(doc.preview_mode(), PreviewMode::Preview); + assert!(doc.readonly && !doc.shows_text()); + let reference = dir.join("decoded.properties"); + std::fs::write(&reference, "greeting=你好\nkey=中\n").unwrap(); + let mut decoded = app_with(&reference, false); + paint(&mut decoded); + decoded.set_preview_mode(PreviewMode::Preview); + paint(&mut decoded); + for row in 0..2 { + let rendered = row_pixels(&app, app.layout.editor, row); + assert!(rendered.iter().any(|pixel| *pixel != rendered[0])); + assert_eq!(rendered, row_pixels(&decoded, decoded.layout.editor, row)); + } + + // 预览是只读的:输入不改变文档(版本号不变;先前的修改仍未保存)。 + let revision = app.editor.active().unwrap().revision; + app.run(Command::Insert("x".into())); + assert_eq!(app.editor.active().unwrap().revision, revision); + // 预览期间磁盘上的文件仍是原文,未保存的修改没有写出去。 + assert_eq!(std::fs::read_to_string(&path).unwrap(), SOURCE); + + // 切回代码恢复可编辑,未保存的修改仍在。 + click_mode(&mut app, PreviewMode::Source); + let doc = app.editor.active().unwrap(); + assert!(doc.shows_text() && !doc.readonly); + assert!(doc.is_dirty()); + assert_eq!( + doc.text().line_content(0).slice().to_string(), + "greeting=\\u4F60\\u597D" + ); + + // 撤销:回到打开时的文字。 + app.run_action(crate::keymap::Action::Undo); + assert!(!app.editor.active().unwrap().is_dirty()); + assert_eq!( + app.editor + .active() + .unwrap() + .text() + .line_content(1) + .slice() + .to_string(), + "farewell=\\u518D\\u89C1 # \\u6CE8\\u91CA" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 分栏和预览按 Properties 种类记忆。窗口恢复时不改变其他种类的首选方式。 +#[test] +fn properties_remembers_its_own_preview_mode() { + let (mut app, dir) = properties("properties-remembered"); + let second = dir.join("other.properties"); + let markdown = dir.join("notes.md"); + std::fs::write(&second, "a=\\u4E00\n").unwrap(); + std::fs::write(&markdown, "# 标题\n").unwrap(); + + app.choose_preview_mode(PreviewMode::Split); + let saved = |app: &App| app.state.preview_modes.get("properties").cloned(); + assert_eq!(saved(&app).as_deref(), Some("split")); + app.editor.preview_defaults[PreviewKind::Properties as usize] = PreviewMode::Source; + app.apply_preview_state(); + assert_eq!( + app.editor.preview_defaults[PreviewKind::Properties as usize], + PreviewMode::Split + ); + + app.open_path(&second); + paint(&mut app); + assert_eq!( + app.editor.active().unwrap().preview_mode(), + PreviewMode::Split + ); + app.choose_preview_mode(PreviewMode::Preview); + assert_eq!(saved(&app).as_deref(), Some("preview")); + // 其他预览种类不受影响。 + app.open_path(&markdown); + paint(&mut app); + assert_eq!( + app.editor.active().unwrap().preview_mode(), + PreviewMode::Source + ); + + // 新窗口按状态恢复:Properties 只看预览,Markdown 仍是源代码。 + app.editor.preview_defaults = [PreviewMode::Source; PreviewKind::ALL.len()]; + app.apply_preview_state(); + assert_eq!( + app.editor.preview_defaults, + [ + PreviewMode::Source, + PreviewMode::Source, + PreviewMode::Source, + PreviewMode::Source, + PreviewMode::Preview + ] + ); + + // 改回代码:状态清空。 + app.open_path(&second); + paint(&mut app); + app.choose_preview_mode(PreviewMode::Source); + assert_eq!(saved(&app), None); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 源码自动换行时,预览按物理行定位。键盘翻页后,切回源码仍在同一行附近。 +#[test] +fn properties_preview_keeps_the_source_line_and_scrolls_with_keys() { + use crate::keymap::{KeyCode, Mods, Stroke}; + use winit::keyboard::{Key, NamedKey}; + + use_vscode_keys(); + let command = if cfg!(target_os = "macos") { + Mods::META + } else { + Mods::CTRL + }; + let toggle = Stroke { + key: KeyCode::Char('v'), + mods: command | Mods::SHIFT, + }; + let dir = sample_folder("properties-wrapped-preview"); + let path = dir.join("long.properties"); + let mut source = format!("long={}\n", "long word ".repeat(400)); + for index in 0..100 { + source.push_str(&format!("key{index}=\\u4F60\\u597D\n")); + } + std::fs::write(&path, source).unwrap(); + let mut app = app_with(&path, false); + app.config.word_wrap = Some(true); + paint(&mut app); + + // 分栏线和左侧滚动条相邻,滑块中心仍然用于滚动源码。 + click_mode(&mut app, PreviewMode::Split); + let track = app.scroll_track(); + let thumb = scrollbar_thumb(track, 0.0, app.content_height()).unwrap(); + assert_eq!( + app.hover_at(thumb.x + thumb.w / 2.0, thumb.y + thumb.h / 2.0), + Hover::Scrollbar(Scrollbar::Editor) + ); + assert_eq!( + app.hover_at(app.layout.split.x - 0.5, thumb.y + thumb.h / 2.0), + Hover::SplitDivider + ); + click_mode(&mut app, PreviewMode::Source); + + let doc = app.editor.active().unwrap(); + let row = doc.row_of(1); + assert!(row > 1); + let selection = doc.selection; + app.set_active_scroll(row as f64); + + assert!(app.on_shortcut(toggle)); + paint(&mut app); + assert_eq!(app.preview.properties.top_line, 1.0); + let pane = app.layout.editor; + click(&mut app, (pane.x + pane.w / 2.0, pane.y + pane.h / 2.0)); + assert!(app.properties_key(&Key::Named(NamedKey::PageDown), false)); + let shown = app.preview.properties.top_line.floor() as usize; + assert!(shown > 1); + + let other = dir.join("other.properties"); + std::fs::write(&other, "key=other\n").unwrap(); + app.open_path(&other); + paint(&mut app); + app.open_path(&path); + paint(&mut app); + assert_eq!(app.preview.properties.top_line.floor() as usize, shown); + + assert!(app.on_shortcut(toggle)); + paint(&mut app); + let doc = app.editor.active().unwrap(); + assert_eq!(doc.line_of_row(doc.scroll_line as usize), shown); + assert_eq!(doc.selection, selection); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 切回代码并滚动后再次打开分栏:右侧预览从左侧当前的阅读行开始,不回到旧位置。 +#[test] +fn reopening_split_starts_the_preview_at_the_source_line() { + let dir = sample_folder("properties-split-reopen"); + let path = dir.join("long.properties"); + std::fs::write(&path, "key=\\u4F60\\u597D\n".repeat(120)).unwrap(); + let mut app = app_with(&path, false); + paint(&mut app); + + click_mode(&mut app, PreviewMode::Split); + click_mode(&mut app, PreviewMode::Source); + app.set_active_scroll(51.0); + paint(&mut app); + click_mode(&mut app, PreviewMode::Split); + assert_eq!(app.preview.properties.top_line.floor() as usize, 51); + assert_eq!(app.properties_area(), Some(app.layout.split)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 分栏因窗口太窄被隐藏后切到预览:从源码当前的阅读行开始,而不是回到旧位置。 +#[test] +fn switching_a_hidden_split_to_preview_keeps_the_source_line() { + use winc_render::Renderer; + + /// 把离屏界面的窗口改为 `size`(逻辑像素)并重新布局。 + fn resize(app: &mut App, size: (f32, f32)) { + let background = app.palette.frame_bg; + let renderer = Renderer::offscreen(size.0, size.1, SCALE, background, None, None).unwrap(); + app.frame.renderer = Some(renderer); + app.relayout(); + app.clamp_scroll(); + } + + let dir = sample_folder("properties-split-hidden"); + let path = dir.join("long.properties"); + std::fs::write(&path, "key=\\u4F60\\u597D\n".repeat(120)).unwrap(); + let mut app = app_with(&path, false); + paint(&mut app); + + click_mode(&mut app, PreviewMode::Split); + assert_eq!(app.properties_area(), Some(app.layout.split)); + // 窗口缩到分栏放不下:右侧预览隐藏,模式仍是分栏。 + resize(&mut app, (640.0, 600.0)); + paint(&mut app); + assert_eq!( + app.editor.active().unwrap().preview_mode(), + PreviewMode::Split + ); + assert!(app.properties_area().is_none()); + assert_eq!(app.layout.split.w, 0.0); + + app.set_active_scroll(51.0); + paint(&mut app); + app.set_preview_mode(PreviewMode::Preview); + paint(&mut app); + assert_eq!(app.preview.properties.top_line.floor() as usize, 51); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 同一行在源码中更宽,预览的横向滚动范围以解码后的文字为准。 +#[test] +fn properties_preview_scrolls_only_as_far_as_the_decoded_text() { + let dir = sample_folder("properties-horizontal-preview"); + let path = dir.join("long.properties"); + let reference = dir.join("decoded.properties"); + // 原文超出编辑器的默认显示上限,解码后的译文仍能整行显示。 + std::fs::write(&path, format!("key={}\n", "\\u4F60".repeat(2_000))).unwrap(); + std::fs::write(&reference, format!("key={}\n", "你".repeat(2_000))).unwrap(); + let mut app = app_with(&path, false); + paint(&mut app); + let source_max = app.text_max_scroll_x(); + assert!(source_max > 0.0); + app.editor.active_mut().unwrap().scroll_x = source_max; + + click_mode(&mut app, PreviewMode::Preview); + let max = app.preview.properties.max_scroll_x; + assert!(max > 0.0 && max < source_max); + let mut decoded = app_with(&reference, false); + paint(&mut decoded); + decoded.set_preview_mode(PreviewMode::Preview); + paint(&mut decoded); + assert_eq!(max, decoded.preview.properties.max_scroll_x); + let pane = app.layout.editor; + let origin = (pane.x + pane.w / 2.0, pane.y + pane.h / 2.0); + let target = app.scroll_target_at(origin.0, origin.1); + app.scroll_target_by(target, origin, false, (-source_max * 2.0, 0.0)); + assert_eq!(app.preview.properties.scroll_x, max); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 同一个文档在多个窗格里共用预览模式,每个窗格沿用自己的阅读位置。 +#[test] +fn properties_preview_aligns_each_pane_after_switching_modes() { + use crate::keymap::Action; + use winit::keyboard::{Key, NamedKey}; + + let dir = sample_folder("properties-pane-preview"); + let path = dir.join("long.properties"); + std::fs::write(&path, "key=\\u4F60\n".repeat(120)).unwrap(); + let mut app = app_with(&path, false); + let left = app.editor.panes.focused; + assert!(app.run_action(Action::SplitRight)); + let right = app.editor.panes.focused; + app.set_preview_mode(PreviewMode::Preview); + paint(&mut app); + assert!(app.properties_key(&Key::Named(NamedKey::PageDown), false)); + assert!(app.preview.properties.top_line > 15.0); + + app.focus_pane(left); + app.set_preview_mode(PreviewMode::Source); + app.with_pane(right, |app| app.set_active_scroll(15.0)); + app.set_preview_mode(PreviewMode::Preview); + paint(&mut app); + assert_eq!(app.preview.properties.top_line, 0.0); + assert_eq!( + app.with_pane(right, |app| app.preview.properties.top_line), + 15.0 + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 拖动分栏分隔线和预览的两条滚动条都能改变各自的滚动位置与宽度。 +#[test] +fn properties_preview_drags_its_scrollbars_and_split_divider() { + use winc_editor::PreviewMode; + use winit::event::MouseButton; + + let dir = sample_folder("properties-drag"); + let path = dir.join("long.properties"); + let mut source = format!("long={}\n", "\\u4F60".repeat(2_000)); + for index in 0..120 { + source.push_str(&format!("key{index}=\\u4F60\\u597D\n")); + } + std::fs::write(&path, source).unwrap(); + let mut app = app_with(&path, false); + paint(&mut app); + + // 分栏:拖动分隔线,预览一侧随之变宽。 + click_mode(&mut app, PreviewMode::Split); + let before = app.layout.split.w; + let divider = app.layout.split_divider; + let (x, y) = (divider.x + divider.w / 2.0, divider.y + divider.h / 2.0); + app.on_mouse_move(x, y); + assert_eq!(app.pointer.hover, Hover::SplitDivider); + app.on_mouse_down(MouseButton::Left); + app.on_mouse_move(x - 60.0, y); + app.on_mouse_up(MouseButton::Left); + paint(&mut app); + assert!(app.layout.split.w > before); + assert_eq!(app.properties_area(), Some(app.layout.split)); + + // 只看预览:先拖动水平滚动条,此时最长的解码行在顶部。 + click_mode(&mut app, PreviewMode::Preview); + let (track, _, content) = app.properties_hscrollbar().unwrap(); + assert!(content > track.w); + assert!(hscrollbar_thumb(track, 0.0, content).is_some()); + let y = track.bottom() - 4.0; + app.on_mouse_move(track.x + 8.0, y); + assert!(matches!( + app.pointer.hover, + Hover::Scrollbar(Scrollbar::PropertiesHorizontal) + )); + app.on_mouse_down(MouseButton::Left); + app.on_mouse_move(track.right(), y); + app.on_mouse_up(MouseButton::Left); + assert!(app.preview.properties.scroll_x > 0.0); + + // 拖动竖直滚动条到底部,顶部行随之移动。 + let (track, _, content) = app.properties_vscrollbar().unwrap(); + let thumb = scrollbar_thumb(track, 0.0, content).unwrap(); + let x = track.right() - 4.0; + app.on_mouse_move(x, thumb.y + thumb.h / 2.0); + assert!(matches!( + app.pointer.hover, + Hover::Scrollbar(Scrollbar::Properties) + )); + app.on_mouse_down(MouseButton::Left); + app.on_mouse_move(x, track.bottom()); + app.on_mouse_up(MouseButton::Left); + assert!(app.preview.properties.top_line > 0.0); + let _ = std::fs::remove_dir_all(&dir); +} + +/// 预览期间关闭有未保存修改的标签并选「保存」:写回源代码的转义写法,而不是预览中显示的 +/// 文字,然后照常关闭。 +#[test] +fn a_previewing_properties_tab_saves_its_source_when_closing() { + let (mut app, dir) = properties("properties-save-in-preview"); + let path = dir.join("messages_zh.properties"); + app.run_action(crate::keymap::Action::SelectAll); + app.run(Command::Insert("greeting=\\u4F60\\u597D\n".into())); + app.set_preview_mode(PreviewMode::Preview); + paint(&mut app); + assert!(app.editor.active().unwrap().readonly); + + app.close_tab(0); + assert!(app.closing.prompt.is_some()); + app.answer_save_prompt(SaveChoice::Save); + assert!(app.editor.documents.is_empty()); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "greeting=\\u4F60\\u597D\n" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/winc-app/src/app/snapshot/workspace/tabs.rs b/crates/winc-app/src/app/snapshot/workspace/tabs.rs index 9c99fc1c..4b179840 100644 --- a/crates/winc-app/src/app/snapshot/workspace/tabs.rs +++ b/crates/winc-app/src/app/snapshot/workspace/tabs.rs @@ -378,7 +378,7 @@ fn svg_opens_as_source_and_toggles_to_a_preview() { app.run_action(Action::TogglePreview); assert_eq!( app.status.message.as_deref(), - Some("仅支持预览 SVG、Markdown、CSV 和 TSV 文件") + Some("仅支持预览 SVG、Markdown、LaTeX、CSV、TSV 和 Properties 文件") ); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/winc-app/src/app/vim.rs b/crates/winc-app/src/app/vim.rs index 9426d2ba..cf6faffc 100644 --- a/crates/winc-app/src/app/vim.rs +++ b/crates/winc-app/src/app/vim.rs @@ -284,6 +284,7 @@ impl App { /// 的一侧。 fn vim_applies(&self) -> bool { self.focus == Focus::Editor + && !self.properties_focused() && (self.vim_document().is_some_and(Document::shows_text) || self.vim_side().is_some()) } diff --git a/crates/winc-app/src/app/workspace/files.rs b/crates/winc-app/src/app/workspace/files.rs index 37978ddc..d0e9197e 100644 --- a/crates/winc-app/src/app/workspace/files.rs +++ b/crates/winc-app/src/app/workspace/files.rs @@ -569,6 +569,7 @@ impl App { if self.editor.active != Some(index) { self.auto_save_active(); + self.unfocus_properties(); } self.editor.active = Some(index); self.load_active_in_background(); @@ -790,8 +791,9 @@ impl App { let Some(doc) = self.editor.document(id) else { continue; }; + // 预览期间的临时只读不阻止保存:与显式保存一致,自动保存写的也是源代码。 let candidate = - doc.is_dirty() && doc.title.is_none() && doc.unwritable_reason().is_none(); + doc.is_dirty() && doc.title.is_none() && doc.save_blocked_reason().is_none(); // 文件已从磁盘上删除:不自动写回,改为提示一次重新创建的方法;文件恢复后被再次删除时 // 重新提示。 if candidate && doc.deleted_on_disk() { diff --git a/crates/winc-app/src/layout.rs b/crates/winc-app/src/layout.rs index b0c046e4..2e3d50bf 100644 --- a/crates/winc-app/src/layout.rs +++ b/crates/winc-app/src/layout.rs @@ -499,6 +499,10 @@ pub enum Scrollbar { Table, /// 表格预览的水平滚动条。 TableHorizontal, + /// Properties 预览的竖直滚动条。 + Properties, + /// Properties 预览的水平滚动条。 + PropertiesHorizontal, /// 设置页(含快捷键列表)的竖直滚动条。 Settings, } diff --git a/crates/winc-app/src/view/editor.rs b/crates/winc-app/src/view/editor.rs index 62e3c1ee..9acdafe9 100644 --- a/crates/winc-app/src/view/editor.rs +++ b/crates/winc-app/src/view/editor.rs @@ -198,6 +198,10 @@ pub(super) fn draw_editor(app: &mut App, frame: &mut Frame<'_>) { return; } let doc = &app.editor.documents[index]; + if doc.properties_preview() { + super::preview::properties::draw(app, frame, app.layout.editor, doc.id); + return; + } if doc .preview_kind() .is_some_and(winc_editor::PreviewKind::typeset) diff --git a/crates/winc-app/src/view/editor/area.rs b/crates/winc-app/src/view/editor/area.rs index a2ac0fe0..41a36ba9 100644 --- a/crates/winc-app/src/view/editor/area.rs +++ b/crates/winc-app/src/view/editor/area.rs @@ -179,7 +179,7 @@ pub(super) fn draw_text_area(app: &mut App, frame: &mut Frame<'_>, index: usize) active_guide: line::active_guide(text, caret_line, &visible, tab_width, indent_unit), columns: columns.as_deref(), language: doc.highlighter.language(), - focused: app.focus == Focus::Editor, + focused: app.focus == Focus::Editor && !app.properties_focused(), show_matches, // 光标所在的词在屏幕上其他位置的出现。查找条打开时只标注查找结果,避免两种底色混杂; // 屏幕上只有该词本身时不标注。 diff --git a/crates/winc-app/src/view/editor/picture.rs b/crates/winc-app/src/view/editor/picture.rs index a3edccdd..1a20478d 100644 --- a/crates/winc-app/src/view/editor/picture.rs +++ b/crates/winc-app/src/view/editor/picture.rs @@ -50,6 +50,10 @@ pub(in crate::view) fn draw_split(app: &mut App, frame: &mut Frame<'_>) { } return; } + if kind == Some(winc_editor::PreviewKind::Properties) { + crate::view::preview::properties::draw(app, frame, area, id); + return; + } if app.preview.split.doc != Some(id) { return; } diff --git a/crates/winc-app/src/view/preview.rs b/crates/winc-app/src/view/preview.rs index 035e26d3..e5a41fab 100644 --- a/crates/winc-app/src/view/preview.rs +++ b/crates/winc-app/src/view/preview.rs @@ -1,7 +1,7 @@ //! 预览的绘制:Markdown 预览的排版和绘制、表格预览、PDF 预览。 //! //! `markdown` 排版并绘制 Markdown、图片和公式,`table` 绘制 xlsx、csv 工作簿的表格,`pdf` 逐页 -//! 绘制渲染好的 PDF 页面;表格的 +//! 绘制渲染好的 PDF 页面,`properties` 绘制把 Unicode 转义换成字符后的 Properties 文本;表格的 //! 读取(xlsx 包、数字格式、单元格文字)在 `winc_preview::table`,这一层只管排版、绘制和 //! 命中测试。 //! @@ -10,4 +10,5 @@ pub(in crate::view) mod latex; pub(crate) mod markdown; pub(in crate::view) mod pdf; +pub(crate) mod properties; pub(crate) mod table; diff --git a/crates/winc-app/src/view/preview/properties.rs b/crates/winc-app/src/view/preview/properties.rs new file mode 100644 index 00000000..3981a445 --- /dev/null +++ b/crates/winc-app/src/view/preview/properties.rs @@ -0,0 +1,103 @@ +//! Properties 预览:在当前窗格中按物理行绘制解码后的文字。 + +use winc_core::{Lines, text::slice_cells}; +use winc_editor::DocumentId; +use winc_render::{Frame, Rect}; + +use crate::app::{App, ScrollArea}; +use crate::layout::{drawn_scroll_line, hscrollbar_thumb}; +use crate::theme::TEXT_PAD; +use crate::view::{draw_scrollbar, draw_thumb}; + +/// 按编辑区的等宽字体和制表符宽度绘制本屏文字。 +pub(in crate::view) fn draw(app: &mut App, frame: &mut Frame<'_>, area: Rect, id: DocumentId) { + app.prepare_properties(); + let Some((text_rect, scroll_x, width)) = app.properties_hscrollbar() else { + return; + }; + let lh = app.fonts.line_height; + let view = &app.preview.properties; + let scroll = drawn_scroll_line(view.top_line, lh); + let metrics = app.metrics.mono; + let lead = (lh - (metrics.ascent + metrics.descent)) / 2.0 + metrics.ascent; + let tab_width = app.editor.active_tab_width(); + let last_line = app + .editor + .active() + .map_or(0, |doc| doc.text().line_count().saturating_sub(1)); + let origin_x = text_rect.x + TEXT_PAD - scroll_x; + for (line, chars) in view.lines() { + let top = f64::from(text_rect.y) + (line as f64 - scroll) * f64::from(lh); + if top >= f64::from(text_rect.bottom()) { + break; + } + if let Some(((first, from), (last, to))) = view.selection() + && (first..=last).contains(&line) + { + let start = if line == first { + from.min(chars.len()) + } else { + 0 + }; + let end = if line == last { + to.min(chars.len()) + } else { + chars.len() + }; + let at = + |col| origin_x + slice_cells(&chars[..col], 0, tab_width) as f32 * app.metrics.cell; + let left = at(start); + let right = at(end) + + if line < last && line < last_line { + app.metrics.cell * 0.6 + } else { + 0.0 + }; + let color = if app.editor_focused() && app.properties_focused() { + app.palette.selection + } else { + app.palette.selection_inactive + }; + if right > left { + frame.rect_clipped( + Rect::new(left, top.round() as f32, right - left, lh), + color, + 0.0, + text_rect, + ); + } + } + let baseline = (top + f64::from(lead)).round() as f32; + crate::view::editor::draw_glyphs( + app, + frame, + chars, + &[], + origin_x, + baseline, + tab_width, + text_rect, + ); + } + if let Some((_, scroll, content)) = app.properties_vscrollbar() { + draw_scrollbar( + app, + frame, + ScrollArea::Properties, + id.0, + area, + scroll, + content, + ); + } + let thumb = hscrollbar_thumb(text_rect, scroll_x, width); + let look = app.scrollbar_look( + ScrollArea::PropertiesHorizontal, + id.0, + scroll_x, + thumb.map(|_| text_rect), + ); + if let Some(thumb) = thumb { + draw_thumb(frame, app.palette, thumb, look); + } +} diff --git a/crates/winc-config/src/state.rs b/crates/winc-config/src/state.rs index 64199d75..0ec610ce 100644 --- a/crates/winc-config/src/state.rs +++ b/crates/winc-config/src/state.rs @@ -1287,25 +1287,27 @@ fn window_json(frame: &WindowFrame) -> Json { Json::object(window) } -/// 从 `state.json` 的 `window` 一节读出窗口的大小和位置;缺项或者数值不合理时为 `None`。 -/// 读取 `previewMode`:对象按种类取各自的方式,字符串用于全部种类。 +/// 读取 `previewMode`:对象按种类取各自的方式,旧版字符串设置只用于 Markdown、SVG 和表格。 fn preview_modes(json: Option<&Json>) -> BTreeMap { - const KINDS: [&str; 3] = ["markdown", "svg", "table"]; + const LEGACY: [&str; 3] = ["markdown", "svg", "table"]; let valid = |mode: &&str| matches!(*mode, "split" | "preview"); match json { Some(Json::Object(modes)) => (modes.iter()) - .filter(|(kind, _)| KINDS.contains(&kind.as_str())) + .filter(|(kind, _)| { + LEGACY.contains(&kind.as_str()) || matches!(kind.as_str(), "latex" | "properties") + }) .filter_map(|(kind, mode)| { Some((kind.clone(), mode.as_str().filter(valid)?.to_owned())) }) .collect(), Some(Json::String(mode)) if valid(&mode.as_str()) => { - KINDS.map(|kind| (kind.to_owned(), mode.clone())).into() + LEGACY.map(|kind| (kind.to_owned(), mode.clone())).into() } _ => BTreeMap::new(), } } +/// 从 `state.json` 的 `window` 一节读出窗口的大小和位置;缺项或者数值不合理时为 `None`。 fn window_frame(json: &std::collections::BTreeMap) -> Option { let number = |key: &str| json.get(key).and_then(Json::as_number); let (width, height, scale) = (number("width")?, number("height")?, number("scale")?); diff --git a/crates/winc-config/src/state/tests.rs b/crates/winc-config/src/state/tests.rs index 19bfe550..8f31f7c3 100644 --- a/crates/winc-config/src/state/tests.rs +++ b/crates/winc-config/src/state/tests.rs @@ -193,7 +193,7 @@ fn preview_modes_are_read_per_kind() { .collect::>() }; let pair = |kind: &str, mode: &str| (kind.to_owned(), mode.to_owned()); - // 字符串用于全部种类。 + // 旧版字符串设置作用于 Markdown、SVG 和表格。 assert_eq!( modes(r#"{"previewMode": "split"}"#), [ @@ -202,10 +202,34 @@ fn preview_modes_are_read_per_kind() { pair("table", "split") ] ); + assert_eq!( + modes(r#"{"previewMode": "preview"}"#), + [ + pair("markdown", "preview"), + pair("svg", "preview"), + pair("table", "preview") + ] + ); // 未知的种类和方式跳过。 let text = r#"{"previewMode": {"markdown": "preview", "svg": "x", "pdf": "split"}}"#; assert_eq!(modes(text), [pair("markdown", "preview")]); assert!(modes(r#"{"previewMode": "source"}"#).is_empty()); + + for mode in ["split", "preview"] { + let text = format!( + r#"{{"previewMode": {{"latex": "preview", "properties": "{mode}", "table": "split"}}}}"# + ); + let state = State::parse(&text); + assert_eq!( + modes(&text), + [ + pair("latex", "preview"), + pair("properties", mode), + pair("table", "split") + ] + ); + assert_eq!(State::parse(&state.to_json()), state); + } } #[test] diff --git a/crates/winc-editor/src/document.rs b/crates/winc-editor/src/document.rs index ab901b0d..22c141f4 100644 --- a/crates/winc-editor/src/document.rs +++ b/crates/winc-editor/src/document.rs @@ -175,15 +175,18 @@ pub enum PreviewKind { Table, /// LaTeX:预览只读。 Latex, + /// Properties:预览把 Unicode 转义显示为字符,由界面按源代码的行布局绘制。 + Properties, } impl PreviewKind { /// 全部种类。 - pub const ALL: [PreviewKind; 4] = [ + pub const ALL: [PreviewKind; 5] = [ PreviewKind::Svg, PreviewKind::Markdown, PreviewKind::Table, PreviewKind::Latex, + PreviewKind::Properties, ]; /// 是否按 Markdown 预览排版(Markdown,以及转换成 Markdown 的 LaTeX)。 @@ -198,19 +201,20 @@ impl PreviewKind { "markdown" => Some(PreviewKind::Markdown), "csv" | "tsv" => Some(PreviewKind::Table), "latex" => Some(PreviewKind::Latex), + "properties" => Some(PreviewKind::Properties), _ => None, } } } -/// 可预览文件(SVG、Markdown)的显示方式。 +/// 可预览文本文件的显示方式。 #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PreviewMode { /// 只显示源代码。 Source, /// 左侧显示源代码(可以继续编辑),右侧随文字实时预览。 Split, - /// 只显示预览,文档暂时只读。 + /// 只显示预览。 Preview, } @@ -509,7 +513,7 @@ pub struct Document { pub log: Option>, /// 编辑区按十六进制显示文件的字节,而不是文本;只读,文本为空。 pub hex: Option>, - /// 切换到预览之前的 `readonly`:SVG 的预览期间强制只读,切回源代码时恢复该值。 + /// 切换到预览之前的 `readonly`,离开预览时恢复该值。 readonly_before_preview: bool, /// 分栏预览(`PreviewMode::Split`):文本仍然显示,右侧的预览由界面管理。 split: bool, @@ -517,6 +521,8 @@ pub struct Document { /// /// SVG 的预览使用 `picture`。 rendered: bool, + /// 是否为 Properties 仅预览模式:编辑区只读绘制把 Unicode 转义换成字符后的文本。 + properties: bool, /// 不对应文件的只读标签(格式化工具的输出、安装说明)的标题。 pub title: Option, /// 阅读标签的内容:编辑区显示排版后的 Markdown,没有可切换的源代码,文本为空。 @@ -633,6 +639,7 @@ impl Document { readonly_before_preview: false, split: false, rendered: false, + properties: false, title: None, reading: None, revision: 0, @@ -978,15 +985,42 @@ impl Document { (self.locked, self.all_locked) = held; } - /// 返回文档因自身的状态而只读的原因(显示给用户),此时也不能保存。 + /// 返回文档因自身的状态而不能编辑的原因(显示给用户)。 /// /// 不包括用户设置的只读。 pub fn unwritable_reason(&self) -> Option<&'static str> { + self.unwritable_reason_for(self.readonly, self.previewing()) + } + + /// 返回阻止保存的原因;Properties 的仅预览模式仍可保存源代码,源代码本身的只读限制 + /// 照常生效。 + /// + /// 其他预览方式(图片、SVG、表格)在预览期间的只读与 `unwritable_reason` 一致;保存 + /// 写的一直是源代码缓冲。 + pub fn save_blocked_reason(&self) -> Option<&'static str> { + if self.properties { + self.unwritable_reason_for(self.readonly_before_preview, false) + } else { + self.unwritable_reason() + } + } + + /// 返回阻止保存前修改(`.editorconfig` 清理、保存时格式化)的原因。 + /// + /// Properties 的仅预览期间仍可修改源代码;图片、SVG、表格的预览以及用户设置的只读 + /// 照常阻止。 + pub(crate) fn preprocessing_blocked_reason(&self) -> Option<&'static str> { + self.save_blocked_reason() + .or_else(|| self.locked.then(|| t!("editor-readonly-locked"))) + .or_else(|| self.all_locked.then(|| t!("editor-readonly-all"))) + } + + fn unwritable_reason_for(&self, readonly: bool, previewing: bool) -> Option<&'static str> { match &self.text { - _ if !self.readonly => None, + _ if !readonly => None, _ if self.pending => Some(t!("editor-readonly-pending")), _ if self.unsupported.is_some() => Some(t!("editor-readonly-unsupported")), - _ if self.previewing() => Some(t!("editor-readonly-previewing")), + _ if previewing => Some(t!("editor-readonly-previewing")), _ if self.title.is_some() => Some(t!("editor-readonly-tab")), _ if self.hex.is_some() => Some(t!("editor-readonly-hex")), _ if self.encoding == Encoding::Binary => Some(t!("editor-readonly-binary")), @@ -1250,6 +1284,17 @@ impl Document { } } + /// 应用对源代码的修改,用于保存前的清理和格式化;Properties 仅预览期间的临时只读 + /// 不阻止这些修改。用户设置的只读和源代码自身的只读照常阻止。 + pub(crate) fn apply_to_source(&mut self, transaction: Transaction) { + let held = self.readonly; + if self.properties { + self.readonly = self.readonly_before_preview; + } + self.apply(transaction); + self.readonly = held; + } + /// 记录最近一次改动(`revision` 已递增)的起始行 `line`。 fn note_edit(&mut self, line: usize) { self.edits.push_back((self.revision, line)); diff --git a/crates/winc-editor/src/document/disk.rs b/crates/winc-editor/src/document/disk.rs index 2ede09b0..f189bb6c 100644 --- a/crates/winc-editor/src/document/disk.rs +++ b/crates/winc-editor/src/document/disk.rs @@ -214,7 +214,7 @@ impl Document { )); }; - if let Some(reason) = self.unwritable_reason() { + if let Some(reason) = self.save_blocked_reason() { return Err(io::Error::new(io::ErrorKind::PermissionDenied, reason)); } @@ -856,14 +856,18 @@ impl Document { /// 换上读好的内容 `loaded`:按编码决定是否只读,更新编码、换行风格、修改时间和缩进检测。 pub(super) fn set_content(&mut self, loaded: Loaded) { - let overlong = matches!(&loaded.text, Content::Large(large) if large.has_overlong_lines()); + let mode = self.preview_mode(); + self.text = loaded.text; + if mode != PreviewMode::Source && !self.can_preview() { + self.clear_preview(); + } + let overlong = matches!(&self.text, Content::Large(large) if large.has_overlong_lines()); self.readonly = matches!(loaded.encoding, Encoding::Lossy | Encoding::Binary) || overlong; // 正在预览时仍保持只读;切回源代码时恢复为新读取内容对应的 `readonly`。 if self.previewing() { self.readonly_before_preview = self.readonly; self.readonly = true; } - self.text = loaded.text; self.whole.forget(); self.clear_folds(); self.encoding = loaded.encoding; diff --git a/crates/winc-editor/src/document/disk/save_job.rs b/crates/winc-editor/src/document/disk/save_job.rs index c2ed748a..6706b589 100644 --- a/crates/winc-editor/src/document/disk/save_job.rs +++ b/crates/winc-editor/src/document/disk/save_job.rs @@ -157,7 +157,7 @@ impl Document { t!("editor-file-no-path"), )); }; - if let Some(reason) = self.unwritable_reason() { + if let Some(reason) = self.save_blocked_reason() { return Err(io::Error::new(io::ErrorKind::PermissionDenied, reason)); } let text = match &self.text { @@ -200,7 +200,7 @@ impl Document { t!("editor-file-no-path"), )); }; - if let Some(reason) = self.unwritable_reason() { + if let Some(reason) = self.save_blocked_reason() { return Err(io::Error::new(io::ErrorKind::PermissionDenied, reason)); } self.write_copy(copy)?; diff --git a/crates/winc-editor/src/document/indentation.rs b/crates/winc-editor/src/document/indentation.rs index 81aa98af..dc4e68dd 100644 --- a/crates/winc-editor/src/document/indentation.rs +++ b/crates/winc-editor/src/document/indentation.rs @@ -141,7 +141,7 @@ impl Document { if to.is_none() { self.editorconfig = config.clone(); } - if !config.tidies() || self.readonly_reason().is_some() { + if !config.tidies() || self.preprocessing_blocked_reason().is_some() { return false; } let Content::Rope(rope) = &self.text else { @@ -183,7 +183,7 @@ impl Document { Transaction::new(changes, all[primary], mapped[after], EditKind::Other); transaction.extra_before = others(&all, primary); transaction.extra_after = others(&mapped, after); - self.apply(transaction); + self.apply_to_source(transaction); true } } diff --git a/crates/winc-editor/src/document/preview.rs b/crates/winc-editor/src/document/preview.rs index 40d66f04..9657b811 100644 --- a/crates/winc-editor/src/document/preview.rs +++ b/crates/winc-editor/src/document/preview.rs @@ -1,5 +1,4 @@ -//! 文档预览:图片、SVG、Markdown 与表格的呈现、编辑区与预览之间的切换,以及解码好的图片、 -//! 读好的表格等派生状态。 +//! 文档预览:编辑区与预览之间的切换,以及解码好的图片、读好的表格等派生状态。 use super::*; @@ -12,8 +11,8 @@ impl Document { } } - /// 是否在编辑区显示文本:不是图片、差异、日志、阅读标签或无法打开的文件,且 SVG 没有切换 - /// 到预览。 + /// 是否在编辑区显示普通文本。图片、差异、日志、阅读标签、无法打开的文件以及只看预览时 + /// 各自使用专门的界面。 /// /// 光标、查找、折叠等只对文本有意义。 pub fn shows_text(&self) -> bool { @@ -21,6 +20,7 @@ impl Document { && self.picture.is_none() && (self.table.is_none() || self.split) && !self.rendered + && !self.properties && self.diff.is_none() && self.log.is_none() && self.hex.is_none() @@ -36,7 +36,8 @@ impl Document { self.shows_text() || self.rendered } - /// 是否可以切换到预览:语言是 SVG、Markdown、LaTeX、CSV 或 TSV 的文本,且不是大文件。 + /// 是否可以切换到预览:SVG、Markdown、LaTeX、CSV、TSV 和 Properties 文本, + /// 其中只有表格支持大文件。 pub fn can_preview(&self) -> bool { self.preview_kind().is_some() } @@ -45,7 +46,7 @@ impl Document { /// /// 按文档当前的语言判断,与文件名无关:未保存的新文件和扩展名不符的文件选择语言后同样可以预览。 pub fn preview_kind(&self) -> Option { - if self.unsupported.is_some() || self.title.is_some() { + if !self.holds_file_text() || self.title.is_some() { return None; } let kind = PreviewKind::of(self.highlighter.language())?; @@ -53,14 +54,27 @@ impl Document { (!self.is_large() || kind == PreviewKind::Table).then_some(kind) } - /// 是否正在只看预览(SVG 的图、排好版的 Markdown 或 csv 的表格)。 + /// 是否是 Properties 文件:可以切换代码、分栏和预览。 + pub fn is_properties(&self) -> bool { + self.preview_kind() == Some(PreviewKind::Properties) + } + + /// 是否正在只看 Properties 预览;分栏右侧的预览不算(见 [`Document::is_properties`])。 + pub fn properties_preview(&self) -> bool { + self.properties + } + + /// 是否正在只看预览(SVG、Markdown、LaTeX、表格或 Properties 的转换文本)。 pub(super) fn previewing(&self) -> bool { - self.picture.is_some() || self.rendered || (self.table.is_some() && !self.split) + self.picture.is_some() + || self.rendered + || self.properties + || (self.table.is_some() && !self.split) } - /// 文本是否可以编辑。 + /// 源代码是否可以编辑。 /// - /// 与 `readonly` 不同:正在预览的 SVG 在预览期间暂时只读,文本仍可编辑,切回源代码即可 + /// 与 `readonly` 不同:只看预览时界面可以暂时只读,切回源代码即可 /// 修改;未保存的修改仍需备份,也可以换成磁盘版本。 pub fn text_editable(&self) -> bool { if self.previewing() && self.can_preview() { @@ -85,20 +99,14 @@ impl Document { /// 换成 `mode` 显示。 /// - /// 只看 SVG、表格、LaTeX 的预览期间文档只读(看不到文字),离开时恢复原来的只读状态; + /// 只看 SVG、表格、LaTeX、Properties 的预览期间文档只读,离开时恢复原来的只读状态; /// Markdown 的预览可以直接编辑,不改只读状态。不满足 [`Document::can_preview`] 时不切换, /// 返回 `false`。 pub fn set_preview_mode(&mut self, mode: PreviewMode) -> bool { let Some(kind) = self.preview_kind() else { return false; }; - if self.previewing() { - self.picture = None; - self.rendered = false; - self.readonly = self.readonly_before_preview; - } - // 表格在只看预览和分栏时都有,换显示方式时一律重新读。 - self.table = None; + self.clear_preview(); self.split = mode == PreviewMode::Split; if self.split && kind == PreviewKind::Table { self.table = Some(TableView::loading(self.revision)); @@ -112,12 +120,25 @@ impl Document { PreviewKind::Svg => self.picture = Some(PictureState::Loading), PreviewKind::Markdown | PreviewKind::Latex => self.rendered = true, PreviewKind::Table => self.table = Some(TableView::loading(self.revision)), + PreviewKind::Properties => self.properties = true, } } true } - /// 在 SVG 的源代码(或分栏)和只看预览之间切换,返回切换后是否处于预览。 + /// 退出文本预览,恢复源代码的只读状态,清除派生的预览内容。 + pub(super) fn clear_preview(&mut self) { + if self.previewing() { + self.picture = None; + self.rendered = false; + self.properties = false; + self.readonly = self.readonly_before_preview; + } + self.table = None; + self.split = false; + } + + /// 在源代码(或分栏)和只看预览之间切换,返回切换后是否处于预览。 /// /// 不满足 [`Document::can_preview`] 时不切换,返回 `false`。 pub fn toggle_preview(&mut self) -> bool { diff --git a/crates/winc-editor/src/document/tests.rs b/crates/winc-editor/src/document/tests.rs index f821d88f..20940c53 100644 --- a/crates/winc-editor/src/document/tests.rs +++ b/crates/winc-editor/src/document/tests.rs @@ -102,6 +102,113 @@ fn save_round_trip_preserves_bytes() { fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn image_and_workbook_previews_cannot_overwrite_their_files() { + let dir = scratch("readonly-binary-previews"); + for (name, kind, bytes) in [ + ("image.png", Unsupported::Image, &b"\x89PNG\r\n\x1a\n"[..]), + ("workbook.xlsx", Unsupported::Workbook, &b"PK\x03\x04"[..]), + ] { + let path = dir.join(name); + fs::write(&path, bytes).unwrap(); + let mut doc = Document::open_any(DocumentId(1), path.clone()); + assert_eq!(doc.unsupported, Some(kind)); + + assert_eq!( + doc.save().unwrap_err().kind(), + io::ErrorKind::PermissionDenied + ); + assert_eq!( + doc.begin_save().err().unwrap().kind(), + io::ErrorKind::PermissionDenied + ); + let copy = dir.join("copy"); + assert_eq!( + doc.begin_handed_save(©).err().unwrap().kind(), + io::ErrorKind::PermissionDenied + ); + assert_eq!( + doc.save_as(copy.clone()).unwrap_err().kind(), + io::ErrorKind::PermissionDenied + ); + assert_eq!(doc.path.as_deref(), Some(path.as_path())); + assert!(!copy.exists()); + assert_eq!(fs::read(&path).unwrap(), bytes); + } + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn properties_full_preview_can_save_pending_source_edits() { + let dir = scratch("properties-preview-save"); + let path = dir.join("a.properties"); + let original = "greeting=\\u4F60\\u597D\n"; + fs::write(&path, original).unwrap(); + let mut doc = Document::open(DocumentId(1), path.clone()).unwrap(); + + assert!(doc.set_preview_mode(PreviewMode::Split)); + assert_eq!(doc.preview_mode(), PreviewMode::Split); + assert!(doc.shows_text() && doc.text_editable() && !doc.readonly); + doc.execute(Command::Insert("# edited\n".into()), 10, 4); + assert!(doc.is_dirty()); + assert!(doc.set_preview_mode(PreviewMode::Preview)); + assert!(!doc.shows_text() && doc.text_editable() && doc.readonly); + // 自动保存与显式保存使用同一个判断。 + assert!(doc.save_blocked_reason().is_none()); + doc.execute(Command::Insert("unexpected".into()), 10, 4); + assert_eq!(fs::read_to_string(&path).unwrap(), original); + + assert!(doc.begin_save().unwrap().is_none()); + doc.save().unwrap(); + let expected = format!("# edited\n{original}"); + assert_eq!(fs::read_to_string(&path).unwrap(), expected); + assert!(!doc.is_dirty()); + + let copy = dir.join("another.properties"); + doc.save_as(copy.clone()).unwrap(); + assert_eq!(doc.preview_mode(), PreviewMode::Preview); + assert_eq!(fs::read_to_string(©).unwrap(), expected); + assert!(doc.set_preview_mode(PreviewMode::Source)); + assert!(doc.shows_text() && !doc.readonly); + doc.execute(Command::Undo, 10, 4); + assert_eq!(doc.text().rope().unwrap().to_string(), original); + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn full_previews_preserve_source_save_restrictions() { + let dir = scratch("readonly-source-previews"); + let bytes = b"key=value\xff\n"; + let path = dir.join("readonly.properties"); + fs::write(&path, bytes).unwrap(); + let mut doc = Document::open(DocumentId(1), path.clone()).unwrap(); + doc.reopen_with_encoding(Encoding::Utf8).unwrap(); + assert_eq!(doc.encoding, Encoding::Lossy); + assert!(doc.set_preview_mode(PreviewMode::Preview)); + assert_eq!( + doc.save().unwrap_err().kind(), + io::ErrorKind::PermissionDenied + ); + assert_eq!(fs::read(&path).unwrap(), bytes); + assert!(doc.set_preview_mode(PreviewMode::Split)); + assert!(doc.shows_text() && doc.readonly); + + for (name, text) in [("a.svg", ""), ("a.csv", "id,name\n1,test\n")] { + let path = dir.join(name); + fs::write(&path, text).unwrap(); + let mut doc = Document::open(DocumentId(1), path.clone()).unwrap(); + assert!(doc.set_preview_mode(PreviewMode::Preview)); + // 图片和表格的预览仍不能写回:自动保存同样跳过。 + assert!(doc.save_blocked_reason().is_some()); + assert_eq!( + doc.save().unwrap_err().kind(), + io::ErrorKind::PermissionDenied + ); + assert_eq!(fs::read_to_string(&path).unwrap(), text); + } + fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn rejects_binary_and_marks_invalid_utf8_readonly() { let dir = scratch("bin"); @@ -447,6 +554,33 @@ fn tidying_keeps_every_cursor_and_its_line() { fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn properties_preview_tidies_and_saves_the_source() { + let dir = scratch("properties-preview-tidy"); + fs::write( + dir.join(".editorconfig"), + "root = true\n[*]\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n", + ) + .unwrap(); + let path = dir.join("a.properties"); + fs::write(&path, "key=\\u4F60 ").unwrap(); + let mut doc = Document::open(DocumentId(1), path.clone()).unwrap(); + assert!(doc.set_preview_mode(PreviewMode::Preview)); + + // 预览期间仍按 .editorconfig 清理源代码,再写回磁盘。 + assert!(doc.tidy_for_save(None, false)); + doc.save().unwrap(); + assert_eq!(fs::read_to_string(&path).unwrap(), "key=\\u4F60\n"); + assert_eq!(doc.preview_mode(), PreviewMode::Preview); + assert!(doc.readonly); + + // 清理仍可撤销:回到源代码后撤销,原文的空白和缺失的末尾换行都回来了。 + assert!(doc.set_preview_mode(PreviewMode::Source)); + doc.execute(Command::Undo, 10, 4); + assert_eq!(doc.text_range(0, usize::MAX).unwrap(), "key=\\u4F60 "); + fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn a_failed_save_as_keeps_the_old_path() { let dir = scratch("save-as-fails"); @@ -634,6 +768,39 @@ fn growing_files_only_read_what_was_added() { fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn properties_preview_returns_to_source_when_a_disk_reload_makes_it_large() { + let dir = scratch("properties-preview-reload"); + let path = dir.join("a.properties"); + for (mode, line, readonly) in [ + (PreviewMode::Preview, "entry=\\u4F60\n", false), + (PreviewMode::Split, "entry=\\u4F60\n", false), + (PreviewMode::Preview, "x", true), + ] { + fs::write(&path, "before=\\u4F60\n").unwrap(); + let mut doc = Document::open(DocumentId(1), path.clone()).unwrap(); + assert!(doc.set_preview_mode(mode)); + fs::write(&path, line.repeat(LARGE_FILE as usize / line.len() + 1)).unwrap(); + + assert_eq!(doc.sync_with_disk().unwrap(), DiskChange::Reloaded); + assert!(doc.is_large() && doc.shows_text() && !doc.can_preview()); + assert_eq!(doc.preview_mode(), PreviewMode::Source); + assert_eq!(doc.readonly, readonly); + doc.execute(Command::Insert("#".into()), 10, 4); + assert_eq!(doc.is_dirty(), !readonly); + if !readonly { + doc.execute(Command::Undo, 10, 4); + assert!(!doc.is_dirty()); + } + + fs::write(&path, "after=\\u597D\n").unwrap(); + assert_eq!(doc.sync_with_disk().unwrap(), DiskChange::Reloaded); + assert!(doc.can_preview() && doc.shows_text() && !doc.readonly); + assert_eq!(doc.preview_mode(), PreviewMode::Source); + } + fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn large_files_edit_save_and_undo() { let dir = scratch("large"); diff --git a/crates/winc-editor/src/tests.rs b/crates/winc-editor/src/tests.rs index e7a1cf96..2916519b 100644 --- a/crates/winc-editor/src/tests.rs +++ b/crates/winc-editor/src/tests.rs @@ -3,6 +3,27 @@ use super::*; +#[test] +fn opening_properties_as_hex_ignores_the_saved_preview_mode() { + let dir = crate::test_util::scratch("properties-hex"); + let path = dir.join("a.properties"); + std::fs::write(&path, "key=\\u4F60\n").unwrap(); + + for mode in [PreviewMode::Split, PreviewMode::Preview] { + let mut editor = Editor::default(); + editor.preview_defaults[PreviewKind::Properties as usize] = mode; + let index = editor.open(&path); + assert_eq!(editor.documents[index].preview_mode(), mode); + + assert!(editor.show_hex(index) && editor.load(index)); + let doc = &mut editor.documents[index]; + assert!(doc.hex.is_some() && doc.readonly); + assert!(!doc.can_preview() && !doc.set_preview_mode(mode)); + assert_eq!(doc.preview_mode(), PreviewMode::Source); + } + std::fs::remove_dir_all(&dir).unwrap(); +} + #[cfg(unix)] #[test] fn documents_under_a_symlinked_folder_follow_a_rename_in_the_tree() { diff --git a/crates/winc-editor/src/tools/format.rs b/crates/winc-editor/src/tools/format.rs index 1d8db6b8..c2d73acf 100644 --- a/crates/winc-editor/src/tools/format.rs +++ b/crates/winc-editor/src/tools/format.rs @@ -1066,7 +1066,7 @@ impl Document { /// /// 文档只读(含预览、二进制、无法解码)或属于大文件时返回原因。 pub fn format_source(&self) -> Result { - if let Some(reason) = self.readonly_reason() { + if let Some(reason) = self.preprocessing_blocked_reason() { return Err(reason.to_owned()); } match &self.text { @@ -1087,7 +1087,7 @@ impl Document { changes: Vec, top: usize, ) -> Option { - if self.text.rope() != Some(sent) || self.readonly_reason().is_some() { + if self.text.rope() != Some(sent) || self.preprocessing_blocked_reason().is_some() { return None; } if changes.is_empty() { @@ -1098,7 +1098,7 @@ impl Document { // `map_positions` 按输入的数量返回位置,因此这里正好取到三个。 let mapped = diff::map_positions(&changes, &[before.anchor, before.head, top]); let after = Selection::new(mapped[0], mapped[1]); - self.apply(Transaction::new(changes, before, after, EditKind::Other)); + self.apply_to_source(Transaction::new(changes, before, after, EditKind::Other)); self.goal_cell = None; self.detected_indent = indent::detect(&self.text); Some(mapped[2]) diff --git a/crates/winc-editor/src/tools/format/tests.rs b/crates/winc-editor/src/tools/format/tests.rs index 8ae322d2..b9e12e81 100644 --- a/crates/winc-editor/src/tools/format/tests.rs +++ b/crates/winc-editor/src/tools/format/tests.rs @@ -634,3 +634,26 @@ fn tools_found_in_a_wsl_distro_are_remembered_until_forgotten() { formatter.forget_wsl(); assert_eq!(formatter.wsl_asked("Ubuntu", "ruff"), None); } + +#[test] +fn properties_preview_can_read_and_apply_formatted_source() { + use crate::{Command, DocumentId, PreviewMode}; + + let old = "key=\\u4F60\n"; + let new = "key = \\u4F60\n"; + let mut doc = Document::from_text(DocumentId(1), old); + doc.set_language("a.properties"); + assert!(doc.set_preview_mode(PreviewMode::Preview)); + + // 预览期间仍提供源代码给格式化工具,结果也写回源代码。 + let sent = doc.format_source().unwrap(); + assert_eq!( + doc.apply_formatted(&sent, diff::line_changes(old, new), 0), + Some(0) + ); + assert_eq!(doc.text_range(0, usize::MAX).unwrap(), new); + + assert!(doc.set_preview_mode(PreviewMode::Source)); + doc.execute(Command::Undo, 10, 4); + assert_eq!(doc.text_range(0, usize::MAX).unwrap(), old); +} diff --git a/crates/winc-i18n/locales/en-US/preview.ftl b/crates/winc-i18n/locales/en-US/preview.ftl index 9062a5c9..acdd1550 100644 --- a/crates/winc-i18n/locales/en-US/preview.ftl +++ b/crates/winc-i18n/locales/en-US/preview.ftl @@ -2,7 +2,7 @@ ## Preview mode -preview-mode-unsupported = Only SVG, Markdown, CSV, and TSV files can be previewed +preview-mode-unsupported = Only SVG, Markdown, LaTeX, CSV, TSV, and Properties files can be previewed preview-mode-source = Source preview-mode-split = Split preview-mode-preview = Preview diff --git a/crates/winc-i18n/locales/zh-CN/preview.ftl b/crates/winc-i18n/locales/zh-CN/preview.ftl index 773f3dd7..23dbd081 100644 --- a/crates/winc-i18n/locales/zh-CN/preview.ftl +++ b/crates/winc-i18n/locales/zh-CN/preview.ftl @@ -2,7 +2,7 @@ ## 预览模式 -preview-mode-unsupported = 仅支持预览 SVG、Markdown、CSV 和 TSV 文件 +preview-mode-unsupported = 仅支持预览 SVG、Markdown、LaTeX、CSV、TSV 和 Properties 文件 preview-mode-source = 代码 preview-mode-split = 分栏 preview-mode-preview = 预览 diff --git a/crates/winc-preview/src/lib.rs b/crates/winc-preview/src/lib.rs index ea0e6568..107d1326 100644 --- a/crates/winc-preview/src/lib.rs +++ b/crates/winc-preview/src/lib.rs @@ -2,7 +2,8 @@ //! //! `image` 解码位图并缩放,`svg` 解析矢量图并按显示大小绘制,`markdown` 把 Markdown 转成排版 //! 用的块和行内文字,`table` 把 xlsx、csv 读成各行的单元格文字,`docx`、`epub`、`latex` 把文档 -//! 转换成 Markdown 文本,`synctex` 读 TeX 源码与 PDF 位置的对照。 +//! 转换成 Markdown 文本,`synctex` 读 TeX 源码与 PDF 位置的对照,`properties` 把 Properties 中的 +//! Unicode 转义换成可读字符。 //! //! 只认字节和文本,不知道文档、标签和界面;编辑器决定什么时候预览,界面负责排版和绘制。 @@ -17,6 +18,7 @@ pub mod latex; pub mod markdown; mod ooxml; pub mod pdf; +pub mod properties; pub mod svg; pub mod synctex; pub mod table; diff --git a/crates/winc-preview/src/properties.rs b/crates/winc-preview/src/properties.rs new file mode 100644 index 00000000..7a96a005 --- /dev/null +++ b/crates/winc-preview/src/properties.rs @@ -0,0 +1,129 @@ +//! Java `.properties` 的可读显示:把 `\uXXXX` 转义换成字符,其余内容原样保留。 +//! +//! 只做显示用的文本变换,不解析键和值:注释、空行、重复的键、缩进和行布局都留在原来的位置, +//! 每一行单独处理,因而不会改变原文的行数和顺序。转换只认 `\u` 加四位十六进制;`\t`、`\n` +//! 等 Java 的其他转义、落单的反斜杠、无效或残缺的转义都按原文显示。 + +/// 把 `text` 中每一行的 Unicode 转义换成对应的字符,返回显示用的文本。 +/// +/// 换行符原样保留,转义不会跨行组合。成对的高、低代理项转义合成一个补充平面的字符;落单的 +/// 代理项、控制字符和行分隔符保留转义写法,在屏幕上不会变成看不见的字符或断行。 +pub fn decode(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(start) = rest.find('\\') { + // 普通文字按片复制,逐个检查以反斜杠开头的片段。 + out.push_str(&rest[..start]); + rest = &rest[start..]; + if let Some(after) = rest.strip_prefix(r"\\") { + out.push_str(r"\\"); + rest = after; + } else if let Some((character, after)) = decoded_escape(rest) { + out.push(character); + rest = after; + } else { + out.push('\\'); + rest = &rest[1..]; + } + } + out.push_str(rest); + out +} + +/// 读取小写 u 和四位十六进制组成的 UTF-16 码元。 +fn escape_unit(text: &str) -> Option<(u32, &str)> { + let (digits, rest) = text.strip_prefix(r"\u")?.split_at_checked(4)?; + let mut value = 0; + for digit in digits.chars() { + value = value * 16 + digit.to_digit(16)?; + } + Some((value, rest)) +} + +/// 相邻的高、低代理项合成一个字符。无法显示的转义留给调用方按原文复制。 +fn decoded_escape(text: &str) -> Option<(char, &str)> { + let (unit, rest) = escape_unit(text)?; + let (scalar, rest) = if (0xD800..=0xDBFF).contains(&unit) { + let (low, rest) = escape_unit(rest)?; + if !(0xDC00..=0xDFFF).contains(&low) { + return None; + } + (0x1_0000 + ((unit - 0xD800) << 10) + (low - 0xDC00), rest) + } else { + (unit, rest) + }; + let character = char::from_u32(scalar)?; + let preserve = character.is_control() || matches!(character, '\u{2028}' | '\u{2029}'); + (!preserve).then_some((character, rest)) +} + +#[cfg(test)] +mod tests { + use super::decode; + + #[test] + fn decodes_unicode_escapes() { + assert_eq!(decode(r"greeting=\u4F60\u597D"), "greeting=你好"); + // 已经可读的字符和转义混排时都保留。 + assert_eq!(decode(r"a=\u4F60好"), "a=你好"); + assert_eq!(decode(r"key\ u=value"), r"key\ u=value"); + // 十六进制大小写都认。 + assert_eq!(decode(r"\u4f60\u4F60"), "你你"); + } + + #[test] + fn combines_surrogate_pairs() { + assert_eq!(decode(r"emoji=\uD83D\uDE00"), "emoji=😀"); + // 落单的高、低代理项仍是原来的转义。 + assert_eq!(decode(r"\uD83D"), r"\uD83D"); + assert_eq!(decode(r"\uDE00"), r"\uDE00"); + assert_eq!(decode(r"\uD83Dx"), r"\uD83Dx"); + // 高代理项后面跟着的不是低代理项时,两个转义分别处理。 + assert_eq!(decode(r"\uD83DA"), "\\uD83DA"); + let separated = "\\uD83D\r\n\\uDE00"; + assert_eq!(decode(separated), separated); + } + + #[test] + fn keeps_literal_backslashes_and_other_escapes() { + // 两个反斜杠是一对:后面的 `u` 不是转义。 + assert_eq!(decode(r"a=\\u4F60"), r"a=\\u4F60"); + assert_eq!(decode(r"a=\\\u4F60"), r"a=\\你"); + assert_eq!(decode(r"a=\\"), r"a=\\"); + // 标准 Java 转义不属于本变换。 + assert_eq!(decode(r"a=1\tb\:c\nd"), r"a=1\tb\:c\nd"); + // 末尾落单的反斜杠。 + assert_eq!(decode("a=\\"), "a=\\"); + } + + #[test] + fn keeps_malformed_escapes_as_written() { + assert_eq!(decode(r"\u12G4"), r"\u12G4"); + assert_eq!(decode(r"\u+123"), r"\u+123"); + assert_eq!(decode(r"\u你0"), r"\u你0"); + assert_eq!(decode(r"\u12"), r"\u12"); + assert_eq!(decode(r"\u"), r"\u"); + assert_eq!(decode(r"\uu0041"), r"\uu0041"); + assert_eq!(decode(r"\U4F60"), r"\U4F60"); + } + + #[test] + fn keeps_controls_and_line_separators_escaped() { + assert_eq!(decode(r"a=\u000A b"), r"a=\u000A b"); + assert_eq!(decode(r"a=\u0009b"), r"a=\u0009b"); + assert_eq!(decode(r"a=\u007F"), r"a=\u007F"); + assert_eq!(decode(r"a=\u2028b"), r"a=\u2028b"); + assert_eq!(decode(r"a=\u2029b"), r"a=\u2029b"); + } + + #[test] + fn preserves_the_line_layout() { + let source = "# 标题=\\u4F60\n\n key\\ value = \\u597D\\\nnext=\\u4E2D\r\n# 注释 \\u597D\nkey=\\u4E00\nkey=\\u4E8C\n"; + let shown = decode(source); + assert_eq!( + shown, + "# 标题=你\n\n key\\ value = 好\\\nnext=中\r\n# 注释 好\nkey=一\nkey=二\n" + ); + assert_eq!(shown.lines().count(), source.lines().count()); + } +}