diff --git a/crates/argus-core/src/startup.rs b/crates/argus-core/src/startup.rs index 6c66dd62..eb7f0a35 100644 --- a/crates/argus-core/src/startup.rs +++ b/crates/argus-core/src/startup.rs @@ -3,12 +3,13 @@ mod packaged; -use std::path::Path; +use std::{io::ErrorKind, os::windows::fs::OpenOptionsExt, path::Path}; use serde::Serialize; use windows::Win32::Foundation::{ ERROR_FILE_NOT_FOUND, ERROR_SUCCESS, FILETIME, MAX_PATH, WIN32_ERROR, }; +use windows::Win32::Storage::FileSystem::{DELETE, FILE_FLAG_OPEN_REPARSE_POINT}; use windows::Win32::System::Com::{ CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, IPersistFile, STGM_READ, @@ -508,6 +509,20 @@ fn remove_file(folder: &Path, name: &str, recycle: bool) -> Result<(), ActionErr if !path.is_file() { return Err(ActionError::NotFound); } + // Check the caller's delete access on the directory entry itself before + // handing it to the Shell. Release the handle before the recycle operation. + if let Err(error) = std::fs::File::options() + .access_mode(DELETE.0) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT.0) + .open(&path) + { + crate::diagnostics::file_failure("startup open for deletion", &path, &error); + return Err(match error.kind() { + ErrorKind::PermissionDenied => ActionError::AccessDenied, + ErrorKind::NotFound => ActionError::NotFound, + _ => ActionError::Os(error.to_string()), + }); + } // The paths, each ended by a NUL, and the list by another. let mut from = wide(&path.to_string_lossy()); from.push(0); @@ -727,10 +742,11 @@ mod tests { .expect("icacls"); assert!(status.success()); } - assert!(matches!( - remove_file(&folder.0, "Locked.lnk", true), - Err(ActionError::AccessDenied) - )); + let result = remove_file(&folder.0, "Locked.lnk", true); + assert!( + matches!(result, Err(ActionError::AccessDenied)), + "{result:?}" + ); assert!(folder.0.join("Locked.lnk").exists()); } diff --git a/docs/guide/README.md b/docs/guide/README.md index b273f2eb..ea69df04 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -118,7 +118,7 @@ CSV 使用带 BOM 的 UTF-8 编码,可在 Excel 中打开。名称、描述或 选中应用组时,详情面板显示该组的 CPU 与内存曲线、资源合计、最早启动时间、累计读数之和、按 CPU 排序的成员与文件位置。单击成员可查看单进程详情。结束、优先级和效率模式操作仅作用于选中组。 -面板右上角的复制按钮(Ctrl+Shift+C)将面板所列内容复制为文字,按“【进程】”“【资源】”等小节分段,暂无读数的项目不复制;进程页的列表获得焦点时按 Ctrl+C 复制选中项的名称(与名称列显示的一致),面板或其他位置有选中的文字时,两组快捷键都改为复制所选文字。进程的右键菜单中,“复制”子菜单可复制名称、映像名称、PID、映像路径、命令行或详细信息;在某一列上单击右键时,菜单另有“复制“列名””,复制该行在这一列显示的内容,例如在 CPU 列上为“复制“CPU””。 +面板右上角的复制按钮(Ctrl+Shift+C)将面板所列内容复制为文字,按“【进程】”“【资源】”等小节分段,暂无读数的项目不复制;进程页的列表获得焦点时按 Ctrl+C 复制选中项的名称(与名称列显示的一致),面板或其他位置有选中的文字时,两组快捷键都改为复制所选文字。进程的右键菜单中,“复制”子菜单可复制名称、映像名称、PID、映像路径、命令行或详细信息;在某一列上单击右键时,菜单另有“复制“列名””,复制该行在这一列显示的内容,例如在 CPU 列上为“复制“CPU””。服务、启动与连接页的列表同样支持:Ctrl+C 复制名称列显示的名称,Ctrl+Shift+C 或右键菜单的“复制详细信息”以“列名: 内容”逐行复制该行显示的各列(空白与暂无读数的列除外),在某一列上单击右键时同样可“复制“列名””。 网络速率默认以字节每秒显示(KB/s、MB/s,与磁盘一致),可以在“设置 → 数据与历史”里改为比特每秒(Kbps、Mbps,与网卡的链路速度、宽带套餐一致),概况带、进程表、详细信息面板和历史页随之切换;性能页的网络视图总是同时显示两种。 @@ -314,7 +314,7 @@ Windows 触摸屏支持点按按钮、选择列表项,以及双击展开或折 | 选择 | ↑ ↓ | | 折叠 / 展开 | ← →;分组标题上也可按 Enter 或空格 | | 打开详细信息 | Enter | -| 复制名称 / 详细信息 | 进程页 Ctrl+C / Ctrl+Shift+C;有选中的文字时复制所选文字 | +| 复制名称 / 详细信息 | 进程、服务、启动与连接页 Ctrl+C / Ctrl+Shift+C;有选中的文字时复制所选文字 | | 横向滚动列表 | Shift+滚轮(指针位于列表上) | | 结束进程 | 进程页 Alt+E;列表获得焦点时也可按 Delete(Shift+Delete 跳过确认) | | 显示 / 隐藏窗口(全局) | Ctrl+Alt+Esc,可在设置中更改 | diff --git a/locales/de-DE/settings.json b/locales/de-DE/settings.json index 31ca4669..e14a5e6b 100644 --- a/locales/de-DE/settings.json +++ b/locales/de-DE/settings.json @@ -98,8 +98,8 @@ "ends": "Wählen Sie das erste / letzte Element aus", "expand": "Prozesse: Reduzieren/Erweitern einer Gruppe oder Kategorie oder Auswählen eines übergeordneten/untergeordneten Elements", "details": "Prozesse: Details öffnen", - "copyName": "Prozesse: Namen der Auswahl kopieren", - "copyDetails": "Prozesse: Details der Auswahl kopieren", + "copyName": "Namen der Auswahl kopieren", + "copyDetails": "Details der Auswahl kopieren", "endTable": "Prozesse: Auswahl beenden, mit Bestätigung", "endDirect": "Prozesse: Auswahl ohne Bestätigung beenden", "clear": "Auswahl löschen; löschen Sie zuerst die Prozesssuche, falls eine aktiv ist.", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 9b9e10c0..4bdcdbe8 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -98,8 +98,8 @@ "ends": "Select the first / last item", "expand": "Processes: collapse / expand a group or category, or select a parent / child", "details": "Processes: open details", - "copyName": "Processes: copy the name of the selection", - "copyDetails": "Processes: copy the details of the selection", + "copyName": "Copy the name of the selection", + "copyDetails": "Copy the details of the selection", "endTable": "Processes: end the selection, with confirmation", "endDirect": "Processes: end the selection without confirmation", "clear": "Clear selection; clear the process search first if one is active.", diff --git a/locales/es-ES/settings.json b/locales/es-ES/settings.json index 85a84a62..39436e86 100644 --- a/locales/es-ES/settings.json +++ b/locales/es-ES/settings.json @@ -98,8 +98,8 @@ "ends": "Seleccione el primer/último elemento", "expand": "Procesos: contraer/expandir un grupo o categoría, o seleccionar un padre/hijo", "details": "Procesos: abrir detalles", - "copyName": "Procesos: copiar el nombre de la selección", - "copyDetails": "Procesos: copiar los detalles de la selección", + "copyName": "Copiar el nombre de la selección", + "copyDetails": "Copiar los detalles de la selección", "endTable": "Procesos: finalizar la selección, con confirmación", "endDirect": "Procesos: finalizar la selección sin confirmación", "clear": "Borrar selección; borre primero la búsqueda de procesos si hay alguna activa.", diff --git a/locales/fr-FR/settings.json b/locales/fr-FR/settings.json index 26cfd0dc..4e89a2c7 100644 --- a/locales/fr-FR/settings.json +++ b/locales/fr-FR/settings.json @@ -98,8 +98,8 @@ "ends": "Sélectionnez le premier/dernier élément", "expand": "Processus : réduire/développer un groupe ou une catégorie, ou sélectionner un parent/enfant", "details": "Processus : ouvrir les détails", - "copyName": "Processus : copier le nom de la sélection", - "copyDetails": "Processus : copier les détails de la sélection", + "copyName": "Copier le nom de la sélection", + "copyDetails": "Copier les détails de la sélection", "endTable": "Processus : terminer la sélection, avec confirmation", "endDirect": "Processus : terminer la sélection sans confirmation", "clear": "Effacer la sélection ; effacez d’abord la recherche de processus si elle est active.", diff --git a/locales/ja-JP/settings.json b/locales/ja-JP/settings.json index a4e83280..657b5387 100644 --- a/locales/ja-JP/settings.json +++ b/locales/ja-JP/settings.json @@ -98,8 +98,8 @@ "ends": "最初/最後の項目を選択", "expand": "プロセス:グループまたはカテゴリを折りたたむ/展開する、または親/子を選択する", "details": "プロセス:詳細を開く", - "copyName": "プロセス:選択項目の名前をコピー", - "copyDetails": "プロセス:選択項目の詳細をコピー", + "copyName": "選択項目の名前をコピー", + "copyDetails": "選択項目の詳細をコピー", "endTable": "プロセス一覧:確認後に選択項目を終了", "endDirect": "プロセス一覧:確認を省略して選択項目を終了", "clear": "選択をクリアします。プロセス検索がアクティブな場合は、最初にそれをクリアします。", diff --git a/locales/ru-RU/settings.json b/locales/ru-RU/settings.json index 01b9cc8e..b7585c48 100644 --- a/locales/ru-RU/settings.json +++ b/locales/ru-RU/settings.json @@ -98,8 +98,8 @@ "ends": "Выбор первого/последнего элемента", "expand": "Процессы: свернуть/развернуть группу или категорию или выбрать родительский/дочерний элемент", "details": "Процессы: открыть сведения", - "copyName": "Процессы: копировать имя выбранного элемента", - "copyDetails": "Процессы: копировать сведения о выбранном элементе", + "copyName": "Копировать имя выбранного элемента", + "copyDetails": "Копировать сведения о выбранном элементе", "endTable": "Процессы: завершить выбранные элементы с подтверждением", "endDirect": "Процессы: завершить выбранные элементы без подтверждения", "clear": "Снять выделение; если активен поиск процессов, сначала очистить его.", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 11576cdd..365838c5 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -98,8 +98,8 @@ "ends": "选择第一项 / 最后一项", "expand": "进程列表:折叠 / 展开进程组或分组,或选择父项 / 子项", "details": "进程列表:打开详细信息", - "copyName": "进程列表:复制选中项的名称", - "copyDetails": "进程列表:复制选中项的详细信息", + "copyName": "复制选中项的名称", + "copyDetails": "复制选中项的详细信息", "endTable": "进程列表:结束选中项,操作前确认", "endDirect": "进程列表:直接结束选中项,跳过确认", "clear": "取消选择;进程列表有搜索条件时先清空搜索。", diff --git a/locales/zh-TW/settings.json b/locales/zh-TW/settings.json index 446114a2..3ecb3b32 100644 --- a/locales/zh-TW/settings.json +++ b/locales/zh-TW/settings.json @@ -76,8 +76,8 @@ "ends": "選取第一項 / 最後一項", "expand": "處理程序清單:摺疊 / 展開處理程序群組或分組,或選取父項 / 子項", "details": "處理程序清單:開啟詳細資料", - "copyName": "處理程序清單:複製選取項目的名稱", - "copyDetails": "處理程序清單:複製選取項目的詳細資料", + "copyName": "複製選取項目的名稱", + "copyDetails": "複製選取項目的詳細資料", "endTable": "處理程序清單:結束選取項目,操作前確認", "endDirect": "處理程序清單:直接結束選取項目,略過確認", "clear": "取消選取;處理程序清單有搜尋條件時先清除搜尋。", diff --git a/src-gpui/src/commands.rs b/src-gpui/src/commands.rs index 04c9581a..6370aba1 100644 --- a/src-gpui/src/commands.rs +++ b/src-gpui/src/commands.rs @@ -1015,6 +1015,13 @@ pub fn history_move( Ok(settings_view(&app)) } +pub fn history_reset_dir( + app: crate::native_runtime::Host, + move_records: bool, +) -> Result { + history_move(app, String::new(), move_records) +} + pub fn history_open_dir(dir: State<'_, HistoryDir>) -> Result<(), String> { open_folder(&dir.read()).map_err(|_| tr!("history.error.open")) } diff --git a/src-gpui/src/dispatch.rs b/src-gpui/src/dispatch.rs index 7e701c48..af6bc606 100644 --- a/src-gpui/src/dispatch.rs +++ b/src-gpui/src/dispatch.rs @@ -14,10 +14,6 @@ fn argument(args: &Value, key: &str) -> Result) -> Result { - serde_json::to_value(result.map_err(Value::String)?) - .map_err(|_| Value::String(argus_core::tr!("app.invalidRequest"))) -} pub fn invoke(host: &Host, name: &str, args: Value) -> Result { match name { "desktop_shell" => Ok(serde_json::to_value(crate::commands::desktop_shell()) @@ -301,15 +297,13 @@ pub fn invoke(host: &Host, name: &str, args: Value) -> Result { argument::>(&args, "keys")?, )) .expect("serializable command response")), - "history_events" => serde_json::to_value( - crate::commands::history_events( - host.state(), - argument::(&args, "from")?, - argument::(&args, "to")?, - ) - .map_err(Value::String)?, + "history_events" => crate::commands::history_events( + host.state(), + argument::(&args, "from")?, + argument::(&args, "to")?, ) - .map_err(|_| Value::String(argus_core::tr!("app.invalidRequest"))), + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), "history_channels" => Ok(serde_json::to_value(crate::commands::history_channels( host.state(), argument::(&args, "from")?, @@ -347,29 +341,36 @@ pub fn invoke(host: &Host, name: &str, args: Value) -> Result { ) .map(|value| serde_json::to_value(value).expect("serializable command response")) .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), - "history_move" => history_settings(crate::commands::history_move( + "set_history_enabled" => crate::commands::set_history_enabled( host.clone(), - argument(&args, "dir")?, - argument(&args, "moveRecords")?, - )), - "history_reset_dir" => history_settings(crate::commands::history_move( + host.state(), + host.state(), + argument::(&args, "enabled")?, + ) + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), + "set_history_options" => crate::commands::set_history_options( host.clone(), - String::new(), - argument(&args, "moveRecords")?, - )), - "history_open_dir" => crate::commands::history_open_dir(host.state()) - .map(|()| Value::Null) - .map_err(Value::String), - "set_history_options" => history_settings(crate::commands::set_history_options( + argument::(&args, "options")?, + ) + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), + "history_move" => crate::commands::history_move( host.clone(), - argument(&args, "options")?, - )), - "set_history_enabled" => history_settings(crate::commands::set_history_enabled( + argument::(&args, "dir")?, + argument::(&args, "moveRecords")?, + ) + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), + "history_reset_dir" => crate::commands::history_reset_dir( host.clone(), - host.state(), - host.state(), - argument(&args, "enabled")?, - )), + argument::(&args, "moveRecords")?, + ) + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), + "history_open_dir" => crate::commands::history_open_dir(host.state()) + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), "set_kernel_sensors" => crate::commands::set_kernel_sensors( host.clone(), host.state(), diff --git a/src-gpui/src/frontend.rs b/src-gpui/src/frontend.rs index 725609a5..8daa86fa 100644 --- a/src-gpui/src/frontend.rs +++ b/src-gpui/src/frontend.rs @@ -15,6 +15,7 @@ mod icon_motion; mod inline; mod layout; mod leaks; +mod list_copy; mod lists; mod menus; mod model; diff --git a/src-gpui/src/frontend/backend.rs b/src-gpui/src/frontend/backend.rs index a9963d19..149d9fb7 100644 --- a/src-gpui/src/frontend/backend.rs +++ b/src-gpui/src/frontend/backend.rs @@ -1199,9 +1199,11 @@ impl Desktop { cx.stop_propagation(); return; } - // Ctrl+C copies the selected process's name and Ctrl+Shift+C its + // Ctrl+C copies the selected row's name and Ctrl+Shift+C its // details, unless text is selected: the window copies that instead. - if self.page == "processes" + // A process's details are the details pane's, another list's the + // columns it shows (`list_copy`). + if list_copy::LISTS.contains(&self.page.as_str()) && key == "c" && m.control && !m.alt @@ -1212,8 +1214,13 @@ impl Desktop { .and_then(|index| self.rows.get(index)) .filter(|row| row.section.is_none()) { - let action = if m.shift { + let action = if m.shift && self.page == "processes" { Action::CopyDetails(row.key.clone()) + } else if m.shift { + let Some(details) = self.cells_text(row, cx) else { + return; + }; + Action::CopyAs(details, label("actions.copyWhat.details")) } else { Action::Copy(row.title.clone(), "actions.copyWhat.name") }; diff --git a/src-gpui/src/frontend/list_copy.rs b/src-gpui/src/frontend/list_copy.rs new file mode 100644 index 00000000..b50cd5ee --- /dev/null +++ b/src-gpui/src/frontend/list_copy.rs @@ -0,0 +1,206 @@ +//! Copying from the service, startup and connection lists as the process +//! list does: Ctrl+C the selection's name, Ctrl+Shift+C its details, and a +//! right press on a cell offers that column's text. +//! +//! These lists have no details pane: their details are the columns the +//! table shows, read through the table so they keep its units and language. +use super::*; + +/// The lists whose rows copy their cells. The process list copies its own +/// details (`Desktop::details_text`) but shares the column copy. +pub(super) const LISTS: [&str; 4] = ["processes", "services", "startup", "network"]; + +/// Whether `page` copies its details from the table's cells. +pub(super) fn copies_cells(page: &str) -> bool { + LISTS.contains(&page) && page != "processes" +} + +/// The cells worth copying: text a reader can use, without empty cells or +/// the placeholder for a missing reading. +pub(super) fn cell_lines(cells: Vec<(String, String)>, missing: &str) -> Vec<(String, String)> { + cells + .into_iter() + .filter(|(_, value)| !value.trim().is_empty() && value != missing) + .collect() +} + +/// `lines` as text, each through `field` ("Name: value"), one per line as +/// the process details are. +pub(super) fn lines_text( + lines: &[(String, String)], + field: impl Fn(&str, &str) -> String, +) -> String { + lines + .iter() + .map(|(name, value)| field(name, value)) + .collect::>() + .join("\n") +} + +/// Where a row menu takes more copy items: after its last copy item (a copy +/// action, or the process list's copy submenu), else at its end. +pub(super) fn copy_position(items: &[MenuItem]) -> usize { + items + .iter() + .rposition(|item| { + matches!(item.action, Action::Copy(..) | Action::CopyAs(..)) + || (!item.children.is_empty() && item.icon == Some("CopyIcon")) + }) + .map_or(items.len(), |at| at + 1) +} + +/// Whether a menu item copies text. +fn is_copy(item: &MenuItem) -> bool { + matches!(item.action, Action::Copy(..) | Action::CopyAs(..)) +} + +/// `items` with their copy items and `more` in one "Copy" submenu (`title`), +/// as the process list's menu has it: where the first copy item was, else +/// at the end. A long menu then keeps its height in a short window. +pub(super) fn gather_copies( + items: Vec, + more: Vec, + title: String, +) -> Vec { + let at = items.iter().position(is_copy); + let (mut copies, mut rest): (Vec<_>, Vec<_>) = items.into_iter().partition(is_copy); + for copy in &mut copies { + // Submenu entries go without the icon the menu gives the submenu. + copy.icon = None; + } + copies.extend(more); + let at = at.unwrap_or(rest.len()); + rest.insert( + at, + MenuItem::new(title, Action::CloseOverlay) + .icon("CopyIcon") + .submenu(copies), + ); + rest +} + +impl Desktop { + /// The details of `row` on a list that copies its cells: every column + /// the table shows. None when there is nothing to copy. + pub(in crate::frontend) fn cells_text(&self, row: &Row, cx: &App) -> Option { + if !copies_cells(&self.page) || row.section.is_some() { + return None; + } + let lines = cell_lines(self.row_cells(row, cx), &label("format.missing")); + (!lines.is_empty()).then(|| { + lines_text(&lines, |name, value| { + tr!("details.copy.field", name = name, value = value) + }) + }) + } +} + +#[cfg(test)] +mod tests { + // Named imports keep the glob-imported GPUI `test` macro out of scope. + use super::{ + Action, MenuItem, cell_lines, copies_cells, copy_position, gather_copies, lines_text, + }; + + #[test] + fn copies_gather_in_one_submenu_where_the_first_was() { + let item = |label: &str, action| MenuItem::new(label, action); + let copy = |label: &str| { + item(label, Action::Copy("x".into(), "actions.copyWhat.name")).icon("CopyIcon") + }; + let menu = vec![ + item("start", Action::CloseOverlay), + item("open", Action::CloseOverlay), + copy("service name"), + MenuItem::separator(), + item("delete", Action::CloseOverlay), + copy("late copy"), + ]; + let more = vec![ + item("display name", Action::CopyAs("y".into(), "name".into())), + MenuItem::separator(), + item("details", Action::CopyAs("z".into(), "details".into())), + ]; + let menu = gather_copies(menu, more, "Copy".into()); + let labels: Vec<_> = menu.iter().map(|item| item.label.as_str()).collect(); + assert_eq!(labels, ["start", "open", "Copy", "", "delete"]); + let submenu = &menu[2]; + assert_eq!(submenu.icon, Some("CopyIcon")); + let children: Vec<_> = submenu + .children + .iter() + .map(|item| item.label.as_str()) + .collect(); + assert_eq!( + children, + ["service name", "late copy", "display name", "", "details"] + ); + assert!(submenu.children.iter().all(|child| child.icon.is_none())); + // The cell's own copy then follows the submenu. + assert_eq!(copy_position(&menu), 3); + // A menu without copies takes the submenu at its end. + let plain = gather_copies( + vec![item("a", Action::CloseOverlay)], + Vec::new(), + "Copy".into(), + ); + assert_eq!(plain.last().map(|item| item.label.as_str()), Some("Copy")); + } + + fn cell(name: &str, value: &str) -> (String, String) { + (name.into(), value.into()) + } + + #[test] + fn only_the_other_lists_copy_their_cells() { + for page in ["services", "startup", "network"] { + assert!(copies_cells(page)); + } + for page in ["processes", "performance", "history"] { + assert!(!copies_cells(page)); + } + } + + #[test] + fn details_leave_out_empty_and_missing_cells() { + let cells = vec![ + cell("Name", "Dnscache"), + cell("PID", ""), + cell("Description", " "), + cell("Publisher", "—"), + cell("Status", "Running"), + ]; + let lines = cell_lines(cells, "—"); + assert_eq!(lines, [cell("Name", "Dnscache"), cell("Status", "Running")]); + assert_eq!( + lines_text(&lines, |name, value| format!("{name}={value}")), + "Name=Dnscache\nStatus=Running" + ); + assert_eq!(lines_text(&[], |name, _| name.into()), ""); + } + + #[test] + fn copy_items_join_the_menu_after_its_last_copy() { + let item = |action| MenuItem::new("item", action); + let copy = || item(Action::Copy("x".into(), "actions.copyWhat.name")); + let menu = [ + item(Action::CloseOverlay), + copy(), + item(Action::CloseOverlay), + copy(), + MenuItem::separator(), + item(Action::CloseOverlay), + ]; + assert_eq!(copy_position(&menu), 4); + let submenu = [ + item(Action::CloseOverlay), + item(Action::CloseOverlay) + .icon("CopyIcon") + .submenu(vec![copy()]), + MenuItem::separator(), + ]; + assert_eq!(copy_position(&submenu), 2); + let none = [item(Action::CloseOverlay), MenuItem::separator()]; + assert_eq!(copy_position(&none), 2); + } +} diff --git a/src-gpui/src/frontend/menus.rs b/src-gpui/src/frontend/menus.rs index 23468984..def35d99 100644 --- a/src-gpui/src/frontend/menus.rs +++ b/src-gpui/src/frontend/menus.rs @@ -1091,25 +1091,57 @@ impl Desktop { } else if row.user.is_none() { return; } + // The other lists copy the cells shown as their details, taken now: + // a connection can leave the list while its menu is open. + let details = self.cells_text(&row, cx); + // Their name column is what Ctrl+C copies; it gets its own item, as + // the process list's copy submenu has "Name". + let first = tables::first_column(&self.page); + let name_cell = details + .is_some() + .then(|| self.cell_copy(&row, first, cx)) + .flatten(); let cell = column - .filter(|_| row.section.is_none() && self.page == "processes") + .filter(|key| { + row.section.is_none() + && list_copy::LISTS.contains(&self.page.as_str()) + && !(name_cell.is_some() && *key == first) + }) .and_then(|key| self.cell_copy(&row, key, cx)); let mut items = self.row_menu(&row); - if let Some((name, value)) = cell { - // After the copy submenu, as the cell's own copy. - let at = items - .iter() - .position(|item| !item.children.is_empty() && item.icon == Some("CopyIcon")) - .map_or(items.len(), |at| at + 1); + let column_item = |(name, value): (String, String)| { let nothing = value.is_empty() || value == label("format.missing"); - items.insert( - at, + MenuItem::new( + tr!("processes.menu.copyColumn", column = &name), + Action::CopyAs(value, tr!("processes.menu.columnWhat", column = &name)), + ) + .disabled(nothing) + }; + // The other lists gather their copies in one submenu, the clicked + // column's too, so the menu keeps its height whatever it holds (a + // note adds a row): the page's own copies, the name (Ctrl+C), the + // column, then the details (Ctrl+Shift+C). + if let Some(details) = details { + let mut more = Vec::new(); + if let Some((name, value)) = name_cell { + more.push( + MenuItem::new(name, Action::CopyAs(value, label("actions.copyWhat.name"))) + .hint("Ctrl+C"), + ); + } + more.extend(cell.map(column_item)); + more.push(MenuItem::separator()); + more.push( MenuItem::new( - tr!("processes.menu.copyColumn", column = &name), - Action::CopyAs(value, tr!("processes.menu.columnWhat", column = &name)), + label("processes.menu.details"), + Action::CopyAs(details, label("actions.copyWhat.details")), ) - .disabled(nothing), + .hint("Ctrl+Shift+C"), ); + items = list_copy::gather_copies(items, more, label("common.edit.copy")); + } else if let Some(cell) = cell { + // The process list's cell copy follows its copy submenu. + items.insert(list_copy::copy_position(&items), column_item(cell)); } self.open_popup(items, window, cx); cx.notify(); @@ -1181,7 +1213,7 @@ impl Desktop { .icon("FolderIcon") .disabled(!boolean(raw, "exists") || path.is_none()), MenuItem::new( - label("startup.menu.copyCommand"), + label("common.command"), Action::Copy(text(raw, "command").into(), "startup.copied.command"), ) .icon("CopyIcon") @@ -1521,7 +1553,7 @@ impl Desktop { .icon("FolderIcon") .disabled(binary.is_none()), MenuItem::new( - label("services.menu.copyName"), + label("common.name"), Action::Copy(name.into(), "services.copied.name"), ) .icon("CopyIcon"), @@ -1588,7 +1620,7 @@ impl Desktop { .disabled(!closable), MenuItem::separator(), MenuItem::new( - label("connections.menu.copyLocal"), + label("connections.column.localAddress"), Action::Copy( endpoint(text(raw, "localAddress"), &raw["localPort"]), "connections.copied.local", @@ -1596,7 +1628,7 @@ impl Desktop { ) .icon("CopyIcon"), MenuItem::new( - label("connections.menu.copyRemote"), + label("connections.column.remoteAddress"), Action::Copy( remote .map(|r| endpoint(r, &raw["remotePort"])) diff --git a/src-gpui/src/frontend/tables.rs b/src-gpui/src/frontend/tables.rs index a19a3df7..9a2474e0 100644 --- a/src-gpui/src/frontend/tables.rs +++ b/src-gpui/src/frontend/tables.rs @@ -435,6 +435,26 @@ fn entry_cell(raw: &Value, field: &Field) -> String { } } +/// What copying `row`'s cell in `field` gives: its text, with what the cell +/// draws apart from the text, such as an IPv6 connection's "v6" tag. +fn copied_cell(row: &Row, field: &Field, bits: bool) -> String { + let text = display_cell(row, field, bits); + if field.kind == CellKind::Protocol { + protocol_copy(text, boolean(&row.raw, "ipv6")) + } else { + text + } +} + +/// A protocol as copied: "TCPv6" for IPv6, as the protocol filter names it. +fn protocol_copy(protocol: String, ipv6: bool) -> String { + if ipv6 && !protocol.is_empty() { + format!("{protocol}v6") + } else { + protocol + } +} + fn display_cell(row: &Row, field: &Field, bits: bool) -> String { if field.kind == CellKind::NetworkRate { row.metric(field.key) @@ -1828,7 +1848,22 @@ impl TableDelegate for NativeTable { cx: &mut Context>, ) -> impl IntoElement { let content = self.td_content(row_index, column, window, cx); - self.gliding_cell(column, false, content) + let key = self.fields.get(column).map(|field| field.key); + // The row menu offers to copy the cell under the pointer. Rows Argus + // draws note it themselves (`body`); here the cell does, before the + // row's own right press opens the menu. + div() + .size_full() + .min_w_0() + .flex() + .items_center() + .on_mouse_down( + MouseButton::Right, + cx.listener(move |state, _: &MouseDownEvent, _, _| { + state.delegate_mut().context_column = key; + }), + ) + .child(self.gliding_cell(column, false, content)) } fn render_tr( &mut self, @@ -2897,10 +2932,21 @@ impl Desktop { key: &str, cx: &App, ) -> Option<(String, String)> { - let state = self.table.as_ref()?.read(cx); - let delegate = state.delegate(); + let delegate = self.exportable_table(cx)?; let field = delegate.fields.iter().find(|field| field.key == key)?; - Some((field.label.clone(), display_cell(row, field, delegate.bits))) + Some((field.label.clone(), copied_cell(row, field, delegate.bits))) + } + /// Every column of the current table with `row`'s cell in it, as the + /// table shows them. + pub(in crate::frontend) fn row_cells(&self, row: &Row, cx: &App) -> Vec<(String, String)> { + let Some(delegate) = self.exportable_table(cx) else { + return Vec::new(); + }; + delegate + .fields + .iter() + .map(|field| (field.label.clone(), copied_cell(row, field, delegate.bits))) + .collect() } /// Display names of the services running in each process, by PID. pub(in crate::frontend) fn hosted_services(&self) -> HashMap> { @@ -3252,9 +3298,17 @@ pub(super) fn descending_first(page: &str, key: &str) -> bool { mod tests { // Named imports keep the glob-imported GPUI `test` macro out of scope. use super::{ - Value, json, prefs, restore_sort, saved_filters, sort_columns, sort_preference, sortable, + Value, json, prefs, protocol_copy, restore_sort, saved_filters, sort_columns, + sort_preference, sortable, }; + #[test] + fn copied_protocols_keep_the_ipv6_tag() { + assert_eq!(protocol_copy("TCP".into(), true), "TCPv6"); + assert_eq!(protocol_copy("UDP".into(), false), "UDP"); + assert_eq!(protocol_copy(String::new(), true), ""); + } + #[test] fn saved_orders_keep_persistent_column_ids() { // Values a preferences.json from the saved preferences holds.