diff --git a/architecture.md b/architecture.md index 75f11be..eba68a4 100644 --- a/architecture.md +++ b/architecture.md @@ -28,6 +28,13 @@ selection signals blocked and preserve the selected rule identity without refill observation strings never feed persistence. Limit-version mismatch retains dated old usage with an explicit waiting state and unknown excess. The settings schema and reminder state remain unchanged. +Actions that read or change the scanned entries (`main_window._WAIT_FOR_SCAN`) stay enabled while a scan or a +source operation runs; `MainWindow._run_action` and `_explain_busy` intercept them and `gui.busy_notice` says +why they wait, in the status bar and next to the pointer. Actions that start a scan themselves +(`_WAIT_FOR_OPERATION`) wait only for operations. `move_to_trash`, `delete_permanently` and the context menu's +folder rescan explain the same way, so panel buttons never fail silently; authority checks are unchanged +(U-20261118-02). + `MainWindow.folder_context` resolves a typed `FolderContext` from the current result and selection, checking scan ownership, shared operation busy state, closing, links and virtual roots. Files use their containing folder. `DetailsPanel.set_folder_context` displays its copyable path and unavailable @@ -768,6 +775,9 @@ unusable dates. New selections/scan roots invalidate old replies; MainWindow joi ChartStack navigation updates all charts and records one visit; stepping history does not append it. Detached nodes are pruned after edits, new scans reset references, and deep ancestor paths use a scroll area with a collapsed menu instead of widening the chart. Shortcuts apply while Chart is visible. +The Up, Back, Forward and ancestor buttons take no focus, so `ResultsView.focus_chart` gives it to the +chart after each; `MainWindow._leave_path_box` moves focus from the path box or start page to the tree +when a scan begins. Enter meant for the chart therefore never reaches the path box (U-20261119-01). `printing` captures the visible results before opening QPrintDialog, then QPrinter fits those pixels on one printable page. PDF export uses the same fitted layout via QPdfWriter on ExportWorker, avoiding @@ -1202,10 +1212,12 @@ on Windows by default the size rounded up to the volume's clusters, the system a files, 0 for files whose data is elsewhere (cloud placeholders, offline), never opening those. Each finished folder's files are added to the running totals of every folder above it. The root is handed out first (`started`), so `FolderTreeModel` shows the tree in live mode while it grows: each folder's -children are a sorted copy frozen until the next `refresh()`, which the window calls every 700 ms (a layout -change that moves persistent indexes, so expanded folders, selection and scroll position survive). A tick -whose shown folders keep their members, sorted order and child presence only notifies the root and folder -rows and repaints the visible tree, since file rows' own values are final when added (U-20261017-76). The +children are a sorted copy frozen until the next `refresh()` (a layout change that moves persistent indexes, +so expanded folders, selection and scroll position survive). `gui.live_refresh.LiveRefresh` calls it every +700 ms at the fastest; each call is timed until the event loop is about to wait, and the next one waits four +times that, up to 5 s, so live refreshes take at most about a fifth of the window's time however many rows +are expanded (U-20261118-01). A tick whose shown folders keep their members, sorted order and child presence +only notifies the root row and repaints the visible tree (U-20261017-76, U-20261118-01). The calling thread reports progress about ten times a second and watches the cancel event. When every folder is read, totals are added up again bottom-up and children sorted largest first; `analyse()` (largest files, per-type totals) runs still off the GUI thread and `succeeded(ScanOutcome)` ends live mode. Stop diff --git a/docs/guide.md b/docs/guide.md index 4c9c3c6..84907a5 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -365,7 +365,10 @@ To give FileTree to someone without Python, compile it with Nuitka into a progra Dropping a folder scans it in place and accepts only the Copy action, preserving the source even when Shift requests Move. 2. **Watch it fill in**: the tree appears right away and the biggest folders move to the top while FileTree works; the largest files and file types follow when the scan ends. *Stop* (or Esc) ends the - scan at any time and keeps what was read so far, marked as incomplete. + scan at any time and keeps what was read so far, marked as incomplete. While it runs, actions that read + or change the scanned files (Move to Recycle Bin, Rescan, exports and the like) wait for it: using one + says so in the status bar and next to the pointer instead of doing nothing. With many folders open the + tree refreshes less often, so the window stays responsive. 3. **Find what takes the space**: the biggest folders are at the top of the tree. Open a folder with the arrow next to it, or explore the chart on the right. diff --git a/docs/guide_ja.md b/docs/guide_ja.md index 35a308b..79d4905 100644 --- a/docs/guide_ja.md +++ b/docs/guide_ja.md @@ -288,7 +288,7 @@ FileTree を Python を持たない人に渡すには、Nuitka を使用して ## 使い方 -1. **スキャン対象を選択**: クリック * フォルダーを選択します…* またはスタート ページのドライブの 1 つを選択し、フォルダーをウィンドウにドラッグするか、上部のボックスにパスを入力して Enter を押します。コマンド ライン `je-file-tree D:\Projects` (または `python start_file_tree.py D:\Projects`) からスキャンを開始することもできます。フォルダーをドロップすると、フォルダーがその場でスキャンされ、コピー アクションのみが受け入れられ、Shift キーが移動を要求した場合でもソースが保持されます。 2. **入力を見てください**: ツリーがすぐに表示され、FileTree が動作している間、最大のフォルダーが一番上に移動します。スキャンが終了すると、最大のファイルとファイルの種類が続きます。 *Stop* (または Esc) でいつでもスキャンを終了し、それまでに読み取った内容を保持し、不完全としてマークします。 3. **スペースを占めるものを見つけます**: 最大のフォルダーがツリーの一番上にあります。横にある矢印のあるフォルダーを開くか、右側のグラフを調べてください。 +1. **スキャン対象を選択**: クリック * フォルダーを選択します…* またはスタート ページのドライブの 1 つを選択し、フォルダーをウィンドウにドラッグするか、上部のボックスにパスを入力して Enter を押します。コマンド ライン `je-file-tree D:\Projects` (または `python start_file_tree.py D:\Projects`) からスキャンを開始することもできます。フォルダーをドロップすると、フォルダーがその場でスキャンされ、コピー アクションのみが受け入れられ、Shift キーが移動を要求した場合でもソースが保持されます。 2. **入力を見てください**: ツリーがすぐに表示され、FileTree が動作している間、最大のフォルダーが一番上に移動します。スキャンが終了すると、最大のファイルとファイルの種類が続きます。 *Stop* (または Esc) でいつでもスキャンを終了し、それまでに読み取った内容を保持し、不完全としてマークします。スキャン中は、スキャン結果を読み取ったり変更したりする操作(ごみ箱への移動、再スキャン、エクスポートなど)はスキャンの完了を待ちます。その間に使うと、何も起きないのではなく、ステータス バーとポインターの横に理由が表示されます。展開したフォルダーが多いときは、ウィンドウを操作できるようにフォルダー ツリーの更新間隔を広げます。 3. **スペースを占めるものを見つけます**: 最大のフォルダーがツリーの一番上にあります。横にある矢印のあるフォルダーを開くか、右側のグラフを調べてください。 ### 結果の読み取り diff --git a/docs/guide_ko.md b/docs/guide_ko.md index d359ad6..3a912ea 100644 --- a/docs/guide_ko.md +++ b/docs/guide_ko.md @@ -288,7 +288,7 @@ Python이 없는 사람에게 FileTree를 제공하려면 Nuitka를 사용하여 ## 사용방법 -1. **검사 대상 선택**: *폴더 선택…* 또는 시작 페이지의 드라이브 중 하나를 클릭하거나 폴더를 창으로 드래그하거나 상단 상자에 경로를 입력하고 Enter 키를 누릅니다. `je-file-tree D:\Projects`(또는 `python start_file_tree.py D:\Projects`) 명령줄에서 스캔을 시작할 수도 있습니다. 폴더를 삭제하면 폴더가 제자리에 스캔되고 복사 작업만 허용되며 Shift가 이동을 요청하는 경우에도 소스가 유지됩니다. 2. **채워지는 것을 지켜보세요**: 트리가 즉시 나타나고 FileTree가 작동하는 동안 가장 큰 폴더가 맨 위로 이동합니다. 스캔이 끝나면 가장 큰 파일과 파일 형식이 따릅니다. *Stop*(또는 Esc)은 언제든지 스캔을 종료하고 지금까지 읽은 내용을 불완전으로 표시하여 유지합니다. 3. **공간을 차지하는 항목 찾기**: 가장 큰 폴더가 트리 상단에 있습니다. 옆에 화살표가 있는 폴더를 열거나 오른쪽에 있는 차트를 탐색하세요. +1. **검사 대상 선택**: *폴더 선택…* 또는 시작 페이지의 드라이브 중 하나를 클릭하거나 폴더를 창으로 드래그하거나 상단 상자에 경로를 입력하고 Enter 키를 누릅니다. `je-file-tree D:\Projects`(또는 `python start_file_tree.py D:\Projects`) 명령줄에서 스캔을 시작할 수도 있습니다. 폴더를 삭제하면 폴더가 제자리에 스캔되고 복사 작업만 허용되며 Shift가 이동을 요청하는 경우에도 소스가 유지됩니다. 2. **채워지는 것을 지켜보세요**: 트리가 즉시 나타나고 FileTree가 작동하는 동안 가장 큰 폴더가 맨 위로 이동합니다. 스캔이 끝나면 가장 큰 파일과 파일 형식이 따릅니다. *Stop*(또는 Esc)은 언제든지 스캔을 종료하고 지금까지 읽은 내용을 불완전으로 표시하여 유지합니다. 스캔 중에는 스캔 결과를 읽거나 바꾸는 작업(휴지통으로 이동, 다시 스캔, 내보내기 등)이 스캔이 끝날 때까지 기다립니다. 그동안 이런 작업을 누르면 아무 반응이 없는 대신 상태 표시줄과 포인터 옆에 이유가 표시됩니다. 펼친 폴더가 많으면 창이 계속 반응하도록 폴더 트리의 갱신 간격을 늘립니다. 3. **공간을 차지하는 항목 찾기**: 가장 큰 폴더가 트리 상단에 있습니다. 옆에 화살표가 있는 폴더를 열거나 오른쪽에 있는 차트를 탐색하세요. ### 결과 읽기 diff --git a/docs/guide_zh-CN.md b/docs/guide_zh-CN.md index 708d2f4..2815458 100644 --- a/docs/guide_zh-CN.md +++ b/docs/guide_zh-CN.md @@ -290,7 +290,7 @@ python start_file_tree.py 1. **选择要扫描的地方**:在起始页点“选择文件夹…”或其中一个磁盘、把文件夹拖到窗口上,或在上方的输入框输入路径后按 Enter。也可以从命令行直接开始扫描:`je-file-tree D:\Projects`(或 `python start_file_tree.py D:\Projects`)。 拖动文件夹会在原位置扫描,且只接受复制操作;即使用 Shift 请求移动,也会保留来源。 -2. **边扫边看**:文件夹树会立刻出现,FileTree 一边加总,最大的文件夹一边往上排;最大的文件与文件类型在扫描结束时补上。随时可以点“停止”(或按 Esc)结束扫描,已经读到的部分会留下来并标示为不完整。 +2. **边扫边看**:文件夹树会立刻出现,FileTree 一边加总,最大的文件夹一边往上排;最大的文件与文件类型在扫描结束时补上。随时可以点“停止”(或按 Esc)结束扫描,已经读到的部分会留下来并标示为不完整。扫描进行中,会读取或更改扫描结果的操作(移到回收站、重新扫描、导出等)须等扫描完成;这时点击它们,状态栏与鼠标指针旁会说明原因,而不是没有反应。展开的文件夹很多时,文件夹树会放慢刷新频率,让窗口保持可操作。 3. **找出占空间的东西**:最大的文件夹排在最上面。点文件夹旁的箭头看里面的内容,或在右边的图表里浏览。 ### 看懂结果 diff --git a/docs/guide_zh-TW.md b/docs/guide_zh-TW.md index fd7163e..ba7201a 100644 --- a/docs/guide_zh-TW.md +++ b/docs/guide_zh-TW.md @@ -290,7 +290,7 @@ python start_file_tree.py 1. **選擇要掃描的地方**:在起始頁按「選擇資料夾…」或其中一顆磁碟、把資料夾拖曳到視窗上,或在上方的方框輸入路徑後按 Enter。也可以從命令列直接開始掃描:`je-file-tree D:\Projects`(或 `python start_file_tree.py D:\Projects`)。 拖曳資料夾會在原位置掃描,且只接受複製動作;即使用 Shift 要求移動,也會保留來源。 -2. **邊掃邊看**:資料夾樹會立刻出現,FileTree 一邊加總,最大的資料夾一邊往上排;最大的檔案與檔案類型在掃描結束時補上。隨時可以按「停止」(或 Esc)結束掃描,已經讀到的部分會留下來並標示為不完整。 +2. **邊掃邊看**:資料夾樹會立刻出現,FileTree 一邊加總,最大的資料夾一邊往上排;最大的檔案與檔案類型在掃描結束時補上。隨時可以按「停止」(或 Esc)結束掃描,已經讀到的部分會留下來並標示為不完整。掃描進行中,會讀取或變更掃描結果的操作(移到資源回收筒、重新掃描、匯出等)須等掃描完成;這時按下它們,狀態列與滑鼠指標旁會說明原因,而不是沒有反應。展開的資料夾很多時,資料夾樹會放慢更新頻率,讓視窗保持可操作。 3. **找出佔空間的東西**:最大的資料夾排在最上面。按資料夾旁的箭頭看裡面的內容,或在右邊的圖表裡瀏覽。 ### 看懂結果 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 8ef106f..7ba1077 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -504,3 +504,48 @@ - **變更**:範例改用隱藏屬性(0x2),測試的用意不變。本機重新執行所有含屬性值的 18 個測試檔:236 個通過。 - **檔案**:`test/test_windows_scan_metadata.py`。 - **待辦**:無。 + +## U-20261118-01 · 2026-11-18 · 掃描中的即時更新依耗時拉開間隔,不再逐列通知資料夾 · #snapshot #perf #gui #scan + + +- **原因**:使用者回報「顯示的資料夾太多時介面很卡」與「掃描更新時介面可能卡頓」。 +- **量測方法**:Windows 11、Python 3.14、PySide6,隱藏視窗(`WA_DontShowOnScreen`),在工作階段暫存資料夾自建 42,653 個資料夾/65,000 個檔案(其中一個資料夾含 20,000 個子資料夾),以 10 毫秒計時器量測事件迴圈的停頓;另以合成樹量測 `FolderTreeModel` 加 `QTreeView`。量測腳本只讀取自建的暫存資料,未刪除任何使用者資料。 +- **找到的原因**: + - 即時更新中,若顯示的資料夾成員與順序未變,`_repaint_live_folders` 仍對每段連續的資料夾列送出 `dataChanged`。Qt 的 `QTreeView::dataChanged` 會對範圍內每一列再詢問 `hasChildren`,一次更新約產生 18 萬次 Qt 呼叫 Python。U-20261017-76 量測的是 10 萬個「檔案」,檔案列不會被通知,所以當時沒有發現「資料夾」多時的成本。 + - 有新列或順序改變時,`layoutChanged` 會讓 Qt 重新排版所有展開的列,每列約兩次 Python 呼叫(`index`、`hasChildren`)。顯示 10 萬個資料夾時,一次約需 0.5 至 0.7 秒,而更新固定每 700 毫秒一次,視窗在兩次更新之間幾乎沒有空檔。這部分是 `QTreeView` 搭配 Python 模型的固有成本。 + - 掃描結束後瀏覽(捲動、選取、圖表進出資料夾、麵包屑)在這組資料上每次都低於 0.2 秒,不是主要原因。 +- **變更**: + - `FolderTreeModel._repaint_live_folders` 只通知根目錄列。`ResultsView.refresh_live` 本來就會重繪樹狀檢視的可見區域,畫面上的列會讀到最新總量,畫面外的列在顯示時才讀取。 + - 新增 `gui/live_refresh.py` 的 `LiveRefresh`,取代主視窗固定 700 毫秒的計時器:每次更新都計時,直到事件迴圈準備等待為止(包含 Qt 延後到下一輪執行的排版與繪製)。下一次更新等待耗時的 4 倍,下限 700 毫秒、上限 5 秒,因此即時更新最多佔用視窗約五分之一的時間。每次新的掃描都從 700 毫秒開始。 +- **結果**: + - 合成樹顯示 10 萬個資料夾,未變更的即時更新(含後續事件處理)中位數 342 毫秒降為 90 毫秒;2 萬個資料夾時 106 毫秒降為 62 毫秒。 + - 同樣 10 萬個資料夾、每次更新都有新列的 15 秒事件迴圈:固定 700 毫秒時,視窗有 71% 的時間被佔用,可回應的時間只有 18%,最長停頓 1,205 毫秒;改為依耗時調整後,佔用降為 22%,可回應的時間升為 79%,最長停頓 489 毫秒(剩下的是 Qt 對 10 萬列的一次排版)。 + - 在只顯示 2 萬個資料夾的實際掃描中,新舊版本的差異落在雜訊範圍內(兩者每次更新約 110 至 150 毫秒)。 +- **驗證**:新增 `test/test_live_refresh.py`(間隔界限、耗時長的更新會拉開下一次、耗時短時恢復、重新開始與停止);`test_tree_live_refresh.py` 改為只預期根目錄列的通知。`test_gui.py`、`test_layers.py`、`test_live_refresh.py` 與 17 個 `test_tree*.py`:264 個通過,1 個已知的長路徑測試失敗(本機未啟用 Windows 長路徑);`ruff check .`。 +- **未驗證**:使用者實際的磁碟與畫面;顯示超過 10 萬列時,單次排版的停頓仍會隨列數增加。 +- **檔案**:`je_file_tree/gui/tree_model.py`、`gui/live_refresh.py`、`gui/main_window.py`;`test/test_live_refresh.py`、`test/test_tree_live_refresh.py`;`architecture.md`。 +- **待辦**:無。 + +## U-20261118-02 · 2026-11-18 · 掃描或操作進行中按下須等待的操作時說明原因 · #decision #gui #ux #i18n + +- **原因**:使用者回報「掃描時如果不能執行某些操作,按下時應該要提醒」。先前掃描中,右鍵選單仍列出「移到資源回收筒」、「永久刪除」與「重新掃描這個資料夾」,按下卻沒有任何反應(`move_to_trash`、`delete_permanently`、`rescan_folder` 直接返回);選單列的對應項目與快速鍵(Delete、F5、Ctrl+F 等)則變成灰色,按下同樣沒有反應。 +- **決定**: + - 會讀取或變更掃描結果的操作(`main_window._WAIT_FOR_SCAN`)在掃描或檔案操作進行中保持可用;按下時不執行,改為在狀態列與滑鼠指標旁說明須等待掃描完成,或先停止掃描(Esc)。 + - 本身會開始掃描或重新啟動的操作(開啟資料夾、多個資料夾、以系統管理員身分重新啟動,`_WAIT_FOR_OPERATION`)只在另一項檔案操作進行中時說明等待原因。 + - 第一次掃描期間雖然還沒有結果,但已可選取即時資料夾樹,因此與結果相關的操作也保持可用並說明原因。 + - 右鍵選單的「重新掃描這個資料夾」,以及 `move_to_trash`、`delete_permanently`(右鍵選單、清理與重複檔案面板都經由這兩個入口),在等待時也會說明原因。 + - 沒有掃描或操作在進行時,行為與先前相同;分析尚未完成時停用的報告匯出也維持不變。 +- **檔案**:`je_file_tree/gui/busy_notice.py`、`gui/main_window.py`、`gui/strings.py`(`busy_scanning`、`busy_operation` 兩個字串,五種語言);`test/test_busy_notice.py`、`test/test_background_gui.py`;`docs/guide.md` 與四種語言的翻譯;`architecture.md`。 +- **驗證**:新增 `test/test_busy_notice.py`(7 個案例:名稱處理、五種語言、選單操作保持可用並說明、第一次掃描的即時樹、面板入口、右鍵重新掃描、其他操作進行中)。原本斷言「忙碌時停用」的 5 個測試改為斷言「可用並說明原因」:`test_background_gui.py`、`test_elevation_worker.py`、`test_permanent_delete_gui.py`、`test_trash_undo_gui.py`、`test_workspace_gui.py`。所有引用操作狀態、移除入口或右鍵選單的 37 個測試檔,加上 `test_i18n.py`、`test_readme_parity.py`:更新後全部通過(1 個已知的長路徑測試排除);`ruff check .`。 +- **待辦**:無。 + +## U-20261119-01 · 2026-11-19 · 圖表上切換上下層時按 Enter 會重新掃描整個根目錄 · #done #fix #gui #scan + +- **原因**:`progress.md` #143。使用者回報:未變更任何設定(「跟隨變更」為預設的關閉),在資料夾圖表上切換上下層時,有時會重新掃描整個根目錄。 +- **重現**:以隱藏視窗實際操作工作階段暫存資料夾中的自建資料。在路徑框輸入路徑並按 Enter 開始掃描後,鍵盤焦點仍留在路徑框;圖表的「上一層」、上一頁、下一頁與麵包屑按鈕都是不取得焦點的工具按鈕,用它們切換層級時焦點也不會移開。此時按 Enter(圖表的「進入資料夾」),按鍵實際送到路徑框,觸發「掃描路徑」,重新掃描整個根目錄;按 Backspace(圖表的「上一層」)則會刪掉路徑框的字元。在圖表上直接點選或連按兩下不會開始掃描(四種圖表的點選、連按兩下、右鍵、滾輪、滑鼠側鍵與方向鍵都試過)。 +- **修正**: + - `MainWindow._leave_path_box`:開始掃描時,若焦點在路徑框、「掃描路徑」按鈕或起始頁,就移到資料夾樹。 + - `ResultsView.focus_chart`:按下「上一層」、上一頁、下一頁或麵包屑後,把焦點交給畫面上的圖表,之後的 Enter 與 Backspace 都由圖表處理。 +- **驗證**:新增 `test/test_chart_focus.py`(2 個案例:從路徑框開始掃描後焦點在資料夾樹;焦點刻意留在路徑框時,使用圖表按鈕後按 Enter 與 Backspace 不會開始掃描,路徑框文字不變)。兩個案例在修正前都失敗。麵包屑、圖表、樹狀圖、起始頁、路徑框與開始掃描相關的測試檔:307 個通過(1 個已知的長路徑測試排除);`ruff check .`。 +- **檔案**:`je_file_tree/gui/main_window.py`、`gui/results_view.py`;`test/test_chart_focus.py`;`architecture.md`;`progress.md`(刪除 #143)。 +- **待辦**:無。 diff --git a/docs/updates/README.md b/docs/updates/README.md index 69b5806..f72f2e9 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -70,6 +70,9 @@ In the same commit: delete the item from `progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261119-01 | 2026-11-19 | 圖表上切換上下層時按 Enter 會重新掃描整個根目錄 | #done #fix #gui #scan | [2026-11](2026-11.md) | +| U-20261118-02 | 2026-11-18 | 掃描或操作進行中按下須等待的操作時說明原因 | #decision #gui #ux #i18n | [2026-11](2026-11.md) | +| U-20261118-01 | 2026-11-18 | 掃描中的即時更新依耗時拉開間隔,不再逐列通知資料夾 | #snapshot #perf #gui #scan | [2026-11](2026-11.md) | | U-20261115-14 | 2026-11-15 | CI 發現一個測試以檔案表索引旗標當範例屬性 | #incident #ci #scanner #windows | [2026-11](2026-11.md) | | U-20261115-13 | 2026-11-15 | 計入硬連結與其他分頁的刪除不再重掃整個根目錄 | #decision #gui #scan #perf | [2026-11](2026-11.md) | | U-20261115-12 | 2026-11-15 | 新建立的空資料夾掃描後被判定已變更 | #incident #fix #scanner #native #windows | [2026-11](2026-11.md) | diff --git a/je_file_tree/gui/busy_notice.py b/je_file_tree/gui/busy_notice.py new file mode 100644 index 0000000..1546099 --- /dev/null +++ b/je_file_tree/gui/busy_notice.py @@ -0,0 +1,43 @@ +"""Say why an action did nothing: a scan or another operation is running and it has to wait. + +While a scan runs (or a move to the Recycle Bin, a deletion, an undo or a review in this or another +tab), the actions that would read or change the scanned entries cannot start. Pressing one used to do +nothing at all; now it stays enabled and, when used, says why it waits and what ends the wait. The +notice goes to the status bar and, as a tooltip, next to the pointer, where the user just clicked. +""" + +from __future__ import annotations + +from PySide6.QtCore import QPoint +from PySide6.QtGui import QCursor +from PySide6.QtWidgets import QMainWindow, QToolTip + +from je_file_tree.gui.i18n import tr + +NOTICE_MS = 8000 # as long as the window's other status messages + + +def action_name(text: str) -> str: + """A menu text as it reads in a sentence: no mnemonic ampersands or trailing ellipsis.""" + name = text.replace("&&", "\0").replace("&", "").replace("\0", "&").strip() + for ending in ("…", "..."): + if name.endswith(ending): + name = name[:-len(ending)].rstrip() + return name + + +def busy_text(action: str, *, scanning: bool) -> str: + """The notice for ``action``, which waits for the running scan or for another operation.""" + return tr("busy_scanning" if scanning else "busy_operation", action=action_name(action)) + + +def show_busy(window: QMainWindow, action: str, *, scanning: bool) -> str: + """Show why ``action`` did not start, in the status bar and next to the pointer; returns the text.""" + text = busy_text(action, scanning=scanning) + window.statusBar().showMessage(text, NOTICE_MS) + pointer = QCursor.pos() + inside = window.rect().contains(window.mapFromGlobal(pointer)) + bar = window.statusBar() + where = pointer if inside else bar.mapToGlobal(QPoint(0, 0)) + QToolTip.showText(where, text, window, window.rect(), NOTICE_MS) + return text diff --git a/je_file_tree/gui/live_refresh.py b/je_file_tree/gui/live_refresh.py new file mode 100644 index 0000000..501428f --- /dev/null +++ b/je_file_tree/gui/live_refresh.py @@ -0,0 +1,75 @@ +"""Space a running scan's live refreshes by what each one cost the window. + +A live refresh shows what the scan added: the folder tree relays out every shown row, the treemap +redraws. Its cost grows with the rows on screen: with 100,000 shown folders one refresh kept the window +busy about 0.7 s, against a fixed 700 ms period, so the window was never free between two refreshes +(U-20261118-01). Each refresh is therefore timed until the window's event loop is about to wait again, +which includes the layout and painting Qt defers to the following event pass, and the next one waits +``SPACING`` times that long, between ``FASTEST_MS`` and ``SLOWEST_MS``. +""" + +from __future__ import annotations + +import time +from collections.abc import Callable + +from PySide6.QtCore import QAbstractEventDispatcher, QObject, QTimer + +FASTEST_MS = 700 # the period while refreshes are cheap +SLOWEST_MS = 5000 # the scan still shows progress this often, however many rows are shown +SPACING = 4 # wait four times a refresh's busy time: refreshes take at most a fifth of the window's time + + +def interval_for(busy_ms: float) -> int: + """The wait before the next refresh after one that kept the window busy ``busy_ms``.""" + return round(min(SLOWEST_MS, max(FASTEST_MS, busy_ms * SPACING))) + + +class LiveRefresh(QObject): + """A repeating timer for ``refresh`` whose period follows the measured cost of each call.""" + + def __init__(self, refresh: Callable[[], None], parent: QObject) -> None: + super().__init__(parent) + self._refresh = refresh + self._timer = QTimer(self) + self._timer.setInterval(FASTEST_MS) + self._timer.timeout.connect(self._tick) + self._started: float | None = None + self._dispatcher: QAbstractEventDispatcher | None = None + + @property + def interval(self) -> int: + """The current period in milliseconds.""" + return self._timer.interval() + + def isActive(self) -> bool: # noqa: N802 - mirrors QTimer + """Whether refreshes are running.""" + return self._timer.isActive() + + def start(self) -> None: + """Start refreshing at the fastest period (a new scan starts with an empty tree).""" + self._timer.start(FASTEST_MS) + + def stop(self) -> None: + """Stop refreshing; a measurement still pending is dropped when it arrives.""" + self._timer.stop() + + def _tick(self) -> None: + self._started = time.perf_counter() + self._refresh() + dispatcher = QAbstractEventDispatcher.instance() + if dispatcher is not None and self._dispatcher is None: + self._dispatcher = dispatcher + dispatcher.aboutToBlock.connect(self._settled) + + def _settled(self) -> None: + """The event loop is about to wait: the refresh and the work it queued are done.""" + dispatcher, self._dispatcher = self._dispatcher, None + if dispatcher is not None: + dispatcher.aboutToBlock.disconnect(self._settled) + started, self._started = self._started, None + if started is None or not self._timer.isActive(): + return + interval = interval_for((time.perf_counter() - started) * 1000) + if interval != self._timer.interval(): + self._timer.setInterval(interval) diff --git a/je_file_tree/gui/main_window.py b/je_file_tree/gui/main_window.py index e71ec3a..060b2c1 100644 --- a/je_file_tree/gui/main_window.py +++ b/je_file_tree/gui/main_window.py @@ -51,6 +51,8 @@ from je_file_tree.gui.scan_preferences import MAX_SCAN_WORKERS as _MAX_SCAN_WORKERS, SCAN_FLAGS, ScanDefaults from je_file_tree.gui.special_files import SpecialFilesDialog from je_file_tree.gui.live_compare import LiveCompareDialog +from je_file_tree.gui.live_refresh import LiveRefresh +from je_file_tree.gui.busy_notice import show_busy from je_file_tree.gui.git_history import GitHistoryDialog from je_file_tree.gui.history import HistoryDialog, HistorySettings, configured_history, history_folder, history_limit from je_file_tree.gui.recurring_review import RecurringReview @@ -112,14 +114,23 @@ from je_file_tree.gui.window_fit import fit_window WELCOME_PAGE, RESULTS_PAGE = range(2) -# How often the tree of a running scan is refreshed. -LIVE_REFRESH_MS = 700 _MAX_RECENT = 10 _UNITS = (AUTO_UNIT, *SIZE_UNITS[1:5]) _LISTED_NAMES = 8 # entries named in a Recycle Bin question; the rest are counted _MAX_REFUSAL_NOTICE = 1024 _ACTION_ICONS = {"open": "folder", "rescan": "refresh", "stop": "stop", "help": "help"} _STATUS_TIMEOUT_MS = 8000 +# Actions that read or change the scanned entries wait for a running scan or source operation. They stay +# enabled meanwhile and, when used, say why they wait instead of doing nothing (gui.busy_notice). +_WAIT_FOR_SCAN = frozenset({ + "rescan", "export_folders", "export_largest", "export_list", "export_json", "export_chart_png", + "export_chart_svg", "print_view", "export_view_pdf", "export_report_html", "export_report_xlsx", "trash", + "permanent_delete", "find", "compare", "special_files", "live_compare", "git_history", "history", + "recurring", "scan_presets", "projects", "programs", "virtual_disks", "file_times", "volumes", "disks", + "bins", "cleanup_policy", +}) +# These start a scan or a restart themselves, so only a running source operation makes them wait. +_WAIT_FOR_OPERATION = frozenset({"open", "multi_scan", "elevate"}) ASK_ADMIN_KEY = "ask_admin_at_start" EXCLUSIONS_KEY = "exclusions" SEARCHES_KEY = "saved_searches" @@ -196,9 +207,7 @@ def __init__(self, settings: QSettings | None = None, *, operations: OperationGr self.pages = QStackedWidget() for page in (self.welcome, self.results): self.pages.addWidget(page) - self._live_timer = QTimer(self) - self._live_timer.setInterval(LIVE_REFRESH_MS) - self._live_timer.timeout.connect(self.results.refresh_live) + self._live_timer = LiveRefresh(self.results.refresh_live, self) # spaced by its cost (U-20261118-01) self.setCentralWidget(self.pages) self.path_edit = QLineEdit() self._actions: dict[str, QAction] = {} @@ -420,10 +429,22 @@ def _begin_scan(self, path: str | tuple[str, ...], *, exact_allocation: bool = F self.results.begin_scan() self.scan_activity_changed.emit() self.pages.setCurrentIndex(RESULTS_PAGE) + self._leave_path_box() self._update_actions() self._live_timer.start() after_threads((*self._scan_workers, *background, *following), lambda: self._dispatch_scan(worker), self) + def _leave_path_box(self) -> None: + """Move keyboard focus from the path box (or the start page) to the results of a new scan. + + Focus stayed in the path box after Enter started a scan, so a later Enter meant for the chart + or the tree scanned the whole root again and Backspace edited the path (U-20261119-01). + """ + focused = self.focusWidget() # the window's own focus, also while another program is active + if (focused is None or focused is self.path_edit or focused is self._scan_path + or self.welcome.isAncestorOf(focused)): + self.results.focus_results() + def _dispatch_scan(self, worker: ScanWorker) -> None: if self._closing or worker is not self._worker or worker is not self._pending_scan: return @@ -555,7 +576,8 @@ def show_menu_for(self, node: Node, picked: Sequence[Node], point: QPoint, *, ch entries.append(("archive_stop", lambda: self.results.archives.stop(node))) if node.is_dir and not node.is_link: entries.append(("menu_show_chart", lambda: self._show_in_chart(node))) - entries.append(("menu_rescan_here", lambda: self.rescan_folder(node))) + entries.append(("menu_rescan_here", lambda: self._explain_busy(tr("menu_rescan_here")) + or self.rescan_folder(node))) entries.append(("menu_scan_here", lambda: self.start_scan(node.path))) if (elevation.supported() and self._worker is None and not self.operation_busy and self.results.outcome is not None and self.results.outcome.result.root.path is not None): @@ -851,7 +873,9 @@ def move_to_trash(self, nodes: Sequence[Node], *, copies: CopyApproval | None = """ chosen = _movable(nodes) root = self.results.tree_model.root - if (not chosen or root is None or root.path is None or self._worker is not None or self.operation_busy + if (not chosen or root is None or root.path is None + or self._explain_busy(tr("action_trash")) # a scan or operation runs: say so + or self._worker is not None or self.operation_busy or copies is not None and not copies.matches(root, chosen) or proposal is not None and (not proposal.matches(root, chosen) or not self._proposal_current(proposal))): @@ -916,8 +940,9 @@ def delete_permanently(self, nodes: Sequence[Node]) -> None: """ chosen = _movable(nodes) root = self.results.tree_model.root - if (not chosen or root is None or root.path is None or self._worker is not None or self.operation_busy - or self._closing): + if (not chosen or root is None or root.path is None + or self._explain_busy(tr("permanent_delete")) # a scan or operation runs: say so + or self._worker is not None or self.operation_busy or self._closing): return managed = {node for node in chosen if system_file(node.path) is not None} if managed: @@ -1247,6 +1272,23 @@ def _find(self) -> None: if self.pages.currentIndex() == RESULTS_PAGE and self.results.outcome is not None: self.results.show_search() + def _run_action(self, key: str, run: Callable[[], object]) -> None: + """Run a menu action, or say why it waits for the running scan or operation (``_WAIT_FOR_SCAN``).""" + waits = key in _WAIT_FOR_SCAN or key in _WAIT_FOR_OPERATION + if waits and self._explain_busy(self._actions[key].text(), scan=key in _WAIT_FOR_SCAN): + return + run() + + def _explain_busy(self, action: str, *, scan: bool = True) -> bool: + """Whether ``action`` has to wait (a scan, with ``scan``, or a source operation); if so, say so.""" + if self._closing: + return False + scanning = scan and self._worker is not None + if not scanning and not self.operation_busy: + return False + show_busy(self, action, scanning=scanning) + return True + def _trash_selected(self) -> None: if self.pages.currentIndex() == RESULTS_PAGE: self.move_to_trash(self.results.focused_selection()) @@ -1692,10 +1734,11 @@ def _build_actions(self) -> None: action = QAction(self) if shortcut is not None: action.setShortcut(QKeySequence(shortcut)) - action.triggered.connect(lambda _checked=False, run=handler: run()) + action.triggered.connect(lambda _checked=False, run=handler, name=key: self._run_action(name, run)) self._actions[key] = action self._reclaim_action = QAction(self) - self._reclaim_action.triggered.connect(lambda _checked=False: self.show_reclaim()) + self._reclaim_action.triggered.connect( + lambda _checked=False: self._explain_busy(self._reclaim_action.text()) or self.show_reclaim()) self._configure_actions() def _configure_actions(self) -> None: @@ -1881,43 +1924,40 @@ def _update_actions(self) -> None: self.pending_source_workers() if self._operations is not None: self._operations.refresh(self) - self._actions["elevate"].setEnabled( - not self._closing and not self.operation_busy and not self._settings_dialogs) + # Actions in _WAIT_FOR_SCAN / _WAIT_FOR_OPERATION stay enabled while a scan or an operation runs, so + # that using one says why it waits (_run_action) instead of a greyed item doing nothing. scanning = self._worker is not None or self.operation_busy - self._actions["scan_presets"].setEnabled(not scanning and not self._closing and not self._settings_dialogs) - self.welcome.presets.setEnabled(self._actions["scan_presets"].isEnabled()) - self._actions["recurring"].setEnabled(self._recurring_show is not None and not scanning) - has_results = self.results.outcome is not None + self._actions["elevate"].setEnabled(not self._closing and not self._settings_dialogs) + self._actions["scan_presets"].setEnabled(not self._closing and not self._settings_dialogs) + self.welcome.presets.setEnabled(self._actions["scan_presets"].isEnabled() and not scanning) + self._actions["recurring"].setEnabled(self._recurring_show is not None) self._actions["stop"].setEnabled(scanning) - self._actions["open"].setEnabled(not self.operation_busy) - self._actions["cleanup_policy"].setEnabled(not scanning) - self._actions["live_compare"].setEnabled(not scanning) - self._actions["volumes"].setEnabled(not scanning) - self._actions["disks"].setEnabled(not scanning) - self._actions["bins"].setEnabled(not scanning) - self._actions["rescan"].setEnabled(bool(self._last_path or self._last_roots) and not scanning) - for key in ("export_folders", "export_largest", "export_json", "export_chart_png", "trash", "permanent_delete", - "find", "compare"): - self._actions[key].setEnabled(has_results and not scanning) - self._actions["export_chart_svg"].setEnabled(has_results and not scanning - and self.results.charts.mode in SVG_MODES) - for key in ("print_view", "export_view_pdf", "special_files", "git_history", "projects", "history", - "programs", "virtual_disks", "file_times"): - self._actions[key].setEnabled(has_results and not scanning) - for key in ("export_report_html", "export_report_xlsx"): - self._actions[key].setEnabled(has_results and not scanning and not self.operation_busy - and not self._analysers) - self._actions['export_list'].setEnabled(has_results and not scanning - and self.results.current_list() is not None) - virtual = has_results and self.results.outcome.result.root.path is None - for key in ("trash", "permanent_delete", "history", "git_history"): - self._actions[key].setEnabled(has_results and not scanning and not virtual) - self._reclaim_action.setEnabled(has_results and not scanning and not virtual) - self._actions["multi_scan"].setEnabled(not self.operation_busy) + for key in ("open", "multi_scan", "cleanup_policy", "live_compare", "volumes", "disks", "bins"): + self._actions[key].setEnabled(True) + self._actions["rescan"].setEnabled(bool(self._last_path or self._last_roots)) + # A running scan's live tree can be selected before there is an outcome: its actions explain the wait. + self._update_result_actions(self.results.outcome is not None + or scanning and self.results.tree_model.root is not None) self.welcome.scan_all.setEnabled(not scanning and bool(self.welcome.drive_rows)) self._update_bin_buttons() self._update_refresh_notice() + def _update_result_actions(self, shown: bool) -> None: + """Enable the actions on the results on screen (``shown``); a running scan makes them explain instead.""" + for key in ("export_folders", "export_largest", "export_json", "export_chart_png", "find", "compare", + "print_view", "export_view_pdf", "special_files", "projects", "programs", "virtual_disks", + "file_times"): + self._actions[key].setEnabled(shown) + self._actions["export_chart_svg"].setEnabled(shown and self.results.charts.mode in SVG_MODES) + for key in ("export_report_html", "export_report_xlsx"): + self._actions[key].setEnabled(shown and not self._analysers) + self._actions["export_list"].setEnabled(shown and self.results.current_list() is not None) + outcome = self.results.outcome + virtual = outcome is not None and outcome.result.root.path is None + for key in ("trash", "permanent_delete", "history", "git_history"): + self._actions[key].setEnabled(shown and not virtual) + self._reclaim_action.setEnabled(shown and not virtual) + def _update_bin_buttons(self) -> None: ready = not self._closing and self._worker is None and not self.operation_busy idle = ready and not self._bin_labels.busy diff --git a/je_file_tree/gui/results_view.py b/je_file_tree/gui/results_view.py index 4173021..6e39f58 100644 --- a/je_file_tree/gui/results_view.py +++ b/je_file_tree/gui/results_view.py @@ -442,6 +442,14 @@ def selected_nodes(self) -> list[Node]: """Every entry selected in the tree (Ctrl+click and Shift+click pick several).""" return _selected_in(self.tree) + def focus_chart(self) -> None: + """Give keyboard focus to the chart on screen, where its navigation keys work.""" + self.charts.current_chart().setFocus(Qt.FocusReason.OtherFocusReason) + + def focus_results(self) -> None: + """Give keyboard focus to the folder tree (a new scan fills it).""" + self.tree.setFocus(Qt.FocusReason.OtherFocusReason) + def focused_selection(self) -> list[Node]: """The entries selected where the keyboard is: the largest-files, search or duplicates list, else the tree.""" for view in (self.largest_table, self.search_table, self.duplicates.view, self.cleanup.view): @@ -748,6 +756,13 @@ def _assemble_chart_tab(self) -> None: """The Chart tab: the path and view buttons, the treemap options, the charts and the legend.""" self._treemap_up.clicked.connect(self.charts.zoom_out) self.breadcrumbs.navigate.connect(self.charts.set_view_root) + # The Up, Back, Forward and ancestor buttons take no focus of their own: hand it to the chart, so + # that Enter (into a folder) and Backspace (up) go on there and never reach the path box at the + # top, where Enter scanned the whole root again (U-20261119-01). + self._treemap_up.clicked.connect(self.focus_chart) + self.breadcrumbs.back.clicked.connect(self.focus_chart) + self.breadcrumbs.forward.clicked.connect(self.focus_chart) + self.breadcrumbs.navigate.connect(lambda _node: self.focus_chart()) self.charts.node_clicked.connect(self._treemap_clicked) self.charts.view_root_changed.connect(self._treemap_root_changed) self.charts.context_menu_requested.connect(self._emit_menu) diff --git a/je_file_tree/gui/strings.py b/je_file_tree/gui/strings.py index aedfc49..e0fd860 100644 --- a/je_file_tree/gui/strings.py +++ b/je_file_tree/gui/strings.py @@ -11,6 +11,10 @@ def _cjk(html: str) -> str: EN: dict[str, str] = { + "busy_scanning": ("“{action}” has to wait for the scan that is running. " + "Let it finish, or stop it first (Esc)."), + "busy_operation": ("“{action}” has to wait: another operation on the scanned files is still running. " + "Try again once it has finished."), "budget_filter": "Show budgets", "budget_filter_all": "All budgets", "budget_filter_over": "Over limit", @@ -1913,6 +1917,10 @@ def _cjk(html: str) -> str: } ZH_TW: dict[str, str] = { + "busy_scanning": ("掃描進行中,「{action}」須等掃描完成才能執行。" + "請等掃描結束,或先停止掃描(Esc)。"), + "busy_operation": ("另一項檔案操作仍在進行,「{action}」須等它完成才能執行。" + "請在操作結束後再試一次。"), "budget_filter": "顯示預算", "budget_filter_all": "全部預算", "budget_filter_over": "超過上限", @@ -3609,6 +3617,10 @@ def _cjk(html: str) -> str: } ZH_CN: dict[str, str] = { + "busy_scanning": ("扫描进行中,“{action}”须等扫描完成才能执行。" + "请等扫描结束,或先停止扫描(Esc)。"), + "busy_operation": ("另一项文件操作仍在进行,“{action}”须等它完成才能执行。" + "请在操作结束后再试一次。"), "budget_filter": "显示预算", "budget_filter_all": "全部预算", "budget_filter_over": "超过上限", @@ -5317,6 +5329,10 @@ def _cjk(html: str) -> str: JA: dict[str, str] = { + "busy_scanning": ("スキャン中のため「{action}」は実行できません。" + "スキャンの完了を待つか、先にスキャンを停止してください(Esc)。"), + "busy_operation": ("別のファイル操作が実行中のため「{action}」は実行できません。" + "操作の完了後にもう一度お試しください。"), "budget_filter": "予算を表示", "budget_filter_all": "すべての予算", "budget_filter_over": "上限超過", @@ -7428,6 +7444,10 @@ def _cjk(html: str) -> str: KO: dict[str, str] = { + "busy_scanning": ("스캔이 진행 중이라 '{action}'을(를) 실행할 수 없습니다. " + "스캔이 끝날 때까지 기다리거나 먼저 스캔을 중지하세요(Esc)."), + "busy_operation": ("다른 파일 작업이 진행 중이라 '{action}'을(를) 실행할 수 없습니다. " + "작업이 끝난 후 다시 시도하세요."), "budget_filter": "예산 표시", "budget_filter_all": "모든 예산", "budget_filter_over": "한도 초과", diff --git a/je_file_tree/gui/tree_model.py b/je_file_tree/gui/tree_model.py index f32b9d1..02d5999 100644 --- a/je_file_tree/gui/tree_model.py +++ b/je_file_tree/gui/tree_model.py @@ -169,28 +169,16 @@ def refresh(self) -> None: self._live_presence = self._shown_presence() if self._live else {} def _repaint_live_folders(self) -> None: - """Notify the root and every shown folder row: during a scan only folder totals change. + """Notify the root row only: during a scan only totals change, and the view repaints the rest. - A file row's own values are final when the scanner adds it; only its share of the growing - parent changes, which the view repaints on screen (ResultsView.refresh_live). One range over - every shown row made Qt query hasChildren 100,000 times (about 0.3 s, U-20261017-76). + ``ResultsView.refresh_live`` repaints the tree's viewport, so every row on screen reads its + fresh totals; rows off screen read them when they are shown. Qt's ``QTreeView::dataChanged`` + queries ``hasChildren`` for every row of a range, so notifying the shown folder rows cost a + Python call per folder: with 100,000 shown folders a tick took 342 ms against 117 ms with the + root alone (U-20261118-01). """ - last = len(COLUMN_KEYS) - 1 if self._root is not None: - self.dataChanged.emit(self.index(0, 0), self.index(0, last), []) - for parent in tuple(self._queried_parents): - parent_index = self.index_for(parent) - if not parent_index.isValid(): - continue - start = None - order = self._orders.get(id(parent), ()) - for row, node in enumerate((*order, None)): - if node is not None and node.is_dir: - start = row if start is None else start - elif start is not None: - self.dataChanged.emit(self.index(start, 0, parent_index), - self.index(row - 1, last, parent_index), []) - start = None + self.dataChanged.emit(self.index(0, 0), self.index(0, len(COLUMN_KEYS) - 1), []) def _shown_presence(self) -> dict[int, bool]: """Whether each shown folder has entries, which decides its expand arrow; reads frozen live orders.""" diff --git a/test/test_background_gui.py b/test/test_background_gui.py index b979458..fa0f6b6 100644 --- a/test/test_background_gui.py +++ b/test/test_background_gui.py @@ -15,6 +15,7 @@ from je_file_tree.core.cleanup_policy import CleanupPolicy, RuleSetting from je_file_tree.core.history import ScanHistory, load_recurring from je_file_tree.core.recurring import ProposalCancelledError +from je_file_tree.gui.busy_notice import busy_text from je_file_tree.gui import app as gui_app, background_monitor as service, background_worker as workers from je_file_tree.gui.background_dialog import BackgroundDialog from je_file_tree.gui.app import create_workspace @@ -406,8 +407,11 @@ def test_recurring_view_guard_serializes_tabs_and_never_runs_sources(monitored, called = [] def view(dialog): - assert monitored.operations.busy and not owner._actions["recurring"].isEnabled() - assert not other._actions["recurring"].isEnabled() + assert monitored.operations.busy + # The other tab's action stays usable but waits, saying so, instead of opening a second view. + assert other._actions["recurring"].isEnabled() + other._actions["recurring"].trigger() + assert other.statusBar().currentMessage() == busy_text(other._actions["recurring"].text(), scanning=False) called.append(True) return 0 diff --git a/test/test_busy_notice.py b/test/test_busy_notice.py new file mode 100644 index 0000000..8a94ed8 --- /dev/null +++ b/test/test_busy_notice.py @@ -0,0 +1,133 @@ +"""Actions that wait for a running scan or operation say so when used, instead of doing nothing.""" + +from __future__ import annotations + +import time +from pathlib import Path + +import pytest +from PySide6.QtCore import QCoreApplication, QEvent, QSettings +from PySide6.QtWidgets import QApplication, QMenu + +from conftest import make_tree +from je_file_tree.gui import i18n +from je_file_tree.gui import main_window as main_window_module +from je_file_tree.gui.app import create_window +from je_file_tree.gui.busy_notice import action_name, busy_text +from je_file_tree.gui.i18n import tr + + +def _wait(app: QApplication, done, timeout: float = 10.0) -> None: + deadline = time.monotonic() + timeout + while not done(): + assert time.monotonic() < deadline, "timed out" + app.processEvents() + time.sleep(0.01) + app.processEvents() + + +@pytest.fixture +def window(qapp: QApplication, tmp_path: Path): + settings = QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat) + settings.setValue("language", "en") + main = create_window(settings) + yield main + main._worker = None + main._trash_worker = None + main.close() + _wait(qapp, lambda: main._close_ready) + main.deleteLater() + QCoreApplication.sendPostedEvents(main, QEvent.Type.DeferredDelete) + i18n.set_language(i18n.DEFAULT_LANGUAGE) + + +@pytest.fixture +def scanned(window, qapp: QApplication, tmp_path: Path): + folder = tmp_path / "scan" + folder.mkdir() + make_tree(folder, {"photos": {"a.jpg": b"a" * 300}, "notes.txt": b"n" * 20}) + window.start_scan(str(folder)) + _wait(qapp, lambda: window.results.outcome is not None and window._worker is None) + return window.results.outcome.result.root + + +def test_action_names_read_like_part_of_a_sentence(): + assert action_name("&Move to Recycle Bin") == "Move to Recycle Bin" + assert action_name("Export the chart…") == "Export the chart" + assert action_name("Save && close...") == "Save & close" + + +def test_every_language_names_the_action_in_both_notices(): + for language in i18n.STRINGS: + i18n.set_language(language) + assert "Rescan" in busy_text("&Rescan…", scanning=True) + assert "Rescan" in busy_text("Rescan", scanning=False) + i18n.set_language("en") + assert busy_text("Rescan", scanning=True) != busy_text("Rescan", scanning=False) + + +def test_menu_actions_stay_enabled_during_a_scan_and_explain_instead_of_running(window, scanned, monkeypatch): + monkeypatch.setattr(window, "move_to_trash", lambda *_args, **_kwargs: pytest.fail("ran during a scan")) + window._worker = object() # a running scan + window._update_actions() + for key in ("trash", "permanent_delete", "rescan", "find", "export_json", "volumes"): + assert window._actions[key].isEnabled(), key + window.results.select_node(scanned.children[0]) + window._actions["trash"].trigger() + assert window.statusBar().currentMessage() == busy_text(window._actions["trash"].text(), scanning=True) + rescans = [] + monkeypatch.setattr(window, "start_scan", lambda *args, **_kwargs: rescans.append(args)) + window._actions["rescan"].trigger() + assert rescans == [] + assert window.statusBar().currentMessage() == busy_text(window._actions["rescan"].text(), scanning=True) + window._worker = None + window._update_actions() + window._actions["rescan"].trigger() # once the scan is over the action simply runs + assert len(rescans) == 1 + + +def test_a_live_tree_before_any_result_offers_its_actions_with_the_notice(window, scanned): + window.results._outcome = None # a first scan: only the live tree is on screen + window._worker = object() + window._update_actions() + assert window._actions["trash"].isEnabled() and window._actions["export_json"].isEnabled() + window._worker = None + window._update_actions() + assert not window._actions["trash"].isEnabled() and not window._actions["export_json"].isEnabled() + + +def test_removals_from_menus_and_panels_explain_while_a_scan_runs(window, scanned): + entry = scanned.children[0] + window._worker = object() + window.move_to_trash([entry]) # a context menu or a clean-up panel button calls these directly + assert window.statusBar().currentMessage() == busy_text(tr("action_trash"), scanning=True) + window.delete_permanently([entry]) + assert window.statusBar().currentMessage() == busy_text(tr("permanent_delete"), scanning=True) + assert entry in scanned.children + + +def test_rescan_this_folder_in_the_context_menu_explains_while_a_scan_runs(window, scanned, monkeypatch): + folder = next(child for child in scanned.children if child.is_dir) + + class ChoosingMenu(QMenu): + def exec(self, *_args: object) -> None: # instead of waiting for a click, choose Rescan this folder + next(action for action in self.actions() if action.text() == tr("menu_rescan_here")).trigger() + + monkeypatch.setattr(main_window_module, "QMenu", ChoosingMenu) + monkeypatch.setattr(window, "rescan_folder", lambda *_args, **_kwargs: pytest.fail("ran during a scan")) + window._worker = object() + window.show_menu_for(folder, [folder], window.mapToGlobal(window.rect().center())) + assert window.statusBar().currentMessage() == busy_text(tr("menu_rescan_here"), scanning=True) + + +def test_another_operation_makes_scan_starting_actions_wait_too(window, scanned, monkeypatch): + monkeypatch.setattr(main_window_module.QFileDialog, "getExistingDirectory", + lambda *_args, **_kwargs: pytest.fail("asked for a folder during an operation")) + window._trash_worker = object() # a move to the Recycle Bin is running + window._update_actions() + assert window._actions["open"].isEnabled() + window._actions["open"].trigger() + assert window.statusBar().currentMessage() == busy_text(window._actions["open"].text(), scanning=False) + window._trash_worker = None + window._worker = object() # a scan alone does not hold up Open: choosing a folder starts a new scan + assert not window._explain_busy(window._actions["open"].text(), scan=False) diff --git a/test/test_chart_focus.py b/test/test_chart_focus.py new file mode 100644 index 0000000..8115441 --- /dev/null +++ b/test/test_chart_focus.py @@ -0,0 +1,85 @@ +"""Keys meant for the chart never reach the path box, where Enter scanned the whole root (U-20261119-01).""" + +from __future__ import annotations + +import time +from pathlib import Path + +import pytest +from PySide6.QtCore import QCoreApplication, QEvent, QSettings, Qt +from PySide6.QtTest import QTest +from PySide6.QtWidgets import QApplication + +from conftest import make_tree +from je_file_tree.gui import i18n +from je_file_tree.gui.app import create_window +from je_file_tree.gui.results_view import CHART_TAB + + +def _wait(app: QApplication, done, timeout: float = 10.0) -> None: + deadline = time.monotonic() + timeout + while not done(): + assert time.monotonic() < deadline, "timed out" + app.processEvents() + time.sleep(0.01) + app.processEvents() + + +@pytest.fixture +def window(qapp: QApplication, tmp_path: Path): + settings = QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat) + settings.setValue("language", "en") + main = create_window(settings) + main.show() + yield main + main.close() + _wait(qapp, lambda: main._close_ready) + main.deleteLater() + QCoreApplication.sendPostedEvents(main, QEvent.Type.DeferredDelete) + i18n.set_language(i18n.DEFAULT_LANGUAGE) + + +def _scan_from_the_path_box(window, qapp: QApplication, folder: Path) -> None: + """Type the folder and press Enter, as a user starts a scan from the box at the top.""" + window.path_edit.setFocus() + window.path_edit.setText(str(folder)) + QTest.keyClick(window.path_edit, Qt.Key.Key_Return) + _wait(qapp, lambda: window.results.outcome is not None and window._worker is None) + + +@pytest.fixture +def folder(tmp_path: Path) -> Path: + root = tmp_path / "scan" + root.mkdir() + make_tree(root, {"photos": {"2024": {"a.jpg": b"a" * 400}, "b.jpg": b"b" * 200}, "notes.txt": b"n" * 20}) + return root + + +def test_a_scan_started_from_the_path_box_moves_focus_to_the_results(window, qapp, folder): + _scan_from_the_path_box(window, qapp, folder) + assert window.focusWidget() is window.results.tree + + +def test_enter_and_backspace_after_the_chart_buttons_stay_in_the_chart(window, qapp, folder, monkeypatch): + _scan_from_the_path_box(window, qapp, folder) + window.path_edit.setFocus() # the worst case: the path box has focus while the chart is used + results = window.results + results.tabs.setCurrentIndex(CHART_TAB) + root = results.tree_model.root + photos = next(child for child in root.children if child.name == "photos") + scans = [] + monkeypatch.setattr(window, "_begin_scan", lambda *args, **kwargs: scans.append(args)) + results.breadcrumbs.navigate.emit(photos) # an ancestor button or Back/Forward + assert window.focusWidget() is results.charts.current_chart() + QTest.mouseClick(results._treemap_up, Qt.MouseButton.LeftButton) + assert results.charts.view_root is root + assert window.focusWidget() is results.charts.current_chart() + for key in (Qt.Key.Key_Return, Qt.Key.Key_Backspace): + QTest.keyClick(window.focusWidget(), key) + assert scans == [], "a key meant for the chart scanned the whole root again" + assert window.path_edit.text() == str(folder), "Backspace edited the path box" + for button in (results.breadcrumbs.back, results.breadcrumbs.forward): + window.path_edit.setFocus() + button.setEnabled(True) + QTest.mouseClick(button, Qt.MouseButton.LeftButton) + assert window.focusWidget() is results.charts.current_chart() diff --git a/test/test_elevation_worker.py b/test/test_elevation_worker.py index 8bf01c0..7524746 100644 --- a/test/test_elevation_worker.py +++ b/test/test_elevation_worker.py @@ -7,6 +7,7 @@ import pytest from test_gui import _wait +from je_file_tree.gui.busy_notice import busy_text from je_file_tree.gui.elevation_dialog import ElevationDialog, ElevationWorker from je_file_tree.gui.i18n import tr @@ -154,7 +155,10 @@ def test_busy_or_closing_windows_do_not_launch(window, monkeypatch): window._path_dialogs.add(guard) try: window._update_actions() - assert not window._actions["elevate"].isEnabled() + elevate = window._actions["elevate"] + assert elevate.isEnabled() # it stays usable and says why it waits (U-20261118-02) + elevate.trigger() + assert window.statusBar().currentMessage() == busy_text(elevate.text(), scanning=False) window.restart_as_admin() finally: window._path_dialogs.discard(guard) diff --git a/test/test_live_refresh.py b/test/test_live_refresh.py new file mode 100644 index 0000000..977e2ae --- /dev/null +++ b/test/test_live_refresh.py @@ -0,0 +1,60 @@ +"""A running scan's live refreshes are spaced by what each one cost the window (U-20261118-01).""" + +import time + +from PySide6.QtCore import QEventLoop, QObject, QTimer + +from je_file_tree.gui.live_refresh import FASTEST_MS, SLOWEST_MS, SPACING, LiveRefresh, interval_for + + +def _run(qapp, milliseconds): + """Run the event loop for ``milliseconds``, letting it wait (and announce that) between events.""" + loop = QEventLoop() + QTimer.singleShot(milliseconds, loop.quit) + loop.exec() + + +def test_the_wait_is_a_multiple_of_the_busy_time_within_bounds(): + assert interval_for(0) == FASTEST_MS + assert interval_for(FASTEST_MS / SPACING - 1) == FASTEST_MS + assert interval_for(300) == 300 * SPACING + assert interval_for(10_000) == SLOWEST_MS + + +def test_a_costly_refresh_spaces_the_next_one_and_a_cheap_one_restores_the_pace(qapp): + owner = QObject() + costs = [0.3, 0.0] + calls = [] + + def refresh(): + cost = costs[min(len(calls), len(costs) - 1)] + calls.append(time.perf_counter()) + time.sleep(cost) + + live = LiveRefresh(refresh, owner) + live.start() + assert live.interval == FASTEST_MS + _run(qapp, FASTEST_MS + 600) # the first, costly refresh ran and the loop went idle after it + assert len(calls) == 1 + assert 300 * SPACING <= live.interval <= SLOWEST_MS + spaced = live.interval + _run(qapp, spaced + 800) # the cheap second refresh brings the period back to the fastest + assert len(calls) >= 2 + assert calls[1] - calls[0] >= spaced / 1000 * 0.9 + assert live.interval == FASTEST_MS + live.stop() + assert not live.isActive() + + +def test_a_new_start_begins_at_the_fastest_pace_and_stop_drops_a_late_measurement(qapp): + owner = QObject() + live = LiveRefresh(lambda: time.sleep(0.3), owner) + live.start() + _run(qapp, FASTEST_MS + 600) + assert live.interval > FASTEST_MS + live.start() + assert live.interval == FASTEST_MS + live._tick() + live.stop() # the scan ended before the window went idle: the measurement changes nothing + _run(qapp, 50) + assert live.interval == FASTEST_MS and not live.isActive() diff --git a/test/test_permanent_delete_gui.py b/test/test_permanent_delete_gui.py index df3577c..84bca12 100644 --- a/test/test_permanent_delete_gui.py +++ b/test/test_permanent_delete_gui.py @@ -22,6 +22,7 @@ from je_file_tree.core.node import Node from je_file_tree.core.protected import PROGRAMS, Protection from je_file_tree.core.system_files import SystemFile +from je_file_tree.gui.busy_notice import busy_text from je_file_tree.gui import i18n, main_window from je_file_tree.gui import permanent_delete as gui_delete from je_file_tree.gui.permanent_delete import LISTED, PermanentDeleteWorker, PermanentReportDialog @@ -286,7 +287,10 @@ def test_the_action_sits_beside_the_trash_action_and_follows_its_state(window, q assert action.isEnabled() == trash.isEnabled() is True window._path_dialogs.add(object()) window._update_actions() - assert action.isEnabled() == trash.isEnabled() is False + # While an operation runs both stay usable and say why they wait (U-20261118-02). + assert action.isEnabled() == trash.isEnabled() is True + action.trigger() + assert window.statusBar().currentMessage() == busy_text(action.text(), scanning=False) window._path_dialogs.clear() window._update_actions() diff --git a/test/test_trash_undo_gui.py b/test/test_trash_undo_gui.py index f103c3b..cbde1f2 100644 --- a/test/test_trash_undo_gui.py +++ b/test/test_trash_undo_gui.py @@ -211,7 +211,7 @@ def partial(plan, **_kwargs): # Model a delayed GUI observer; native work stays held until the test releases it. time.sleep(gui_delay) qapp.processEvents() - assert window.operation_busy and not window._actions["open"].isEnabled() + assert window.operation_busy and window._actions["open"].isEnabled() # it explains the wait instead window.start_scan(str(source.parent)) assert window._worker is None, "scan cannot overlap an active inverse operation" window.close() diff --git a/test/test_tree_live_refresh.py b/test/test_tree_live_refresh.py index bccc374..b107ec8 100644 --- a/test/test_tree_live_refresh.py +++ b/test/test_tree_live_refresh.py @@ -1,4 +1,4 @@ -"""Live ticks repaint unchanged shown rows and relayout every structural change (U-20261017-76).""" +"""Live ticks repaint unchanged shown rows and relayout every structural change (U-20261017-76, U-20261118-01).""" from PySide6.QtCore import Qt @@ -31,7 +31,7 @@ def _record(model): return events -def test_unchanged_members_and_order_only_repaint_root_and_folder_rows(qapp): +def test_unchanged_members_and_order_only_repaint_the_root_row(qapp): model, root, folder, empty = _live_tree() _show(model, root) model.refresh() # the first live tick learns which shown folders have entries @@ -40,8 +40,9 @@ def test_unchanged_members_and_order_only_repaint_root_and_folder_rows(qapp): root.size = 61 model.refresh() assert events["layouts"] == 0 - # Rows by size: folder (31), file1 (20), file0 (10), empty (0): two folder runs; file rows are not notified. - assert [change[:2] for change in events["changes"]] == [(root, root), (folder, folder), (empty, empty)] + # The view repaints the rows on screen (ResultsView.refresh_live); notifying every shown folder row + # made Qt ask hasChildren once per folder (U-20261118-01). + assert [change[:2] for change in events["changes"]] == [(root, root)] assert all(change[2:] == (0, model.columnCount() - 1) for change in events["changes"]) assert _show(model, root) == [folder, root.children[3], root.children[2], empty] diff --git a/test/test_workspace_gui.py b/test/test_workspace_gui.py index 51175b3..8374e55 100644 --- a/test/test_workspace_gui.py +++ b/test/test_workspace_gui.py @@ -10,6 +10,7 @@ from test_gui import _wait from test_worker_lifecycle import _held_follow from je_file_tree.core.operations import MoveReceipt +from je_file_tree.gui.busy_notice import busy_text from je_file_tree.gui import change_watch, file_actions, i18n, main_window, scan_worker from je_file_tree.gui.app import create_workspace from je_file_tree.gui.qt_translation import apply_qt_translation @@ -72,7 +73,9 @@ def test_operation_owner_blocks_peer_commands_before_confirmation(workspace, tmp try: first._update_actions() assert first.operation_busy and second.operation_busy - assert not second._actions["open"].isEnabled() + assert second._actions["open"].isEnabled() # usable, but it says why it waits (U-20261118-02) + second._actions["open"].trigger() + assert second.statusBar().currentMessage() == busy_text(second._actions["open"].text(), scanning=False) monkeypatch.setattr(scan_worker.ScanWorker, "start", lambda _self: pytest.fail("peer scan dispatched")) monkeypatch.setattr(QMessageBox, "question", lambda *_args: pytest.fail("peer Trash approval dispatched")) second.move_to_trash(chosen)