From fcbe358c2c38ca5e9053c9042540739f84b199bf Mon Sep 17 00:00:00 2001 From: RGiskard7 <43444131+RGiskard7@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:14:05 +0100 Subject: [PATCH] =?UTF-8?q?fix:=20en=20Windows,=20renombrar=20o=20mover=20?= =?UTF-8?q?una=20carpeta=20se=20reintenta=20medio=20segundo=20si=20otro=20?= =?UTF-8?q?programa=20tiene=20algo=20de=20dentro=20abierto;=20los=20tests?= =?UTF-8?q?=20de=20la=20limpieza=20y=20de=20los=20visores=20ya=20no=20depe?= =?UTF-8?q?nden=20de=20la=20barra=20de=20rutas=20ni=20dejan=20ficheros=20a?= =?UTF-8?q?biertos,=20y=20los=20PR=20pasan=20tambi=C3=A9n=20los=20tests=20?= =?UTF-8?q?en=20Windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/latest-jylos.yml | 23 ++++++ changelog.md | 3 +- .../jylos/data/dao/filesystem/FileMoves.java | 67 +++++++++++++++++ .../dao/filesystem/FolderDAOFileSystem.java | 20 ++--- .../data/dao/filesystem/FileMovesTest.java | 74 +++++++++++++++++++ .../controller/VaultCleanupSupportTest.java | 5 +- .../ui/theme/FlatButtonsComponentsTest.java | 29 ++++++-- 7 files changed, 201 insertions(+), 20 deletions(-) create mode 100644 jylos/src/main/java/com/example/jylos/data/dao/filesystem/FileMoves.java create mode 100644 jylos/src/test/java/com/example/jylos/data/dao/filesystem/FileMovesTest.java diff --git a/.github/workflows/latest-jylos.yml b/.github/workflows/latest-jylos.yml index 61175b6..12155a6 100644 --- a/.github/workflows/latest-jylos.yml +++ b/.github/workflows/latest-jylos.yml @@ -16,6 +16,29 @@ concurrency: cancel-in-progress: true jobs: + # The release runs the tests on Windows too: running them here as well finds what only + # fails there (paths written with "\", files Windows will not delete while open) before a + # tag is pushed, not after. + test-windows: + name: Build and test (Windows) + runs-on: windows-latest + timeout-minutes: 30 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + cache: maven + + - name: Compile and run tests + shell: bash + run: mvn -B -f jylos/pom.xml clean test + test: name: Build and test runs-on: ubuntu-latest diff --git a/changelog.md b/changelog.md index 6c431ac..c538cfb 100644 --- a/changelog.md +++ b/changelog.md @@ -180,7 +180,8 @@ - lo mismo al mover, borrar o crear notas y carpetas en una carpeta recién renombrada o movida; - guardar la nota abierta después de renombrar o mover su carpeta ya no deja una copia con la ruta anterior; - cambiar solo mayúsculas y minúsculas del nombre de una carpeta ("trabajo" a "Trabajo") ahora la renombra; - - renombrar una carpeta con el nombre de otra que ya existe en el mismo sitio muestra un error, en lugar de no hacer nada. + - renombrar una carpeta con el nombre de otra que ya existe en el mismo sitio muestra un error, en lugar de no hacer nada; + - en Windows, renombrar o mover una carpeta se reintenta durante medio segundo si otro programa (el antivirus, el indexador, un cliente de sincronización) tiene abierto un instante algo de dentro, en lugar de fallar. ## [2.5.8] - 2026-11-04 diff --git a/jylos/src/main/java/com/example/jylos/data/dao/filesystem/FileMoves.java b/jylos/src/main/java/com/example/jylos/data/dao/filesystem/FileMoves.java new file mode 100644 index 0000000..af1b3e3 --- /dev/null +++ b/jylos/src/main/java/com/example/jylos/data/dao/filesystem/FileMoves.java @@ -0,0 +1,67 @@ +package com.example.jylos.data.dao.filesystem; + +import java.io.IOException; +import java.nio.file.AccessDeniedException; +import java.nio.file.FileSystemException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Moves a folder or file, trying again for a moment when the system refuses it because another + * program has it open. Windows does that while an antivirus, the search indexer or a sync + * client looks at a file just written; it lets go within a fraction of a second. A move that + * cannot work (the target exists, the source is gone) fails at once. + */ +final class FileMoves { + + /** How many times a move is tried, a short wait apart (half a second in all). */ + static final int ATTEMPTS = 10; + private static final long WAIT_MILLIS = 50; + + /** The move itself, {@link Files#move} outside tests. */ + @FunctionalInterface + interface Mover { + void move(Path from, Path to) throws IOException; + } + + /** The wait between two tries, {@link Thread#sleep} outside tests. */ + @FunctionalInterface + interface Waiter { + void waitFor(long millis) throws InterruptedException; + } + + private FileMoves() { + } + + static void move(Path from, Path to) throws IOException { + move(from, to, (source, target) -> Files.move(source, target), Thread::sleep); + } + + static void move(Path from, Path to, Mover mover, Waiter waiter) throws IOException { + for (int attempt = 1; ; attempt++) { + try { + mover.move(from, to); + return; + } catch (FileSystemException e) { + if (!inUseForAMoment(e) || attempt >= ATTEMPTS) { + throw e; + } + } + try { + waiter.waitFor(WAIT_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted while moving " + from, e); + } + } + } + + /** + * Refused because something has it open: access denied, or a plain file system error (the + * file in use). Its subclasses say why the move cannot work: the target exists, the source + * is gone, the folder is not empty. + */ + private static boolean inUseForAMoment(FileSystemException e) { + return e instanceof AccessDeniedException || e.getClass() == FileSystemException.class; + } +} diff --git a/jylos/src/main/java/com/example/jylos/data/dao/filesystem/FolderDAOFileSystem.java b/jylos/src/main/java/com/example/jylos/data/dao/filesystem/FolderDAOFileSystem.java index 23ab501..a2c4504 100644 --- a/jylos/src/main/java/com/example/jylos/data/dao/filesystem/FolderDAOFileSystem.java +++ b/jylos/src/main/java/com/example/jylos/data/dao/filesystem/FolderDAOFileSystem.java @@ -155,10 +155,10 @@ public void updateFolder(Folder folder) { List metadataDocumentIds = collectMetadataDocumentIds(currentPath); if (sameFolder) { Path step = currentPath.resolveSibling(newName + ".jylos-renaming"); - Files.move(currentPath, step); - Files.move(step, newPath); + FileMoves.move(currentPath, step); + FileMoves.move(step, newPath); } else { - Files.move(currentPath, newPath); + FileMoves.move(currentPath, newPath); } redirects.record(rootPath.relativize(currentPath).toString(), rootPath.relativize(newPath).toString()); moveDocumentMetadataEntries(metadataDocumentIds, @@ -230,7 +230,7 @@ public void deleteFolder(String id) { targetPath = targetPath.getParent().resolve(name + "_" + System.currentTimeMillis()); } - Files.move(path, targetPath); + FileMoves.move(path, targetPath); moveDocumentMetadataEntries(metadataDocumentIds, normalizedId, FileSystemNames.normalizeId(rootPath.relativize(targetPath).toString())); @@ -330,7 +330,7 @@ public void restoreFolder(String id) { } List metadataDocumentIds = collectMetadataDocumentIds(srcPath); - Files.move(srcPath, targetPath); + FileMoves.move(srcPath, targetPath); moveDocumentMetadataEntries(metadataDocumentIds, normalizedId, FileSystemNames.normalizeId(rootPath.relativize(targetPath).toString())); @@ -464,7 +464,7 @@ public void addNote(Folder folder, Note note) { try { if (!sourcePath.equals(targetPath)) { - Files.move(sourcePath, targetPath); + FileMoves.move(sourcePath, targetPath); moveDocumentMetadataIfNeeded( FileSystemNames.normalizeId(rootPath.relativize(sourcePath).toString()), FileSystemNames.normalizeId(rootPath.relativize(targetPath).toString()), @@ -505,7 +505,7 @@ public void moveNoteToRoot(Note note) { Path targetPath = uniqueDocumentTargetPath(requestedPath); try { - Files.move(sourcePath, targetPath); + FileMoves.move(sourcePath, targetPath); moveDocumentMetadataIfNeeded( FileSystemNames.normalizeId(rootPath.relativize(sourcePath).toString()), FileSystemNames.normalizeId(rootPath.relativize(targetPath).toString()), @@ -544,7 +544,7 @@ public void removeNote(Folder folder, Note note) { Path targetPath = uniqueDocumentTargetPath(requestedPath); try { - Files.move(sourcePath, targetPath); + FileMoves.move(sourcePath, targetPath); moveDocumentMetadataIfNeeded( FileSystemNames.normalizeId(rootPath.relativize(sourcePath).toString()), FileSystemNames.normalizeId(rootPath.relativize(targetPath).toString()), @@ -616,7 +616,7 @@ public void addSubFolder(Folder parent, Folder subFolder) { try { List metadataDocumentIds = collectMetadataDocumentIds(subPath); - Files.move(subPath, targetPath); + FileMoves.move(subPath, targetPath); redirects.record(rootPath.relativize(subPath).toString(), rootPath.relativize(targetPath).toString()); moveDocumentMetadataEntries(metadataDocumentIds, FileSystemNames.normalizeId(rootPath.relativize(subPath).toString()), @@ -655,7 +655,7 @@ public void moveFolderToRoot(Folder folder) { try { List metadataDocumentIds = collectMetadataDocumentIds(sourcePath); - Files.move(sourcePath, targetPath); + FileMoves.move(sourcePath, targetPath); redirects.record(rootPath.relativize(sourcePath).toString(), rootPath.relativize(targetPath).toString()); moveDocumentMetadataEntries(metadataDocumentIds, FileSystemNames.normalizeId(rootPath.relativize(sourcePath).toString()), diff --git a/jylos/src/test/java/com/example/jylos/data/dao/filesystem/FileMovesTest.java b/jylos/src/test/java/com/example/jylos/data/dao/filesystem/FileMovesTest.java new file mode 100644 index 0000000..8ab4bf9 --- /dev/null +++ b/jylos/src/test/java/com/example/jylos/data/dao/filesystem/FileMovesTest.java @@ -0,0 +1,74 @@ +package com.example.jylos.data.dao.filesystem; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.nio.file.AccessDeniedException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.FileSystemException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +/** + * Windows refuses for a moment to move a folder or file that another program has just opened + * (an antivirus, the search indexer, a sync client): the move is tried again a few times before + * it fails. A move that cannot work (the target exists, the source is gone) fails at once. + */ +class FileMovesTest { + + private static final Path FROM = Path.of("Trabajo"); + private static final Path TO = Path.of("Oficina"); + + private final List tries = new ArrayList<>(); + private final List waits = new ArrayList<>(); + + /** A move that is refused {@code refusals} times with {@code refusal}, then works. */ + private FileMoves.Mover refusing(int refusals, IOException refusal) { + return (from, to) -> { + tries.add(from + "->" + to); + if (tries.size() <= refusals) { + throw refusal; + } + }; + } + + @Test + void aMoveRefusedForAMomentIsTriedAgain() throws Exception { + FileMoves.move(FROM, TO, refusing(2, new AccessDeniedException("Trabajo")), waits::add); + + assertEquals(List.of("Trabajo->Oficina", "Trabajo->Oficina", "Trabajo->Oficina"), tries); + assertEquals(2, waits.size(), "a short wait before each new try"); + } + + @Test + void aFileInUseByAnotherProgramIsTriedAgainToo() throws Exception { + FileMoves.move(FROM, TO, refusing(1, new FileSystemException("Trabajo", null, + "The process cannot access the file because it is being used by another process")), waits::add); + + assertEquals(2, tries.size()); + } + + @Test + void aMoveStillRefusedFailsWithItsReason() { + AccessDeniedException refusal = new AccessDeniedException("Trabajo"); + + AccessDeniedException thrown = assertThrows(AccessDeniedException.class, + () -> FileMoves.move(FROM, TO, refusing(Integer.MAX_VALUE, refusal), waits::add)); + + assertEquals(refusal, thrown); + assertEquals(FileMoves.ATTEMPTS, tries.size()); + } + + @Test + void aMoveThatCannotWorkFailsAtOnce() { + assertThrows(FileAlreadyExistsException.class, () -> FileMoves.move(FROM, TO, + refusing(Integer.MAX_VALUE, new FileAlreadyExistsException("Oficina")), waits::add)); + + assertEquals(1, tries.size()); + assertEquals(List.of(), waits); + } +} diff --git a/jylos/src/test/java/com/example/jylos/ui/controller/VaultCleanupSupportTest.java b/jylos/src/test/java/com/example/jylos/ui/controller/VaultCleanupSupportTest.java index b5fffc8..ffbc191 100644 --- a/jylos/src/test/java/com/example/jylos/ui/controller/VaultCleanupSupportTest.java +++ b/jylos/src/test/java/com/example/jylos/ui/controller/VaultCleanupSupportTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -41,7 +42,9 @@ private Runnable command(NoteService notes, boolean accept) { Map handlers = new EnumMap<>(ActionType.class); support.register(handlers, () -> notes, key -> key, status::add, () -> null); support.useForTests(Runnable::run, Runnable::run, (count, backups) -> { - asked.add(count + " " + vault.relativize(backups).toString().replaceAll("\\d", "N")); + // The folder the copies go to, written with "/" whatever the system's separator. + asked.add(count + " " + vault.relativize(backups).toString().replace(File.separatorChar, '/') + .replaceAll("\\d", "N")); return accept; }); return handlers.getOrDefault(ActionType.VAULT_CLEANUP, () -> status.add("no command")); diff --git a/jylos/src/test/java/com/example/jylos/ui/theme/FlatButtonsComponentsTest.java b/jylos/src/test/java/com/example/jylos/ui/theme/FlatButtonsComponentsTest.java index f324f49..204287e 100644 --- a/jylos/src/test/java/com/example/jylos/ui/theme/FlatButtonsComponentsTest.java +++ b/jylos/src/test/java/com/example/jylos/ui/theme/FlatButtonsComponentsTest.java @@ -36,6 +36,7 @@ import javafx.scene.control.ButtonBase; import javafx.scene.control.Label; import javafx.scene.control.Toggle; +import javafx.scene.image.ImageView; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.FlowPane; @@ -145,7 +146,7 @@ void buttonsAreFlat(String theme, String view) throws Exception { return out; }); - if ("pdf".equals(view)) { + if ("pdf".equals(view) || "image".equals(view)) { closeWhenLoaded(shown.get()); } @@ -153,16 +154,16 @@ void buttonsAreFlat(String theme, String view) throws Exception { } /** - * The PDF viewer reads its file in the background (its page count, "/ 0", changes once it - * has) and keeps the document open while it is shown; it closes it when taken out of its - * window. Done here once it has loaded, so the - * file is no longer open when the temporary folder is deleted (Windows refuses to delete an - * open file). + * The viewers read their file in the background: the image viewer until the image has + * loaded, the PDF viewer until its page count ("/ 0") changes, keeping the document open + * while it is shown and closing it when taken out of its window. Both are waited for and + * taken out here, so no file is open when the temporary folder is deleted (Windows refuses + * to delete an open file). */ private static void closeWhenLoaded(Pane host) throws Exception { long deadline = System.nanoTime() + 20_000_000_000L; - while (!onFx(() -> all(host).stream().anyMatch(n -> n instanceof Label l && l.getText() != null && l.getText().matches("/ [1-9]\\d*")))) { - assertTrue(System.nanoTime() < deadline, "the PDF viewer loaded its document"); + while (!onFx(() -> loaded(host))) { + assertTrue(System.nanoTime() < deadline, "the viewer loaded its file"); Thread.sleep(50); } onFx(() -> { @@ -171,6 +172,18 @@ private static void closeWhenLoaded(Pane host) throws Exception { }); } + private static boolean loaded(Pane host) { + for (Node node : all(host)) { + if (node instanceof ImageView image && image.getImage() != null && image.getImage().getProgress() >= 1) { + return true; + } + if (node instanceof Label label && label.getText() != null && label.getText().matches("/ [1-9]\\d*")) { + return true; + } + } + return false; + } + private static List all(Parent root) { List out = new ArrayList<>(); walk(root, out);